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        if let Err(reason) = crate::render::is_wit_world_ref(&self.wit) {
1410            let (de, para, wit) = edge();
1411            return Err(AplicacaoError::ContratoWitInvalid {
1412                de,
1413                para,
1414                wit,
1415                reason,
1416            });
1417        }
1418
1419        if self.is_http() {
1420            if subject.is_some() || slot.is_some() {
1421                let (de, para, wit) = edge();
1422                return Err(AplicacaoError::ContratoWrongTarget {
1423                    de,
1424                    para,
1425                    wit,
1426                    expected: WitTarget::HTTP_FIELD_NAME,
1427                });
1428            }
1429            let ep = endpoint.ok_or_else(|| {
1430                let (de, para, wit) = edge();
1431                AplicacaoError::ContratoMissingTarget {
1432                    de,
1433                    para,
1434                    wit,
1435                    expected: WitTarget::HTTP_FIELD_NAME,
1436                }
1437            })?;
1438            if ep.is_empty() {
1439                let (de, para) = self.edge_pair();
1440                return Err(AplicacaoError::ContratoEndpointEmpty { de, para });
1441            }
1442            if !ep.starts_with('/') {
1443                let (de, para) = self.edge_pair();
1444                return Err(AplicacaoError::ContratoEndpointNotAbsolute {
1445                    de,
1446                    para,
1447                    endpoint: ep.to_string(),
1448                });
1449            }
1450            // The `:endpoint` lands verbatim as a Cilium L7 `path:` rule
1451            // (caixa-mesh/src/lib.rs:311) and shares the K8s Gateway
1452            // API v1 HTTPPathMatch.value admission grammar with the
1453            // sibling `:entrada :paths` axis. Until this gate landed
1454            // `target()` only refused the empty string + the missing-
1455            // leading-`/` form; a structurally invalid endpoint
1456            // (`"/charge?token=X"` — query in path slot, `"/foo bar"` —
1457            // un-percent-encoded whitespace, `"/api/café"` — non-ASCII,
1458            // `"/api//bar"` — consecutive slash, `"/api/../etc"` —
1459            // path-traversal segment, the >1024-byte slug) silently
1460            // passed validate and the failure surfaced at apply time
1461            // as a Cilium policy rejection / silent traffic drop, far
1462            // from the source caixa.lisp. Same Gateway API HTTPPathMatch
1463            // grammar `:entrada :paths` already gates (55410e4), now
1464            // shared with `:contratos :endpoint` through the lifted
1465            // `crate::render::is_gateway_api_http_path` predicate.
1466            if let Err(reason) = crate::render::is_gateway_api_http_path(ep) {
1467                let (de, para) = self.edge_pair();
1468                return Err(AplicacaoError::ContratoEndpointInvalid {
1469                    de,
1470                    para,
1471                    endpoint: ep.to_string(),
1472                    reason,
1473                });
1474            }
1475            return Ok(WitTarget::Http { endpoint: ep });
1476        }
1477        if self.is_pubsub() {
1478            if endpoint.is_some() || slot.is_some() {
1479                let (de, para, wit) = edge();
1480                return Err(AplicacaoError::ContratoWrongTarget {
1481                    de,
1482                    para,
1483                    wit,
1484                    expected: WitTarget::PUBSUB_FIELD_NAME,
1485                });
1486            }
1487            let s = subject.ok_or_else(|| {
1488                let (de, para, wit) = edge();
1489                AplicacaoError::ContratoMissingTarget {
1490                    de,
1491                    para,
1492                    wit,
1493                    expected: WitTarget::PUBSUB_FIELD_NAME,
1494                }
1495            })?;
1496            if s.is_empty() {
1497                let (de, para) = self.edge_pair();
1498                return Err(AplicacaoError::ContratoSubjectEmpty { de, para });
1499            }
1500            // The `:subject` lands at runtime as the NATS subject the
1501            // producer publishes to and the consumer subscribes from.
1502            // Until this gate landed `target()` only refused the
1503            // empty string; a structurally invalid subject
1504            // (`"foo..bar"` — empty token between separators,
1505            // `"foo.>.bar"` — non-trailing `>` wildcard the NATS
1506            // server's subject parser rejects, `"foo bar"` —
1507            // un-percent-encoded whitespace, `"foo.café"` —
1508            // un-percent-encoded non-ASCII, `".foo"` / `"foo."` —
1509            // empty leading/trailing tokens, the >256-byte
1510            // paste-from-binary slug) silently passed validate and
1511            // the failure surfaced at runtime as a NATS server-side
1512            // `-ERR 'Invalid Subject'` on publish / subscribe, or as
1513            // a silent message drop, far from the source caixa.lisp.
1514            // Same Gateway API HTTPPathMatch / WIT-IDL grammar
1515            // trajectory `:contratos :endpoint` (4f0390b) and
1516            // `:contratos :wit` (6226bf4) already gate, now shared
1517            // with `:contratos :subject` through the lifted
1518            // `crate::render::is_nats_subject` predicate.
1519            if let Err(reason) = crate::render::is_nats_subject(s) {
1520                let (de, para) = self.edge_pair();
1521                return Err(AplicacaoError::ContratoSubjectInvalid {
1522                    de,
1523                    para,
1524                    subject: s.to_string(),
1525                    reason,
1526                });
1527            }
1528            return Ok(WitTarget::PubSub { subject: s });
1529        }
1530        if self.is_store() {
1531            if endpoint.is_some() || subject.is_some() {
1532                let (de, para, wit) = edge();
1533                return Err(AplicacaoError::ContratoWrongTarget {
1534                    de,
1535                    para,
1536                    wit,
1537                    expected: WitTarget::STORE_FIELD_NAME,
1538                });
1539            }
1540            let sl = slot.ok_or_else(|| {
1541                let (de, para, wit) = edge();
1542                AplicacaoError::ContratoMissingTarget {
1543                    de,
1544                    para,
1545                    wit,
1546                    expected: WitTarget::STORE_FIELD_NAME,
1547                }
1548            })?;
1549            if sl.is_empty() {
1550                let (de, para) = self.edge_pair();
1551                return Err(AplicacaoError::ContratoSlotEmpty { de, para });
1552            }
1553            // Value-shape gate on the third (and last) typed payload
1554            // axis the `WitContract::target` dispatch carries — the
1555            // peer of [`crate::render::is_gateway_api_http_path`] for
1556            // `:endpoint` (4f0390b) and [`crate::render::is_nats_subject`]
1557            // for `:subject` (63e18a0). Until this gate landed
1558            // `target()` only refused the empty string; a structurally
1559            // invalid slot (`"check out/$order"` — un-percent-encoded
1560            // whitespace whose runtime behavior varies unpredictably
1561            // across kv backends, `"checkout/\x01order"` — control
1562            // character that Redis admits but corrupts on next read
1563            // and DynamoDB rejects outright, `"chéckout/$order"` —
1564            // un-percent-encoded non-ASCII byte each backend re-encodes
1565            // differently, `"checkout\n/$order"` — embedded newline,
1566            // the 513-byte paste-from-binary slug) silently passed
1567            // validate and surfaced at runtime as a per-backend kv
1568            // write rejection (DynamoDB / etcd) or as a silent
1569            // next-read corruption (Redis-via-RESP3), far from the
1570            // source caixa.lisp with no field naming which `:contratos`
1571            // edge carried the typo. The lifted predicate makes the
1572            // kv-backend intersection-floor a substrate-level
1573            // invariant at validate time, not a runtime "this passed
1574            // validate but the kv backend rejected on first write"
1575            // surprise — closes the typed payload-axis value-shape
1576            // trajectory across all three legs of the four
1577            // [`WitTarget`] arms (HTTP / PubSub / Store / Capability)
1578            // that caixa-mesh + the future kv emitters land in.
1579            if let Err(reason) = crate::render::is_wasi_keyvalue_slot(sl) {
1580                let (de, para) = self.edge_pair();
1581                return Err(AplicacaoError::ContratoSlotInvalid {
1582                    de,
1583                    para,
1584                    slot: sl.to_string(),
1585                    reason,
1586                });
1587            }
1588            return Ok(WitTarget::Store { slot: sl });
1589        }
1590
1591        // Unrecognized WIT world — must not carry any payload target.
1592        if endpoint.is_some() || subject.is_some() || slot.is_some() {
1593            let (de, para, wit) = edge();
1594            return Err(AplicacaoError::ContratoWrongTarget {
1595                de,
1596                para,
1597                wit,
1598                expected: WitTarget::CAPABILITY_EXPECTED,
1599            });
1600        }
1601        Ok(WitTarget::Capability)
1602    }
1603
1604    /// Substrate-canonical post-validation projection of the typed
1605    /// [`WitTarget`] view — the panic-on-failure shorthand every renderer
1606    /// downstream of an [`AplicacaoSpec`] that has already crossed the
1607    /// [`AplicacaoSpec::validate`] gate (typically via a caixa-mesh
1608    /// [`typed_view`]-shaped entry point that composes `validate` into
1609    /// the projection) reaches through when it needs the typed
1610    /// [`WitTarget`] and knows the containing [`AplicacaoSpec::validate`]
1611    /// has already admitted the `(:wit, :endpoint/:subject/:slot)` shape
1612    /// coherence for every `:contratos` entry. The peer accessor to the
1613    /// [`Self::target`] `Result`-returning validator on the same
1614    /// per-`:contratos` typed-projection axis — [`Self::target`] is the
1615    /// pre-validation validator that computes the projection *and* raises
1616    /// the [`AplicacaoError::Contrato*`] diagnostic cascade on any
1617    /// (`:wit`, payload) mismatch; this method is the post-validation
1618    /// projection every downstream consumer reaches through once the
1619    /// pre-validation gate has succeeded.
1620    ///
1621    /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
1622    ///
1623    /// Prior to this lift the "call `.target()` then `.expect(…)` with
1624    /// the same message" pattern sat inline at two production sites with
1625    /// no compile-time link between them: the
1626    /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)` CNP
1627    /// L7 introspection branch at `caixa-mesh/src/lib.rs:2825`
1628    /// (`c.target().expect("validated by typed_view").http_endpoint()`)
1629    /// and the [`caixa_feira::cmd::app`] `feira app graph` per-`:contratos`
1630    /// payload-column printer at `caixa-feira/src/cmd/app.rs:110`
1631    /// (`c.target().expect("validated by typed_view").graph_label()`),
1632    /// each open-coding the same `.target().expect("validated by
1633    /// typed_view")` pair with the message spelled twice. A future
1634    /// vocabulary shift on the panic-message axis (a tightening from
1635    /// `"validated by typed_view"` to `"validated by AplicacaoSpec::
1636    /// validate"` as the substrate's validator entry-point vocabulary
1637    /// sharpens, a per-consumer disambiguation, an M4 promotion of the
1638    /// panic to a `debug_assert` under a `--release` build profile) would
1639    /// have had to be threaded through both open-coded call sites in
1640    /// lockstep or one consumer would silently disagree with the peer on
1641    /// which invariant the panic message names. Same "same shape written
1642    /// verbatim ≥ 2 times becomes a typed helper" duplication-budget
1643    /// discipline the sibling [`Self::edge_pair`] /
1644    /// [`Self::edge_triple`] / [`Self::identity`] composite-projection
1645    /// lifts already establish on the paired composite-projection axis;
1646    /// this lift extends it onto the post-validation typed-view axis.
1647    ///
1648    /// Every future downstream consumer of the projected typed view
1649    /// (the future M4 per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao`
1650    /// CR materializer's per-edge admission webhook, the future
1651    /// Envoy-side per-typed-arm `local_rate_limit.descriptor_entries`
1652    /// bucket-key resolver, the future per-`:contratos`-edge mTLS overlay
1653    /// resolver, the future `feira app graph --l7` / `--pubsub` /
1654    /// `--kv` per-shape column emitters) reaches through this one typed
1655    /// dispatch on the substrate primitive rather than an open-coded
1656    /// per-consumer `.target().expect(…)` pair with the message
1657    /// re-inlined. The invariant the accessor's panic path pins — "this
1658    /// call is only reachable after [`AplicacaoSpec::validate`] has
1659    /// succeeded on the containing spec" — is the substrate's answer to
1660    /// give exactly once, at the primitive, not once per consumer.
1661    ///
1662    /// # Panics
1663    ///
1664    /// Panics with [`Self::PROJECTED_INVARIANT_MSG`] if [`Self::target`]
1665    /// would return an `Err` — i.e. if this contract's
1666    /// (`:wit`, `:endpoint`/`:subject`/`:slot`) shape has not been
1667    /// crossed by the [`AplicacaoSpec::validate`] gate cascade. Call
1668    /// this accessor only from a code path that has already reached the
1669    /// containing [`AplicacaoSpec`] through a validating entry-point
1670    /// (caixa-mesh's [`typed_view`], caixa-feira's `feira app graph`'s
1671    /// [`typed_view`] compose, the future M4 CR admission webhook's
1672    /// per-CR validate). Use [`Self::target`] instead on any pre-
1673    /// validation code path.
1674    ///
1675    /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
1676    #[must_use]
1677    pub fn target_projected(&self) -> WitTarget<'_> {
1678        self.target().expect(Self::PROJECTED_INVARIANT_MSG)
1679    }
1680
1681    /// Canonical panic message the [`Self::target_projected`]
1682    /// post-validation projection accessor threads through when the
1683    /// caller has violated the "call only after [`AplicacaoSpec::validate`]
1684    /// has succeeded" precondition. Lifted as a `pub const` on the
1685    /// [`WitContract`] surface so the byte-string lives in one place
1686    /// across the substrate — the [`Self::target_projected`] method
1687    /// body, the two prior production call sites' comments now naming
1688    /// the const, and every future consumer that must format-match the
1689    /// panic-message shape (a future test suite that asserts the panic-
1690    /// message byte-string across a fuzzed invalid-contract corpus,
1691    /// a future custom-panic hook in `caixa-operator` that surfaces the
1692    /// message with per-`:contratos` telemetry, the future admission
1693    /// webhook's per-CR validate-error report) reaches through the same
1694    /// canonical `&'static str`. A future rebrand on the panic-message
1695    /// axis (a tightening from `"validated by typed_view"` to `"validated
1696    /// by AplicacaoSpec::validate"` as the substrate's validator
1697    /// entry-point vocabulary sharpens once caixa-core grows a
1698    /// `Caixa::validated_aplicacao_view` companion to caixa-mesh's
1699    /// [`typed_view`]) lands at one caixa-core edit rather than a
1700    /// coordinated per-consumer sweep — same "one canonical declaration
1701    /// per axis, next to the accessor that reads it" discipline the peer
1702    /// [`WitTarget::CAPABILITY_LABEL`] / [`WitTarget::CAPABILITY_EXPECTED`]
1703    /// / [`WitTarget::CAPABILITY_GRAPH_LABEL`] payload-less-arm scalar-
1704    /// const family already establishes on the paired per-consumer-axis
1705    /// diagnostic-scalar surface.
1706    pub const PROJECTED_INVARIANT_MSG: &'static str = "validated by typed_view";
1707}
1708
1709/// Borrowed identity key for the typed-graph duplicate-`:contratos`
1710/// gate (see [`AplicacaoSpec::validate`]): every field that
1711/// distinguishes one contract from another, in declaration order
1712/// (`(de, para, wit, endpoint, subject, slot)`). Two [`WitContract`]s
1713/// with equal [`ContratoIdentity`]s are the same typed edge declared
1714/// twice — the graph-edge analogue of duplicate `:membros` /
1715/// `:placement :clusters` / `:entrada :paths` entries. Lifted as a
1716/// type alias so the duplicate-gate's `HashSet<…>` type doesn't trip
1717/// clippy's `type_complexity` lint (and so a future axis added to
1718/// `WitContract` is one alias edit, not a coordinated rewrite of
1719/// every set instantiation).
1720pub type ContratoIdentity<'a> = (
1721    &'a str,
1722    &'a str,
1723    &'a str,
1724    Option<&'a str>,
1725    Option<&'a str>,
1726    Option<&'a str>,
1727);
1728
1729/// Typed view of a [`WitContract`]'s payload target. Each variant
1730/// carries the field its WIT shape requires; constructing a `Http`
1731/// view without an endpoint is impossible by the type system.
1732///
1733/// Renderers (caixa-mesh L7 rules, feira app graph) match on this
1734/// instead of probing `Option<String>` fields one by one — the
1735/// "which payload field is set?" question is answered once, at
1736/// validation time.
1737#[derive(Debug, Clone, Copy, PartialEq, Eq, gen_platform::IsVariant)]
1738pub enum WitTarget<'a> {
1739    /// HTTP-shaped WIT world. Carries the configured request path.
1740    Http { endpoint: &'a str },
1741    /// Pub-sub-shaped WIT world. Carries the event-stream subject.
1742    ///
1743    /// The `IsVariant` derive would auto-name the predicate `is_pub_sub`
1744    /// (`discriminant_to_snake("PubSub") == "pub_sub"`); the explicit
1745    /// `#[is_variant(name = "pubsub")]` override keeps the emitted
1746    /// method name byte-identical to the sibling
1747    /// [`WitContract::is_pubsub`] predicate (the paired shape-side
1748    /// arm-discriminator that routes through
1749    /// [`wit_shape_is_pubsub`] on the wit-world-ref scalar rather than
1750    /// through `matches!` on the variant), so the two arm-discriminator
1751    /// axes — target-side variant-arm and shape-side ref-prefix — reach
1752    /// every downstream consumer through the same `is_pubsub()` name.
1753    #[is_variant(name = "pubsub")]
1754    PubSub { subject: &'a str },
1755    /// Key-value-shaped WIT world. Carries the slot template.
1756    Store { slot: &'a str },
1757    /// A typed capability edge with no payload selector — the WIT
1758    /// world stands on its own (rare; reserved for plain capability
1759    /// imports or M4-and-later WIT worlds we haven't shaped yet).
1760    Capability,
1761}
1762
1763impl<'a> WitTarget<'a> {
1764    /// Canonical author-facing `:contratos` payload field name for the
1765    /// HTTP-shaped arm — the `expected: &'static str` scalar the
1766    /// [`AplicacaoError::ContratoMissingTarget`] /
1767    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1768    /// through, the `:endpoint "…"` keyword the [`WitTarget::label`]
1769    /// duplicate-edge diagnostic emits, and the `endpoint=…` prefix
1770    /// the `feira app graph` verb prints. Peer of
1771    /// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
1772    /// on the payload-field-name axis; declared as a peer const next
1773    /// to the [`WitTarget::Http`] variant so a future rename on the
1774    /// author-surface `(defcaixa … :contratos ((:de … :para … :wit …
1775    /// :endpoint …)))` field lands in exactly one place, not scattered
1776    /// across the [`WitContract::target`] gate's six `expected:`
1777    /// literals, the label template, and every downstream consumer
1778    /// that prints a per-arm prefix. Same trajectory as the peer
1779    /// [`WitTarget::label`] lift (174e96a): a single source of truth
1780    /// for the arm's shape, next to the variant declaration.
1781    pub const HTTP_FIELD_NAME: &'static str = "endpoint";
1782    /// Canonical author-facing `:contratos` payload field name for the
1783    /// pub-sub-shaped arm. Peer of [`WitTarget::HTTP_FIELD_NAME`] /
1784    /// [`WitTarget::STORE_FIELD_NAME`] on the payload-field-name axis;
1785    /// see [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1786    pub const PUBSUB_FIELD_NAME: &'static str = "subject";
1787    /// Canonical author-facing `:contratos` payload field name for the
1788    /// key/value-store-shaped arm. Peer of
1789    /// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`]
1790    /// on the payload-field-name axis; see
1791    /// [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1792    pub const STORE_FIELD_NAME: &'static str = "slot";
1793
1794    /// Canonical stable human-readable label the payload-less
1795    /// [`WitTarget::Capability`] arm renders as under [`Self::label`] —
1796    /// the byte-string every consumer that formats a payload-less
1797    /// typed capability edge as text lands on (the
1798    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` diagnostic
1799    /// naming which identical edge was declared twice, the future
1800    /// `feira app graph` verb's per-arm prefix, the future M4 per-edge
1801    /// policy resolver's audit view, the operator's mesh-graph audit).
1802    /// Peer of the payload-arm [`Self::HTTP_FIELD_NAME`] /
1803    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`]
1804    /// author-facing label-scalar consts — the same
1805    /// "one canonical declaration per arm, next to the variant, so a
1806    /// future rename lands in one place" discipline extended to the
1807    /// payload-less arm. Until this lift landed the byte-string sat
1808    /// twice — once inline in [`Self::label`]'s [`WitTarget::Capability`]
1809    /// match arm, once in the pin test asserting the label's
1810    /// [`WitTarget::Capability`] output — with no compile-time link
1811    /// between the two: a rebrand on either side (an operator-facing
1812    /// vocabulary shift, a per-consumer disambiguation like
1813    /// `"(capability — no payload; typed edge only)"`) would silently
1814    /// desynchronize until a downstream consumer surfaced the drift at
1815    /// runtime.
1816    pub const CAPABILITY_LABEL: &'static str = "(capability — no payload)";
1817
1818    /// Canonical `expected:` scalar the
1819    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1820    /// through for the payload-less [`WitTarget::Capability`] arm — the
1821    /// byte-string authors read as "this WIT world's shape is not one
1822    /// of {`HTTP`, `PubSub`, `Store`}, so it must not carry
1823    /// `:endpoint` / `:subject` / `:slot`". Peer of the payload-arm
1824    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1825    /// [`Self::STORE_FIELD_NAME`] consts on the
1826    /// `ContratoWrongTarget::expected` axis — the fourth arm of the
1827    /// same "which payload field name goes in the diagnostic" dispatch
1828    /// the three payload-arm consts cover, extended to the payload-less
1829    /// arm. Until this lift landed the byte-string sat twice — once
1830    /// inline in the [`Self::target`] Capability-arm rejection at the
1831    /// production dispatch, once in the pin test asserting the
1832    /// diagnostic's `expected:` scalar carries `"none"` verbatim — with
1833    /// no compile-time link between the two: a rebrand on either side
1834    /// (an author-facing vocabulary shift to `"capability"` /
1835    /// `"(none)"` / `"no-payload"` as the WIT registry's shape
1836    /// vocabulary sharpens, a per-consumer disambiguation as M4 splits
1837    /// [`WitTarget::Capability`] into per-shape peers) would silently
1838    /// desynchronize until a downstream consumer surfaced the drift at
1839    /// runtime. Same "one canonical declaration per arm, next to the
1840    /// variant, so a future rename lands in one place" discipline the
1841    /// peer [`Self::CAPABILITY_LABEL`] lift (7ed03a3-era) already
1842    /// established for the payload-less arm's human-readable label
1843    /// axis; this lift extends it onto the peer diagnostic-scalar axis
1844    /// so both halves of the "how does the Capability arm surface at
1845    /// its two consumer axes (human-readable label, wrong-target
1846    /// diagnostic)" pipeline route through peer consts declared next
1847    /// to the variant.
1848    ///
1849    /// Pairwise-distinctness against the three payload-arm scalars
1850    /// ([`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1851    /// [`Self::STORE_FIELD_NAME`]) is pinned by the sibling
1852    /// `wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`
1853    /// test — the 4-way closure of the 3-way
1854    /// `wit_target_field_names_are_pairwise_distinct` sibling pin onto
1855    /// the `ContratoWrongTarget::expected` axis, matching the peer
1856    /// `m3_placement_estrategia_consts_are_pairwise_distinct` closed-set
1857    /// scalar-value distinctness discipline the sibling M3 typed-enum
1858    /// discriminator axis already carries.
1859    pub const CAPABILITY_EXPECTED: &'static str = "none";
1860
1861    /// Canonical `feira app graph` per-`:contratos`-edge payload-column
1862    /// byte-string the payload-less [`WitTarget::Capability`] arm renders
1863    /// as under [`Self::graph_label`] — the sibling
1864    /// [`WitTarget::CAPABILITY_LABEL`] scalar on the peer graph-verb
1865    /// payload-column axis (the graph verb spells payload-less as
1866    /// `(capability-only)`, distinct from the duplicate-`:contratos`
1867    /// diagnostic's `(capability — no payload)` on the human-readable
1868    /// [`Self::label`] axis). Peer of [`Self::CAPABILITY_LABEL`] /
1869    /// [`Self::CAPABILITY_EXPECTED`] on the payload-less-arm scalar-const
1870    /// family — extends the "one canonical declaration per arm, next to
1871    /// the variant, so a future rename lands in one place" discipline
1872    /// onto the third payload-less-arm consumer axis (`feira app graph`
1873    /// payload column, joining the [`Self::label`] duplicate-`:contratos`
1874    /// diagnostic axis and the [`Self::target`] wrong-target diagnostic
1875    /// axis).
1876    ///
1877    /// Until this lift landed the byte-string sat inline in
1878    /// [`caixa-feira`]'s `cmd::app::GraphArgs::run` per-`:contratos` payload-
1879    /// column match at `caixa-feira/src/cmd/app.rs:111` as a raw
1880    /// `"(capability-only)".to_string()` literal, with no compile-time link
1881    /// back to the [`WitTarget::Capability`] variant declaration nor to
1882    /// the sibling [`Self::CAPABILITY_LABEL`] / [`Self::CAPABILITY_EXPECTED`]
1883    /// peer consts already carrying the "one canonical declaration per
1884    /// payload-less-arm consumer axis" discipline. A rebrand on either
1885    /// side (the graph verb's operator-facing vocabulary tightening from
1886    /// `"(capability-only)"` to `"capability"` / `"(capability edge)"` as
1887    /// the WIT registry vocabulary sharpens, an M4 split of
1888    /// [`Self::Capability`] into per-shape peers) would silently
1889    /// desynchronize the graph-verb byte-string from the paired
1890    /// per-arm-adjacent const and land two spellings of the same axis in
1891    /// two spots.
1892    pub const CAPABILITY_GRAPH_LABEL: &'static str = "(capability-only)";
1893
1894    /// The `(author-facing field name, payload)` pair this typed target
1895    /// arm carries — `Some((HTTP_FIELD_NAME, endpoint))` for
1896    /// [`Self::Http`], `Some((PUBSUB_FIELD_NAME, subject))` for
1897    /// [`Self::PubSub`], `Some((STORE_FIELD_NAME, slot))` for
1898    /// [`Self::Store`], `None` for the payload-less
1899    /// [`Self::Capability`] arm.
1900    ///
1901    /// Lifted as the single 4-arm dispatch that both [`Self::label`]
1902    /// (formats `":{field} {payload:?}"` on `Some`, falls to
1903    /// [`Self::CAPABILITY_LABEL`] on `None`) and [`Self::field_name`]
1904    /// (returns the first component) route through, so a future
1905    /// [`WitTarget`] variant addition — the M4-and-later per-edge WIT
1906    /// registry may split [`Self::Http`] into `Rest` / `Grpc` peers,
1907    /// or extend [`Self::Store`] with a `Queue`-shaped peer — becomes
1908    /// exactly one new match-arm here (a compile-time exhaustiveness
1909    /// error otherwise), not a coordinated three-way rewrite of the
1910    /// prior [`Self::label`] template + [`Self::field_name`] dispatch
1911    /// + every downstream consumer that reaches for the pair.
1912    ///
1913    /// Until this lift landed the three payload arms sat in
1914    /// [`Self::label`] as three near-identical `format!(":{} {…:?}", …)`
1915    /// invocations (one per variant, each hand-quoting the paired
1916    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1917    /// [`Self::STORE_FIELD_NAME`] const) — the canonical
1918    /// "same shape, written N times" duplication THEORY.md §I.3.5
1919    /// ("Generation first, composition second, hand-authoring last;
1920    /// the duplication budget is zero") promotes to a build-time
1921    /// concern, with each per-arm site paired to its own const with no
1922    /// compile-time link between the format template and the arm's
1923    /// payload extraction.
1924    #[must_use]
1925    pub const fn payload_pair(&self) -> Option<(&'static str, &'a str)> {
1926        match *self {
1927            WitTarget::Http { endpoint } => Some((Self::HTTP_FIELD_NAME, endpoint)),
1928            WitTarget::PubSub { subject } => Some((Self::PUBSUB_FIELD_NAME, subject)),
1929            WitTarget::Store { slot } => Some((Self::STORE_FIELD_NAME, slot)),
1930            WitTarget::Capability => None,
1931        }
1932    }
1933
1934    /// The canonical author-facing `:contratos` payload field name
1935    /// this typed target arm carries (`Http` → `Some("endpoint")`,
1936    /// `PubSub` → `Some("subject")`, `Store` → `Some("slot")`), or
1937    /// `None` for the payload-less `Capability` arm.
1938    ///
1939    /// Routes through [`Self::payload_pair`] — the single 4-arm
1940    /// dispatch [`Self::label`] also reads — so a future variant
1941    /// addition is one match-arm edit at [`Self::payload_pair`], not a
1942    /// per-consumer rewrite. Same "exhaustive-match at one canonical
1943    /// dispatch, thin projections at each consumer" trajectory the
1944    /// peer [`PlacementStrategy::as_str`] / [`std::fmt::Display`]
1945    /// pair (0a2f653) landed on the sibling M3 typed-enum axis.
1946    #[must_use]
1947    pub const fn field_name(&self) -> Option<&'static str> {
1948        match self.payload_pair() {
1949            Some((f, _)) => Some(f),
1950            None => None,
1951        }
1952    }
1953
1954    /// The underlying scalar the payload-carrying arm carries — the
1955    /// per-arm request path ([`Self::Http`] `:endpoint`), event-stream
1956    /// subject ([`Self::PubSub`] `:subject`), or slot template
1957    /// ([`Self::Store`] `:slot`), borrowed from the typed slot's own
1958    /// `&'a str` storage — or `None` on the payload-less
1959    /// [`Self::Capability`] arm.
1960    ///
1961    /// Thin projection onto the single 4-arm [`Self::payload_pair`]
1962    /// dispatch (`self.payload_pair().map(|(_, p)| p)` in `const fn`
1963    /// form) — peer of [`Self::field_name`] (`.payload_pair().0`) on
1964    /// the paired sub-selector axis. Both per-half accessors read from
1965    /// one authoritative match, so a future [`WitTarget`] variant
1966    /// addition (`Rest`/`Grpc` split of [`Self::Http`], `Queue`-shaped
1967    /// peer of [`Self::Store`]) lands at exactly one caixa-core edit
1968    /// on [`Self::payload_pair`] and both per-half projections + every
1969    /// downstream consumer picks the new arm up by construction — no
1970    /// coordinated N-way rewrite across the paired accessor dispatches,
1971    /// the [`Self::label`] / [`Self::graph_label`] format templates,
1972    /// and every future WIT-registry-shaped consumer.
1973    ///
1974    /// Peer of the sibling [`caixa-flux`][caixa-flux-crate]
1975    /// `GitRefSpec::ref_value` projection on the `FluxCD` source-
1976    /// controller `spec.ref.<field>` axis — same "one paired dispatch,
1977    /// both per-half projections as thin readers, every downstream
1978    /// consumer through the same match" discipline extended onto the
1979    /// M3 `:contratos` payload-arm axis. Closes the discipline-parity
1980    /// gap between the two paired-dispatch surfaces: the peer
1981    /// [`Self::payload_pair`] + [`Self::field_name`] pair carried only
1982    /// the first-component projection until this lift; the second-
1983    /// component sibling now sits alongside so both halves reach every
1984    /// future consumer through the same substrate-primitive dispatch.
1985    ///
1986    /// [caixa-flux-crate]: https://docs.rs/caixa-flux/latest/caixa_flux/enum.GitRefSpec.html#method.ref_value
1987    #[must_use]
1988    pub const fn payload(&self) -> Option<&'a str> {
1989        match self.payload_pair() {
1990            Some((_, p)) => Some(p),
1991            None => None,
1992        }
1993    }
1994
1995    /// Substrate-canonical per-arm HTTP-endpoint scalar accessor every
1996    /// consumer that fans on the L7-HTTP-shaped payload keys off —
1997    /// returns the [`Self::Http`]-arm's author-declared request path
1998    /// verbatim as an `Option<&'a str>`, `Some(endpoint)` when the
1999    /// projected target is [`Self::Http { endpoint }`], `None` on the
2000    /// three sibling arms ([`Self::PubSub`] / [`Self::Store`] /
2001    /// [`Self::Capability`], each of which carries no HTTP endpoint by
2002    /// definition).
2003    ///
2004    /// The [`Self::Http`] arm carries the Cilium L7 `HTTPNetworkPolicy`
2005    /// `path:` rule payload every substrate-side L7-introspecting
2006    /// per-`(:de, :para)` `CiliumNetworkPolicy` emitter reads (today: the
2007    /// [`caixa_mesh::cilium_network_policies`] per-edge `toPorts[].rules
2008    /// .http[0].path` scalar the HTTP-shape-only L7 rule builder emits
2009    /// on the L7 introspection branch; every peer WIT shape stays
2010    /// L4-only because Cilium can't introspect NATS / key-value / plain
2011    /// capability edges), and every future L7-introspecting consumer
2012    /// of the projected target's HTTP endpoint (the future M4
2013    /// per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao` CR
2014    /// materializer's per-edge L7 admission-webhook overlay, the
2015    /// future Envoy-side `local_rate_limit.descriptor_entries` per-HTTP-
2016    /// path bucket-key resolver, the future per-`:contratos`-edge
2017    /// mTLS-required overlay's HTTP-shape scope filter, the future
2018    /// `feira app graph --l7` per-Aplicacao HTTP-path column) reaches
2019    /// through the same typed dispatch.
2020    ///
2021    /// Prior to this lift the sole production consumer of the projected-
2022    /// target HTTP endpoint — the [`caixa_mesh::cilium_network_policies`]
2023    /// per-edge L7 introspection branch at `caixa-mesh/src/lib.rs:2759`
2024    /// (`if let WitTarget::Http { endpoint } = c.target().expect(…) {
2025    /// http_rule.insert_string(CILIUM_KEY_PATH, endpoint.to_string()); …
2026    /// }`) — reached the payload through a raw per-arm `if let` pattern-
2027    /// match that expressed no compile-time link back to the substrate
2028    /// primitive's typed dispatch, sibling to the [`WitContract`] pre-
2029    /// projection [`WitContract::endpoint`] (7020470) `Option<&str>`
2030    /// scalar accessor on the peer per-`:contratos` raw-field axis but
2031    /// with no post-projection peer on the typed-view surface. A future
2032    /// [`WitTarget`] variant addition that splits [`Self::Http`] into
2033    /// peers (a `Rest`/`Grpc` split once the WIT registry stabilizes
2034    /// gRPC-shaped worlds per this enum's own docstring at
2035    /// aplicacao.rs:1341-1343 — with a `Rest`-arm `endpoint: &'a str`
2036    /// payload alongside a `Grpc`-arm `service_method: &'a str` payload)
2037    /// would have had to be threaded through the caixa-mesh L7 emit
2038    /// branch's raw `if let` in lockstep — either coalescing the two
2039    /// L7-HTTP-family arms under a shared `path:` emit, or splitting the
2040    /// emit path per-arm — with no substrate-primitive dispatch making
2041    /// the "which arms count as L7-HTTP-shaped for path-emission
2042    /// purposes" question the substrate's answer to give. Lifting the
2043    /// resolution to a typed method on the substrate primitive means
2044    /// every downstream L7-HTTP-facing consumer of the Aplicacao's
2045    /// projected-target HTTP endpoint reaches for exactly one typed
2046    /// dispatch — the resolver's accept-set migrates as a unit on any
2047    /// future arm-family widening, and the caixa-mesh L7 emit branch
2048    /// reads through the same substrate primitive.
2049    ///
2050    /// Peer of the sibling pre-projection [`WitContract::endpoint`]
2051    /// (7020470) `Option<&str>` scalar accessor on the raw
2052    /// `:contratos :endpoint` field-access axis — same "one typed
2053    /// dispatch on the substrate primitive, thin projections at each
2054    /// consumer" discipline extended onto the peer post-projection typed-
2055    /// view surface (the [`WitContract::endpoint`] pre-projection
2056    /// accessor returns `Some` for any author-declared `:endpoint`
2057    /// value regardless of the paired `:wit` world's HTTP-shape
2058    /// classification — the raw slot before validation crosses it —
2059    /// while this post-projection [`Self::http_endpoint`] accessor
2060    /// returns `Some` iff the target has been projected onto the
2061    /// [`Self::Http`] arm, i.e. only after the [`WitContract::target`]
2062    /// gate has admitted the `(:wit, :endpoint/:subject/:slot)` shape
2063    /// coherence; the two accessors close the pre-projection /
2064    /// post-projection pair on the HTTP-endpoint axis). Sibling of the
2065    /// unified pan-arm [`Self::payload`] (`Option<&'a str>` for any of
2066    /// the three payload-carrying arms) — extends the per-arm
2067    /// projection family onto the [`Self::Http`] specialization axis
2068    /// that the pan-arm accessor's shape blends into a single arm-
2069    /// agnostic view; paired with [`Self::pubsub_subject`] /
2070    /// [`Self::store_slot`] on the sibling per-arm axes so every
2071    /// per-payload-arm shape carries a named post-projection accessor
2072    /// on the same shape as `http_endpoint`, closing the per-arm-shape
2073    /// accept-set the substrate primitive owns.
2074    #[must_use]
2075    pub const fn http_endpoint(&self) -> Option<&'a str> {
2076        match *self {
2077            WitTarget::Http { endpoint } => Some(endpoint),
2078            WitTarget::PubSub { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
2079        }
2080    }
2081
2082    /// Substrate-canonical per-arm pub-sub-subject scalar accessor every
2083    /// consumer that fans on the pub-sub-shaped payload keys off —
2084    /// returns the [`Self::PubSub`]-arm's author-declared event-stream
2085    /// subject verbatim as an `Option<&'a str>`, `Some(subject)` when
2086    /// the projected target is [`Self::PubSub { subject }`], `None` on
2087    /// the three sibling arms ([`Self::Http`] / [`Self::Store`] /
2088    /// [`Self::Capability`], each of which carries no NATS-shaped
2089    /// subject by definition).
2090    ///
2091    /// The [`Self::PubSub`] arm carries the NATS-server-accepted subject
2092    /// the future substrate-side pub-sub-introspecting per-`(:de, :para)`
2093    /// consumer keys off (the M4 per-Aplicacao NATS `Stream` / `Consumer`
2094    /// CR materializer's `spec.subjects[]` projection, the future
2095    /// Envoy-side per-subject `local_rate_limit.descriptor_entries`
2096    /// bucket-key resolver, the future `feira app graph --pubsub`
2097    /// per-Aplicacao subject column, any future substrate-lifted
2098    /// pub-sub-shape emitter that reads a projected `WitTarget` in the
2099    /// same shape [`caixa_mesh::cilium_network_policies`] reads the
2100    /// HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today). Every
2101    /// future pub-sub-shape consumer reaches for the same typed
2102    /// dispatch this accessor exposes so the "which arm carries the
2103    /// subject scalar?" answer lives at one caixa-core edit rather
2104    /// than open-coded across per-consumer `if let WitTarget::PubSub
2105    /// { subject } = c.target()…` pattern-matches.
2106    ///
2107    /// Peer of the sibling [`Self::http_endpoint`] (5d6dc92 trajectory)
2108    /// per-arm HTTP-endpoint accessor on the peer per-arm axis and of
2109    /// the pre-projection [`WitContract::subject`] scalar accessor on
2110    /// the raw `:contratos :subject` field-access axis — same "one
2111    /// typed dispatch on the substrate primitive, thin projections at
2112    /// each consumer" discipline extended onto the per-arm pub-sub
2113    /// post-projection axis. The pre-projection accessor returns
2114    /// `Some` for any author-declared `:subject` value regardless of
2115    /// the paired `:wit` world's pub-sub-shape classification (the raw
2116    /// slot before validation crosses it); this post-projection
2117    /// accessor returns `Some` iff the target has been projected onto
2118    /// the [`Self::PubSub`] arm, i.e. only after the
2119    /// [`WitContract::target`] gate has admitted the
2120    /// `(:wit, :endpoint/:subject/:slot)` shape coherence — closing
2121    /// the pre-/post-projection pair on the pub-sub-subject axis to
2122    /// match the pair the [`WitContract::endpoint`] +
2123    /// [`Self::http_endpoint`] surfaces already close on the peer
2124    /// HTTP-endpoint axis.
2125    ///
2126    /// Sibling of the unified pan-arm [`Self::payload`]
2127    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2128    /// extends the per-arm projection family onto the [`Self::PubSub`]
2129    /// specialization axis that the pan-arm accessor's shape blends
2130    /// into a single arm-agnostic view; the pair
2131    /// (`pubsub_subject`, `store_slot`) closes the trio
2132    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) so every
2133    /// payload arm now carries its own per-arm-shape post-projection
2134    /// accessor.
2135    #[must_use]
2136    pub const fn pubsub_subject(&self) -> Option<&'a str> {
2137        match *self {
2138            WitTarget::PubSub { subject } => Some(subject),
2139            WitTarget::Http { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
2140        }
2141    }
2142
2143    /// Substrate-canonical per-arm key/value-store-slot scalar accessor
2144    /// every consumer that fans on the store-shaped payload keys off —
2145    /// returns the [`Self::Store`]-arm's author-declared slot template
2146    /// verbatim as an `Option<&'a str>`, `Some(slot)` when the
2147    /// projected target is [`Self::Store { slot }`], `None` on the
2148    /// three sibling arms ([`Self::Http`] / [`Self::PubSub`] /
2149    /// [`Self::Capability`], each of which carries no
2150    /// key/value-store slot by definition).
2151    ///
2152    /// The [`Self::Store`] arm carries the WASI-key/value-accepted slot
2153    /// template (validated by [`crate::render::is_wasi_keyvalue_slot`])
2154    /// every future substrate-side store-introspecting per-`(:de,
2155    /// :para)` consumer keys off (the M4 per-Aplicacao WASI-key/value
2156    /// namespace / prefix reconciler's per-slot projection, the future
2157    /// per-store-backend routing overlay's slot-shape gate, the future
2158    /// `feira app graph --store` per-Aplicacao slot column, any future
2159    /// substrate-lifted store-shape emitter that reads a projected
2160    /// `WitTarget` in the same shape [`caixa_mesh::cilium_network_policies`]
2161    /// reads the HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today).
2162    /// Every future store-shape consumer reaches for the same typed
2163    /// dispatch this accessor exposes so the "which arm carries the
2164    /// slot scalar?" answer lives at one caixa-core edit rather than
2165    /// open-coded across per-consumer
2166    /// `if let WitTarget::Store { slot } = c.target()…`
2167    /// pattern-matches.
2168    ///
2169    /// Peer of the sibling [`Self::http_endpoint`] +
2170    /// [`Self::pubsub_subject`] per-arm accessors on the peer per-arm
2171    /// axes and of the pre-projection [`WitContract::slot`] scalar
2172    /// accessor on the raw `:contratos :slot` field-access axis — same
2173    /// "one typed dispatch on the substrate primitive, thin projections
2174    /// at each consumer" discipline extended onto the per-arm store
2175    /// post-projection axis. Closes the pre-/post-projection pair on
2176    /// the store-slot axis to match the pairs the
2177    /// [`WitContract::endpoint`] + [`Self::http_endpoint`] and
2178    /// [`WitContract::subject`] + [`Self::pubsub_subject`] surfaces
2179    /// already close on the peer HTTP-endpoint and pub-sub-subject
2180    /// axes; the substrate-side pre-/post-projection accessor family
2181    /// now spans all three payload arms as a matched trio, so any
2182    /// future arm-shape widening (a `Rest`/`Grpc` split of
2183    /// [`Self::Http`], a `Queue`-shaped peer of [`Self::Store`]) that
2184    /// lands one accessor without threading through the sibling
2185    /// pre-projection or the peer per-arm post-projection surfaces a
2186    /// compile-time exhaustiveness error at the substrate primitive,
2187    /// not a silent per-consumer split at renderer emit time.
2188    ///
2189    /// Sibling of the unified pan-arm [`Self::payload`]
2190    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2191    /// closes the per-arm projection family onto the [`Self::Store`]
2192    /// specialization axis that the pan-arm accessor's shape blends
2193    /// into a single arm-agnostic view. The trio
2194    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) partitions the
2195    /// pan-arm accept-set on every payload-carrying arm: exactly one
2196    /// per-arm accessor returns `Some(payload)` and the two peers
2197    /// return `None`, and every payload-less [`Self::Capability`]
2198    /// input returns `None` on all three — the partition the sibling
2199    /// `wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`
2200    /// pin locks in load-bearing.
2201    #[must_use]
2202    pub const fn store_slot(&self) -> Option<&'a str> {
2203        match *self {
2204            WitTarget::Store { slot } => Some(slot),
2205            WitTarget::Http { .. } | WitTarget::PubSub { .. } | WitTarget::Capability => None,
2206        }
2207    }
2208
2209    /// Render this typed target as a stable human-readable label
2210    /// (`:endpoint "/charge"`, `:subject "events.x"`,
2211    /// `:slot "checkout/$order"`, or `(capability — no payload)` when
2212    /// the WIT world is a pure capability edge).
2213    ///
2214    /// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
2215    /// gate so the diagnostic names *which* identical edge was
2216    /// declared twice (not just which `(de, para, wit)` triple).
2217    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2218    /// on the payload-carrying arms (`Some((field, payload)) →
2219    /// format!(":{field} {payload:?}")`) and through the lifted
2220    /// [`Self::CAPABILITY_LABEL`] const on the payload-less
2221    /// [`Self::Capability`] arm — so a future variant addition (the
2222    /// M4-and-later per-edge WIT registry may split [`Self::Http`]
2223    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2224    /// `Queue`-shaped peer) becomes a single new match-arm on
2225    /// [`Self::payload_pair`] rather than a rewrite of this template
2226    /// (and every downstream consumer that reaches for the label
2227    /// shape: the per-edge policy resolver in M4, the `feira app
2228    /// graph` view, the operator's mesh-graph audit). Until this
2229    /// lift landed the three payload arms carried three near-identical
2230    /// per-arm `format!(":{} {…:?}", …)` invocations, and the
2231    /// [`Self::Capability`] arm carried the payload-less byte-string
2232    /// twice (once inline here, once in the pin test) — closing the
2233    /// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
2234    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
2235    /// / 4a1e490) peer-const lifts already established for the
2236    /// payload-carrying arms.
2237    #[must_use]
2238    pub fn label(&self) -> String {
2239        match self.payload_pair() {
2240            Some((field, payload)) => format!(":{field} {payload:?}"),
2241            None => Self::CAPABILITY_LABEL.to_string(),
2242        }
2243    }
2244
2245    /// Render this typed target as the `feira app graph` per-`:contratos`
2246    /// payload-column byte-string (`endpoint=/charge`, `subject=events.x`,
2247    /// `slot=checkout/$order`, or [`Self::CAPABILITY_GRAPH_LABEL`] on the
2248    /// payload-less arm).
2249    ///
2250    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2251    /// on the payload-carrying arms (`Some((field, payload)) →
2252    /// format!("{field}={payload}")`) and through the lifted
2253    /// [`Self::CAPABILITY_GRAPH_LABEL`] const on the payload-less
2254    /// [`Self::Capability`] arm — so a future variant addition
2255    /// (the M4-and-later per-edge WIT registry may split [`Self::Http`]
2256    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2257    /// `Queue`-shaped peer) becomes one match-arm edit at
2258    /// [`Self::payload_pair`], propagating through this graph-verb
2259    /// projection at zero call-site cost, sibling to the peer
2260    /// [`Self::label`] duplicate-`:contratos` diagnostic emission on the
2261    /// same 4-arm dispatch.
2262    ///
2263    /// Until this lift landed the [`caixa-feira`]
2264    /// `cmd::app::GraphArgs::run` per-`:contratos` payload column
2265    /// (`caixa-feira/src/cmd/app.rs:101-112`) hand-rolled the same 4-arm
2266    /// dispatch inline, re-projecting `HTTP_FIELD_NAME` /
2267    /// `PUBSUB_FIELD_NAME` / `STORE_FIELD_NAME` under a per-arm
2268    /// `format!("{}={endpoint}", ...)` template and hard-coding
2269    /// `"(capability-only)"` as a fifth payload-less scalar with no link
2270    /// back to the paired [`WitTarget::Capability`] variant declaration.
2271    /// A future variant addition would have had to be threaded through
2272    /// both [`Self::label`] (via [`Self::payload_pair`]) *and* the graph
2273    /// verb's inline match in lockstep or the two projections would
2274    /// silently disagree on the arm-set the graph verb prints — the
2275    /// duplicate-`:contratos` diagnostic reading one shape while the
2276    /// graph verb's payload column silently dropped the new arm to
2277    /// `(capability-only)`. Lifting the graph-verb projection onto the
2278    /// same substrate-primitive [`Self::payload_pair`] dispatch closes
2279    /// the axis: both projections migrate as a unit.
2280    ///
2281    /// The `field=payload` (no colon prefix, `=` separator, no `Debug`
2282    /// quoting) shape is graph-verb-canonical — distinct from the
2283    /// sibling [`Self::label`] `":{field} {payload:?}"` shape the
2284    /// duplicate-`:contratos` diagnostic seeds (see
2285    /// [`Self::CAPABILITY_LABEL`] vs. [`Self::CAPABILITY_GRAPH_LABEL`]
2286    /// on the payload-less axis for the paired distinction).
2287    #[must_use]
2288    pub fn graph_label(&self) -> String {
2289        match self.payload_pair() {
2290            Some((field, payload)) => format!("{field}={payload}"),
2291            None => Self::CAPABILITY_GRAPH_LABEL.to_string(),
2292        }
2293    }
2294}
2295
2296/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
2297/// pretty-printed byte-string every consumer that formats a typed
2298/// payload target as user-facing text lands on (the
2299/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
2300/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
2301/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
2302/// graph` per-`:contratos`-edge payload column that reaches the graph
2303/// verb through `format!("{target}")`, the future M4 per-edge policy
2304/// resolver's per-edge audit-log line, the operator's mesh-graph
2305/// per-edge inspection view) reaches for the same lifted
2306/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
2307/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
2308/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
2309/// routes through — extending the three-path-convergence
2310/// (`Debug` for structural inspection, `Display` for user-facing text,
2311/// per-arm typed accessor for the canonical byte-string) discipline the
2312/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
2313/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
2314/// onto the fourth (and only remaining) typed-shape-discriminator axis
2315/// on the caixa surface.
2316///
2317/// Pre-lift the two paths were structurally independent — every consumer
2318/// reaching for a payload byte-string past the [`WitTarget::label`]
2319/// helper had to pick between three paths ([`WitTarget::label`],
2320/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
2321/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
2322/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
2323/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
2324/// that reached for `format!("{target}")` — the canonical shape every
2325/// user-facing pretty-print site on the sibling typed-enum axes already
2326/// uses — would silently land on the `Debug` derive's structural output
2327/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
2328/// than the `label()` helper's stable byte-string (`:endpoint
2329/// "/charge"` — the author-facing `:contratos` keyword form) the
2330/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
2331/// already threads through. The two spellings would diverge silently in
2332/// every downstream diagnostic / graph / audit line reached through
2333/// `format!` rather than through the `label()` helper. Routing
2334/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
2335/// path: every `format!("{v}")` call reaches the same
2336/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
2337/// and the duplicate-`:contratos` gate already route through, so a
2338/// future variant addition (the M4-and-later per-edge WIT registry may
2339/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
2340/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
2341/// consumer at exactly one place — the [`WitTarget::payload_pair`]
2342/// match — rather than fanning out through hand-rolled per-arm
2343/// [`std::fmt::Display`] arms.
2344///
2345/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
2346/// is the typed view returned by [`WitContract::target`], not a
2347/// closed-set discriminator enum with a gen-platform Discriminant
2348/// registration, so the `Debug` derive's structural output (which every
2349/// `{v:?}` consumer still reaches) stays distinct from the `Display`
2350/// helper's stable pretty-printed byte-string. `Debug` reveals variant
2351/// shape for structural inspection; `Display` (via `label`) reveals the
2352/// stable author-facing payload projection.
2353///
2354/// Pin tests
2355/// [`tests::wit_target_display_routes_through_label_helper`] and
2356/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
2357/// assert the two paths agree byte-for-byte on every variant, so a
2358/// future variant addition or `label()` reimplementation that hand-rolls
2359/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
2360/// build error visible at caixa-core test time, not a silent
2361/// per-consumer dispatch miss at diagnostic / audit / graph time.
2362impl std::fmt::Display for WitTarget<'_> {
2363    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2364        f.write_str(&self.label())
2365    }
2366}
2367
2368// ── one Aplicacao member ─────────────────────────────────────────────
2369
2370/// A Servico participating in the Aplicacao. Same shape as
2371/// `crate::supervisor::ChildSpec` but without a restart policy —
2372/// supervision is per-Servico (each member has its own
2373/// `:supervisor`), the Aplicacao orchestrates *placement*.
2374#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2375#[serde(rename_all = "camelCase")]
2376pub struct Membro {
2377    /// Member caixa's `:nome`. Resolves through the same dep
2378    /// resolution path as `crate::dep::Dep`.
2379    pub caixa: String,
2380
2381    /// Semver constraint.
2382    pub versao: String,
2383}
2384
2385impl Membro {
2386    /// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
2387    /// accessor every consumer that reads the member's Servico identity
2388    /// keys off — returns the author-declared `:membros :caixa`
2389    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
2390    /// own [`String`] storage.
2391    ///
2392    /// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
2393    /// participating in the Aplicacao — validated by
2394    /// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
2395    /// (via [`validate_membro_caixa`]), unique across the Aplicacao's
2396    /// `:membros` list, distinct from the Aplicacao's own `:nome` (via
2397    /// [`validate_no_self_membership`]) — and every downstream consumer
2398    /// that fans on the member's identity keys off this scalar (the
2399    /// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
2400    /// lookup, the per-`:membros` duplicate gate's dedup key, the
2401    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
2402    /// identity, the self-membership gate, the
2403    /// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
2404    /// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
2405    /// CR materializer's per-member resolver).
2406    ///
2407    /// Prior to this lift the `.caixa` byte-string was read inline at
2408    /// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
2409    /// set collector at
2410    /// `self.membros.iter().map(|m| m.caixa.as_str())`, the
2411    /// [`validate_membros`] validation-side member-caixa gate at
2412    /// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
2413    /// per-member duplicate-gate dedup key at
2414    /// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
2415    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
2416    /// `adj.entry(m.caixa.as_str()).or_default()`, and the
2417    /// [`validate_no_self_membership`] self-loop gate at
2418    /// `m.caixa == parent_nome`) — five open-coded field-accesses that
2419    /// expressed no compile-time link back to the typed slot. Every
2420    /// caixa-mesh `metadata.name` derived from a `:membros :caixa`
2421    /// value flows through the [`caixa_mesh::fleet_programs`] per-entry
2422    /// `name:` axis, so a future extension of the `:membros :caixa`
2423    /// axis to a richer author surface — a per-cluster alias table the
2424    /// operator pins through a future `:placement`-scoped slot, a
2425    /// namespace-qualified rewrite the M4 CR materializer applies
2426    /// per-CR, a per-member overlay from the future `:membros
2427    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
2428    /// acknowledges — would have had to be threaded through every
2429    /// open-coded copy in lockstep or one consumer would silently
2430    /// disagree with the peers on which caixa a given member resolves
2431    /// to. A member-set lookup that treated the name as `"cart"` while
2432    /// the peer adjacency map treated it as `"tenant-a/cart"` would
2433    /// silently split the `:contratos` membership-lookup diagnostic from
2434    /// the cycle-detector's node identity — a two-consumer split at the
2435    /// validator far from the source `caixa.lisp` with no field naming
2436    /// the identity-drift root cause. Lifting the resolution rule to a
2437    /// typed method on the substrate primitive means every downstream
2438    /// consumer of the Aplicacao's per-`:membros` identity surface
2439    /// reaches for exactly one typed dispatch — the resolver's
2440    /// accept-set migrates as a unit on any future axis addition.
2441    ///
2442    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2443    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2444    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2445    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2446    /// destination-Servico scalar accessors — same "one typed dispatch
2447    /// on the substrate primitive, thin projections at each consumer"
2448    /// discipline extended onto the per-`:membros` member-caixa `:nome`
2449    /// byte-string axis. Named `nome()` to match the tatara-lisp
2450    /// author-surface term the field's docstring already reaches for
2451    /// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
2452    /// [`crate::dep::Dep::nome`] field-name discipline the substrate
2453    /// already carries — the accessor's name maps directly onto the
2454    /// canonical caixa-identity vocabulary rather than shadowing the
2455    /// field's storage-side `caixa` label.
2456    #[must_use]
2457    pub const fn nome(&self) -> &str {
2458        self.caixa.as_str()
2459    }
2460
2461    /// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
2462    /// requirement scalar accessor every consumer that reads the
2463    /// member's version pin keys off — returns the author-declared
2464    /// `:membros :versao` byte-string verbatim as a `&str`, borrowed
2465    /// from the typed slot's own [`String`] storage.
2466    ///
2467    /// The `:membros :versao` slot carries the Cargo-shaped semver
2468    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
2469    /// pins which release of the member-caixa the Aplicacao composes
2470    /// against — the same requirement grammar the peer `:deps :versao`
2471    /// / `:children :versao` axes carry, resolved through the shared
2472    /// [`crate::render::require_valid_versao_requirement`] cascade and
2473    /// the shared [`crate::version::parse_requirement`] parser. Every
2474    /// downstream consumer that fans on the member's version pin keys
2475    /// off this scalar (the [`validate_membros`] per-member requirement
2476    /// gate at `require_valid_versao_requirement(m.versao_requirement(),
2477    /// …)`, the [`feira app graph`] per-member `println!("    - {} {}",
2478    /// m.nome(), m.versao_requirement())` line, every future per-cluster
2479    /// version-lock overlay the operator pins through a future
2480    /// `:placement`-scoped slot, the future
2481    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
2482    /// version resolver, the future `feira app deploy` pipeline's
2483    /// per-member lacre BLAKE3-closure lookup).
2484    ///
2485    /// Prior to this lift the `.versao` byte-string was accessed inline
2486    /// at two `&str`-shaped sites — the [`validate_membros`]
2487    /// requirement-gate call `require_valid_versao_requirement(&m.versao,
2488    /// …)` and the `feira app graph` per-member printer's `println!(
2489    /// "    - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
2490    /// prior to this lift) — two open-coded field-accesses that expressed
2491    /// no compile-time link back to the typed slot. A future extension of
2492    /// the `:membros :versao` axis to a richer author surface (a
2493    /// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2494    /// flow, a lacre-projected concrete-version rewrite the operator
2495    /// materializes at CR-admission time, a future `:membros :versao-lock`
2496    /// per-cluster override slot) would have had to be threaded through
2497    /// every open-coded copy in lockstep or one consumer would silently
2498    /// disagree with the peers on which release constraint a given
2499    /// member resolves to. Lifting the resolution rule to a typed method
2500    /// on the substrate primitive means every downstream requirement-
2501    /// facing consumer reaches for exactly one typed dispatch — the
2502    /// resolver's accept-set migrates as a unit on any future axis
2503    /// addition.
2504    ///
2505    /// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
2506    /// member-caixa `:nome` scalar accessor — the pair
2507    /// `(nome(), versao_requirement())` jointly projects the
2508    /// `(caixa, versao)` field pair every renderer that fans on
2509    /// per-member identity + version pin keys off, closing the last
2510    /// unlifted per-`:membros` scalar axis so every downstream
2511    /// per-`:membros` reader now routes through a typed dispatch on the
2512    /// substrate primitive. Named `versao_requirement()` rather than
2513    /// `versao()` because the field's storage-side `.versao` label is
2514    /// already the author-surface term (`:versao`); the accessor's name
2515    /// carries the semantic role — the semver *requirement* string the
2516    /// shared [`crate::version::parse_requirement`] entry-point consumes
2517    /// — so a raw field access and a typed dispatch read differently at
2518    /// every consumer site.
2519    ///
2520    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2521    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2522    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2523    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2524    /// destination-Servico scalar accessors — same "one typed dispatch
2525    /// on the substrate primitive, thin projections at each consumer"
2526    /// discipline extended onto the per-`:membros` member-`:versao`
2527    /// semver-requirement byte-string axis.
2528    #[must_use]
2529    pub const fn versao_requirement(&self) -> &str {
2530        self.versao.as_str()
2531    }
2532}
2533
2534// ── mesh-level policies ──────────────────────────────────────────────
2535
2536/// Mesh policies that apply to every `:contratos` edge unless
2537/// overridden per-edge in M4. V0 is a single global policy block.
2538#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
2539#[serde(rename_all = "camelCase")]
2540pub struct MeshPolicy {
2541    /// Per-call timeout. Authored as a duration string (`"30s"`).
2542    #[serde(
2543        default,
2544        skip_serializing_if = "Option::is_none",
2545        with = "supervisor::duration_codec"
2546    )]
2547    pub timeout: Option<Duration>,
2548
2549    /// Number of retries on transient failure. None = no retries.
2550    #[serde(default, skip_serializing_if = "Option::is_none")]
2551    pub retries: Option<u32>,
2552
2553    /// Circuit breaker config. Trips after N failures within W
2554    /// duration; closes after a cooldown.
2555    #[serde(default, skip_serializing_if = "Option::is_none")]
2556    pub circuit_breaker: Option<CircuitBreaker>,
2557
2558    /// Whether mTLS is required for every contrato. Default: true
2559    /// (sandboxing-by-default; explicit opt-out only).
2560    #[serde(default, skip_serializing_if = "Option::is_none")]
2561    pub mtls_required: Option<bool>,
2562
2563    /// Token-bucket rate limit. Authored as `"100/s"` or
2564    /// `"5000/m"`; stored as `(rate, window)`.
2565    #[serde(
2566        default,
2567        skip_serializing_if = "Option::is_none",
2568        with = "rate_limit_codec"
2569    )]
2570    pub rate_limit: Option<RateLimit>,
2571}
2572
2573impl MeshPolicy {
2574    /// True when no `:politicas` axis carries a value — every field is
2575    /// `None`. The same emptiness contract every other M2/M3 typed
2576    /// surface carries ([`crate::LimitsSpec::is_empty`],
2577    /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
2578    /// typed slot onto a cluster artifact key off this predicate to
2579    /// decide "emit the slot" vs "skip the slot entirely", so an
2580    /// authored-but-unset `:politicas (())` round-trips to a rendered
2581    /// artifact that's structurally identical to one that omits the
2582    /// slot. Lifted as a typed predicate (rather than per-renderer
2583    /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
2584    /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
2585    /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
2586    /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
2587    /// not a coordinated rewrite of every consumer that's reaching
2588    /// for the emptiness semantic.
2589    #[must_use]
2590    pub const fn is_empty(&self) -> bool {
2591        self.timeout().is_none()
2592            && self.retries().is_none()
2593            && self.circuit_breaker().is_none()
2594            && self.mtls_required().is_none()
2595            && self.rate_limit().is_none()
2596    }
2597
2598    /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
2599    /// per-call-deadline scalar accessor every consumer of the
2600    /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
2601    /// returns the author-declared `:politicas :timeout` typed
2602    /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
2603    /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
2604    /// is `Copy`, so the accessor returns by value; no borrow of
2605    /// `&self` past the call). `None` when the slot is absent (the
2606    /// "cluster default applies — typically the gateway class's
2607    /// implementation-side per-request wall-clock cap" arm caixa-mesh's
2608    /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
2609    /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
2610    /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
2611    /// round-trips to a rendered `HTTPRoute` structurally identical to
2612    /// one that omits the slot).
2613    ///
2614    /// The `:politicas :timeout` slot carries the "no infinite blocking"
2615    /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
2616    /// the typed slot's `Option<Duration>` accept-set (zero-floor
2617    /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
2618    /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
2619    /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
2620    /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
2621    /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
2622    /// Every downstream consumer that reads the per-call cap keys off
2623    /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
2624    /// renderers key off to decide "emit :politicas overlay" vs "skip
2625    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
2626    /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
2627    /// fans the deadline into every rule via
2628    /// [`crate::render::single_field_overlay`], the future M4 per-
2629    /// Aplicacao Gateway API reconciler materialization pass, the
2630    /// future per-`:contratos`-edge timeout-override overlay the
2631    /// MESH-COMPOSITION §III.2 roadmap acknowledges).
2632    ///
2633    /// Prior to this lift the `.timeout` field was accessed inline at
2634    /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
2635    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
2636    /// …)` call — two open-coded field-accesses that expressed no
2637    /// compile-time link back to the typed slot. A future extension of
2638    /// the `:politicas :timeout` axis to a richer author surface — a
2639    /// per-`:contratos`-edge timeout override the operator pins through
2640    /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
2641    /// roadmap acknowledges, a per-cluster timeout-default overlay the
2642    /// M4 CR materializer resolves per-CR, a split of the single
2643    /// per-call `Duration` into a richer `{request, backendRequest}`
2644    /// pair once the Gateway API's per-rule `timeouts` block grows the
2645    /// upstream-facing backendRequest arm alongside the client-facing
2646    /// request arm — would have had to be threaded through both open-
2647    /// coded copies in lockstep or the emptiness predicate and the
2648    /// caixa-mesh emit path would silently disagree on which per-call
2649    /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
2650    /// whose only axis is a `Some :timeout` would satisfy `is_empty()
2651    /// == false` while the renderer's overlay-emit path silently read
2652    /// a drifted other value, or vice versa: an author's `:timeout
2653    /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
2654    /// the emptiness predicate still classified the policy as non-
2655    /// empty, and every `kubectl -n tatara-system get httproute -o yaml
2656    /// | grep -A2 timeouts` audit would land on a route whose author's
2657    /// typed slot value silently vanished at the renderer layer).
2658    /// Lifting the resolution to a typed method on the substrate
2659    /// primitive means every downstream consumer of the Aplicacao's
2660    /// per-`:politicas` deadline surface reaches for exactly one typed
2661    /// dispatch — the resolver's accept-set migrates as a unit on any
2662    /// future axis addition.
2663    ///
2664    /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
2665    /// family (sibling of the peer per-`:politicas`
2666    /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
2667    /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
2668    /// `Option<bool>` accessor — same "one typed dispatch on the
2669    /// substrate primitive, thin projections at each consumer"
2670    /// discipline extended onto the peer per-`:politicas` typed-
2671    /// [`Duration`] optional-scalar axis; closes the "optional per-slot
2672    /// numeric-Copy-T scalar" projection pattern the sibling
2673    /// `Option<u32>` / `Option<bool>` lifts opened, since every
2674    /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
2675    /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
2676    /// than a scalar). Named `timeout()` to match the storage field's
2677    /// name; the accessor's identity maps onto the canonical MESH-
2678    /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
2679    #[must_use]
2680    pub const fn timeout(&self) -> Option<Duration> {
2681        self.timeout
2682    }
2683
2684    /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
2685    /// retry-budget scalar accessor every consumer of the Aplicacao's
2686    /// Gateway API v1.x per-rule retry-cap keys off — returns the
2687    /// author-declared `:politicas :retries` typed `u32` verbatim as an
2688    /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
2689    /// storage (`Option<u32>` is `Copy`, so the accessor returns by
2690    /// value; no borrow of `&self` past the call). `None` when the slot
2691    /// is absent (the "cluster default applies — typically 'no retries
2692    /// beyond a single dispatch attempt'" arm the caixa-mesh
2693    /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
2694    /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
2695    /// this predicate too, so an authored-but-unset `:politicas
2696    /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
2697    /// identical to one that omits the slot).
2698    ///
2699    /// The `:politicas :retries` slot carries the "transient failure
2700    /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
2701    /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
2702    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
2703    /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
2704    /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
2705    /// count scalar the caixa-mesh `retry_overlay` builder writes.
2706    /// Every downstream consumer that reads the retry cap keys off this
2707    /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
2708    /// renderers key off to decide "emit :politicas overlay" vs "skip
2709    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
2710    /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
2711    /// the value into every rule via [`crate::render::single_field_overlay`],
2712    /// the future M4 per-Aplicacao Gateway API reconciler
2713    /// materialization pass, the future per-`:contratos`-edge retry-
2714    /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
2715    /// acknowledges).
2716    ///
2717    /// Prior to this lift the `.retries` field was accessed inline at
2718    /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
2719    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
2720    /// …)` call — two open-coded field-accesses that expressed no
2721    /// compile-time link back to the typed slot. A future extension of
2722    /// the `:politicas :retries` axis to a richer author surface — a
2723    /// per-`:contratos`-edge retry override the operator pins through a
2724    /// future `:contratos :retries` slot, a per-cluster retry-default
2725    /// overlay the M4 CR materializer resolves per-CR, a promotion of
2726    /// the plain `u32` attempt-count to a richer `{attempts, codes,
2727    /// backoff}` sub-block once the Gateway API grows the peer
2728    /// `retry.codes` / `retry.backoff` axes — would have had to be
2729    /// threaded through both open-coded copies in lockstep or the
2730    /// emptiness predicate and the caixa-mesh emit path would silently
2731    /// disagree on which retry budget a given [`MeshPolicy`] resolves to
2732    /// (a `:politicas` block whose only axis is a `Some :retries` would
2733    /// satisfy `is_empty() == false` while the renderer's overlay-emit
2734    /// path silently read a drifted other value, or vice versa: an
2735    /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
2736    /// block while the emptiness predicate still classified the policy
2737    /// as non-empty). Lifting the resolution to a typed method on the
2738    /// substrate primitive means every downstream consumer of the
2739    /// Aplicacao's per-`:politicas` retry surface reaches for exactly
2740    /// one typed dispatch — the resolver's accept-set migrates as a
2741    /// unit on any future axis addition.
2742    ///
2743    /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
2744    /// family (sibling of the peer per-`:politicas`
2745    /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
2746    /// same "one typed dispatch on the substrate primitive, thin
2747    /// projections at each consumer" discipline extended onto the
2748    /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
2749    /// the "optional per-slot numeric-Copy-T scalar" projection pattern
2750    /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
2751    /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
2752    /// fold on). Named `retries()` to match the storage field's name;
2753    /// the accessor's identity maps onto the canonical MESH-COMPOSITION
2754    /// §III.2 vocabulary the slot's docstring already carries.
2755    #[must_use]
2756    pub const fn retries(&self) -> Option<u32> {
2757        self.retries
2758    }
2759
2760    /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
2761    /// enforcement-toggle scalar accessor every consumer of the
2762    /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
2763    /// — returns the author-declared `:politicas :mtls-required` typed
2764    /// bool verbatim as an `Option<bool>`, copied out of the typed
2765    /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
2766    /// the accessor returns by value; no borrow of `&self` past the
2767    /// call). `None` when the slot is absent (the "cluster default
2768    /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
2769    /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
2770    /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
2771    /// this predicate too, so an authored-but-unset `:politicas
2772    /// (:mtls-required ())` round-trips to a rendered
2773    /// `CiliumNetworkPolicy` structurally identical to one that omits
2774    /// the slot).
2775    ///
2776    /// The `:politicas :mtls-required` slot carries the "explicit opt-
2777    /// out only, sandboxing-by-default" mTLS-enforcement toggle
2778    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
2779    /// `{None, Some(true), Some(false)}` accept-set maps onto the
2780    /// Cilium `authentication.mode` bijection through
2781    /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
2782    /// handshake enforced), `Some(false) → "disabled"` (handshake
2783    /// skipped — the debug-edge opt-out), `None` → omit the block
2784    /// (cluster default applies). Every downstream consumer that
2785    /// reads the toggle keys off this scalar (the
2786    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2787    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2788    /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
2789    /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
2790    /// ingress rule via [`crate::render::single_field_overlay`], the
2791    /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
2792    /// materialization pass, the future per-`:contratos`-edge mTLS
2793    /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2794    ///
2795    /// Prior to this lift the `.mtls_required` field was accessed
2796    /// inline at two sites — [`MeshPolicy::is_empty`]'s
2797    /// `self.mtls_required.is_none()` arm and caixa-mesh's
2798    /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
2799    /// two open-coded field-accesses that expressed no compile-time
2800    /// link back to the typed slot. A future extension of the
2801    /// `:politicas :mtls-required` axis to a richer author surface —
2802    /// a per-`:contratos`-edge mTLS override the operator pins through
2803    /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
2804    /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
2805    /// M4 CR materializer resolves per-CR, a three-valued
2806    /// `{None, Some(true), Some(false), Some(Optional)}` promotion
2807    /// once Cilium's `authentication.mode` grows an `"optional"` arm —
2808    /// would have had to be threaded through both open-coded copies in
2809    /// lockstep or the emptiness predicate and the caixa-mesh emit
2810    /// path would silently disagree on which toggle a given
2811    /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
2812    /// axis is a `Some`
2813    /// `:mtls-required` would satisfy `is_empty() == false` while the
2814    /// renderer's overlay-emit path silently read a drifted other
2815    /// value, or vice versa). Lifting the resolution to a typed method
2816    /// on the substrate primitive means every downstream consumer of
2817    /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
2818    /// for exactly one typed dispatch — the resolver's accept-set
2819    /// migrates as a unit on any future axis addition.
2820    ///
2821    /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
2822    /// family (peer of the sibling per-`:placement`
2823    /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
2824    /// same "one typed dispatch on the substrate primitive, thin
2825    /// projections at each consumer" discipline extended onto the
2826    /// peer per-`:politicas` typed-bool optional-scalar axis; opens
2827    /// the "optional per-slot Copy-T scalar" projection pattern the
2828    /// sibling per-`:politicas` `:retries` (Option<u32>) /
2829    /// `:timeout` (Option<Duration>) future lifts fold on). Named
2830    /// `mtls_required()` to match the storage field's name; the
2831    /// accessor's identity maps onto the canonical MESH-COMPOSITION
2832    /// §III.2 vocabulary the slot's docstring already carries.
2833    #[must_use]
2834    pub const fn mtls_required(&self) -> Option<bool> {
2835        self.mtls_required
2836    }
2837
2838    /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
2839    /// `local_rate_limit`-mesh token-bucket-declaration scalar
2840    /// accessor every consumer of the Aplicacao's per-`:politicas`
2841    /// per-`(rate, window)` rate-limit surface keys off — returns the
2842    /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
2843    /// verbatim as an `Option<RateLimit>`, copied out of the typed
2844    /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
2845    /// `Copy`, so the accessor returns by value; no borrow of `&self`
2846    /// past the call). `None` when the slot is absent (the "cluster
2847    /// default applies — typically 'no per-Aplicacao rate declaration,
2848    /// gateway-class per-listener default applies'" arm the future
2849    /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
2850    /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
2851    /// `rate_limit().is_none()` arm reads this predicate too, so an
2852    /// authored-but-unset `:politicas (:rate-limit ())` round-trips
2853    /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
2854    /// identical to one that omits the slot).
2855    ///
2856    /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
2857    /// token-bucket rate declaration" contract (MESH-COMPOSITION
2858    /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
2859    /// (rate lower-bounded by 1 through
2860    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
2861    /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
2862    /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
2863    /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
2864    /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
2865    /// bijection the future `CiliumClusterwideEnvoyConfig` per-
2866    /// `:politicas` overlay emits. Every downstream consumer that
2867    /// reads the rate declaration keys off this scalar (the
2868    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2869    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2870    /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
2871    /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
2872    /// `rl.window` against [`is_canonical_rate_limit_window`], the
2873    /// future M4 per-Aplicacao Envoy reconciler materialization pass,
2874    /// the future per-`:contratos`-edge rate-limit override the
2875    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2876    ///
2877    /// Prior to this lift the `.rate_limit` field was accessed inline
2878    /// at two sites — [`MeshPolicy::is_empty`]'s
2879    /// `self.rate_limit.is_none()` arm and the `validate_politicas`
2880    /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
2881    /// field-accesses that expressed no compile-time link back to the
2882    /// typed slot. A future extension of the `:politicas :rate-limit`
2883    /// axis to a richer author surface — a per-`:contratos`-edge
2884    /// rate-limit override the operator pins through a future
2885    /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
2886    /// roadmap acknowledges, a per-cluster rate-limit-default overlay
2887    /// the M4 CR materializer resolves per-CR, a promotion of the
2888    /// plain `(rate, window)` scalar pair to a richer
2889    /// `{rate, window, burst, key}` sub-block once Envoy's
2890    /// `local_rate_limit` grows the peer `burst_size` /
2891    /// `descriptor_key` axes — would have had to be threaded through
2892    /// both open-coded copies in lockstep or the emptiness predicate
2893    /// and the validate gate would silently disagree on which rate
2894    /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
2895    /// block whose only axis is a `Some :rate-limit` would satisfy
2896    /// `is_empty() == false` while the validate path silently read a
2897    /// drifted other value, or vice versa: an author's
2898    /// `:rate-limit "100/s"` would omit the value-shape gate while the
2899    /// emptiness predicate still classified the policy as non-empty).
2900    /// Lifting the resolution to a typed method on the substrate
2901    /// primitive means every downstream consumer of the Aplicacao's
2902    /// per-`:politicas` rate-limit surface reaches for exactly one
2903    /// typed dispatch — the resolver's accept-set migrates as a unit
2904    /// on any future axis addition.
2905    ///
2906    /// First `Option<Copy-composite-T>`-return accessor on the M3
2907    /// mesh-slot family — closes the last un-lifted per-`:politicas`
2908    /// scalar-value axis. Peer of the sibling per-`:politicas`
2909    /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
2910    /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
2911    /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
2912    /// "one typed dispatch on the substrate primitive, thin
2913    /// projections at each consumer" discipline extended onto the
2914    /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
2915    /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
2916    /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
2917    /// sub-accessors rather than a top-level accessor because
2918    /// consumers reach for the axes not the aggregate). Named
2919    /// `rate_limit()` to match the storage field's name; the
2920    /// accessor's identity maps onto the canonical MESH-COMPOSITION
2921    /// §III.2 vocabulary the slot's docstring already carries.
2922    #[must_use]
2923    pub const fn rate_limit(&self) -> Option<RateLimit> {
2924        self.rate_limit
2925    }
2926
2927    /// Substrate-canonical per-`:politicas` `:circuit-breaker`
2928    /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
2929    /// declaration scalar accessor every consumer of the Aplicacao's
2930    /// per-`:politicas` breaker declaration keys off — returns the
2931    /// author-declared `:politicas :circuit-breaker` typed
2932    /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
2933    /// copied out of the typed slot's own `Option<CircuitBreaker>`
2934    /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
2935    /// by value; no borrow of `&self` past the call). `None` when the
2936    /// slot is absent (the "cluster default applies — typically 'no
2937    /// per-Aplicacao breaker declaration, gateway-class per-listener
2938    /// default applies'" arm the future caixa-mesh
2939    /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
2940    /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
2941    /// arm reads this predicate too, so an authored-but-unset
2942    /// `:politicas (:circuit-breaker ())` round-trips to a rendered
2943    /// `CiliumClusterwideEnvoyConfig` structurally identical to one
2944    /// that omits the slot).
2945    ///
2946    /// The `:politicas :circuit-breaker` slot carries the
2947    /// "per-Aplicacao consecutive-transient-failure trip declaration"
2948    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2949    /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
2950    /// zero-floor rejected through
2951    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2952    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
2953    /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
2954    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
2955    /// canonical-form pinned through
2956    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
2957    /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
2958    /// bijection the future `CiliumClusterwideEnvoyConfig`
2959    /// per-`:politicas` overlay emits. Every downstream consumer that
2960    /// reads the breaker declaration keys off this scalar (the
2961    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2962    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2963    /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
2964    /// that brackets `cb.max_failures()` against
2965    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
2966    /// [`POLICY_BREAKER_WINDOW_MAX`] via
2967    /// [`crate::render::require_positive_canonical_bounded_duration`],
2968    /// the future M4 per-Aplicacao Envoy reconciler materialization
2969    /// pass, the future per-`:contratos`-edge breaker override the
2970    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2971    ///
2972    /// Prior to this lift the `.circuit_breaker` field was accessed
2973    /// inline at two sites — [`MeshPolicy::is_empty`]'s
2974    /// `self.circuit_breaker.is_none()` arm and the
2975    /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
2976    /// bind — two open-coded field-accesses that expressed no
2977    /// compile-time link back to the typed slot. A future extension of
2978    /// the `:politicas :circuit-breaker` axis to a richer author
2979    /// surface — a per-`:contratos`-edge breaker override the operator
2980    /// pins through a future `:contratos :circuit-breaker` slot the
2981    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
2982    /// breaker-default overlay the M4 CR materializer resolves per-CR,
2983    /// a promotion of the plain `(max_failures, window)` scalar pair to
2984    /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
2985    /// sub-block once Envoy's `outlier_detection` grows the peer
2986    /// ejection-percentage / ejection-time axes — would have had to be
2987    /// threaded through both open-coded copies in lockstep or the
2988    /// emptiness predicate and the validate gate would silently
2989    /// disagree on which breaker declaration a given [`MeshPolicy`]
2990    /// resolves to (a `:politicas` block whose only axis is a
2991    /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
2992    /// the validate path silently read a drifted other value, or vice
2993    /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
2994    /// "60s"))` would omit the value-shape gate while the emptiness
2995    /// predicate still classified the policy as non-empty). Lifting
2996    /// the resolution to a typed method on the substrate primitive
2997    /// means every downstream consumer of the Aplicacao's
2998    /// per-`:politicas` breaker surface reaches for exactly one typed
2999    /// dispatch — the resolver's accept-set migrates as a unit on any
3000    /// future axis addition.
3001    ///
3002    /// Second `Option<Copy-composite-T>`-return accessor on the M3
3003    /// mesh-slot family (sibling of the peer per-`:politicas`
3004    /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
3005    /// on the same composite-Copy shape, and of the sibling per-
3006    /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
3007    /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
3008    /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
3009    /// `Option<bool>` accessors on the sibling primitive-Copy axes —
3010    /// same "one typed dispatch on the substrate primitive, thin
3011    /// projections at each consumer" discipline extended onto the last
3012    /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
3013    /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
3014    /// match the storage field's name; the accessor's identity maps
3015    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3016    /// docstring already carries. Closes the last unlifted
3017    /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
3018    /// reader now routes through a typed dispatch on the substrate
3019    /// primitive.
3020    #[must_use]
3021    pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
3022        self.circuit_breaker
3023    }
3024}
3025
3026#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
3027#[serde(rename_all = "camelCase")]
3028pub struct CircuitBreaker {
3029    pub max_failures: u32,
3030    #[serde(with = "supervisor::duration_codec_required")]
3031    pub window: Duration,
3032}
3033
3034impl CircuitBreaker {
3035    /// Substrate-canonical per-`:politicas :circuit-breaker`
3036    /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
3037    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3038    /// breaker trip-count keys off — returns the author-declared
3039    /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
3040    /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
3041    /// so the accessor returns by value; no borrow of `&self` past the
3042    /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
3043    /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
3044    /// axis; a `CircuitBreaker` past pattern-match is definitionally
3045    /// present, and its `:max-failures` field carries the trip count as a
3046    /// required-axis scalar).
3047    ///
3048    /// The `:politicas :circuit-breaker :max-failures` axis carries the
3049    /// "consecutive-transient-failure trip threshold" contract
3050    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
3051    /// (zero-floor rejected through
3052    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
3053    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
3054    /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
3055    /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
3056    /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
3057    /// Every downstream consumer that reads the trip threshold keys off
3058    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3059    /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
3060    /// canonical `require_positive_bounded_u32` helper, the future M4
3061    /// per-Aplicacao Envoy config reconciler materialization pass, the
3062    /// future per-`:contratos`-edge breaker-override overlay the
3063    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3064    ///
3065    /// Prior to this lift the `.max_failures` field was accessed inline
3066    /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
3067    /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
3068    /// open-coded field-access that expressed no compile-time link back
3069    /// to the typed sub-struct axis. A future extension of the
3070    /// `:max-failures` axis to a richer author surface — a
3071    /// per-`:contratos`-edge breaker override the operator pins through a
3072    /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
3073    /// #3 roadmap acknowledges, a per-cluster max-failures-default
3074    /// overlay the M4 CR materializer resolves per-CR, a promotion of the
3075    /// plain `u32` trip count to a richer
3076    /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
3077    /// tuple once Envoy's `outlier_detection` block's peer axes come into
3078    /// scope, a per-Envoy-cluster minimum-request-volume gate before the
3079    /// count arms — would have had to be threaded through every open-
3080    /// coded copy in lockstep or the validate gate and the future M4
3081    /// emit path would silently disagree on which trip threshold a given
3082    /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
3083    /// would satisfy validate while the emit path silently read a drifted
3084    /// other value, or vice versa: a validated typed slot would land at
3085    /// the emit boundary as a no-op breaker whose trip threshold is
3086    /// structurally never reached). Lifting the resolution to a typed
3087    /// method on the substrate primitive means every downstream consumer
3088    /// of the Aplicacao's per-`:politicas :circuit-breaker`
3089    /// trip-threshold surface reaches for exactly one typed dispatch —
3090    /// the resolver's accept-set migrates as a unit on any future axis
3091    /// addition.
3092    ///
3093    /// First sub-struct scalar accessor on the M3 mesh-slot family
3094    /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
3095    /// scalar" projection pattern the sibling `CircuitBreaker::window` /
3096    /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
3097    /// closes the last unlifted per-`:politicas` scalar-value axis after
3098    /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
3099    /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
3100    /// Same "one typed dispatch on the substrate primitive, thin
3101    /// projections at each consumer" discipline the peer
3102    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
3103    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
3104    /// [`Membro::versao_requirement`] (a40b0e3),
3105    /// [`Entrada::destination`] (6db982c) accessors carry on their
3106    /// respective per-mesh-slot-atom scalar-value axes, extended onto the
3107    /// per-sub-struct required-`u32` axis. Named `max_failures()` to
3108    /// match the storage field's name; the accessor's identity maps onto
3109    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3110    /// docstring already carries.
3111    #[must_use]
3112    pub const fn max_failures(&self) -> u32 {
3113        self.max_failures
3114    }
3115
3116    /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
3117    /// Envoy-outlier-detection rolling-observation-interval scalar
3118    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3119    /// breaker rolling-window duration keys off — returns the
3120    /// author-declared `:politicas :circuit-breaker :window` typed
3121    /// `Duration` verbatim, copied out of the typed slot's own
3122    /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
3123    /// by value; no borrow of `&self` past the call). Non-optional (the
3124    /// surrounding `Option<CircuitBreaker>` is the "slot present?"
3125    /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
3126    /// `CircuitBreaker` past pattern-match is definitionally present,
3127    /// and its `:window` field carries the rolling-observation interval
3128    /// as a required-axis scalar).
3129    ///
3130    /// The `:politicas :circuit-breaker :window` axis carries the
3131    /// "consecutive-transient-failure rolling-observation interval"
3132    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
3133    /// `Duration` accept-set (zero-floor rejected through
3134    /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
3135    /// residue rejected through
3136    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
3137    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
3138    /// Envoy `outlier_detection.interval` per-cluster
3139    /// ejection-observation-interval scalar (equivalently the future
3140    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3141    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3142    /// consumer that reads the rolling-observation interval keys off
3143    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3144    /// integer-millisecond canonical-form + cap bracket at
3145    /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
3146    /// [`crate::render::require_positive_canonical_bounded_duration`]
3147    /// helper, the future M4 per-Aplicacao Envoy config reconciler
3148    /// materialization pass, the future per-`:contratos`-edge
3149    /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
3150    /// acknowledges).
3151    ///
3152    /// Prior to this lift the `.window` field was accessed inline at
3153    /// one production site — [`AplicacaoSpec::validate_politicas`]'s
3154    /// `require_positive_canonical_bounded_duration(cb.window, …)`
3155    /// call — one open-coded field-access that expressed no compile-
3156    /// time link back to the typed sub-struct axis. A future extension
3157    /// of the `:window` axis to a richer author surface — a
3158    /// per-`:contratos`-edge window override the operator pins through
3159    /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
3160    /// #3 roadmap acknowledges, a per-cluster window-default overlay
3161    /// the M4 CR materializer resolves per-CR, a promotion of the plain
3162    /// `Duration` observation interval to a richer
3163    /// `{interval, base_ejection_time, max_ejection_percent}` tuple
3164    /// once Envoy's `outlier_detection` block's peer axes come into
3165    /// scope, a per-Envoy-cluster minimum-request-volume gate before
3166    /// the window arms — would have had to be threaded through every
3167    /// open-coded copy in lockstep or the validate gate and the future
3168    /// M4 emit path would silently disagree on which observation
3169    /// interval a given [`CircuitBreaker`] resolves to (an author's
3170    /// `:window "60s"` would satisfy validate while the emit path
3171    /// silently read a drifted other value, or vice versa: a validated
3172    /// typed slot would land at the emit boundary as a breaker whose
3173    /// observation window is structurally so wide that no realistic
3174    /// failure-rate shape can trip it). Lifting the resolution to a
3175    /// typed method on the substrate primitive means every downstream
3176    /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
3177    /// observation-window surface reaches for exactly one typed
3178    /// dispatch — the resolver's accept-set migrates as a unit on any
3179    /// future axis addition.
3180    ///
3181    /// Second sub-struct scalar accessor on the M3 mesh-slot family —
3182    /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
3183    /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
3184    /// required-axis, extended onto the per-sub-struct required-`Duration`
3185    /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
3186    /// axis. Same "one typed dispatch on the substrate primitive, thin
3187    /// projections at each consumer" discipline the peer
3188    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
3189    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
3190    /// [`Membro::versao_requirement`] (a40b0e3),
3191    /// [`Entrada::destination`] (6db982c) accessors carry on their
3192    /// respective per-mesh-slot-atom scalar-value axes, extended onto
3193    /// the per-sub-struct required-`Duration` axis. Named `window()` to
3194    /// match the storage field's name; the accessor's identity maps onto
3195    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3196    /// docstring already carries.
3197    #[must_use]
3198    pub const fn window(&self) -> Duration {
3199        self.window
3200    }
3201}
3202
3203#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3204pub struct RateLimit {
3205    /// Requests per window.
3206    pub rate: u32,
3207    /// Window duration.
3208    pub window: Duration,
3209}
3210
3211impl RateLimit {
3212    /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
3213    /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
3214    /// every consumer of the Aplicacao's per-`:contratos`-edge
3215    /// rate-limit-bucket capacity keys off — returns the author-declared
3216    /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
3217    /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
3218    /// returns by value; no borrow of `&self` past the call). Non-optional
3219    /// (the surrounding `Option<RateLimit>` is the "slot present?"
3220    /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
3221    /// `RateLimit` past pattern-match is definitionally present, and its
3222    /// `:rate` field carries the token-bucket capacity as a required-axis
3223    /// scalar).
3224    ///
3225    /// The `:politicas :rate-limit` `:rate` axis carries the
3226    /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
3227    /// the typed slot's `u32` accept-set (zero-floor rejected through
3228    /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
3229    /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
3230    /// `local_rate_limit.token_bucket.max_tokens` per-cluster
3231    /// token-bucket-capacity scalar (equivalently the future
3232    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3233    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3234    /// consumer that reads the token-bucket capacity keys off this
3235    /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3236    /// cap bracket that gates on the canonical
3237    /// [`crate::render::require_positive_bounded_u32`] helper, the
3238    /// [`rate_limit_codec::render`] `Duration → unit` projection that
3239    /// emits the `<n>/<s|m|h>` author surface, the future M4
3240    /// per-Aplicacao Envoy config reconciler materialization pass, the
3241    /// future per-`:contratos`-edge rate-limit-override overlay the
3242    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3243    ///
3244    /// Prior to this lift the `.rate` field was accessed inline at three
3245    /// production sites — [`AplicacaoSpec::validate_politicas`]'s
3246    /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
3247    /// [`rate_limit_codec::render`] format-arm arms (canonical-window
3248    /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
3249    /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
3250    /// field-accesses that expressed no compile-time link back to the
3251    /// typed sub-struct axis. A future extension of the `:rate` axis
3252    /// to a richer author surface — a per-`:contratos`-edge rate
3253    /// override the operator pins through a future `:contratos :rate`
3254    /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
3255    /// per-cluster rate-default overlay the M4 CR materializer resolves
3256    /// per-CR, a promotion of the plain `u32` token capacity to a
3257    /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
3258    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
3259    /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
3260    /// before the token arms — would have had to be threaded through
3261    /// every open-coded copy in lockstep or the validate gate, the
3262    /// codec's render path, and the future M4 emit path would silently
3263    /// disagree on which token capacity a given [`RateLimit`] resolves
3264    /// to (an author's `:rate-limit "100/s"` would satisfy validate
3265    /// while the render / emit paths silently read a drifted other
3266    /// value, or vice versa: a validated typed slot would land at the
3267    /// emit boundary as a no-op limiter whose token capacity is
3268    /// structurally so high that no realistic per-edge traffic shape
3269    /// can drain it). Lifting the resolution to a typed method on the
3270    /// substrate primitive means every downstream consumer of the
3271    /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
3272    /// reaches for exactly one typed dispatch — the resolver's
3273    /// accept-set migrates as a unit on any future axis addition.
3274    ///
3275    /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
3276    /// in shape to the peer per-`CircuitBreaker`
3277    /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
3278    /// on the peer per-sub-struct required-axis, extended onto the
3279    /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
3280    /// required-axis scalar" projection pattern the sibling
3281    /// [`RateLimit::window`] future lift folds on. Same "one typed
3282    /// dispatch on the substrate primitive, thin projections at each
3283    /// consumer" discipline the peer [`WitContract::source`] /
3284    /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
3285    /// (0804823), [`Membro::nome`] (4a32abf),
3286    /// [`Membro::versao_requirement`] (a40b0e3),
3287    /// [`Entrada::destination`] (6db982c),
3288    /// [`CircuitBreaker::max_failures`] (3a74062),
3289    /// [`CircuitBreaker::window`] (373957f) accessors carry on their
3290    /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
3291    /// to match the storage field's name; the accessor's identity maps
3292    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3293    /// docstring already carries.
3294    #[must_use]
3295    pub const fn rate(&self) -> u32 {
3296        self.rate
3297    }
3298
3299    /// Substrate-canonical per-`:politicas :rate-limit` `:window`
3300    /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
3301    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3302    /// rate-limit-bucket refill period keys off — returns the
3303    /// author-declared `:politicas :rate-limit` typed `Duration`
3304    /// verbatim, copied out of the typed slot's own `Duration` storage
3305    /// (`Duration` is `Copy`, so the accessor returns by value; no
3306    /// borrow of `&self` past the call). Non-optional (the surrounding
3307    /// `Option<RateLimit>` is the "slot present?" projection at the
3308    /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
3309    /// pattern-match is definitionally present, and its `:window`
3310    /// field carries the token-bucket refill period as a required-axis
3311    /// scalar).
3312    ///
3313    /// The `:politicas :rate-limit` `:window` axis carries the
3314    /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
3315    /// — the typed slot's `Duration` accept-set (constrained to the
3316    /// three canonical windows `{1s, 60s, 3600s}` the
3317    /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
3318    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
3319    /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
3320    /// per-cluster token-bucket-refill-period scalar (equivalently the
3321    /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3322    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3323    /// consumer that reads the token-bucket refill period keys off
3324    /// this scalar (the [`AplicacaoSpec::validate_politicas`]
3325    /// canonical-window gate that keys off
3326    /// [`is_canonical_rate_limit_window`], the
3327    /// [`rate_limit_codec::render`] `Duration → unit` projection that
3328    /// emits the `<n>/<s|m|h>` author surface — canonical arm via
3329    /// [`rate_limit_window_unit`] and non-canonical fallback via
3330    /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
3331    /// reconciler materialization pass, the future per-`:contratos`-
3332    /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
3333    /// roadmap acknowledges).
3334    ///
3335    /// Prior to this lift the `.window` field was accessed inline at
3336    /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
3337    /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
3338    /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
3339    /// error-payload construction on refusal, and the two
3340    /// [`rate_limit_codec::render`] arms
3341    /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
3342    /// and non-canonical-window `rl.window.as_secs()` fallback). Three
3343    /// open-coded field-accesses that expressed no compile-time link
3344    /// back to the typed sub-struct axis. A future extension of the
3345    /// `:window` axis to a richer author surface — a per-`:contratos`-
3346    /// edge window override the operator pins through a future
3347    /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
3348    /// acknowledges, a per-cluster window-default overlay the M4 CR
3349    /// materializer resolves per-CR, a promotion of the plain
3350    /// `Duration` refill period to a richer
3351    /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
3352    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
3353    /// axis comes into scope, an addition of a `"d"` day suffix once
3354    /// Envoy's `rate_limit_action` grows daily-bucket support — would
3355    /// have had to be threaded through every open-coded copy in
3356    /// lockstep or the validate gate, the codec's render path, and
3357    /// the future M4 emit path would silently disagree on which
3358    /// refill period a given [`RateLimit`] resolves to (an author's
3359    /// `:rate-limit "100/s"` would satisfy validate while the render
3360    /// / emit paths silently read a drifted other value, or vice
3361    /// versa: a validated typed slot would land at the emit boundary
3362    /// as a limiter whose refill period is structurally so long that
3363    /// no realistic per-edge traffic shape stays inside the token
3364    /// budget). Lifting the resolution to a typed method on the
3365    /// substrate primitive means every downstream consumer of the
3366    /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
3367    /// reaches for exactly one typed dispatch — the resolver's
3368    /// accept-set migrates as a unit on any future axis addition.
3369    ///
3370    /// Second sub-struct scalar accessor on the `RateLimit` axis —
3371    /// sibling in shape to the just-landed [`RateLimit::rate`]
3372    /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
3373    /// required-axis, extended onto the per-sub-struct
3374    /// required-`Duration` axis; closes the last unlifted
3375    /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
3376    /// per-sub-struct accessor coverage is now complete across both
3377    /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
3378    /// the substrate primitive, thin projections at each consumer"
3379    /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
3380    /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
3381    /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
3382    /// (7f0fd43), [`WitContract::world_ref`] (0804823),
3383    /// [`Membro::nome`] (4a32abf),
3384    /// [`Membro::versao_requirement`] (a40b0e3),
3385    /// [`Entrada::destination`] (6db982c) accessors carry on their
3386    /// respective per-mesh-slot-atom scalar-value axes. Named
3387    /// `window()` to match the storage field's name; the accessor's
3388    /// identity maps onto the canonical MESH-COMPOSITION §III.2
3389    /// vocabulary the slot's docstring already carries.
3390    #[must_use]
3391    pub const fn window(&self) -> Duration {
3392        self.window
3393    }
3394
3395    /// Recognize this rate-limit's `:window` as a canonical
3396    /// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
3397    /// exactly matches one of the three closed-set arm-Durations
3398    /// (`1s` / `60s` / `3600s`), `None` when the window carries a
3399    /// non-canonical magnitude the codec's round-trip would break on
3400    /// (sub-second residue, or a second-magnitude outside the set
3401    /// [`RateLimitUnit::ALL`] enumerates).
3402    ///
3403    /// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
3404    /// returns `Some` here — the validate gate's
3405    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
3406    /// rejects every window this accessor returns `None` on. Downstream
3407    /// consumers past validate (the codec's [`rate_limit_codec::render`]
3408    /// path, the future M4 per-Aplicacao Envoy config reconciler's
3409    /// materialization pass, the future per-`:contratos`-edge rate-limit-
3410    /// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
3411    /// acknowledges) that read the typed unit off a validated slot can
3412    /// pattern-match on the returned `Some` without re-checking
3413    /// canonicality at the consumer layer — the typed enum surface is
3414    /// the load-bearing carrier of the canonicality invariant.
3415    ///
3416    /// Preferred over the free [`is_canonical_rate_limit_window`]
3417    /// module-private helper at any call site that has the typed
3418    /// [`RateLimit`] in hand (the codec's `render` arm at
3419    /// [`rate_limit_codec::render`], the validate gate's canonical-form
3420    /// arm in [`AplicacaoSpec::validate_politicas`], any future
3421    /// per-`:contratos` edge-override overlay resolver): those consumers
3422    /// reach for the typed enum without going through the
3423    /// `.window()` scalar-projection layer, and get the enum value
3424    /// directly (which the codec's render arm can then format via
3425    /// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
3426    /// "typed sub-struct scalar accessor, one dispatch on the substrate
3427    /// primitive" discipline the sibling [`RateLimit::rate`] and
3428    /// [`RateLimit::window`] accessors carry on the peer per-sub-struct
3429    /// scalar-value axes, extended onto the per-`RateLimit` typed-unit
3430    /// projection axis (the third scalar accessor on the [`RateLimit`]
3431    /// axis, first typed-enum-return projection).
3432    ///
3433    /// `pub const fn` — the typed-`RateLimit`-projection dispatch onto
3434    /// the canonical [`RateLimitUnit`] arm now carries the same
3435    /// `const`-eval-surface posture the sibling `pub const fn`
3436    /// [`Self::rate`] / [`Self::window`] scalar-projection accessors on
3437    /// this typed sub-struct already carry, composing through the
3438    /// peer-lifted `pub const fn` [`RateLimitUnit::from_window`]
3439    /// reverse-resolver in `const` context. Any downstream substrate-
3440    /// side `const`-context consumer of the typed unit (a module-scope
3441    /// `const _:() = assert!(matches!(rl.canonical_unit(), Some(RateLimitUnit::Second)))`
3442    /// invariant pin on a typed fixture, a future M4 admission-webhook
3443    /// `const fn` per-`:politicas :rate-limit :window` canonical-arm
3444    /// resolver over a typed [`RateLimit`], any future `const fn`
3445    /// per-`:contratos`-edge rate-limit-override overlay resolver over
3446    /// the substrate primitive) now reaches the same typed dispatch on
3447    /// the substrate primitive at const-eval time as at runtime.
3448    ///
3449    /// Pinned load-bearing at the substrate-primitive level by
3450    /// [`tests::rate_limit_canonical_unit_accessor_is_const_fn`] (const-
3451    /// eval-surface pin via `const fn` wrapper).
3452    #[must_use]
3453    pub const fn canonical_unit(&self) -> Option<RateLimitUnit> {
3454        RateLimitUnit::from_window(self.window)
3455    }
3456}
3457
3458/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
3459/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
3460/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
3461///
3462/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
3463/// the `:politicas :rate-limit` unit surface reads from
3464/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
3465/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
3466/// [`is_canonical_rate_limit_window`] predicate the
3467/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
3468/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
3469/// projection) now lives inside this typed enum's `match self` arms — a
3470/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
3471/// `rate_limit_action` grows daily-bucket support) is one new variant
3472/// plus the exhaustiveness arms on the four methods, so every consumer
3473/// picks it up by compile-time construction rather than a runtime
3474/// table-scan miss.
3475///
3476/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
3477/// scanned via `find_map` at every projection call — an untyped runtime
3478/// walk that carried no compile-time link between the parse arm's
3479/// accepted suffixes, the render arm's emitted suffixes, and the
3480/// validate gate's accepted windows. A future rate-limit-unit addition
3481/// that landed one row without threading through the other consumers
3482/// (or a copy-paste flip that collapsed two rows onto one suffix) would
3483/// silently split the accepted-set across the three consumers — the
3484/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
3485/// for a 24h window that parse can't round-trip, the validate gate
3486/// misses one canonical window. Lifting the pairs onto a typed
3487/// closed-set enum with exhaustive `match` arms makes any such
3488/// half-landed extension a caixa-core build error (the compiler enforces
3489/// arm coverage on every method), not a silent per-consumer drift
3490/// surfacing at apply time. Same "closed-set typed-enum discriminator"
3491/// discipline the sibling [`PlacementStrategy`] (cc8f749),
3492/// [`crate::supervisor::RestartStrategy`],
3493/// [`crate::supervisor::RestartPolicy`],
3494/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
3495/// closed-set typed enums carry on their respective closed-set axes —
3496/// extended onto the seventh closed-set typed-enum discriminator axis
3497/// on the caixa typed surface (the `:politicas :rate-limit :window`
3498/// canonical-unit axis).
3499#[derive(
3500    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
3501)]
3502pub enum RateLimitUnit {
3503    /// 1-second window — canonical author-surface suffix `"s"`
3504    /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3505    /// with a 1s magnitude.
3506    Second,
3507    /// 1-minute window — canonical author-surface suffix `"m"`
3508    /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3509    /// with a 60s magnitude.
3510    Minute,
3511    /// 1-hour window — canonical author-surface suffix `"h"`
3512    /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3513    /// with a 3600s magnitude.
3514    Hour,
3515}
3516
3517impl RateLimitUnit {
3518    /// Exhaustive iteration surface for every consumer that reads the
3519    /// full canonical-unit set (the byte-parity witness against the
3520    /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
3521    /// webhook's accepted-suffix listing in its rejection body, any
3522    /// future round-trip fuzz harness). A future variant addition to
3523    /// [`RateLimitUnit`] extends this slice as a single edit and every
3524    /// consumer picks up the new entry by construction — the compiler-
3525    /// checked exhaustiveness on the sibling method `match` arms is the
3526    /// build-time guarantee that no arm forgets to grow.
3527    pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
3528
3529    /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
3530    /// string every `<n>/<unit>` rate-limit shape carries after its
3531    /// `/` separator. The single source of truth the codec's parse and
3532    /// render arms both dispatch on: the parse arm matches an incoming
3533    /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
3534    /// output; the render arm emits the entry's `as_suffix` verbatim
3535    /// after the rate magnitude.
3536    #[must_use]
3537    pub const fn as_suffix(self) -> &'static str {
3538        match self {
3539            Self::Second => "s",
3540            Self::Minute => "m",
3541            Self::Hour => "h",
3542        }
3543    }
3544
3545    /// Canonical `Duration` for this unit — the token-bucket refill
3546    /// period the [`RateLimit::window`] axis carries when the surrounding
3547    /// slot's `:rate-limit` author surface named this unit.
3548    #[must_use]
3549    pub const fn window(self) -> Duration {
3550        Duration::from_secs(match self {
3551            Self::Second => 1,
3552            Self::Minute => 60,
3553            Self::Hour => 3_600,
3554        })
3555    }
3556
3557    /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
3558    /// `None` when `suffix` is outside the closed-set arm-string set
3559    /// [`Self::as_suffix`] emits. The single `str → Self` projection
3560    /// [`rate_limit_codec::parse`] consumes.
3561    #[must_use]
3562    pub fn from_suffix(suffix: &str) -> Option<Self> {
3563        Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
3564    }
3565
3566    /// Recognize a canonical rate-limit `Duration` as one of the three
3567    /// arms, or `None` when `window` carries sub-second residue or a
3568    /// second-magnitude outside the closed-set arm-window set
3569    /// [`Self::window`] emits. The single `Duration → Self` projection
3570    /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
3571    /// both consume.
3572    ///
3573    /// `pub const fn` — the reverse `Duration → Self` projection now
3574    /// carries the same `const`-eval-surface posture the sibling
3575    /// `pub const fn` [`Self::as_suffix`] / [`Self::window`] scalar-
3576    /// projection accessors on this closed-set typed enum already
3577    /// carry, and the paired `pub const fn` [`RateLimit::canonical_unit`]
3578    /// typed-`RateLimit`-projection sibling composes through in `const`
3579    /// context. Routes byte-for-byte through the peer `pub const fn`
3580    /// [`Self::window`] canonical-`Duration` projection so any future
3581    /// arm-magnitude edit on the sibling accessor reaches this reverse
3582    /// resolver by construction — the `s == Self::<Arm>.window().as_secs()`
3583    /// per-arm probes each dispatch through one `pub const fn` on the
3584    /// substrate primitive rather than a hand-authored per-arm second-
3585    /// magnitude literal that would silently drift on any future
3586    /// [`Self::window`] arm-magnitude edit.
3587    ///
3588    /// Prior to the `const` lift the body dispatched through
3589    /// `Self::ALL.iter().copied().find(|u| u.window() == window)` — an
3590    /// iterator-driven linear scan whose iterator methods
3591    /// (`.iter()` / `.copied()` / `.find()`) and `Duration`-side
3592    /// `PartialEq` dispatch each carry non-`const` bounds on stable
3593    /// Rust 1.94, so any downstream substrate-side `const`-context
3594    /// consumer of the reverse resolver (a module-scope
3595    /// `const _:() = assert!(RateLimitUnit::from_window(<canonical>).is_some())`
3596    /// invariant pin on a typed fixture, a future M4
3597    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
3598    /// webhook `const fn` per-`:politicas` canonical-window floor over a
3599    /// typed [`RateLimit`] scalar, any future `const fn`
3600    /// per-`:contratos`-edge rate-limit-override overlay resolver over
3601    /// the substrate primitive that wants to fan on the canonical unit
3602    /// at compile time) surfaced as a downstream E0015 far from the
3603    /// resolver's own declaration. The `pub const fn` posture closes
3604    /// the drift structurally at caixa-core build time.
3605    ///
3606    /// Pinned load-bearing at the substrate-primitive level by
3607    /// [`tests::rate_limit_unit_from_window_accessor_is_const_fn`] (const-
3608    /// eval-surface pin via `const fn` wrapper) and
3609    /// [`tests::rate_limit_unit_from_window_composes_through_window_accessor`]
3610    /// (composition-witness pin against the peer `Self::window` scalar
3611    /// dispatch).
3612    #[must_use]
3613    pub const fn from_window(window: Duration) -> Option<Self> {
3614        if window.subsec_nanos() != 0 {
3615            return None;
3616        }
3617        // Route through the peer `pub const fn` [`Self::window`]
3618        // canonical-`Duration` projection so any future arm-magnitude
3619        // edit on the sibling accessor reaches this reverse resolver by
3620        // construction — the per-arm `secs` comparison keys off
3621        // `Duration::as_secs` (`pub const fn`), not a hand-authored
3622        // per-arm second-magnitude literal that would silently drift.
3623        let secs = window.as_secs();
3624        if secs == Self::Second.window().as_secs() {
3625            Some(Self::Second)
3626        } else if secs == Self::Minute.window().as_secs() {
3627            Some(Self::Minute)
3628        } else if secs == Self::Hour.window().as_secs() {
3629            Some(Self::Hour)
3630        } else {
3631            None
3632        }
3633    }
3634
3635    /// Canonical rate-limit `Duration` for a unit suffix, or `None` when
3636    /// `suffix` is outside the closed-set arm-string set [`Self::as_suffix`]
3637    /// emits. Composes [`Self::from_suffix`] with [`Self::window`] — the
3638    /// single `&str → Duration` projection [`rate_limit_codec::parse`]
3639    /// consumes.
3640    ///
3641    /// The peer `Duration → &'static str` axis folded onto the substrate
3642    /// primitive [`RateLimit::canonical_unit`] typed accessor once both
3643    /// production consumers ([`rate_limit_codec::render`] and
3644    /// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
3645    /// migrated (61421a6): the free helper's `Duration → &str` projection
3646    /// is now the two-step composition
3647    /// `rl.canonical_unit().map(RateLimitUnit::as_suffix)` every consumer
3648    /// reads through the typed accessor. This lift closes the peer
3649    /// `&str → Duration` axis by folding the vestigial module-private
3650    /// `rate_limit_window_from_unit` delegate onto this associated method
3651    /// — the codec's parse arm and every future wire-side consumer of the
3652    /// `&str → Duration` projection (a future admission-webhook that
3653    /// reads a `:rate-limit` shape off a CR spec's `raw string` value
3654    /// before it's promoted to a validated typed slot, a future
3655    /// `feira lint` shape-probe that reads the author-surface bytes
3656    /// verbatim) now reach for exactly one typed dispatch on the
3657    /// substrate primitive.
3658    ///
3659    /// Same "closed-set typed-enum discriminator with canonical
3660    /// projections per axis" discipline the sibling [`Self::as_suffix`]
3661    /// / [`Self::window`] / [`Self::from_suffix`] / [`Self::from_window`]
3662    /// methods carry — this associated method closes the fifth (and last
3663    /// unlifted) projection axis on the arm-table, so the closed-set enum
3664    /// now owns every `str ↔ Duration ↔ Self` typed dispatch every
3665    /// consumer of the `:politicas :rate-limit :window` axis reaches
3666    /// through. A future rate-limit-unit addition (a `"d"` day suffix
3667    /// once Envoy's `rate_limit_action` grows daily-bucket support, a
3668    /// `"ms"` sub-second window once high-throughput per-edge policies
3669    /// come into scope per MESH-COMPOSITION §III.2 #3) is one new
3670    /// variant plus one arm per method — the compiler enforces
3671    /// exhaustiveness on every consumer's `match self` arms and picks
3672    /// the new unit up by construction across all five projections.
3673    #[must_use]
3674    pub fn window_from_suffix(suffix: &str) -> Option<Duration> {
3675        Self::from_suffix(suffix).map(Self::window)
3676    }
3677}
3678
3679/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
3680/// every consumer that formats a canonical rate-limit unit as user-
3681/// facing text (future M4 admission-webhook rejection bodies naming
3682/// the accepted-suffix set, future `feira app graph` per-`:politicas`
3683/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
3684/// codec's parse arm accepts and the render arm emits. Same
3685/// as_str-through-Display convergence discipline the sibling
3686/// [`PlacementStrategy`], [`crate::CaixaKind`],
3687/// [`crate::supervisor::RestartStrategy`], and
3688/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
3689impl std::fmt::Display for RateLimitUnit {
3690    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3691        f.write_str(self.as_suffix())
3692    }
3693}
3694
3695/// Upper-bound ceiling on the `:politicas :timeout` axis — every
3696/// validated [`MeshPolicy::timeout`] past
3697/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
3698/// (inclusive on both ends, integer-millisecond magnitudes by the
3699/// canonical-form gate immediately preceding).
3700///
3701/// The typed field is `Option<Duration>` (the zero-floor arm
3702/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
3703/// `Duration::ZERO`, and the canonical-form arm
3704/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
3705/// sub-millisecond residue), so a programmatic struct literal
3706/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
3707/// 24h) and the equivalent author-surface form
3708/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
3709/// integer-hour magnitude) both round-trip cleanly through serde — a
3710/// structurally unbounded `Duration` ceiling. A `:timeout` value far
3711/// above the documented production-playbook band (Envoy default `15s`,
3712/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
3713/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
3714/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
3715/// at `~3600s`) silently degenerates the mesh-policy contract: the
3716/// per-call deadline is structurally so long that no realistic
3717/// synchronous-`:contratos` traversal can reach it, so the typed slot
3718/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
3719/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
3720/// blocking" degenerates to a nominal-only contract on the
3721/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
3722/// the sibling `:politicas :retries` axis and the
3723/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
3724/// `:politicas :circuit-breaker :max-failures` axis — all three close
3725/// the "structurally unbounded ceiling on a typed `:politicas` axis"
3726/// footgun the prior zero-floor-and-canonical-form-only checks left
3727/// open.
3728///
3729/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
3730/// shared duration codec emits (`"<n>h"` for any integer-hour
3731/// magnitude) — every value in the canonical authoring form's
3732/// `<integer><unit>` grammar at or below this cap renders to a clean
3733/// canonical string. The cap sits an order of magnitude above every
3734/// documented production-playbook recommendation band (Envoy default
3735/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
3736/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
3737/// configured maximum (`proxy_read_timeout` typical max `3600s`),
3738/// below the clearly-pathological "effectively no timeout" floor
3739/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
3740/// want for a long-running synchronous workflow, but a hard wall above
3741/// which the mesh-level deadline is structurally a non-deadline.
3742/// Lifted as a typed `pub const` so the bound has exactly one source
3743/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3744/// materializer's admission webhook and the caixa-mesh-side
3745/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3746/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3747/// other typed upper bound in this crate carries
3748/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3749/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3750/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3751/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3752pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
3753
3754/// Upper-bound ceiling on the `:politicas :retries` axis — every
3755/// validated [`MeshPolicy::retries`] past
3756/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
3757///
3758/// The typed slot is `Option<u32>` (`None` = no retries on transient
3759/// failure; `Some(0)` already rejected by the
3760/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
3761/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
3762/// .. }`) and the equivalent author-surface form
3763/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
3764/// serde / the codec — a structurally unbounded `u32` ceiling. The
3765/// runtime substrate that consumes the value (Envoy's
3766/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
3767/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
3768/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
3769/// admission cap is 10) translates a four-billion-retry policy into a
3770/// thundering-herd amplification vector on transient failure — the
3771/// caller's one request fans out to `retries` server-side calls per
3772/// edge per traversal, multiplying load by `(retries+1)^depth` across
3773/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
3774/// invariant "no infinite blocking" pairs with a no-runaway-amplification
3775/// invariant on the retry axis; both belong at the typed-slot layer.
3776///
3777/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
3778/// upstream mesh-policy schema that documents one) and sits above the
3779/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
3780/// every documented production playbook): a value the author can
3781/// plausibly want, but a hard wall above which the policy is
3782/// structurally a footgun. Lifted as a typed `pub const` so the bound
3783/// has exactly one source of truth — a future axis reaching for the
3784/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3785/// materializer's admission webhook, the caixa-mesh-side
3786/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
3787/// one place. Same shape every other typed upper bound in this crate
3788/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3789/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3790/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
3791/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3792pub const POLICY_RETRIES_MAX: u32 = 10;
3793
3794/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
3795/// axis — every validated [`CircuitBreaker::max_failures`] past
3796/// [`AplicacaoSpec::validate_politicas`] lies in
3797/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
3798///
3799/// The typed field is `u32` (the zero-floor arm
3800/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
3801/// `0` — a breaker that trips on the first call), so a programmatic
3802/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
3803/// and the equivalent author-surface form
3804/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
3805/// cleanly through serde — a structurally unbounded `u32` ceiling. A
3806/// `max_failures` value far above the documented production-playbook
3807/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
3808/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
3809/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
3810/// typical 5–50) silently disables the breaker's protection role:
3811/// the threshold is structurally so high that no realistic
3812/// failures-per-`:window` traffic shape can reach it, so the breaker
3813/// never trips and the typed slot becomes a no-op carried on every
3814/// emitted Envoy / Cilium L7 overlay. Pairs with the
3815/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
3816/// axis — both close the "structurally unbounded `u32` ceiling on a
3817/// typed policy axis" footgun the prior zero-floor-only checks left
3818/// open.
3819///
3820/// The `1000` ceiling sits an order of magnitude above every
3821/// documented upstream production-playbook recommendation band (the
3822/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
3823/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
3824/// the clearly-pathological "effectively no protection"
3825/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
3826/// plausibly want at hyperscale, but a hard wall above which the
3827/// policy is structurally a no-op. Lifted as a typed `pub const` so
3828/// the bound has exactly one source of truth — the future M4
3829/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3830/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3831/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3832/// one place. Same shape every other typed upper bound in this crate
3833/// carries ([`POLICY_RETRIES_MAX`],
3834/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3835/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3836/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3837pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
3838
3839/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
3840/// every validated [`CircuitBreaker::window`] past
3841/// [`AplicacaoSpec::validate_politicas`] lies in
3842/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
3843/// integer-millisecond magnitudes by the canonical-form gate
3844/// immediately preceding).
3845///
3846/// The typed field is `Duration` (the zero-floor arm
3847/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
3848/// `Duration::ZERO`, and the canonical-form arm
3849/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
3850/// sub-millisecond residue), so a programmatic struct literal
3851/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
3852/// and the equivalent author-surface form
3853/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
3854/// integer-hour magnitude) both round-trip cleanly through serde — a
3855/// structurally unbounded `Duration` ceiling. A `:window` value far
3856/// above the documented production-playbook band (Hystrix
3857/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
3858/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
3859/// Istio `outlierDetection.interval` default `10s`, Envoy
3860/// `outlier_detection.interval` default `10s`, AWS App Mesh
3861/// circuit-breaker time-window typical `30s..=300s`) degenerates the
3862/// breaker's role: a rolling-window failure counter whose window is
3863/// hours long is operationally a lifetime counter, the breaker's
3864/// "recent failures" memory is structurally so long that transient
3865/// failures are never forgotten, and the typed slot becomes a no-op
3866/// trigger that trips once and stays tripped for the lifetime of the
3867/// component carried on every emitted Envoy / Cilium L7 overlay.
3868///
3869/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
3870/// shared duration codec emits (`"<n>h"` for any integer-hour
3871/// magnitude) — every value in the canonical authoring form's
3872/// `<integer><unit>` grammar at or below this cap renders to a clean
3873/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
3874/// cap on the first typed-`Duration` `:politicas` axis: the two
3875/// duration-typed `:politicas` axes now share a single uniform top
3876/// edge so the next typed-slot wiring (the future caixa-mesh
3877/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
3878/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
3879/// admission webhook) reaches for either field knowing the value is
3880/// in `1ms..=1h` without re-validating at the renderer layer. The cap
3881/// sits two orders of magnitude above every documented upstream
3882/// production-playbook recommendation band (Hystrix / resilience4j /
3883/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
3884/// and below the clearly-pathological "rolling window degenerates to
3885/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
3886/// author can plausibly want for a very-low-traffic long-tail
3887/// failure-detection window, but a hard wall above which the breaker's
3888/// rolling-window contract is structurally a lifetime-counter contract.
3889/// Lifted as a typed `pub const` so the bound has exactly one source
3890/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3891/// materializer's admission webhook and the caixa-mesh-side
3892/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3893/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3894/// other typed upper bound in this crate carries
3895/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3896/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3897/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3898/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3899/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3900pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
3901
3902/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
3903/// every validated [`RateLimit::rate`] past
3904/// [`AplicacaoSpec::validate_politicas`] lies in
3905/// `1..=POLICY_RATE_LIMIT_MAX`.
3906///
3907/// The typed field is `u32` (the zero-floor arm
3908/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
3909/// zero-rate limit denies every request, the canonical "I forgot
3910/// that 0 means deny-everything" footgun), so a programmatic struct
3911/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
3912/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
3913/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
3914/// round-trip cleanly through serde — a structurally unbounded `u32`
3915/// ceiling. The runtime substrate consuming the value (Envoy's
3916/// `local_rate_limit.token_bucket.max_tokens`, the future
3917/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3918/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
3919/// rate-limit into a no-op rate-limiter: the bucket capacity is
3920/// structurally so high no realistic per-edge traffic shape can
3921/// drain it, the limiter never trips, and the typed slot becomes a
3922/// "rate-limit declared, no enforcement" footgun — the canonical
3923/// declared-but-inert shape every other `:politicas` cap arm
3924/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
3925/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
3926///
3927/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
3928/// above every documented upstream production-playbook recommendation
3929/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
3930/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
3931/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
3932/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
3933/// `limit_req_zone` typical `1..=1_000` RPS) and below the
3934/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
3935/// `u32::MAX`): a value the author can plausibly want at hyperscale
3936/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
3937/// /h-window arm), but a hard wall above which the policy is
3938/// structurally a no-op carried verbatim on every emitted Envoy /
3939/// Cilium L7 overlay. The cap brackets all three canonical windows
3940/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
3941/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
3942/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
3943/// per-endpoint API band). Lifted as a typed `pub const` so the bound
3944/// has exactly one source of truth — the future M4
3945/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3946/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3947/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3948/// one place. Same shape every other typed upper bound in this crate
3949/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3950/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
3951/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3952/// [`crate::LIMITS_WALL_CLOCK_MAX`],
3953/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3954/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3955pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
3956
3957// `:entrada :host` total-length and per-label cap axes route through
3958// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
3959// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
3960// pair of aplicacao-private aliases the previous `validate_entrada_host`
3961// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
3962// = 63`) were structurally the same K8s Gateway API v1 Hostname
3963// admission-schema bounds — the total-length cap on the OpenAPI
3964// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
3965// same regex — that the peer axes at the caixa-core::render level pin,
3966// so hoisting both readers onto the shared lifted constants closes the
3967// third-occurrence duplication threshold structurally: the M4
3968// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
3969// label validator, the future per-`Certificate` SAN emitter, and every
3970// other per-Gateway-API-Hostname landing site reach the same one place
3971// as the `:entrada :host` gate does — no per-axis alias drift surface
3972// between them, by construction.
3973
3974/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
3975/// extractor expression — the upper bound `validate_placement_shard_key`
3976/// enforces on every well-shaped shard-key past validate. The realistic
3977/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
3978/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
3979/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
3980/// `:placement :affinity` / `:placement :clusters` identifier-shaped
3981/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
3982/// in `:shard-key`" footgun at validate time rather than at the future
3983/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
3984const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
3985
3986/// Reject `:membros :caixa` values the K8s apiserver would refuse at
3987/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3988/// that maps the shared parser-shaped reason into the
3989/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
3990/// is self-locating (the offending `caixa:` is named verbatim) and
3991/// the author can grep their caixa.lisp for `:caixa "<name>"` and
3992/// fix it in one edit. Same diagnostic shape as
3993/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
3994/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
3995fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
3996    // Empty is already gated by `MembroCaixaEmpty` at the call site;
3997    // re-checking here keeps the predicate usable from any future
3998    // call site (the M4 CR materializer) without an empty-check
3999    // footgun. The shared
4000    // [`crate::render::require_valid_dns_1123_label`] helper brackets
4001    // the empty-first + shape cascade every peer name axis
4002    // (`:placement :clusters`, `:placement :affinity`, `:contratos
4003    // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
4004    // `:upgrade-from :module`) routes through, so drift between the
4005    // eight axes' accepted DNS-1123-label sets is structurally
4006    // impossible.
4007    crate::render::require_valid_dns_1123_label(
4008        caixa,
4009        || AplicacaoError::MembroCaixaEmpty,
4010        |reason| AplicacaoError::MembroCaixaInvalid {
4011            caixa: caixa.to_string(),
4012            reason,
4013        },
4014    )
4015}
4016
4017/// Reject `:placement :clusters` entries the K8s apiserver would refuse
4018/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
4019/// that maps the shared parser-shaped reason into the
4020/// [`AplicacaoError::PlacementClusterInvalid`] variant.
4021///
4022/// Cluster names land in DNS-1123-label territory across every consumer:
4023/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
4024/// the `lareira-fleet-programs` aggregator applies to scope programs to
4025/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
4026/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
4027/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
4028/// cluster identity the M4 CR materializer round-trips. Each apiserver-
4029/// side schema enforces the DNS-1123 label rule on admission; a
4030/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
4031/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
4032/// mistaken-identity slug) silently passes the prior empty-/duplicate-
4033/// only gate and the failure surfaces as a no-match at filter time —
4034/// the workload doesn't land in the named cluster, with no diagnostic
4035/// naming the offending `:clusters` entry. Lifting the gate to caixa-
4036/// build time mirrors the `:membros :caixa` value-shape trajectory
4037/// (3f9d7a0) on the peer name axis.
4038///
4039/// The diagnostic carries the offending `cluster:` verbatim plus a
4040/// parser-shaped `reason:` naming the specific violation, so the
4041/// author can grep their caixa.lisp for `:clusters` and fix it in
4042/// one edit. Same diagnostic shape as
4043/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
4044fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
4045    // Empty is already gated by `PlacementClusterEmpty` at the call
4046    // site; re-checking here keeps the predicate usable from any
4047    // future call site (the M4 CR materializer's per-cluster validator)
4048    // without an empty-check footgun. Routes through the shared
4049    // [`crate::render::require_valid_dns_1123_label`] gate the peer
4050    // name axes each land on.
4051    crate::render::require_valid_dns_1123_label(
4052        cluster,
4053        || AplicacaoError::PlacementClusterEmpty,
4054        |reason| AplicacaoError::PlacementClusterInvalid {
4055            cluster: cluster.to_string(),
4056            reason,
4057        },
4058    )
4059}
4060
4061/// Reject `:placement :affinity` hints whose shape can never legitimately
4062/// land in any downstream selector or label-keyed routing axis. Thin
4063/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
4064/// shared parser-shaped reason into the
4065/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
4066/// diagnostic is self-locating (the offending `:affinity` is named
4067/// verbatim) and the author can grep their caixa.lisp for
4068/// `:affinity "<hint>"` and fix it in one edit.
4069///
4070/// The `:affinity` slot carries a placement-engine hint — canonical
4071/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
4072/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
4073/// compression overlay and the future M4 placement-engine's per-hint
4074/// routing axis. Each downstream consumer (caixa-mesh's
4075/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
4076/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4077/// `spec.placement.affinity` admission rule, the future M4 per-hint
4078/// node-affinity / pod-affinity rule generator keying off the same
4079/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
4080/// selector) requires the value to be a DNS-1123 label — K8s label
4081/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
4082/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
4083/// admission rule the apiserver enforces.
4084///
4085/// Until this gate landed an `:affinity "DataLocality"` (the canonical
4086/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
4087/// Python-module-name leak), `:affinity "data.locality"` (the
4088/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
4089/// `:affinity "data-locality-"` (boundary-hyphen violation),
4090/// `:affinity "data locality"` (paste-from-doc whitespace),
4091/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
4092/// 64-byte over-cap slug silently passed the empty-only check and the
4093/// failure surfaced as a no-match at the M3 Adaptive compression
4094/// overlay's filter time (`placement.affinity` carried a malformed
4095/// value, no node matched, the workload landed on the default
4096/// heuristic) — the canonical "declared-but-inert" footgun mirroring
4097/// the empty-:affinity / empty-shard-key / zero-:politicas /
4098/// empty-:contratos-target gates already close on every other
4099/// declare-but-no-opinion axis. Lifting the rejection to a build-time
4100/// gate closes the fifth typed slot on the Aplicacao surface to land
4101/// on the canonical DNS-1123 label floor (after the four Servico-name
4102/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
4103/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
4104/// b0e8748).
4105///
4106/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
4107/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
4108/// validated values are guaranteed-accepted by the apiserver without
4109/// re-validation at any downstream renderer or admission layer.
4110fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
4111    // Empty is gated separately at the call site for a self-locating
4112    // diagnostic; re-checking here keeps the predicate usable from any
4113    // future call site (the M4 CR materializer's per-affinity
4114    // validator) without an empty-check footgun. Routes through the
4115    // shared [`crate::render::require_valid_dns_1123_label`] gate the
4116    // peer name axes each land on.
4117    crate::render::require_valid_dns_1123_label(
4118        affinity,
4119        || AplicacaoError::PlacementAffinityEmpty,
4120        |reason| AplicacaoError::PlacementAffinityInvalid {
4121            affinity: affinity.to_string(),
4122            reason,
4123        },
4124    )
4125}
4126
4127/// Reject `:placement :shard-key` extractor expressions whose shape can
4128/// never legitimately drive the future M4 Akka-style cluster-sharding
4129/// reconciler's hash-extractor pass. Maps the per-byte / length checks
4130/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
4131/// diagnostic is self-locating (the offending `:shard-key` value is
4132/// named verbatim alongside the parser-shaped reason) and the author can
4133/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
4134/// edit.
4135///
4136/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
4137/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
4138/// expression naming the message property to hash on. The realistic
4139/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
4140/// property name; `$tenantId` — Akka entity-id placeholder;
4141/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
4142/// `${tenant}` — interpolation-style template) all sit in the printable
4143/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
4144/// multi-line blob landing in `:shard-key`, an embedded space from a
4145/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
4146/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
4147/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
4148/// check and the failure surfaces at the future M4 reconciler's hash
4149/// pass as a runtime extractor-evaluation error far from the source
4150/// `caixa.lisp`, with no field naming which member's `:shard-key`
4151/// carried the offending value.
4152///
4153/// The contract — the printable ASCII single-token intersection-floor
4154/// every Akka-style entity-id extractor implementation admits:
4155///
4156///   - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
4157///     peer DNS-1123-label-shaped `:placement :affinity` /
4158///     `:placement :clusters` identifier axes; realistic shard-keys sit
4159///     well under 32 bytes, the cap surfaces paste-from-doc multi-line
4160///     blob footguns at validate time;
4161///   - every byte in the printable ASCII range `0x21..=0x7E` —
4162///     rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
4163///     `"$tenantId\n"` from paste-from-aligned-doc /
4164///     paste-from-shell-heredoc), control characters (`\x00..\x1F`,
4165///     `\x7F` — the canonical "embedded null from a copy-paste-binary
4166///     footgun"), and non-ASCII bytes (`"$tenàntId"` —
4167///     un-Punycode-encoded IDN that round-trips inconsistently across
4168///     NFC/NFD normalization).
4169///
4170/// The accepted set is broader than the DNS-1123 label floor the peer
4171/// `:placement :clusters` / `:placement :affinity` axes use because the
4172/// `:shard-key` value is not a K8s `metadata.name` / label-selector
4173/// landing site; it's an extractor expression the future Akka-style
4174/// reconciler reads as a property reference. The realistic forms
4175/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
4176/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
4177/// but every Akka-style entity-id extractor parses. The
4178/// printable-ASCII-token floor accepts every shape any such extractor
4179/// would accept while rejecting the cross-implementation footguns
4180/// (whitespace breaks token boundaries; non-ASCII round-trips
4181/// inconsistently across YAML emitters and NFC/NFD normalization;
4182/// control characters silently corrupt the next read).
4183///
4184/// Until this gate landed `validate_placement` only refused the
4185/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
4186/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
4187/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
4188/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
4189/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
4190/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
4191/// control character from paste-from-binary, the 64-byte over-cap
4192/// paste-from-doc multi-line slug) silently passed validate. The future
4193/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
4194/// would then surface the malformed value either as a runtime
4195/// extractor-evaluation error (whitespace breaks the extractor's token
4196/// boundary, no match) or as a silently-different shard assignment
4197/// across YAML emitters (non-ASCII normalizes differently between the
4198/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
4199/// parser, the same entity ID maps to two distinct shards on a
4200/// re-render). Lifting the shape gate to caixa-build time makes the
4201/// extractor-floor invariant a structural property of every validated
4202/// `Placement`: every `Sharded` placement past `validate_placement` has
4203/// a `:shard-key` the future M4 reconciler can hash without
4204/// re-validating at the runtime layer.
4205///
4206/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
4207/// [`AplicacaoError::ContratoSubjectInvalid`] /
4208/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
4209/// on the peer `:contratos` payload axes — each lifts the
4210/// runtime-side parser's intersection-floor to a caixa-build-time gate,
4211/// closing the canonical "this passed validate but the runtime parser
4212/// rejected it" surprise.
4213fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
4214    // Empty is gated separately at the call site via the more
4215    // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
4216    // re-checking here keeps the predicate usable from any future call
4217    // site (the M4 CR materializer's per-shard-key validator) without
4218    // an empty-check footgun.
4219    if key.is_empty() {
4220        return Err(AplicacaoError::ShardedKeyEmpty);
4221    }
4222    if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
4223        return Err(AplicacaoError::ShardKeyInvalid {
4224            shard_key: key.to_string(),
4225            reason: format!(
4226                "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
4227                 (got {} bytes; realistic Akka-style entity-id extractor expressions \
4228                 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
4229                 well under 32 bytes, this length suggests a paste-from-doc \
4230                 multi-line blob landed in `:shard-key` instead of a single-token \
4231                 extractor expression)",
4232                key.len()
4233            ),
4234        });
4235    }
4236    for &b in key.as_bytes() {
4237        if (0x21..=0x7E).contains(&b) {
4238            continue;
4239        }
4240        let reason = if b == b' ' {
4241            "contains a space (Akka-style entity-id extractor expressions are \
4242             single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
4243             whitespace breaks the extractor's token boundary at the runtime layer, \
4244             and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
4245             a multi-token blob in one `:shard-key` slot)"
4246                .to_string()
4247        } else if b == b'\t' {
4248            "contains a tab character (paste-from-aligned-doc footgun; the \
4249             Akka-style entity-id extractor reads `:shard-key` as a single-token \
4250             reference, embedded whitespace breaks the token boundary at the \
4251             runtime hash-extractor pass)"
4252                .to_string()
4253        } else if b == b'\n' || b == b'\r' {
4254            format!(
4255                "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
4256                 paste-from-multiline-doc footgun; the Akka-style entity-id \
4257                 extractor reads `:shard-key` as a single-token reference, embedded \
4258                 newlines either truncate the value at the YAML emitter layer or \
4259                 break the token boundary at the runtime hash-extractor pass)"
4260            )
4261        } else if b < 0x20 || b == 0x7F {
4262            format!(
4263                "contains control character 0x{b:02x} (the canonical \
4264                 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
4265                 control characters silently corrupt round-trip serialization \
4266                 across YAML emitters and break the runtime hash-extractor's \
4267                 single-token parser)"
4268            )
4269        } else {
4270            format!(
4271                "contains non-ASCII byte 0x{b:02x} (the canonical \
4272                 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
4273                 inconsistently across NFC/NFD normalization on APFS / ext4 / \
4274                 across YAML emitter implementations — the same entity ID can \
4275                 silently map to two distinct shards on a re-render. Use a \
4276                 printable-ASCII extractor expression like `tenantId`, \
4277                 `$tenantId`, or `metadata.tenantId`)"
4278            )
4279        };
4280        return Err(AplicacaoError::ShardKeyInvalid {
4281            shard_key: key.to_string(),
4282            reason,
4283        });
4284    }
4285    Ok(())
4286}
4287
4288/// Reject `:contratos :de` / `:contratos :para` values whose shape
4289/// can never legitimately match a validated `:membros :caixa`. Thin
4290/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
4291/// shared parser-shaped reason into the
4292/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
4293/// diagnostic is self-locating (which slot — `:de` or `:para` — and
4294/// the offending value verbatim) and the author can grep their
4295/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
4296/// one edit.
4297///
4298/// Until this gate landed an empty or DNS-1123-malformed `:de` /
4299/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
4300/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
4301/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
4302/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
4303/// un-Punycode-encoded IDN) silently passed the per-axis check and
4304/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
4305/// membership lookup — diagnostic-framed as "this caixa is not in
4306/// `:membros`" when the root cause is "this `:de` value is not a
4307/// well-shaped Servico-name identifier and could never legitimately
4308/// match any validated member". Because every `:membros :caixa` is
4309/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
4310/// `names` HashSet structurally never contains an empty / malformed
4311/// string, so the membership lookup arm misframes every empty /
4312/// malformed input. Lifting the shape arm ahead of the lookup
4313/// preserves the legitimate `ContratoMemberMissing` arm (a
4314/// well-shaped `:de` that simply isn't in `:membros` — a phantom
4315/// reference) while routing every structurally-impossible-to-match
4316/// input through the narrower self-locating shape diagnostic.
4317///
4318/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
4319/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
4320/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
4321/// to land on the canonical [`crate::render::is_dns_1123_label`]
4322/// floor. The `slot: &'static str` field carries the kebab-case
4323/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
4324/// per-callback-slot diagnostic shape and the
4325/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
4326/// (85f102c) cross-list-tag pattern.
4327fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
4328    // Routes through the shared
4329    // [`crate::render::require_valid_dns_1123_label`] gate the peer
4330    // name axes each land on. The `slot: &'static str` field flows
4331    // through both error variants so the diagnostic names which
4332    // per-edge axis (`:de` vs `:para`) the offending value came from.
4333    crate::render::require_valid_dns_1123_label(
4334        caixa,
4335        || AplicacaoError::ContratoCaixaEmpty { slot },
4336        |reason| AplicacaoError::ContratoCaixaInvalid {
4337            slot,
4338            caixa: caixa.to_string(),
4339            reason,
4340        },
4341    )
4342}
4343
4344/// Reject `:entrada :para` values whose shape can never legitimately
4345/// match a validated `:membros :caixa`. Thin wrapper around
4346/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
4347/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
4348/// variant, so the diagnostic is self-locating (the offending
4349/// `:entrada :para` value is named verbatim) and the author can grep
4350/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
4351///
4352/// Until this gate landed an empty or DNS-1123-malformed `:entrada
4353/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
4354/// ADR typo, `:para "my_cart"` the Python-module-name leak,
4355/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
4356/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
4357/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
4358/// silently passed the per-axis check and surfaced as
4359/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
4360/// — diagnostic-framed as "this caixa is not in `:membros`" when the
4361/// root cause is "this `:entrada :para` value is not a well-shaped
4362/// Servico-name identifier and could never legitimately match any
4363/// validated member". Because every `:membros :caixa` is shape-
4364/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
4365/// `HashSet` structurally never contains an empty / malformed string,
4366/// so the membership lookup arm misframes every empty / malformed
4367/// input. Lifting the shape arm ahead of the lookup preserves the
4368/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
4369/// simply isn't in `:membros` — a phantom reference) while routing
4370/// every structurally-impossible-to-match input through the narrower
4371/// self-locating shape diagnostic.
4372///
4373/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
4374/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
4375/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
4376/// fourth and last Aplicacao-level Servico-name reference axis to
4377/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
4378/// No `slot: &'static str` field because there is only one axis
4379/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
4380/// the simpler shape mirrors [`validate_membro_caixa`] and
4381/// [`validate_placement_cluster`].
4382fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
4383    // Empty is gated separately at the call site for a self-locating
4384    // diagnostic; re-checking here keeps the predicate usable from any
4385    // future call site (the M4 CR materializer's per-`:entrada`
4386    // validator) without an empty-check footgun. Routes through the
4387    // shared [`crate::render::require_valid_dns_1123_label`] gate the
4388    // peer name axes each land on.
4389    crate::render::require_valid_dns_1123_label(
4390        para,
4391        || AplicacaoError::EntradaParaEmpty,
4392        |reason| AplicacaoError::EntradaParaInvalid {
4393            para: para.to_string(),
4394            reason,
4395        },
4396    )
4397}
4398
4399/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
4400/// would refuse at admission time. The contract — exactly the regex
4401/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
4402/// and `HTTPRoute.spec.hostnames[]`,
4403/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
4404/// (max length 253; per-label max length 63):
4405///
4406///   - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
4407///     uppercase, no underscore, no Unicode/IDN — IDN must be
4408///     pre-encoded as Punycode `xn--…` by the author);
4409///   - exactly one optional leading wildcard label (`*.`); a wildcard
4410///     in any non-leading label position is rejected;
4411///   - each `.`-separated label is 1..=63 bytes, with non-hyphen
4412///     alphanumeric at both boundaries (no `-foo`, no `foo-`);
4413///   - total length 1..=253 bytes;
4414///   - no IPv4 literal (Gateway API forbids IP literals);
4415///   - no scheme (`https://`, `http://`), no port (`:8080`), no
4416///     whitespace, no path (`/`).
4417///
4418/// Lifted as a typed gate (rather than an inline cascade in
4419/// `validate()`) so the contract lives in one place — every future
4420/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4421/// materializer's host validator, the future per-`:entrada` SAN
4422/// emission for cert-manager Certificates, the multi-`:entrada`
4423/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
4424/// for the same predicate, not its own. Same compounding shape as
4425/// `is_canonical_rate_limit_window` (808017c) and
4426/// [`WitTarget::label`] (previously the free `contrato_target_label`
4427/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
4428/// per-variant label match is compiler-checked-exhaustive).
4429///
4430/// The diagnostic carries the offending `host:` verbatim plus a
4431/// parser-shaped `reason:` naming the specific violation, so the
4432/// author can grep their caixa.lisp for `:host "<host>"` and fix it
4433/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
4434/// (9888b13).
4435fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
4436    // Empty is already gated by `EmptyEntradaHost` at the call site;
4437    // re-checking here keeps the predicate usable from any future
4438    // call site (M4 CR materializer) without an empty-check footgun.
4439    if host.is_empty() {
4440        return Err(AplicacaoError::EmptyEntradaHost);
4441    }
4442    if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
4443        return Err(AplicacaoError::EntradaHostInvalid {
4444            host: host.to_string(),
4445            reason: format!(
4446                "exceeds Gateway API v1 Hostname max length of {cap} bytes \
4447                 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
4448                host.len(),
4449                cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
4450            ),
4451        });
4452    }
4453    if host.contains("://") {
4454        return Err(AplicacaoError::EntradaHostInvalid {
4455            host: host.to_string(),
4456            reason: "must not carry a scheme (drop the `https://` or `http://` prefix; \
4457                     Gateway API takes the bare hostname)"
4458                .to_string(),
4459        });
4460    }
4461    if host.contains('/') {
4462        return Err(AplicacaoError::EntradaHostInvalid {
4463            host: host.to_string(),
4464            reason: "must not carry a path (drop the `/…` suffix; Gateway API path \
4465                     matching is in `:entrada :paths`)"
4466                .to_string(),
4467        });
4468    }
4469    // After the `://` scheme-prefix and `/` path arms have ruled out the
4470    // two `:`-bearing shapes the Gateway API actively rejects with
4471    // location-shaped diagnostics, any remaining `:` in the host body is
4472    // either the canonical "I put the port in the `:host` slot"
4473    // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
4474    // slot lives one axis away on the same `:entrada` block) or an
4475    // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
4476    // Hostname forbids identically to the IPv4-literal arm below. Both
4477    // shapes silently fell through the `://` and `/` arms before this
4478    // lift and surfaced as a deep `label "<rest>:<port>" contains
4479    // invalid character ':'` diagnostic from the per-byte loop near the
4480    // bottom of this predicate, which named the offending byte but not
4481    // the canonical authoring fix — for the port case the author has to
4482    // know the `:entrada` block carries a separate `:port u16` slot
4483    // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
4484    // move the value over; for the IPv6 case the author has to know
4485    // Gateway API v1 forbids IP literals across the board. The contract
4486    // doc-comment above already promises "no port (`:8080`)" verbatim
4487    // in the rejected-shape enumeration but the predicate's
4488    // implementation refused the `:` only as a side-effect of the
4489    // per-label `[a-z0-9-]` character-class loop; this arm brings the
4490    // implementation in line with the documented contract by surfacing
4491    // the canonical fix at the top-level shape gate, peer with how the
4492    // `://` arm names the scheme prefix and the `/` arm names the
4493    // `:entrada :paths` axis. Same compounding trajectory the recent
4494    // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
4495    // — the typed slot's rejected set matches the apiserver's rejected
4496    // set, structurally, with a self-locating diagnostic at the
4497    // offending axis instead of a deep parser-shape leak.
4498    if host.contains(':') {
4499        return Err(AplicacaoError::EntradaHostInvalid {
4500            host: host.to_string(),
4501            reason: "must not contain `:` (the port belongs in the `:entrada :port` \
4502                     slot — a separate `u16` axis on the same `:entrada` block, \
4503                     defaulting to 8080 — not in the host body; drop the `:<port>` \
4504                     suffix and author the bare hostname. If you intended an IPv6 \
4505                     literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
4506                     Hostname forbids IP literals identically to the IPv4-literal \
4507                     arm — use a DNS name)"
4508                .to_string(),
4509        });
4510    }
4511    // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
4512    // predicate — the same single source of truth every peer
4513    // ASCII-whitespace scan in caixa-core flows through: the four
4514    // typed-magnitude codec sites (`limits::parse_byte_size` backing
4515    // `:limits :memory`, `limits::parse_duration` backing `:limits
4516    // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
4517    // `aplicacao::rate_limit_codec::parse` backing `:politicas
4518    // :rate-limit`) and the shared duration codec
4519    // (`supervisor::duration_codec::parse`) backing `:supervisor
4520    // :restart-window` / `:politicas :timeout` / `:politicas
4521    // :circuit-breaker :window`. This landing closes the last string-typed
4522    // slot in caixa-core still calling `.bytes().any(|b|
4523    // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
4524    // across every typed slot now shares one predicate, so a future
4525    // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
4526    // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
4527    // deliberately excluded from the peer non-ASCII predicate) can
4528    // extend at this shared site in one edit rather than seven
4529    // independent scans diverging over time. Naming the offending byte
4530    // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
4531    // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
4532    // the offending byte verbatim" discipline every peer codec site
4533    // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
4534    // / `supervisor.rs:823` / `aplicacao.rs:1640`).
4535    if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
4536        return Err(AplicacaoError::EntradaHostInvalid {
4537            host: host.to_string(),
4538            reason: format!(
4539                "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
4540                 Hostname is a single-token DNS name — leading, trailing, \
4541                 or embedded whitespace breaks the K8s apiserver's Hostname \
4542                 regex at admission time; the paste-from-aligned-doc / \
4543                 paste-from-shell-history / paste-from-CSV footgun silently \
4544                 lands a multi-token blob in `:entrada :host`. Strip every \
4545                 whitespace byte and author the bare hostname — space \
4546                 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
4547                 refuse identically)"
4548            ),
4549        });
4550    }
4551    // Peer of the ASCII-whitespace scan above: route the non-ASCII
4552    // subset of Unicode `White_Space` through the shared
4553    // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
4554    // single source of truth every peer non-ASCII-whitespace scan in
4555    // caixa-core flows through: `limits::parse_byte_size` (`:limits
4556    // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
4557    // `limits::parse_millicores` (`:limits :cpu`),
4558    // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
4559    // and `supervisor::duration_codec::parse` (`:supervisor
4560    // :restart-window` / `:politicas :timeout` / `:politicas
4561    // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
4562    // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
4563    // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
4564    // paste-from-web-doc), or an EM-SPACE-split host
4565    // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
4566    // survived this predicate's ASCII byte-scan (none of the UTF-8
4567    // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
4568    // `u8::is_ascii_whitespace`), then landed on the per-label
4569    // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
4570    // predicate with the generic `label "…" must start and end with an
4571    // alphanumeric` diagnostic — a "far from source at build-time"
4572    // leak that names the label-shape violation but not the
4573    // paste-from-typography origin the author actually needs to fix.
4574    // Peer with the four codec sites the 1b75b38 landing pinned: the
4575    // typed slot's diagnostic axis names the offending codepoint
4576    // (`U+XXXX`) verbatim rather than laundering the value through a
4577    // downstream label-shape arm, so the author can grep their
4578    // caixa.lisp for the invisible codepoint at the surfaced position
4579    // rather than eyeball a multi-byte host for embedded NBSP / LINE
4580    // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
4581    // discipline the peer ASCII-whitespace arm (720ac3b) carries:
4582    // drift between any two typed-slot sites' non-ASCII-whitespace
4583    // rejection set becomes a single-edit fix at the shared predicate
4584    // rather than N independent inline scans diverging over time, and
4585    // a future stricter classification (BOM `\u{FEFF}` / ZWSP
4586    // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
4587    // `char::is_whitespace`" class the peer non-ASCII predicate's
4588    // doc-comment names as the follow-up trajectory) extends at the
4589    // shared predicate in one edit rather than seven.
4590    if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
4591        return Err(AplicacaoError::EntradaHostInvalid {
4592            host: host.to_string(),
4593            reason: format!(
4594                "contains non-ASCII Unicode whitespace character {ch:?} \
4595                 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
4596                 single-token DNS name limited to `[a-z0-9-]` labels; \
4597                 the paste-from-typography footgun silently lands an \
4598                 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
4599                 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
4600                 `U+3000`, and every other member of the Unicode \
4601                 `White_Space` property outside the ASCII byte range) \
4602                 in `:entrada :host`, which the K8s apiserver's \
4603                 Hostname regex refuses at admission time far from the \
4604                 caixa.lisp source line. Strip every non-ASCII \
4605                 whitespace character and author the bare hostname \
4606                 with only ASCII bytes (write \"checkout.quero.cloud\" \
4607                 verbatim)",
4608                codepoint = ch as u32,
4609            ),
4610        });
4611    }
4612
4613    // Strip the optional single leading wildcard label *before* the
4614    // trailing-dot check so the bare `"*."` form surfaces the more
4615    // self-locating "wildcard without domain" diagnostic instead of
4616    // the generic "trailing dot" one.
4617    let (had_wildcard, rest) = match host.strip_prefix("*.") {
4618        Some(r) => (true, r),
4619        None => (false, host),
4620    };
4621    if had_wildcard && rest.is_empty() {
4622        return Err(AplicacaoError::EntradaHostInvalid {
4623            host: host.to_string(),
4624            reason: "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)".to_string(),
4625        });
4626    }
4627    if rest.contains('*') {
4628        return Err(AplicacaoError::EntradaHostInvalid {
4629            host: host.to_string(),
4630            reason: "wildcard `*` is allowed only as the first label (`*.example.com`); \
4631                     no inner or trailing `*` labels"
4632                .to_string(),
4633        });
4634    }
4635    if rest.ends_with('.') {
4636        return Err(AplicacaoError::EntradaHostInvalid {
4637            host: host.to_string(),
4638            reason: "must not have a trailing `.` (Gateway API hostnames are not \
4639                     fully-qualified with a root dot; the apiserver regex rejects \
4640                     trailing dots)"
4641                .to_string(),
4642        });
4643    }
4644
4645    // Reject pure IPv4 literals: four dot-separated labels, every
4646    // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
4647    // literals as Hostnames.
4648    let labels: Vec<&str> = rest.split('.').collect();
4649    if labels.len() == 4
4650        && labels
4651            .iter()
4652            .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
4653    {
4654        return Err(AplicacaoError::EntradaHostInvalid {
4655            host: host.to_string(),
4656            reason: "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
4657                     literals; use a DNS name)"
4658                .to_string(),
4659        });
4660    }
4661
4662    // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
4663    // hyphen, with non-hyphen at both boundaries.
4664    for label in &labels {
4665        if label.is_empty() {
4666            return Err(AplicacaoError::EntradaHostInvalid {
4667                host: host.to_string(),
4668                reason: "has an empty label (consecutive `..` or a leading `.`)".to_string(),
4669            });
4670        }
4671        if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
4672            return Err(AplicacaoError::EntradaHostInvalid {
4673                host: host.to_string(),
4674                reason: format!(
4675                    "label {label:?} exceeds DNS-1123 label max length of \
4676                     {cap} bytes (got {} bytes)",
4677                    label.len(),
4678                    cap = crate::render::DNS_1123_LABEL_MAX_LEN,
4679                ),
4680            });
4681        }
4682        let bytes = label.as_bytes();
4683        if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
4684            return Err(AplicacaoError::EntradaHostInvalid {
4685                host: host.to_string(),
4686                reason: format!(
4687                    "label {label:?} must start and end with an alphanumeric \
4688                     (no leading or trailing `-`)"
4689                ),
4690            });
4691        }
4692        for &b in bytes {
4693            let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
4694            if !valid {
4695                let msg = if b.is_ascii_uppercase() {
4696                    format!(
4697                        "label {label:?} contains uppercase character {ch:?} \
4698                         (Gateway API hostnames are lowercase-only; use {lower:?})",
4699                        ch = b as char,
4700                        lower = label.to_ascii_lowercase()
4701                    )
4702                } else if b == b'_' {
4703                    format!(
4704                        "label {label:?} contains `_` (Gateway API hostnames \
4705                         allow only `[a-z0-9-]`; use `-` instead)"
4706                    )
4707                } else {
4708                    format!(
4709                        "label {label:?} contains invalid character {ch:?} \
4710                         (Gateway API hostnames allow only `[a-z0-9-]`)",
4711                        ch = b as char
4712                    )
4713                };
4714                return Err(AplicacaoError::EntradaHostInvalid {
4715                    host: host.to_string(),
4716                    reason: msg,
4717                });
4718            }
4719        }
4720    }
4721    Ok(())
4722}
4723
4724/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
4725/// would refuse at admission time. Thin wrapper around
4726/// [`crate::render::is_gateway_api_http_path`] that maps the shared
4727/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
4728/// variant, preserving the more self-locating
4729/// [`AplicacaoError::EntradaPathEmpty`] /
4730/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
4731/// path fails those narrower invariants first.
4732///
4733/// The contract is the canonical HTTP-path grammar — `1..=
4734/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
4735/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
4736/// whitespace/control/non-ASCII bytes — shared with the
4737/// `:contratos :endpoint` axis through the lifted predicate so drift
4738/// between either landing site and the K8s apiserver-side
4739/// HTTPPathMatch.value OpenAPI schema is a build error visible at
4740/// the predicate, not a per-renderer "this passed validate but failed
4741/// admission" surprise. The diagnostic carries the offending `path:`
4742/// verbatim plus a parser-shaped `reason:` naming the specific
4743/// violation, so the author can grep their caixa.lisp for `:paths`
4744/// and fix it in one edit. Same diagnostic shape as
4745/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
4746/// axis.
4747fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
4748    // Empty and missing-leading-`/` are already gated at the call
4749    // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
4750    // checking here keeps the per-axis narrower diagnostics in force
4751    // when the predicate is reached directly (and `is_gateway_api_http_path`
4752    // itself defends against `bytes[0]`-style indexing on empty
4753    // input).
4754    if path.is_empty() {
4755        return Err(AplicacaoError::EntradaPathEmpty);
4756    }
4757    if !path.starts_with('/') {
4758        return Err(AplicacaoError::EntradaPathNotAbsolute {
4759            path: path.to_string(),
4760        });
4761    }
4762    crate::render::is_gateway_api_http_path(path).map_err(|reason| {
4763        AplicacaoError::EntradaPathInvalid {
4764            path: path.to_string(),
4765            reason,
4766        }
4767    })
4768}
4769
4770mod rate_limit_codec {
4771    // `Duration` is no longer named here — the codec routes through
4772    // the substrate primitive [`super::RateLimitUnit::window_from_suffix`]
4773    // (parse arm, `&str → Duration`) and [`super::RateLimit::canonical_unit`]
4774    // (render arm, `Duration → RateLimitUnit`) typed dispatches that carry
4775    // the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection on the
4776    // closed-set enum's arm-table rather than through vestigial free-helper
4777    // delegates.
4778    use super::{RateLimit, RateLimitUnit};
4779    use serde::{Deserialize, Deserializer, Serializer};
4780
4781    pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
4782        match v {
4783            Some(rl) => s.serialize_str(&render(*rl)),
4784            None => s.serialize_none(),
4785        }
4786    }
4787
4788    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
4789        let opt: Option<String> = Option::deserialize(d)?;
4790        match opt {
4791            None => Ok(None),
4792            Some(s) => parse(&s).map(Some).map_err(serde::de::Error::custom),
4793        }
4794    }
4795
4796    fn parse(s: &str) -> Result<RateLimit, String> {
4797        // Whitespace-rejection arm — peer with the leading-`+`
4798        // (`"+100/s"`) and leading-zero (`"0100/s"`) arms below on the
4799        // same canonical-form render-determinism axis. Until this gate
4800        // landed the parser silently tolerated leading / trailing /
4801        // internal whitespace via the top-level `s.trim()` and the
4802        // per-part `rate_str.trim()` / `unit.trim()` calls, so every
4803        // whitespace-carrying shape (`" 100/s"`, `"100/s "`,
4804        // `"100 /s"`, `"100/ s"`, `"100 / s"`, `"100/s\n"`,
4805        // `"\t100/s"`) parsed to the same `RateLimit { 100, 1s }` and
4806        // serde silently round-tripped to `"100/s"` on the next emit
4807        // (a *different* canonical string) — breaking the THEORY.md
4808        // Part V render-determinism contract on the same
4809        // canonical-form-drift axis the leading-`+` arm below (the
4810        // 4eeae98 predecessor) and the leading-zero arm below (the
4811        // 4f46830 predecessor) already close.
4812        //
4813        // The canonical author shape is `<integer>/<s|m|h>` with no
4814        // whitespace bytes anywhere — every string [`render`] emits
4815        // carries none, so the parser's accepted set must match for
4816        // serialize / deserialize to round-trip losslessly. This gate
4817        // makes the pre-existing `s.trim()` / `rate_str.trim()` /
4818        // `unit.trim()` calls below strict no-ops on the accepted set
4819        // (every byte-position match they would perform is now already
4820        // trimmed away by the accepted set itself), while the arm
4821        // surfaces every rejected whitespace-carrying shape with a
4822        // self-locating diagnostic naming the offending byte and the
4823        // canonical form the author intended, peer with every prior
4824        // canonical-form-drift arm on this codec.
4825        //
4826        // Routed through the lifted
4827        // [`crate::render::find_ascii_whitespace_byte`] predicate — the
4828        // same source of truth the four peer typed-magnitude codec
4829        // sites (`limits::parse_byte_size`, `limits::parse_duration`,
4830        // `limits::parse_millicores`, `supervisor::duration_codec`)
4831        // share. `u8::is_ascii_whitespace()` at the predicate covers
4832        // the five WhatWG-conformant ASCII whitespace bytes (space,
4833        // tab, LF, FF, CR); the "single lifted predicate" discipline
4834        // the peer non-ASCII arm below carries on the strictly-
4835        // complementary Unicode `White_Space` class extends here to
4836        // the ASCII byte set as well.
4837        if let Some(b) = crate::render::find_ascii_whitespace_byte(s) {
4838            return Err(format!(
4839                "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
4840                 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
4841                 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
4842                 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
4843                 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
4844                 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
4845                 on first serialize — breaking the THEORY.md Part V render-determinism \
4846                 contract every typed slot carries. Strip every whitespace byte (write \
4847                 `\"100/s\"` verbatim)"
4848            ));
4849        }
4850        // Non-ASCII Unicode `White_Space` arm — the strictly-
4851        // complementary class the ASCII arm above cannot see.
4852        // `str::trim` at the top of every peer codec uses
4853        // `char::is_whitespace` (Unicode `White_Space`, strictly
4854        // wider than the ASCII byte set), so an NBSP (`\u{00A0}`) /
4855        // LINE SEPARATOR (`\u{2028}`) / EM-SPACE (`\u{2003}`)
4856        // survives the byte-scan (its UTF-8 bytes are not in
4857        // `is_ascii_whitespace`), gets silently stripped by the
4858        // top-level `s.trim()` below, and the value round-trips
4859        // through `render` to a *different* canonical form
4860        // (`\"100/s\"`) on next emit — breaking the THEORY.md Part V
4861        // render-determinism contract every typed slot carries.
4862        // Closed here (`:politicas :rate-limit`) and at the three
4863        // peer codec sites (`limits::parse_byte_size`,
4864        // `limits::parse_duration`, `supervisor::duration_codec`)
4865        // through the shared
4866        // [`crate::render::find_non_ascii_whitespace_char`] predicate
4867        // — the "single lifted predicate across all four codec sites
4868        // in one follow-up run" the 24a8ad4 commit body's `Forward
4869        // compounding` bullet named as the next compounding step.
4870        if let Some(ch) = crate::render::find_non_ascii_whitespace_char(s) {
4871            return Err(format!(
4872                "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
4873                 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
4874                 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
4875                 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
4876                 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
4877                 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
4878                 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
4879                 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
4880                 silently strips it at parse entry, and the value round-trips through \
4881                 `render` to a *different* canonical form (`\"100/s\"`) on first \
4882                 serialize — breaking the THEORY.md Part V render-determinism contract \
4883                 every typed slot carries. Strip every non-ASCII whitespace character \
4884                 (write `\"100/s\"` verbatim with only ASCII bytes)",
4885                cp = ch as u32
4886            ));
4887        }
4888        let s = s.trim();
4889        let (rate_str, unit) = s
4890            .split_once('/')
4891            .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
4892        let rate_trim = rate_str.trim();
4893        // The canonical authoring form for `:politicas :rate-limit` is
4894        // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
4895        // non-negative integer with no decimal point and no leading
4896        // sign, so the parser's accepted set must match for
4897        // serialize/deserialize to round-trip without canonical-form
4898        // drift. Until this gate landed the parser accepted any
4899        // `u32::from_str`-shaped magnitude — and current Rust
4900        // `u32::from_str` permissively accepts a leading `+` (`"+100"`
4901        // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
4902        // serde silently round-tripped to `"100/s"` on the next emit
4903        // (a *different* canonical string) — breaking the THEORY.md
4904        // Part V render-determinism contract on the fifth typed-codec
4905        // surface in caixa-core (peer with the four duration codecs the
4906        // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
4907        // already covered: `supervisor::duration_codec` backing three
4908        // typed-duration slots, `limits::parse_duration` backing
4909        // `:limits :wall-clock`, `limits::parse_byte_size` backing
4910        // `:limits :memory`). The fractional / decimal-shaped sibling
4911        // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
4912        // existing rejection arm, but the diagnostic is value-laundered
4913        // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
4914        // doesn't name the canonical-form remediation or the round-trip
4915        // drift the next emit would produce); this gate lifts the
4916        // fractional arm onto the same canonical-form diagnostic the
4917        // peer codecs carry.
4918        //
4919        // Strict canonical form: every byte of the magnitude is an
4920        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
4921        // inputs the gate distinguishes "non-canonical-but-numeric"
4922        // (parses as f64 or i64 — surfaced with a self-locating
4923        // diagnostic naming the canonical authoring form and the
4924        // round-trip drift the rejected shape would produce on first
4925        // serialize) from "garbage" (parses as neither — surfaced with
4926        // the existing narrower `"not a u32"` wording so its
4927        // diagnostic shape remains stable for the parser-shape footgun
4928        // case).
4929        //
4930        // Routed through the lifted
4931        // [`crate::render::is_digit_only_magnitude`] predicate — the
4932        // same source of truth the four peer typed-magnitude codec
4933        // sites share.
4934        let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
4935        if !digit_only {
4936            let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
4937            if numeric {
4938                return Err(format!(
4939                    "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
4940                     canonical authoring form for `:politicas :rate-limit` is \
4941                     `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4942                     with no decimal point and no leading `+` / `-` sign. A fractional / \
4943                     signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
4944                     through `render` to a *different* canonical form (`\"1/s\"`, \
4945                     `\"100/s\"`, parser-reject) on first serialize — breaking the \
4946                     THEORY.md Part V render-determinism contract every typed slot \
4947                     carries. Pick an integer rate that fits the desired window \
4948                     (write `\"6000/m\"` instead of `\"1.66/s\"`)"
4949                ));
4950            }
4951            return Err(format!("rate-limit rate {rate_str:?} not a u32"));
4952        }
4953        // Leading-zero arm — peer with the prior `"+100/s"` arm above
4954        // (4eeae98's predecessor) on the same canonical-form
4955        // render-determinism axis. The digit-only gate accepts
4956        // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
4957        // them losslessly (= 100, 0, 7), but `render` emits the
4958        // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
4959        // a *different* canonical string on the next emit, breaking
4960        // the THEORY.md Part V render-determinism contract the same
4961        // way `"+100/s"` did before the leading-`+` arm landed. The
4962        // single-byte magnitude `"0"` itself round-trips losslessly
4963        // through `render` (`render(0)` emits `"0/s"`) — the
4964        // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
4965        // what refuses rate-zero authoring, so `"0/s"` stays in the
4966        // accepted set at this codec layer and the diagnostic
4967        // partitioning between canonical-form drift (this arm) and
4968        // semantic-zero (the downstream gate) remains stable.
4969        // Peer with the future leading-zero arms on the three peer
4970        // typed-magnitude codecs the trajectory acknowledges:
4971        // `supervisor::duration_codec`, `limits::parse_duration`,
4972        // `limits::parse_byte_size` — each carries the same
4973        // canonical-form-drift class today; this gate lands the
4974        // discipline on the fourth typed-magnitude codec in
4975        // caixa-core first because the peer `"+100/s"` arm above is
4976        // the closest predecessor on the trajectory.
4977        //
4978        // Routed through the lifted
4979        // [`crate::render::is_leading_zero_padded_magnitude`]
4980        // predicate — the same source of truth the four peer
4981        // typed-magnitude codec sites share.
4982        if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
4983            return Err(format!(
4984                "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
4985                 canonical authoring form for `:politicas :rate-limit` is \
4986                 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4987                 with no leading-zero padding on the magnitude. A leading-zero magnitude \
4988                 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
4989                 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
4990                 first serialize — breaking the THEORY.md Part V render-determinism \
4991                 contract every typed slot carries. Strip the leading zeros (write \
4992                 `\"100/s\"` instead of `\"0100/s\"`)"
4993            ));
4994        }
4995        // The digit-only gate guarantees every byte is `[0-9]`, and
4996        // the leading-zero arm above guarantees the magnitude is
4997        // either the single byte `"0"` or starts with `[1-9]`, so
4998        // the only way `u32::from_str` can fail here is overflow
4999        // (the magnitude exceeds `u32::MAX`). Surface that with an
5000        // overflow-shaped wording so the diagnostic names the
5001        // offending magnitude verbatim rather than collapsing onto
5002        // the non-canonical arm. Same shape
5003        // `supervisor::duration_codec` (1c55a2a) carries on the peer
5004        // duration-codec axis.
5005        let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
5006            format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
5007        })?;
5008        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives on
5009        // the closed-set typed enum [`super::RateLimitUnit`]; this parse
5010        // arm reads the `&str → Duration` projection through the
5011        // substrate primitive [`super::RateLimitUnit::window_from_suffix`]
5012        // (a two-step typed dispatch composing [`super::RateLimitUnit::from_suffix`]
5013        // with [`super::RateLimitUnit::window`]) rather than the vestigial
5014        // module-private `rate_limit_window_from_unit` free helper the
5015        // predecessor 61421a6 left as the last unlifted delegate on this
5016        // axis. One typed dispatch on the substrate primitive instead of
5017        // one runtime call through the free-helper delegate; the sole
5018        // production consumer of the `&str → Duration` axis (this parse
5019        // arm) now reaches for exactly one typed method on the closed-set
5020        // enum, sibling to the codec's render arm's
5021        // [`super::RateLimit::canonical_unit`] dispatch on the paired
5022        // `Duration → RateLimitUnit` axis and to the validate gate's
5023        // [`super::RateLimit::canonical_unit`] shape-probe on the
5024        // canonical-window axis. A future rate-limit-unit addition (a
5025        // `"d"` day suffix once Envoy's `rate_limit_action` grows
5026        // daily-bucket support, a `"ms"` sub-second window once
5027        // high-throughput per-edge policies come into scope per
5028        // MESH-COMPOSITION §III.2 #3) is one variant + one arm per method
5029        // on the closed-set enum, and the compiler enforces exhaustiveness
5030        // on every consumer's `match self` arms — this parse arm's
5031        // accepted-suffix set, the render arm's emitted-suffix set, the
5032        // validate gate's canonical-window set, and every future
5033        // per-`:contratos`-edge rate-limit-override overlay all pick it up
5034        // by construction.
5035        let unit = unit.trim();
5036        let window = RateLimitUnit::window_from_suffix(unit)
5037            .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
5038        Ok(RateLimit { rate, window })
5039    }
5040
5041    fn render(rl: RateLimit) -> String {
5042        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
5043        // module scope on the closed-set typed enum [`super::RateLimitUnit`];
5044        // this render arm reads the `Duration → RateLimitUnit` projection
5045        // through the substrate primitive [`super::RateLimit::canonical_unit`]
5046        // (returns `None` on every non-canonical window — the sub-second /
5047        // non-`{1, 60, 3600}` shapes the validate gate rejects), then
5048        // formats the returned typed enum through its
5049        // [`std::fmt::Display`] impl (which routes through
5050        // [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
5051        // the substrate primitive instead of one runtime `find_map`
5052        // walk through the free-helper delegate chain
5053        // [`super::rate_limit_window_unit`] (the vestigial free helper's
5054        // sole production consumer was this arm; every other consumer of
5055        // the `Duration → unit` axis — the validate gate below and the
5056        // future M4 per-Aplicacao Envoy config reconciler — now reads
5057        // the same typed method).
5058        //
5059        // A future rate-limit-unit addition (a `"d"` day suffix once
5060        // Envoy's `rate_limit_action` grows daily-bucket support) is
5061        // one variant + one arm per method on the closed-set enum, and
5062        // the compiler enforces exhaustiveness on every consumer's
5063        // `match self` arms — the codec's `parse` accepted-suffix set,
5064        // this render arm's emitted-suffix set, the validate gate's
5065        // canonical-window set, and every future per-`:contratos`-edge
5066        // rate-limit-override overlay all pick it up by construction.
5067        if let Some(unit) = rl.canonical_unit() {
5068            format!("{}/{unit}", rl.rate())
5069        } else {
5070            // Defensive fallback for non-canonical windows. Note:
5071            // [`AplicacaoSpec::validate_politicas`] rejects any
5072            // non-canonical `:rate-limit :window` via
5073            // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
5074            // a validated `RateLimit` never reaches this branch. The
5075            // emitted `<n>/<k>s` form is *not* round-trippable through
5076            // [`parse`] (which accepts only the closed-set
5077            // [`super::RateLimitUnit`] suffixes, not `<k>s` with an
5078            // explicit count) — the validate gate is what makes the
5079            // round-trip a structural property; this branch exists only
5080            // so a programmatic non-validated serialize doesn't panic.
5081            format!("{}/{}s", rl.rate(), rl.window().as_secs())
5082        }
5083    }
5084}
5085
5086// ── placement strategy ───────────────────────────────────────────────
5087
5088/// How the Aplicacao distributes across clusters. Three options:
5089///
5090/// - `SingleNode` — one cluster runs the app at a time; takeover on
5091///   death (Erlang/OTP distributed-app semantics).
5092/// - `Replicated` — every named cluster runs an instance (active-active).
5093/// - `Sharded` — entities distribute by hash key across clusters
5094///   (Akka cluster sharding).
5095#[derive(
5096    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
5097)]
5098pub enum PlacementStrategy {
5099    SingleNode,
5100    Replicated,
5101    Sharded,
5102}
5103
5104/// Substrate-canonical M3-mesh-shaped per-`:placement :estrategia`
5105/// distribution-strategy default for the `:placement :estrategia` axis —
5106/// the [`PlacementStrategy::Replicated`] active-active-across-every-named-
5107/// cluster arm (MESH-COMPOSITION §II.2), extracted as a typed `pub const`
5108/// so every substrate-side consumer that resolves "what
5109/// [`PlacementStrategy`] variant does an author-omitted `:placement
5110/// :estrategia` slot degrade onto?" reaches for exactly one substrate-
5111/// primitive [`PlacementStrategy`].
5112///
5113/// The `:placement :estrategia` default axis has three production
5114/// consumers on the substrate side today: the [`Default for
5115/// PlacementStrategy`] impl's return arm, the [`Default for Placement`]
5116/// impl's struct-literal `estrategia` field, and the serde-side
5117/// `#[serde(default)]` on [`Placement::estrategia`] that resolves an
5118/// author-omitted `:placement :estrategia` scalar through the [`Default
5119/// for PlacementStrategy`] impl. Prior to this lift the three folded onto
5120/// a raw `Self::Replicated` arm at the [`Default for PlacementStrategy`]
5121/// impl and implicit `PlacementStrategy::default()` routes at the sibling
5122/// consumers, with no compile-time link back to the paired
5123/// [`crate::manifest::Caixa::aplicacao_view`] fold's
5124/// `.unwrap_or_default()` `Option<Placement>` collapse arm — the fourth
5125/// production consumer that resolves an author-omitted `:placement` slot
5126/// (entirely omitted, not just the `:estrategia` scalar within a declared
5127/// `:placement` block) through [`Placement::default`] which then routes
5128/// through this same discriminator. A future coherent rebrand of the
5129/// `:placement :estrategia` default (a widening to `Sharded` once the
5130/// substrate discovers hash-keyed distribution as the more common
5131/// production shape, a tightening to `SingleNode` for stateful Erlang/OTP
5132/// distributed-app-takeover semantics MESH-COMPOSITION §II.1 already
5133/// names, a per-cluster overlay the operator pins through a future
5134/// `:placement-overrides` slot) would have had to migrate a lifted
5135/// discriminator on one path and open-coded discriminators on the peers
5136/// in lockstep or the four consumers would silently drift out of
5137/// pairing. Lifting the resolution rule to a typed `pub const` on the
5138/// substrate primitive means the M3-mesh-canonical `:placement
5139/// :estrategia` default migrates as one unit on any future axis change.
5140///
5141/// The [`PlacementStrategy::Replicated`] value pins MESH-COMPOSITION
5142/// §II.2's active-active-across-every-named-cluster arm — the closest
5143/// canonical M3 production reference the substrate carries, matching the
5144/// caixa-mesh default axis every M3 renderer already keys off (a
5145/// `programs.yaml` fan-out that emits one `HelmRelease` per cluster is
5146/// the canonical shape a `:membros`+`:contratos`-declared Aplicacao lands on
5147/// under the substrate's fleet-programs aggregator without an explicit
5148/// `:placement :estrategia` override). The two alternatives the closed
5149/// [`PlacementStrategy::ALL`] accept-set carries
5150/// ([`PlacementStrategy::SingleNode`] — Erlang/OTP distributed-app
5151/// takeover, MESH-COMPOSITION §II.1; [`PlacementStrategy::Sharded`] —
5152/// Akka-style hash-keyed distribution across clusters,
5153/// MESH-COMPOSITION §II.4) express deliberate takeover / hash-keyed
5154/// postures an author declares explicitly, never a posture an omitted
5155/// slot should silently assume.
5156///
5157/// Lifted as a typed `pub const` so the M3-mesh-canonical default has
5158/// exactly one source of truth on the `:placement :estrategia` axis, on
5159/// the same substrate-primitive lift discipline the sibling M2
5160/// per-supervisor default set carries
5161/// ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`],
5162/// [`crate::supervisor::SUPERVISOR_MAX_RESTARTS_DEFAULT`],
5163/// [`crate::supervisor::SUPERVISOR_RESTART_WINDOW_DEFAULT`],
5164/// [`crate::supervisor::SUPERVISOR_CHILD_RESTART_DEFAULT`]) and the peer
5165/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes
5166/// ([`crate::render::DEFAULT_NAMESPACE`],
5167/// [`crate::render::DEFAULT_LIBRARY_NAME`],
5168/// [`crate::render::DEFAULT_SERVICO_PORT`]). The first typed default on
5169/// the M3 mesh-primitive-defining slot family to converge onto the
5170/// substrate-primitive-lift discipline the M2 supervisor-slot family
5171/// already carries end-to-end.
5172pub const PLACEMENT_ESTRATEGIA_DEFAULT: PlacementStrategy = PlacementStrategy::Replicated;
5173
5174impl Default for PlacementStrategy {
5175    fn default() -> Self {
5176        // Route the [`Default for PlacementStrategy`] impl through the
5177        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
5178        // `pub const` rather than a raw `Self::Replicated` arm — one
5179        // source of truth for the M3-mesh-canonical active-active-
5180        // across-every-named-cluster `:placement :estrategia` default
5181        // (MESH-COMPOSITION §II.2), on the same substrate-primitive
5182        // lift discipline the sibling M2 per-supervisor default set
5183        // ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`] +
5184        // paired halves) carries end-to-end. Pinned by
5185        // `placement_strategy_default_routes_through_lifted_default`.
5186        PLACEMENT_ESTRATEGIA_DEFAULT
5187    }
5188}
5189
5190impl PlacementStrategy {
5191    /// Exhaustive iteration surface for every consumer that reads the
5192    /// full closed-set (the future M4 admission-webhook's accepted-
5193    /// strategy listing in its rejection body, a future `feira app
5194    /// placement --list` CLI-side surfacing of the accepted arm-set,
5195    /// any future round-trip fuzz harness). A future variant addition
5196    /// (an `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint
5197    /// names as a trajectory item) extends this slice as a single edit
5198    /// and every consumer picks up the new entry by construction — the
5199    /// compiler-checked exhaustiveness on the sibling method `match`
5200    /// arms is the build-time guarantee that no arm forgets to grow.
5201    /// Same shape as the sibling closed-set typed enums'
5202    /// [`RateLimitUnit::ALL`] (6bce03d) and
5203    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
5204    /// surfaces — the third closed-set typed enum on the caixa surface
5205    /// to converge onto the same discipline.
5206    pub const ALL: &'static [Self] = &[Self::SingleNode, Self::Replicated, Self::Sharded];
5207
5208    /// Canonical camelCase-schema discriminator scalar this variant
5209    /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
5210    /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
5211    /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5212    /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
5213    /// every substrate consumer that dispatches on the strategy (the
5214    /// `lareira-fleet-programs` aggregator, the future `app-operator`
5215    /// reconciler, the M3 Adaptive compression pass) reads the same
5216    /// byte-string the `Serialize` derive emits — the pin test in
5217    /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
5218    /// asserts the two paths agree.
5219    #[must_use]
5220    pub const fn as_str(self) -> &'static str {
5221        match self {
5222            Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
5223            Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
5224            Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
5225        }
5226    }
5227
5228    /// Substrate-canonical reverse projection on the `:placement
5229    /// :estrategia` closed-set axis — parses the camelCase-schema
5230    /// discriminator scalar back to the typed variant, or `None` when
5231    /// `s` is outside the closed-set arm-string set [`Self::as_str`]
5232    /// emits. Dispatches on the same lifted
5233    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
5234    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5235    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] constants the
5236    /// [`Self::as_str`] emitter walks, so the parse and emit halves of
5237    /// the round-trip migrate through one caixa-core edit on any future
5238    /// arm addition (an `Anycast` mesh-anycast arm the MESH-COMPOSITION
5239    /// §II.5 hint names as a trajectory item lands one variant + one
5240    /// arm per method and the compiler enforces exhaustiveness on every
5241    /// consumer's `match self` arms).
5242    ///
5243    /// Prior to this lift the substrate carried only the forward
5244    /// `Self → &str` projection (the [`Self::as_str`] emitter, the
5245    /// [`std::fmt::Display`] impl routed through it, the `Serialize`
5246    /// derive that emits the same byte-string under
5247    /// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]) — every non-serde
5248    /// consumer that wanted to parse a wire-form strategy scalar had to
5249    /// re-inline a three-arm `match s { "SingleNode" => …, "Replicated"
5250    /// => …, "Sharded" => …, _ => … }` cascade that expressed no
5251    /// compile-time link back to the typed variant's canonical lifted
5252    /// constant. A future variant rename or a per-arm serde-attribute
5253    /// drift would silently split the wire byte-string one non-serde
5254    /// consumer parsed from the one the emitter wrote, with the
5255    /// failure surfacing at parse time far from the rebrand commit.
5256    ///
5257    /// Same closed-set-reverse-projection discipline the sibling
5258    /// [`crate::CaixaKind::from_wire`] (2aa6d23) and
5259    /// [`RateLimitUnit::from_suffix`] typed enums carry on the peer
5260    /// wire-side `str → Self` axes — extended onto the M3 mesh-primitive-
5261    /// defining `:placement :estrategia` closed-set axis, the third
5262    /// substrate-side closed-set typed enum to converge on the two-way
5263    /// `str ↔ Self` round-trip. Method-named `from_wire` (not `from_str`)
5264    /// to match the peer [`crate::CaixaKind::from_wire`] shape verbatim
5265    /// and side-step the [`std::str::FromStr`]-collision clippy
5266    /// (`clippy::should_implement_trait`) the plain `from_str` name
5267    /// carries; a future explicit [`std::str::FromStr`] impl can layer
5268    /// on top by delegating to this canonical arm-dispatch method.
5269    ///
5270    /// Returns `Option<Self>` (rather than `Result<Self, _>`) to match
5271    /// the sibling [`crate::CaixaKind::from_wire`] shape: the caller
5272    /// picks the diagnostic form appropriate for its use site — a
5273    /// future `feira app placement --set` CLI-side arg-parse that wants
5274    /// an `"unknown strategy: {s} (accepted: SingleNode, Replicated,
5275    /// Sharded)"` diagnostic builds one on top by iterating
5276    /// [`Self::ALL`], while the future M4 admission-webhook's rejection
5277    /// path folds `None` onto its per-CR structured refusal body.
5278    #[must_use]
5279    pub fn from_wire(s: &str) -> Option<Self> {
5280        match s {
5281            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE => Some(Self::SingleNode),
5282            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED => Some(Self::Replicated),
5283            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED => Some(Self::Sharded),
5284            _ => None,
5285        }
5286    }
5287
5288    /// Substrate-canonical per-arm predicate naming the cross-slot
5289    /// `:placement :estrategia` ↔ `:placement :shard-key` invariant on the
5290    /// closed-set typed [`PlacementStrategy`] enum: `true` iff the strategy
5291    /// consumes the paired [`Placement::shard_key`] axis (and therefore
5292    /// requires — and is the only strategy that permits — a non-empty
5293    /// `:shard-key` on the paired slot). Today the accept-set is the
5294    /// singleton `{Sharded}` — `Sharded` is the sole Akka-style
5295    /// hash-keyed distribution arm (MESH-COMPOSITION §II.4) that keys off a
5296    /// per-entity extractor expression; `SingleNode` (Erlang/OTP
5297    /// distributed-app takeover — §II.1) and `Replicated` (active-active
5298    /// across every named cluster) have no hash-keyed routing axis to
5299    /// consume the slot and refuse a declared-but-inert `:shard-key`
5300    /// through [`AplicacaoError::ShardKeyOnNonSharded`].
5301    ///
5302    /// Every validated [`Placement`] past [`AplicacaoSpec::validate_placement`]
5303    /// satisfies `placement.shard_key().is_some() ==
5304    /// placement.estrategia().requires_shard_key()` by construction — the
5305    /// cross-slot partition the pin
5306    /// [`tests::validate_placement_admits_paired_shape_iff_strategy_requires_shard_key`]
5307    /// locks load-bearing, so every downstream consumer that reaches for
5308    /// the paired shape (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5309    /// CR materializer's per-CR shard-key resolver, the future
5310    /// [`feira app graph --shard-key`] per-Aplicacao column, the future
5311    /// per-cluster Akka-style cluster-sharding reconciler's per-entity
5312    /// hash-routing gate, the M5 adaptive-placement engine's per-strategy
5313    /// shard-key requirement probe, a future author-facing tatara-lisp
5314    /// linter that flags `(:placement (:estrategia Replicated :shard-key
5315    /// "tenantId"))` shapes before `feira lint` reaches
5316    /// [`AplicacaoSpec::validate`]) can reach for one typed dispatch on
5317    /// the substrate primitive — the predicate names *the cross-slot
5318    /// invariant*, not the arm identity.
5319    ///
5320    /// Prior to this lift the "does this strategy consume `:shard-key`"
5321    /// classification lived under the `gen_platform::IsVariant`-derived
5322    /// [`Self::is_sharded`] predicate at three fixture-builder sites in
5323    /// this crate (the [`tests::placement_strategy_variants_round_trip`]
5324    /// per-variant `Placement`-builder's `if s.is_sharded() { Some("$key"…)
5325    /// } else { None }` cascade, the
5326    /// [`tests::estrategia_returns_placement_estrategia_verbatim_across_permutations`]
5327    /// per-variant `Placement`-builder's `estrategia.is_sharded().then(||
5328    /// "tenantId".to_string())` cascade, and the
5329    /// [`tests::validate_placement_reads_through_lifted_estrategia_accessor`]
5330    /// per-variant spec-mutator's identical `.is_sharded().then(…)`
5331    /// cascade). Each site conflated two semantically distinct questions:
5332    /// "is the variant `Sharded`?" (arm-identity, what
5333    /// [`Self::is_sharded`] answers) and "does the variant consume
5334    /// `:shard-key`?" (cross-slot-invariant, what this predicate answers).
5335    /// The two questions land on the same three-way answer under today's
5336    /// closed accept-set (both trip on the singleton `{Sharded}`), but a
5337    /// future arm addition that consumed `:shard-key` under a different
5338    /// name (a hypothetical `Anycast` mesh-anycast arm the MESH-COMPOSITION
5339    /// §II.5 roadmap-hint names that hash-partitions across the cluster
5340    /// pool by client-IP hash rather than an author-declared extractor
5341    /// expression, a hypothetical `WeightedShard` variant that carries a
5342    /// shard-key + per-cluster weight table under a promoted M5
5343    /// adaptive-placement engine) or an addition that did *not* consume
5344    /// `:shard-key` on a semantically Sharded-shaped arm would silently
5345    /// split the two questions. Any consumer that read
5346    /// `.is_sharded().then(…)` for the shard-key requirement gate would
5347    /// silently misclassify the new arm as non-consuming — a fixture
5348    /// builder would omit `:shard-key` where the new arm required one and
5349    /// [`AplicacaoSpec::validate_placement`] would refuse the fixture with
5350    /// [`AplicacaoError::ShardedWithoutKey`] far from the arm-addition
5351    /// commit, a future M4 CR materializer would fall through the
5352    /// `.is_sharded()`-only branch to the non-shard-key resolver arm and
5353    /// silently emit an empty extractor at the Akka reconciler layer.
5354    ///
5355    /// Lifting the classification as a substrate-primitive method on the
5356    /// closed-set typed enum names the cross-slot invariant on the
5357    /// primitive that owns the partition: every future arm addition
5358    /// declares its `:shard-key` consumption in one place (this predicate's
5359    /// `match self` arm-set), and every downstream consumer that reaches
5360    /// for the paired shape reads through one typed dispatch. Same
5361    /// discipline as the sibling [`WitContract::is_capability`] (7b97d26)
5362    /// per-arm predicate on the pre-projection WIT-shape axis and the
5363    /// [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
5364    /// paired predicate on the post-projection typed-view axis — a
5365    /// per-arm semantic-classification predicate paired with the
5366    /// arm-identity predicate the derive already emits, closing the drift
5367    /// footgun on the cross-slot invariant axis.
5368    ///
5369    /// Method-named `requires_shard_key` (not `has_shard_key`, not
5370    /// `is_shard_keyed`, not `takes_shard_key`) because the cross-slot
5371    /// invariant reads as "this strategy *requires* the paired
5372    /// `:shard-key` axis" — the `SingleNode`/`Replicated` arms *refuse*
5373    /// the axis through [`AplicacaoError::ShardKeyOnNonSharded`], not
5374    /// merely omit it. The `has_*` framing would read as an accessor
5375    /// (returning the presence of an already-carried value) rather than a
5376    /// requirement (naming the invariant the paired slot must satisfy).
5377    /// Returns `bool` (not `Option<()>` or a marker-type witness), same
5378    /// shape as the sibling [`WitContract::is_capability`] /
5379    /// [`Self::is_sharded`] per-arm boolean predicates on the closed-set
5380    /// arm-family, so every consumer reaches for `.requires_shard_key()`
5381    /// as a drop-in replacement for the `.is_sharded()` conflated read
5382    /// without a return-shape migration.
5383    #[must_use]
5384    pub const fn requires_shard_key(self) -> bool {
5385        match self {
5386            Self::Sharded => true,
5387            Self::SingleNode | Self::Replicated => false,
5388        }
5389    }
5390}
5391
5392// Compile-time pins on the [`PlacementStrategy::requires_shard_key`]
5393// cross-slot-invariant per-arm predicate: the module-scope const-eval
5394// assertions below trip at caixa-core build time (not test time) if a
5395// future edit rewires the predicate's arm-set away from the singleton
5396// `{Sharded}` accept-set MESH-COMPOSITION §II.4 pins. The
5397// [`tests::placement_strategy_requires_shard_key_partitions_the_arm_set`]
5398// runtime pin covers the same truth-table with a more descriptive
5399// diagnostic on failure; these const-eval items add a build-time failure
5400// surface strictly stronger than the runtime pin (a downstream renderer's
5401// `const`-context reader that composed against a rebound predicate would
5402// still surface here before the test suite even ran) and side-step the
5403// `clippy::assertions_on_constants` lint the runtime `assert!(CONST)` pin
5404// would otherwise accumulate on the caixa-core module baseline.
5405const _: () = assert!(!PlacementStrategy::SingleNode.requires_shard_key());
5406const _: () = assert!(!PlacementStrategy::Replicated.requires_shard_key());
5407const _: () = assert!(PlacementStrategy::Sharded.requires_shard_key());
5408
5409/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
5410/// the pretty-printed byte-string every consumer that formats the strategy
5411/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
5412/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
5413/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
5414/// per-Aplicacao strategy line, the future M4 CR materializer's per-
5415/// admission-webhook rejection body) reaches for the same lifted
5416/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
5417/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5418/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
5419/// `Serialize` derive already emits under
5420/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
5421/// [`PlacementStrategy::as_str`] helper already returns.
5422///
5423/// Until this lift landed the sibling OTP-shape typed enums —
5424/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
5425/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
5426/// so [`std::fmt::Display`] routes through the same discriminant string
5427/// the wire format emits) — carried a stable [`std::fmt::Display`]
5428/// surface but [`PlacementStrategy`] did not; every consumer reaching
5429/// for a strategy byte-string past the wire format had to pick between
5430/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
5431/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
5432/// derive), any two of which a future variant rename or
5433/// `#[serde(rename_all = "kebab-case")]` attribute would silently
5434/// desynchronize — with the failure surfacing as a downstream renderer /
5435/// operator's per-strategy dispatch reading one spelling while the wire
5436/// format emitted another, far from the source rebrand commit and with
5437/// no field naming the drift. Routing `Display` through
5438/// [`PlacementStrategy::as_str`] makes the three paths
5439/// (`Debug` for structural inspection, `Display` for user-facing text,
5440/// `Serialize` for the wire format) converge on the same lifted
5441/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
5442/// the diagnostic byte-string, and the pretty-printed byte-string move
5443/// as a single unit through one canonical declaration each, by
5444/// construction. Same trajectory as [`PlacementStrategy::as_str`]
5445/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
5446/// closes the third path.
5447///
5448/// Pin tests
5449/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
5450/// and
5451/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
5452/// assert the three paths agree byte-for-byte on every variant, so a
5453/// future variant rename or per-arm serde attribute drift is a build
5454/// error visible at caixa-core test time, not a silent per-consumer
5455/// dispatch miss at apply / reconcile time.
5456impl std::fmt::Display for PlacementStrategy {
5457    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5458        f.write_str(self.as_str())
5459    }
5460}
5461
5462/// Where the Aplicacao runs.
5463#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5464#[serde(rename_all = "camelCase")]
5465pub struct Placement {
5466    /// Distribution strategy.
5467    #[serde(default)]
5468    pub estrategia: PlacementStrategy,
5469
5470    /// Named clusters that host this Aplicacao. Required for
5471    /// `Replicated` and `SingleNode`; for `Sharded` declares the
5472    /// shard pool.
5473    #[serde(default)]
5474    pub clusters: Vec<String>,
5475
5476    /// Optional hint to the placement engine: `"data-locality"`,
5477    /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
5478    #[serde(default, skip_serializing_if = "Option::is_none")]
5479    pub affinity: Option<String>,
5480
5481    /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
5482    #[serde(default, skip_serializing_if = "Option::is_none")]
5483    pub shard_key: Option<String>,
5484}
5485
5486impl Placement {
5487    /// Substrate-canonical per-`:placement` Akka-cluster-sharding
5488    /// `:shard-key` extractor-expression scalar accessor every consumer
5489    /// of the Aplicacao's hash-keyed distribution routing keys off —
5490    /// returns the author-declared `:placement :shard-key` byte-string
5491    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
5492    /// own `Option<String>` storage; `None` when the slot is absent
5493    /// (the canonical shape under `:estrategia Replicated` /
5494    /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
5495    /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
5496    /// partition — `validate` refuses any `Placement` past this call
5497    /// that lands `Some` on a non-`Sharded` strategy or `None` on
5498    /// `Sharded`).
5499    ///
5500    /// The `:placement :shard-key` slot carries the Akka-style
5501    /// cluster-sharding entity-id extractor expression
5502    /// (MESH-COMPOSITION §II.4) — validated by
5503    /// [`validate_placement_shard_key`] to be a non-empty printable-
5504    /// ASCII single-token reference (`tenantId`, `$tenantId`,
5505    /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
5506    /// future M4 Akka-style cluster-sharding reconciler hashes without
5507    /// re-validating at the runtime layer), and every downstream
5508    /// consumer that reads the key keys off this scalar (the
5509    /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
5510    /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
5511    /// declared-but-inert refusal diagnostic, the caixa-mesh
5512    /// per-Aplicacao `placement.shardKey` emit path the substrate
5513    /// operator's per-entity hash-routing reader consumes, the future
5514    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5515    /// per-shard-key resolver).
5516    ///
5517    /// Prior to this lift the `.shard_key` field was accessed inline at
5518    /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
5519    /// `Sharded` arm's `match &self.placement.shard_key { None => …,
5520    /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
5521    /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
5522    /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
5523    /// — two open-coded field-accesses that expressed no compile-time
5524    /// link back to the typed slot. A future extension of the
5525    /// `:placement :shard-key` axis to a richer author surface — a
5526    /// per-cluster override the operator pins through a future
5527    /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
5528    /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
5529    /// alias table the M4 CR materializer resolves per-CR, a
5530    /// per-Aplicacao dynamic `:shard-key` derivation the future
5531    /// adaptive placement engine computes from `:affinity` weights —
5532    /// would have had to be threaded through both open-coded copies in
5533    /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
5534    /// arm refusal would silently disagree on which extractor
5535    /// expression a given Placement resolves to. Lifting the resolution
5536    /// rule to a typed method on the substrate primitive means every
5537    /// downstream consumer of the Aplicacao's per-`:placement`
5538    /// hash-key surface reaches for exactly one typed dispatch — the
5539    /// resolver's accept-set migrates as a unit on any future axis
5540    /// addition.
5541    ///
5542    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
5543    /// [`WitContract::destination`] / [`WitContract::world_ref`]
5544    /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
5545    /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
5546    /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
5547    /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
5548    /// typed dispatch on the substrate primitive, thin projections at
5549    /// each consumer" discipline extended onto the per-`:placement`
5550    /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
5551    /// First `Option<&str>`-return accessor on the M3 mesh-slot family
5552    /// — opens the "optional per-slot scalar" projection pattern the
5553    /// sibling per-`:placement` `:affinity`, per-`:politicas`
5554    /// `:rate-limit` future lifts fold on. Named `shard_key()` to
5555    /// match the storage field's name; the accessor's identity name
5556    /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
5557    /// slot's docstring already carries.
5558    #[must_use]
5559    pub const fn shard_key(&self) -> Option<&str> {
5560        match &self.shard_key {
5561            Some(s) => Some(s.as_str()),
5562            None => None,
5563        }
5564    }
5565
5566    /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
5567    /// compression-hint scalar accessor every weighting-consumer of the
5568    /// Aplicacao's per-hint routing surface keys off — returns the
5569    /// author-declared `:placement :affinity` byte-string verbatim as
5570    /// an `Option<&str>`, borrowed from the typed slot's own
5571    /// `Option<String>` storage; `None` when the slot is absent (the
5572    /// canonical shape of an Aplicacao that leaves the compression
5573    /// weighting up to the placement engine's cluster-default arm — no
5574    /// author-authored `data-locality` / `low-latency` / etc. hint
5575    /// biases the routing).
5576    ///
5577    /// The `:placement :affinity` slot carries the M3 Adaptive-
5578    /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
5579    /// by [`validate_placement_affinity`] to be a DNS-1123 label
5580    /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
5581    /// K8s-conformant label-selector shape every apiserver-side pod-
5582    /// affinity / node-affinity materializer already gates on
5583    /// admission), and every downstream consumer that reads the hint
5584    /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
5585    /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
5586    /// `placement.affinity` overlay emit path the substrate operator's
5587    /// per-hint weighting-consumer reads, the future M4
5588    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
5589    /// pod-affinity / node-affinity selector resolver).
5590    ///
5591    /// Prior to this lift the `.affinity` field was accessed inline at
5592    /// the sole caixa-core site — the
5593    /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
5594    /// `if let Some(a) = &self.placement.affinity { …
5595    /// validate_placement_affinity(a)? … }` cascade — one open-coded
5596    /// field-access that expressed no compile-time link back to the
5597    /// typed slot. A future extension of the `:placement :affinity`
5598    /// axis to a richer author surface — a per-cluster override the
5599    /// operator pins through a future `:placement :affinity-overrides`
5600    /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
5601    /// tenant hint alias table the M4 CR materializer resolves per-CR,
5602    /// a per-Aplicacao dynamic `:affinity` derivation the future
5603    /// adaptive placement engine computes from `:clusters` topology —
5604    /// would have had to be threaded through the open-coded copy in
5605    /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
5606    /// materializer reader that landed on the axis, or the per-hint
5607    /// value-shape gate and its downstream weighting consumers would
5608    /// silently disagree on which hint a given Placement resolves to.
5609    /// Lifting the resolution rule to a typed method on the substrate
5610    /// primitive means every downstream consumer of the Aplicacao's
5611    /// per-`:placement` compression-hint surface reaches for exactly
5612    /// one typed dispatch — the resolver's accept-set migrates as a
5613    /// unit on any future axis addition.
5614    ///
5615    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
5616    /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
5617    /// optional-scalar axis — same "one typed dispatch on the substrate
5618    /// primitive, thin projections at each consumer" discipline extended
5619    /// onto the per-`:placement` M3-Adaptive-compression-hint
5620    /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
5621    /// return accessor on the M3 mesh-slot family; closes the last
5622    /// un-lifted per-`:placement` `Option<String>` axis. Named
5623    /// `affinity()` to match the storage field's name; the accessor's
5624    /// identity name maps onto the canonical MESH-COMPOSITION §II.4
5625    /// vocabulary the slot's docstring already carries.
5626    #[must_use]
5627    pub const fn affinity(&self) -> Option<&str> {
5628        match &self.affinity {
5629            Some(s) => Some(s.as_str()),
5630            None => None,
5631        }
5632    }
5633
5634    /// Substrate-canonical per-`:placement` `:estrategia` distribution-
5635    /// strategy scalar accessor every consumer that dispatches on the
5636    /// Aplicacao's per-cluster distribution shape keys off — returns the
5637    /// author-declared `:placement :estrategia` variant verbatim as a
5638    /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
5639    /// `PlacementStrategy` storage.
5640    ///
5641    /// The `:placement :estrategia` slot carries the closed-set
5642    /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
5643    /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
5644    /// `Replicated` — active-active across every named cluster; `Sharded`
5645    /// — Akka-style hash-keyed entity distribution across the cluster pool
5646    /// per §II.4) that every downstream consumer of the Aplicacao's
5647    /// per-cluster fan-out shape keys off. Validated by
5648    /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
5649    /// the sibling `:shard-key` axis (`shard_key.is_some() ==
5650    /// matches!(estrategia, Sharded)` — the cross-slot partition the
5651    /// [`Placement::shard_key`] accessor's docstring pins), and every
5652    /// downstream consumer that reads the strategy keys off this scalar
5653    /// (the [`AplicacaoSpec::validate_placement`]
5654    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
5655    /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
5656    /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
5657    /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
5658    /// declared-but-inert refusal's
5659    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
5660    /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
5661    /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
5662    /// emit path the substrate operator's per-strategy fan-out reader
5663    /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5664    /// materializer's per-strategy admission-webhook resolver).
5665    ///
5666    /// Prior to this lift the `.estrategia` field was accessed inline at
5667    /// four sites — the [`AplicacaoSpec::validate_placement`]
5668    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
5669    /// `estrategia: self.placement.estrategia`, the same method's
5670    /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
5671    /// partition dispatch, the non-`Sharded`-arm
5672    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
5673    /// `estrategia: self.placement.estrategia`, and the `feira app graph`
5674    /// per-Aplicacao strategy print line at
5675    /// `println!("… {} …", spec.placement.estrategia, …)`
5676    /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
5677    /// expressed no compile-time link back to the typed slot. A future
5678    /// extension of the `:placement :estrategia` axis to a richer author
5679    /// surface (a per-cluster override the operator pins through a future
5680    /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
5681    /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
5682    /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
5683    /// derivation the future adaptive placement engine computes from
5684    /// `:affinity` + `:clusters` topology) would have had to be threaded
5685    /// through every open-coded copy in lockstep — one consumer reading
5686    /// the raw variant while a peer read the operator-resolved variant
5687    /// would silently split the `PlacementWithoutClusters` /
5688    /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
5689    /// partition-dispatch input, a two-consumer split at the validator
5690    /// far from the source `caixa.lisp` with no field naming the
5691    /// strategy-drift root cause. Lifting the resolution rule to a typed
5692    /// method on the substrate primitive means every downstream consumer
5693    /// of the Aplicacao's per-`:placement` distribution-strategy surface
5694    /// reaches for exactly one typed dispatch — the resolver's accept-set
5695    /// migrates as a unit on any future axis addition.
5696    ///
5697    /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
5698    /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
5699    /// same "one typed dispatch on the substrate primitive, thin
5700    /// projections at each consumer" discipline extended onto the
5701    /// per-`:placement` distribution-strategy `Copy`-composite-enum
5702    /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
5703    /// family; first `Copy`-return accessor on the M3 mesh-slot
5704    /// `Placement` type — companion to the sibling per-`:placement`
5705    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
5706    /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
5707    /// optional-scalar axes, closing the last unlifted per-`:placement`
5708    /// scalar-value axis (the closed-set `PlacementStrategy`
5709    /// distribution-strategy discriminator) so every downstream
5710    /// per-`:placement` reader now routes through a typed dispatch on
5711    /// the substrate primitive. Named `estrategia()` to match the storage
5712    /// field's name; the accessor's identity name maps onto the
5713    /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
5714    /// already carries. Declared `pub const fn` (matching the peer M3
5715    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
5716    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
5717    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
5718    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
5719    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
5720    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
5721    /// [`RateLimit`] — every one a `pub const fn`) so every future
5722    /// substrate-side `const`-context consumer of the resolved
5723    /// distribution-strategy variant (a `const _: () = assert!(…)`
5724    /// module-scope invariant pin on a per-fixture typed [`Placement`],
5725    /// a future M4 admission-webhook `const fn` resolver over a typed
5726    /// [`Placement`], any `const fn` composer that fans on the strategy
5727    /// at compile time) reaches through the same typed dispatch on the
5728    /// substrate primitive at const-eval time as at runtime. Pinned by
5729    /// [`placement_estrategia_accessor_is_const_fn`] which witnesses the
5730    /// const-eval posture at module scope via `const _:() = …` items so
5731    /// any future accidental downgrade to non-`const` trips at caixa-core
5732    /// build time.
5733    #[must_use]
5734    pub const fn estrategia(&self) -> PlacementStrategy {
5735        self.estrategia
5736    }
5737
5738    /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
5739    /// per-cluster distribution-target slice accessor every consumer that
5740    /// walks the Aplicacao's declared cluster-pool keys off — returns the
5741    /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
5742    /// `&[String]` slice-view, borrowed from the typed slot's own
5743    /// `Vec<String>` storage (a zero-copy slice-view over the same
5744    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
5745    /// through). Non-optional: the empty slice is the load-bearing
5746    /// pre-validation sentinel every downstream consumer of the paired
5747    /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
5748    /// off — every strategy in the closed
5749    /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
5750    /// requires a non-empty list (`SingleNode` / `Replicated` use the
5751    /// list as hosting / takeover candidates per Erlang/OTP distributed-
5752    /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
5753    /// shard pool per Akka cluster-sharding convention, §II.4), so the
5754    /// `.is_empty()` probe is the shared pre-condition every
5755    /// [`AplicacaoSpec::validate_placement`] arm heads on.
5756    ///
5757    /// The `:placement :clusters` slot carries the K8s-conformant DNS-
5758    /// 1123-label per-cluster distribution-target list — the same
5759    /// set-not-multiset shape the sibling `:membros :caixa` /
5760    /// `:children :caixa` axes carry (`validate_placement`'s per-entry
5761    /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
5762    /// pins the shape). Every downstream consumer that fans on the list
5763    /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
5764    /// pre-flight `.is_empty()` probe that trips
5765    /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
5766    /// per-cluster value-shape + duplicate-detection fan-out loop, the
5767    /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
5768    /// that materializes the list verbatim onto every
5769    /// programs.yaml entry the substrate operator's per-cluster
5770    /// `placement.clusters | contains .Values.cluster` filter reads,
5771    /// the `feira app graph` per-Aplicacao cluster print line, the
5772    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5773    /// per-cluster admission-webhook fan-out, the future M5 adaptive-
5774    /// placement engine's cluster-topology reader).
5775    ///
5776    /// Prior to this lift the `.clusters` `Vec<String>` was accessed
5777    /// inline at three production sites — the
5778    /// [`AplicacaoSpec::validate_placement`] pre-flight
5779    /// `self.placement.clusters.is_empty()` refusal probe, the same
5780    /// method's per-cluster validate loop's
5781    /// `for c in &self.placement.clusters` traversal head, and the
5782    /// `feira app graph` per-Aplicacao print line's
5783    /// `spec.placement.clusters` `{:?}` formatter argument
5784    /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
5785    /// that expressed no compile-time link back to the typed slot. A
5786    /// future extension of the `:placement :clusters` axis to a richer
5787    /// author surface (a per-tenant cluster-pool overlay the operator
5788    /// pins through a future `:placement :clusters-overrides` slot the
5789    /// MESH-COMPOSITION §V cross-cluster-federation roadmap
5790    /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
5791    /// the future M5 adaptive-placement engine computes from
5792    /// `:affinity` weights + live cluster-topology probes, a promotion
5793    /// of the plain `Vec<String>` to a richer `{static, dynamic}`
5794    /// partition once the substrate operator's cluster-membership
5795    /// reconciler comes into typed scope) would have had to be threaded
5796    /// through all three open-coded copies in lockstep or one consumer
5797    /// would silently disagree with the peers on which cluster-pool a
5798    /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
5799    /// reading the raw slot while the peer per-cluster validate loop
5800    /// read an operator-resolved slot would silently split the paired
5801    /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
5802    /// `PlacementClusterDuplicate` refusal cascade's actual traversal
5803    /// input from the pre-flight input, a three-consumer split at the
5804    /// validator and formatter far from the source `caixa.lisp` with
5805    /// no field naming the cluster-pool-drift root cause. Lifting the
5806    /// resolution rule to a typed method on the substrate primitive
5807    /// means every downstream consumer of the Aplicacao's
5808    /// per-`:placement` cluster-pool surface reaches for exactly one
5809    /// typed dispatch — the resolver's accept-set migrates as a unit
5810    /// on any future axis addition.
5811    ///
5812    /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
5813    /// slot — sibling to the seed M2
5814    /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
5815    /// slice-return accessor on the peer per-`:supervisor` static-
5816    /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
5817    /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
5818    /// primitive, thin projections at each consumer" discipline. The
5819    /// three peer `Vec`-carry axes still unlifted at the time of this
5820    /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
5821    /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
5822    /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
5823    /// [`crate::UpgradeFromEntry::instructions`]
5824    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
5825    /// — inherit this accessor's discipline as future compounding runs
5826    /// migrate their consumers onto the shared slice-return shape.
5827    /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
5828    /// type, sibling to the two `Option<&str>`-return
5829    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
5830    /// (74ec2d3) accessors and the `Copy`-return
5831    /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
5832    /// unlifted per-`:placement` field axis (the `Vec<String>`
5833    /// distribution-target-list carrier) so every downstream
5834    /// per-`:placement` reader now routes through a typed dispatch on
5835    /// the substrate primitive. Named `clusters()` to match the storage
5836    /// field's name verbatim and the tatara-lisp author-surface term
5837    /// (`:clusters`) the field's own docstring already carries; the
5838    /// accessor's identity maps onto the canonical MESH-COMPOSITION
5839    /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
5840    /// for. Returns `&[String]` (not `&Vec<String>`) because every
5841    /// downstream consumer of the cluster list treats it as a read-only
5842    /// sequence — the slice-view is the narrowest borrow that supports
5843    /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
5844    /// `.len()`) without leaking the backing `Vec`'s
5845    /// grow/push/reserve surface that no consumer of the typed view
5846    /// reaches for (the storage-side `Vec` remains reachable through
5847    /// the `pub clusters` field for the mutation-carrying serde
5848    /// round-trip and per-test fixture-mutation paths).
5849    #[must_use]
5850    pub const fn clusters(&self) -> &[String] {
5851        self.clusters.as_slice()
5852    }
5853}
5854
5855impl Default for Placement {
5856    fn default() -> Self {
5857        Self {
5858            // Route the struct-literal `estrategia` default arm through
5859            // the substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`]
5860            // typed `pub const` rather than the transitively-derived
5861            // [`PlacementStrategy::default`] route — one source of truth
5862            // for the M3-mesh-canonical [`PlacementStrategy::Replicated`]
5863            // active-active-across-every-named-cluster arm
5864            // (MESH-COMPOSITION §II.2) that both this struct-literal
5865            // altitude and the sibling [`Default for PlacementStrategy`]
5866            // impl already key off through the same substrate primitive.
5867            // Pinned by
5868            // `placement_default_estrategia_routes_through_lifted_default`.
5869            estrategia: PLACEMENT_ESTRATEGIA_DEFAULT,
5870            clusters: Vec::new(),
5871            affinity: None,
5872            shard_key: None,
5873        }
5874    }
5875}
5876
5877// ── external entry point ─────────────────────────────────────────────
5878
5879/// External entry point — what an outside caller sees. Renders to a
5880/// Gateway / Ingress + a route to the named member Servico.
5881#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5882#[serde(rename_all = "camelCase")]
5883pub struct Entrada {
5884    /// Public hostname (e.g. `"checkout.quero.cloud"`).
5885    pub host: String,
5886
5887    /// Member Servico the gateway routes to. Must be in `:membros`.
5888    pub para: String,
5889
5890    /// Optional path filter — if set, only matching paths route to
5891    /// this Aplicacao (the rest fall through to other route rules).
5892    #[serde(default)]
5893    pub paths: Vec<String>,
5894
5895    /// Default port on the destination Servico (the trigger.service.port).
5896    #[serde(default = "default_port")]
5897    pub port: u16,
5898}
5899
5900impl Entrada {
5901    /// Substrate-canonical per-`:entrada` URL-path fallback resolver
5902    /// every HTTPRoute-aware renderer keys off — returns the author-
5903    /// declared `:entrada :paths` list verbatim when non-empty, and the
5904    /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
5905    /// all fallback otherwise (so an Aplicacao author who declares an
5906    /// external `:entrada` block but no per-path rule surface still
5907    /// gets a route whose sole `HTTPPathMatch` matches every incoming
5908    /// request under the paired
5909    /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
5910    ///
5911    /// Prior to this lift the "if `:entrada :paths` is empty use the
5912    /// substrate catch-all; else return each declared path verbatim"
5913    /// cascade lived inline at
5914    /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
5915    /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
5916    /// per-Aplicacao HTTPRoute per-rule path-list emit site the
5917    /// substrate ships today, with no typed method on the substrate
5918    /// primitive that named the rule. A future path-resolution axis
5919    /// addition — a per-cluster `:entrada :default-path` override the
5920    /// operator pins through a future `:placement`-scoped slot, an
5921    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
5922    /// admission-webhook floor that materializes the catch-all before
5923    /// the CR lands, a future per-`:entrada :paths` overlay from a
5924    /// per-cluster policy the future `feira app deploy` pipeline
5925    /// consumes — would have to be threaded through every renderer's
5926    /// inline copy of the cascade in lockstep or one consumer would
5927    /// silently disagree with the peers on which path list a given
5928    /// `:entrada` block resolves to. Lifting the rule to a typed
5929    /// method on the substrate primitive means every downstream
5930    /// HTTPRoute-aware consumer (the M4 CR materializer, the future
5931    /// per-cluster overlay resolver, every future per-Aplicacao
5932    /// snapshot renderer) reaches for exactly one typed dispatch —
5933    /// the resolver's accept-set moves as a unit on any future axis
5934    /// addition.
5935    ///
5936    /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
5937    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
5938    /// per-`:entrada` scalar-value axes — extends the "one typed
5939    /// dispatch on the substrate primitive, thin projections at each
5940    /// consumer" discipline onto the per-`:entrada` path-list
5941    /// resolution axis every HTTPRoute-aware renderer consumes. Same
5942    /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
5943    /// sibling `:politicas` primitive — one typed method on the
5944    /// substrate primitive that names the cascade every renderer
5945    /// otherwise re-inlines.
5946    #[must_use]
5947    pub fn resolved_paths(&self) -> Vec<&str> {
5948        // Route the internal cascade-head + per-entry projection reads
5949        // through the lifted [`Self::paths`] slice accessor rather than
5950        // the raw `self.paths` field access — the substrate-primitive
5951        // per-`:entrada` path-list resolver's two internal reads now
5952        // key off the canonical raw-slot surface every downstream
5953        // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
5954        // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
5955        // entrada summary line's `{:?}` Debug print) routes through, so
5956        // any future rebrand on the typed slot's raw-slot reader lands
5957        // at exactly one place. Same two-consumer coherence discipline
5958        // the sibling `Placement::clusters` (a6e18d7) accessor pins on
5959        // the peer M3 mesh-slot `Vec<String>`-carry axis.
5960        if self.paths().is_empty() {
5961            vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
5962        } else {
5963            self.paths().iter().map(String::as_str).collect()
5964        }
5965    }
5966
5967    /// Substrate-canonical per-`:entrada` DNS-hostname singular
5968    /// accessor every Gateway-API `Listener.hostname` reader keys off
5969    /// — returns the author-declared `:entrada :host` byte-string
5970    /// verbatim as a `&str`, borrowed from the typed slot's own
5971    /// [`String`] storage.
5972    ///
5973    /// Named the "singular" half of the DNS-hostname resolver pair on
5974    /// the substrate primitive: the parent-Gateway per-listener
5975    /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
5976    /// (`Listener.hostname: Option<PreciseHostname>` — at most one
5977    /// hostname per listener), and this accessor is the typed dispatch
5978    /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
5979    /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
5980    /// the per-HTTPRoute `spec.hostnames[]` list axis the same
5981    /// per-Aplicacao ingress-hostname surface projects onto.
5982    ///
5983    /// Prior to this lift the `entrada.host.clone()` byte-string was
5984    /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
5985    /// per-listener singular `hostname:` axis
5986    /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
5987    /// per-HTTPRoute plural `spec.hostnames[]` axis
5988    /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
5989    /// consumers read the same `entrada.host` field but the two-site
5990    /// duplication expressed no compile-time contract that the singular
5991    /// Gateway-listener filter and the plural `HTTPRoute` filter list
5992    /// stay in lockstep on future extensions of the `:entrada` slot to
5993    /// a multi-hostname author surface (an `:entrada :alt-hosts` list
5994    /// overlay, a per-cluster SNI fan-out the operator pins through a
5995    /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
5996    /// Aplicacao` CR materializer's per-listener virtual-host filter
5997    /// admission-webhook overlay). Any such extension would have to be
5998    /// threaded through every renderer's inline copy of the resolution
5999    /// in lockstep or the Gateway listener's `hostname:` filter would
6000    /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
6001    /// — a Gateway-API-conformance divergence whose apply-time symptom
6002    /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
6003    /// `NoMatchingParent` — the API server rejects the route because
6004    /// its `hostnames[]` filter doesn't intersect the parent listener's
6005    /// `hostname` filter) is far from the source `caixa.lisp` and never
6006    /// surfaces in the emitted YAML. Lifting the singular and plural
6007    /// resolvers to typed methods on the substrate primitive means
6008    /// every consumer of the Aplicacao's ingress-hostname surface
6009    /// reaches for exactly one typed dispatch, and the pair-invariant
6010    /// `hostnames() == vec![hostname()]` pinned by the sibling
6011    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
6012    /// keeps the two axes in lockstep by construction.
6013    ///
6014    /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
6015    /// (1449891) path-list resolver on the per-HTTPRoute per-rule
6016    /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
6017    /// the substrate primitive, thin projections at each consumer"
6018    /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
6019    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
6020    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
6021    /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
6022    /// `:entrada` scalar-value + list-value axes.
6023    #[must_use]
6024    pub const fn hostname(&self) -> &str {
6025        self.host.as_str()
6026    }
6027
6028    /// Substrate-canonical per-`:entrada` DNS-hostname plural
6029    /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
6030    /// keys off — returns the singleton `[hostname()]` list under
6031    /// today's single-hostname-per-Aplicacao author surface, and the
6032    /// authoritative multi-hostname list under a future
6033    /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
6034    ///
6035    /// Plural half of the DNS-hostname resolver pair — see the
6036    /// companion [`Entrada::hostname`] docstring for the two-consumer
6037    /// lift + pair-invariant discipline (`hostnames() ==
6038    /// vec![hostname()]`, pinned load-bearing by the sibling
6039    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
6040    /// test).
6041    ///
6042    /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
6043    /// per-`:entrada` plural-list resolver on the per-HTTPRoute
6044    /// per-rule path-list axis — same `Vec<&str>` shape, same
6045    /// substrate-primitive-owns-the-resolver discipline extended to
6046    /// the per-HTTPRoute virtual-host filter-list axis.
6047    #[must_use]
6048    pub fn hostnames(&self) -> Vec<&str> {
6049        vec![self.hostname()]
6050    }
6051
6052    /// Substrate-canonical per-`:entrada` destination-Servico scalar
6053    /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
6054    /// the author-declared `:entrada :para` byte-string verbatim as a
6055    /// `&str`, borrowed from the typed slot's own [`String`] storage.
6056    ///
6057    /// The `:entrada :para` slot names the single member Servico the
6058    /// external Gateway routes to (validated by
6059    /// [`AplicacaoSpec::validate`] to be a
6060    /// [`Membro::caixa`] the Aplicacao declares — a stray
6061    /// `:para` that doesn't name a member is
6062    /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
6063    /// backend-attachment miss at cluster-apply time). Under today's
6064    /// single-destination author surface `:entrada :para` is the ingress
6065    /// apex Servico's canonical identity; under a hypothetical
6066    /// future multi-backend author surface (a `:entrada
6067    /// :split :backends` weighted-fan-out overlay for canary /
6068    /// blue-green traffic-split rollouts, per-path override for
6069    /// path-based per-Servico routing beyond the single-apex model,
6070    /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6071    /// per-CR admission-webhook that promotes the scalar to a
6072    /// weighted list) this accessor is the substrate primitive's typed
6073    /// dispatch every downstream `HTTPRoute`-aware consumer routes
6074    /// through, so the resolution shape migrates as a unit on one
6075    /// caixa-core edit rather than a coordinated rewrite across every
6076    /// renderer's inline field-access.
6077    ///
6078    /// Prior to this lift the `entrada.para` byte-string was accessed
6079    /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
6080    /// `metadata.name` composer's per-destination discriminator arg
6081    /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
6082    /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
6083    /// per-HTTPRoute per-rule `backendRefs[0].name` axis
6084    /// (`entrada.para.clone()`,
6085    /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
6086    /// consumers read the same `entrada.para` field but the two-site
6087    /// duplication expressed no compile-time contract that the HTTPRoute
6088    /// name-discriminator and the per-rule backend name stay in
6089    /// lockstep on future extensions of the `:entrada` slot to a
6090    /// multi-destination author surface. Any such extension would have
6091    /// to be threaded through every renderer's inline copy of the
6092    /// destination projection in lockstep or the HTTPRoute
6093    /// `metadata.name` would silently reference a different destination
6094    /// than its own `backendRefs[]` — an operator-side
6095    /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
6096    /// grep-by-name lookup would land on a route whose `backendRefs[]`
6097    /// silently point at a peer Servico, dropping every external
6098    /// `:entrada` flow at the gateway with the destination-drift root
6099    /// cause invisible in the emitted YAML.
6100    ///
6101    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
6102    /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
6103    /// the per-listener singular / per-HTTPRoute plural filter axes and
6104    /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
6105    /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
6106    /// typed dispatch on the substrate primitive, thin projections at
6107    /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
6108    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
6109    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
6110    /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
6111    /// sibling per-`:entrada` scalar-value + list-value axes — this
6112    /// accessor closes the last unlifted per-`:entrada` scalar axis
6113    /// (the destination-Servico byte-string) so every downstream
6114    /// per-`:entrada` reader now routes through a typed dispatch on
6115    /// the substrate primitive.
6116    #[must_use]
6117    pub const fn destination(&self) -> &str {
6118        self.para.as_str()
6119    }
6120
6121    /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
6122    /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
6123    /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
6124    /// reader keys off — returns the author-declared `:entrada :port`
6125    /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
6126    /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
6127    /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
6128    /// [`AplicacaoError::EntradaPortZero`], not a silent
6129    /// admission-webhook rejection at cluster-apply time).
6130    ///
6131    /// The `:entrada :port` slot carries the destination Servico's
6132    /// canonical in-cluster L4 listener port (`trigger.service.port` on
6133    /// the `pleme-computeunit` library chart), and every downstream
6134    /// consumer that reads the port keys off this scalar (the
6135    /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
6136    /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
6137    /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
6138    /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6139    /// CR materializer's per-Aplicacao gateway port resolver).
6140    ///
6141    /// Prior to this lift the `.port` field was accessed inline at two
6142    /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
6143    /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
6144    /// the [`AplicacaoSpec::port_for_destination`] resolver's
6145    /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
6146    /// open-coded field-accesses that expressed no compile-time link
6147    /// back to the typed slot. A future extension of the `:entrada :port`
6148    /// axis to a richer author surface — a per-cluster override the
6149    /// operator pins through a future `:placement :default-port` slot the
6150    /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
6151    /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
6152    /// heterogeneous listener ports, an M4
6153    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
6154    /// admission-webhook floor that promotes the scalar to a
6155    /// per-destination map — would have had to be threaded through both
6156    /// open-coded copies in lockstep or the structural-floor validator
6157    /// and the [`AplicacaoSpec::port_for_destination`] resolver would
6158    /// silently disagree on which port a given [`Entrada`] resolves to.
6159    /// Lifting the resolution rule to a typed method on the substrate
6160    /// primitive means every downstream consumer of the Aplicacao's
6161    /// per-`:entrada` L4-port surface reaches for exactly one typed
6162    /// dispatch — the resolver's accept-set migrates as a unit on any
6163    /// future axis addition.
6164    ///
6165    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
6166    /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
6167    /// accessors on the per-`:entrada` scalar-value axis — same "one
6168    /// typed dispatch on the substrate primitive, thin projections at
6169    /// each consumer" discipline extended onto the per-`:entrada`
6170    /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
6171    /// the M3 mesh-slot `Entrada` type — closes the last unlifted
6172    /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
6173    /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
6174    /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
6175    /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
6176    /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
6177    /// storage field's name; the accessor's identity name maps onto the
6178    /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
6179    /// already carries. Declared `pub const fn` (matching the peer M3
6180    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
6181    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
6182    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
6183    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
6184    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
6185    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
6186    /// [`RateLimit`], and the sibling per-`:placement`
6187    /// [`Placement::estrategia`] on the peer M3 mesh-slot `Copy`-composite-
6188    /// enum scalar axis — every one a `pub const fn`) so every future
6189    /// substrate-side `const`-context consumer of the resolved
6190    /// per-`:entrada` L4-port scalar (a `const _: () = assert!(…)`
6191    /// module-scope pin on a per-fixture typed [`Entrada`] anchoring
6192    /// `entrada.port() >= SERVICO_PORT_MIN` at compile time, a future M4
6193    /// admission-webhook `const fn` per-CR gateway-port floor over a
6194    /// typed [`Entrada`], any `const fn` composer that fans on the port
6195    /// at compile time) reaches through the same typed dispatch on the
6196    /// substrate primitive at const-eval time as at runtime. Pinned by
6197    /// [`entrada_port_accessor_is_const_fn`] which witnesses the
6198    /// const-eval posture at module scope via `const _:() = …` items so
6199    /// any future accidental downgrade to non-`const` trips at caixa-core
6200    /// build time.
6201    #[must_use]
6202    pub const fn port(&self) -> u16 {
6203        self.port
6204    }
6205
6206    /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
6207    /// slice accessor every HTTPRoute-aware renderer keys off when it
6208    /// wants the raw author-declared path-list (not the fallback-
6209    /// applied projection [`Self::resolved_paths`] returns) — returns
6210    /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
6211    /// borrowed from the typed slot's own [`Vec<String>`] storage.
6212    ///
6213    /// Named the "raw slot" half of the per-`:entrada` path-list resolver
6214    /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
6215    /// (1449891) closes the fallback-applying arm every per-Aplicacao
6216    /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
6217    /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
6218    /// catch-all; non-empty slot → per-entry verbatim projection); this
6219    /// accessor closes the raw-slot arm every consumer that must see the
6220    /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
6221    /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
6222    /// not `Err(EntradaPathEmpty)`, so it cannot route through the
6223    /// fallback-applying sibling; the `feira app graph` per-Aplicacao
6224    /// external-gateway summary line's `{:?}` Debug print — which must
6225    /// name the author's declaration, not the substrate's fallback, so
6226    /// an author reading their graph output can grep their caixa.lisp
6227    /// for the exact list they authored) routes through.
6228    ///
6229    /// Prior to this lift the `.paths` field was accessed inline at four
6230    /// production sites: the two internal reads in [`Self::resolved_paths`]
6231    /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
6232    /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
6233    /// value-shape gate's `for p in &e.paths` traversal head, and the
6234    /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
6235    /// Debug print — four open-coded field-accesses that expressed no
6236    /// compile-time link back to the typed slot. A future extension of
6237    /// the `:entrada :paths` axis to a richer author surface — a
6238    /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
6239    /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
6240    /// spec supports through `matches[].method`), a per-path per-header
6241    /// filter overlay (`matches[].headers[]`), a per-cluster override
6242    /// the operator pins through a future `:placement :path-overlay`
6243    /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6244    /// per-CR admission-webhook that normalized the list at admission
6245    /// time — would have had to be threaded through every open-coded
6246    /// copy in lockstep or the validator's per-entry gate would silently
6247    /// disagree with the renderer's per-entry emit on which list a given
6248    /// `:entrada` block resolves to. Lifting the resolution to a typed
6249    /// method on the substrate primitive means every downstream consumer
6250    /// of the Aplicacao's per-`:entrada` path-list surface reaches for
6251    /// exactly one typed dispatch — the resolver's accept-set migrates
6252    /// as a unit on any future axis addition.
6253    ///
6254    /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
6255    /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
6256    /// carry axis — same "one typed dispatch on the substrate primitive,
6257    /// thin projections at each consumer" discipline extended onto the
6258    /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
6259    /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
6260    /// carrier) so every downstream per-`:entrada` reader now routes
6261    /// through a typed dispatch on the substrate primitive. Returns
6262    /// `&[String]` (not `&Vec<String>`) because every downstream consumer
6263    /// treats the list as a read-only sequence — the slice-view is the
6264    /// narrowest borrow that supports every present + roadmapped consumer
6265    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
6266    /// `Vec`'s grow/push/reserve surface that no consumer of the typed
6267    /// view reaches for (the storage-side `Vec` remains reachable through
6268    /// the `pub paths` field for the mutation-carrying serde round-trip
6269    /// and per-test fixture-mutation paths).
6270    #[must_use]
6271    pub const fn paths(&self) -> &[String] {
6272        self.paths.as_slice()
6273    }
6274}
6275
6276/// Canonical default L4 port every typed Servico exposes on its
6277/// in-cluster K8s Service (the `trigger.service.port` axis the
6278/// `pleme-computeunit` library chart emits, the `:entrada :port` author
6279/// surface defaults to when the author omits the slot, and the
6280/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
6281/// `:entrada` block matches the per-`:contratos` destination Servico).
6282/// The single source of truth all three typed-port consumers reach for:
6283///
6284///   - [`Entrada::port`]'s serde default (via the
6285///     [`default_port`] helper this constant feeds); the author surface
6286///     `(:entrada (:host … :para …))` without an explicit `:port` slot
6287///     reads back as a typed [`Entrada`] carrying this exact value;
6288///   - the
6289///     [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
6290///     emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
6291///     fallback, fired when the typed `:entrada` block doesn't name
6292///     the per-`:contratos` destination Servico — the typed
6293///     `:contratos` graph carries no per-destination port axis (the
6294///     destination port is the destination Servico's
6295///     `lareira-<nome>` chart's `trigger.service.port`, which the
6296///     Aplicacao-level renderer has no visibility into without a
6297///     resolver round-trip), so the renderer falls back to the
6298///     substrate's canonical Servico-port assumption — by
6299///     construction the same value the destination's own
6300///     `pleme-computeunit` chart emits, the same value the
6301///     destination's own typed `:entrada :port` slot defaults to;
6302///   - every future per-Servico renderer the absorption-roadmap
6303///     acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6304///     CR materializer's per-edge port resolver, the future
6305///     per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
6306///     emitter's per-route bucket key, the future caixa-otel
6307///     collector-pipeline emitter's per-Servico scrape port).
6308///
6309/// Until this lift landed the value `8080` lived at two production-code
6310/// call-sites: the [`default_port`] helper at
6311/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
6312/// and the `.unwrap_or(8080)` literal at
6313/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
6314/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
6315/// resolver). A future Servico-port rebrand — the substrate moving the
6316/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
6317/// gateway grows direct `:80` listeners, to `8443` once the substrate
6318/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
6319/// override the operator pins through a future
6320/// `:placement :default-port` slot — without a coordinated edit on
6321/// both sides would silently emit Servicos listening on one port and
6322/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
6323/// The CNP's apply-time symptom (the policy is admitted but every L4
6324/// flow on the destination Servico's actual port silently drops because
6325/// it doesn't match the whitelisted port) is far from the rebrand
6326/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
6327/// in hubble traces, not in `kubectl describe`. Lifting the literal to
6328/// a shared constant closes the drift footgun structurally — both
6329/// consumers read from the same `u16`, so any rebrand reaches both
6330/// sites by construction.
6331///
6332/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
6333/// per-renderer canonical-K8s-axis constant — the namespace string
6334/// and the canonical Servico port both lived as duplicated literals
6335/// across caixa-core / caixa-mesh / caixa-flux before their respective
6336/// lifts. Same "the typed constant lives in one place" discipline the
6337/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
6338/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
6339/// shared-string axes.
6340///
6341/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
6342pub const DEFAULT_SERVICO_PORT: u16 = 8080;
6343
6344/// Structural floor for the typed `:entrada :port` axis — every
6345/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
6346/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
6347///
6348/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
6349/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
6350/// interprets as "let the kernel pick a free port at bind time", not a
6351/// well-defined destination the substrate's per-`:entrada` Gateway API
6352/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
6353/// carrying `port: 0` degenerates to a nominal-only routing target: the
6354/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
6355/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
6356/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
6357/// at build time rather than at `kubectl apply` time), and the
6358/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
6359/// (caixa-mesh/src/lib.rs:2657 through
6360/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
6361/// [`Entrada::port`] typed value — silently emits a policy whose
6362/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
6363/// actual listener, dropping every L4 flow at the eBPF data plane far
6364/// from the source caixa.lisp with no field naming the port-zero-drift
6365/// root cause.
6366///
6367/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
6368/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
6369/// on the top edge (unlike the peer capped-`u32` `:politicas` /
6370/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
6371/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
6372/// well below `u32::MAX` and therefore need explicit typed caps).
6373///
6374/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
6375/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
6376/// scalar every `(:entrada (:host … :para …))` slot without an explicit
6377/// `:port` inherits through the serde default hook; this constant names
6378/// the accept-set floor every declared port must satisfy. The pair is
6379/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
6380/// substrate's default must satisfy its own accept-set floor by
6381/// construction) — a future rebrand that accidentally moved
6382/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
6383/// negative-cast typo, a per-cluster override the operator pins through
6384/// a future `:placement :default-port` slot that lands out-of-range)
6385/// would silently invalidate the serde-default emission at every
6386/// author-side `(:entrada (:host … :para …))` slot — the compile-time
6387/// invariant pin
6388/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
6389/// closes the drift footgun at caixa-core build time.
6390///
6391/// Lifted as a typed `pub const` (rather than an inline `0` literal at
6392/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
6393/// has exactly one source of truth — the future M4
6394/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
6395/// gateway resolver, the future per-Servico
6396/// `computeunit.trigger.service.port` renderer's per-CR port-value
6397/// validator, and every downstream test-fixture navigator asserting
6398/// the accept-set floor all read from one place. Same shape every
6399/// other typed bracket-floor / bracket-ceiling in this crate carries
6400/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
6401/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
6402/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
6403/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
6404/// [`POLICY_RATE_LIMIT_MAX`]).
6405pub const SERVICO_PORT_MIN: u16 = 1;
6406
6407const fn default_port() -> u16 {
6408    DEFAULT_SERVICO_PORT
6409}
6410
6411// ── the typed view ───────────────────────────────────────────────────
6412
6413/// Typed composition view of the flat Aplicacao slots on
6414/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
6415/// validation + downstream renderer consumption.
6416#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
6417#[serde(rename_all = "camelCase")]
6418pub struct AplicacaoSpec {
6419    pub membros: Vec<Membro>,
6420    pub contratos: Vec<WitContract>,
6421    pub politicas: MeshPolicy,
6422    pub placement: Placement,
6423    pub entrada: Option<Entrada>,
6424}
6425
6426impl AplicacaoSpec {
6427    /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
6428    /// per-Aplicacao member-list slice-return accessor every
6429    /// per-Aplicacao member-list reader keys off — returns the author-
6430    /// declared `:membros` list verbatim as a `&[Membro]` slice-view
6431    /// over the same backing buffer the raw `self.membros.as_slice()`
6432    /// field access borrows from.
6433    ///
6434    /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
6435    /// member list — the load-bearing identity of the application graph
6436    /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
6437    /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
6438    /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
6439    /// accessor) with a `:versao` semver-requirement string (through
6440    /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
6441    /// and every downstream consumer that fans on the member-set keys
6442    /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
6443    /// membership-lookup `HashSet<&str>` seed's collect input, the
6444    /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
6445    /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
6446    /// per-member DNS-1123 / semver-requirement / duplicate-detection
6447    /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
6448    /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
6449    /// programs.yaml per-`:membros` fan-out emitter's per-entry
6450    /// mapping-composition loop, the `feira app graph` per-Aplicacao
6451    /// member-count print line and per-member tree traversal,
6452    /// every future wasm-operator (M4) per-Aplicacao CR materializer's
6453    /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
6454    /// placement engine's per-member weight-topology reader).
6455    ///
6456    /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
6457    /// inline at six production sites — the [`AplicacaoSpec::validate`]
6458    /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
6459    /// [`AplicacaoSpec::validate_membros`]'s pre-flight
6460    /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
6461    /// probe, the same method's per-member `for m in &self.membros`
6462    /// validate-loop traversal head, the
6463    /// [`AplicacaoSpec::detect_sync_cycles`]'s
6464    /// `for m in &self.membros` adjacency-list seed, the
6465    /// [`caixa_mesh::programs_for_aplicacao`] emitter's
6466    /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
6467    /// paired with the peer `for m in &spec.membros` per-entry fan-out
6468    /// loop, and the `feira app graph` per-Aplicacao print line's
6469    /// `spec.membros.len()` count formatter argument paired with the
6470    /// peer `for m in &spec.membros` per-member tree traversal — six
6471    /// open-coded field-accesses that expressed no compile-time link
6472    /// back to the typed slot. A future extension of the `:membros`
6473    /// axis to a richer author surface (a per-cluster member-set
6474    /// overlay the operator pins through a future
6475    /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
6476    /// roadmap acknowledges, a per-tenant member-alias table the M4
6477    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
6478    /// CR at admission time, a per-Aplicacao dynamic member-set
6479    /// derivation the future adaptive-placement engine computes from
6480    /// weighted membership topology, a promotion of the plain
6481    /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
6482    /// Orleans-style virtual-actor dynamic-membership comes into typed
6483    /// scope) would have had to be threaded through all six open-coded
6484    /// copies in lockstep or one consumer would silently disagree with
6485    /// the peers on which member-set a given Aplicacao resolves to —
6486    /// the `HashSet<&str>` name-set seed reading the raw slot while
6487    /// the peer `.is_empty()` refusal probe read an operator-resolved
6488    /// slot would silently split the `:contratos` membership-lookup
6489    /// input from the pre-flight-refusal input, a six-consumer split
6490    /// at the validator + programs.yaml emitter + graph printer far
6491    /// from the source `caixa.lisp` with no field naming the member-
6492    /// set-drift root cause. Lifting the resolution rule to a typed
6493    /// method on the substrate primitive means every downstream
6494    /// consumer of the Aplicacao's per-`:membros` member-list surface
6495    /// reaches for exactly one typed dispatch — the resolver's accept-
6496    /// set migrates as a unit on any future axis addition.
6497    ///
6498    /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
6499    /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
6500    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
6501    /// static-child-list `Vec`-carry axis, and to the M3
6502    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
6503    /// on the peer per-`:placement` distribution-target-list `Vec`-
6504    /// carry axis. Same "one typed dispatch on the substrate primitive,
6505    /// thin projections at each consumer" discipline. The two peer
6506    /// `Vec`-carry axes still unlifted at the time of this lift —
6507    /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
6508    /// WIT-typed edge list) and
6509    /// [`crate::UpgradeFromEntry::instructions`]
6510    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
6511    /// — inherit this accessor's discipline as future compounding runs
6512    /// migrate their consumers onto the shared slice-return shape.
6513    /// First `&[T]`-return accessor on the top-level M3 mesh-slot
6514    /// `AplicacaoSpec` type itself, extending the discipline beyond
6515    /// the inner per-slot types ([`crate::Placement`],
6516    /// [`crate::SupervisorSpec`]) onto the outermost typed composition
6517    /// view every renderer consumes. Named `membros()` to match the
6518    /// storage field's name verbatim and the tatara-lisp author-
6519    /// surface term (`:membros`) the field's own docstring already
6520    /// carries; the accessor's identity maps onto the canonical
6521    /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
6522    /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
6523    /// every downstream consumer of the member list treats it as a
6524    /// read-only sequence — the slice-view is the narrowest borrow
6525    /// that supports every present + roadmapped consumer
6526    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
6527    /// backing `Vec`'s grow/push/reserve surface that no consumer of
6528    /// the typed view reaches for (the storage-side `Vec` remains
6529    /// reachable through the `pub membros` field for the mutation-
6530    /// carrying serde round-trip and per-test fixture-mutation paths).
6531    #[must_use]
6532    pub const fn membros(&self) -> &[Membro] {
6533        self.membros.as_slice()
6534    }
6535
6536    /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
6537    /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
6538    /// accessor every per-Aplicacao contract-list reader keys off —
6539    /// returns the author-declared `:contratos` list verbatim as a
6540    /// `&[WitContract]` slice-view over the same backing buffer the raw
6541    /// `self.contratos.as_slice()` field access borrows from.
6542    ///
6543    /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
6544    /// WIT-typed edge list — the load-bearing set of directed edges
6545    /// on the application graph whose nodes are the `:membros` entries
6546    /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
6547    /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
6548    /// six-tuple is the edge identity every downstream duplicate gate
6549    /// keys off). Every per-`:contratos` entry pairs a `:de` source-
6550    /// Servico caller name + a `:para` destination-Servico callee name
6551    /// (through the lifted [`WitContract::source`] +
6552    /// [`WitContract::destination`] (7f0fd43) accessor pair on the
6553    /// caller/callee-Servico axis) with a `:wit` world-reference
6554    /// (through the lifted [`WitContract::world_ref`] (0804823)
6555    /// accessor) and the target-shape-appropriate payload-carrier
6556    /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
6557    /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
6558    /// (ed22b66) accessor on the per-target-shape payload-carrier
6559    /// axis). Every downstream consumer that fans on the edge-set
6560    /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
6561    /// name-set / self-edge / target-shape / dedup fan-out loop, the
6562    /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
6563    /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
6564    /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
6565    /// grouping loop, the `feira app graph` per-Aplicacao contract-
6566    /// count print line and per-contract tree traversal, every future
6567    /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
6568    /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
6569    /// mesh-policy overlay resolver's per-contract typed-edge weight
6570    /// reader).
6571    ///
6572    /// Prior to this lift the `.contratos` `Vec<WitContract>` was
6573    /// accessed inline at four production sites — the
6574    /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
6575    /// per-edge validate-loop traversal head (which drives every
6576    /// per-edge name-set membership lookup, self-edge check,
6577    /// target-shape dispatch, and dedup `HashSet` insert), the
6578    /// [`AplicacaoSpec::detect_sync_cycles`]'s
6579    /// `for c in &self.contratos` adjacency-list seed head (which
6580    /// drives every per-edge sync-vs-pub-sub partition and per-edge
6581    /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
6582    /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
6583    /// `BTreeMap` grouping loop head (which drives every per-CNP
6584    /// fan-out emit), and the `feira app graph` per-Aplicacao print
6585    /// line's `spec.contratos.len()` count formatter argument paired
6586    /// with the peer `for c in &spec.contratos` per-contract tree
6587    /// traversal — four open-coded field-accesses that expressed no
6588    /// compile-time link back to the typed slot. A future extension
6589    /// of the `:contratos` axis to a richer author surface (a
6590    /// per-cluster contract overlay the operator pins through a
6591    /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
6592    /// federation roadmap acknowledges, a per-tenant edge-policy
6593    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
6594    /// materializer resolves per-CR at admission time, a per-edge
6595    /// weight scalar the future adaptive-placement engine reads to
6596    /// bias sync-subgraph routing, a promotion of the plain
6597    /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
6598    /// once virtual-actor-style dynamic-edge composition comes into
6599    /// typed scope) would have had to be threaded through all four
6600    /// open-coded copies in lockstep or one consumer would silently
6601    /// disagree with the peers on which edge-set a given Aplicacao
6602    /// resolves to — the validator's per-edge dedup `HashSet` seed
6603    /// reading the raw slot while the peer sync-cycle adjacency-list
6604    /// seed read an operator-resolved slot would silently split the
6605    /// build-time edge-set gate from the runtime deadlock-detection
6606    /// gate, a four-consumer split at the validator, the cycle
6607    /// detector, the CNP emitter, and the graph printer far from
6608    /// the source `caixa.lisp` with no field naming the edge-set-
6609    /// drift root cause. Lifting the resolution rule to a typed method on the
6610    /// substrate primitive means every downstream consumer of the
6611    /// Aplicacao's per-`:contratos` edge-list surface reaches for
6612    /// exactly one typed dispatch — the resolver's accept-set
6613    /// migrates as a unit on any future axis addition.
6614    ///
6615    /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
6616    /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
6617    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
6618    /// static-child-list `Vec`-carry axis, to the M3
6619    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
6620    /// on the peer per-`:placement` distribution-target-list `Vec`-
6621    /// carry axis, and to the immediately-adjacent sibling M3
6622    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
6623    /// the peer per-`:membros` node-list `Vec`-carry axis — the
6624    /// per-`:contratos` edge-list accessor is the natural pair of
6625    /// the per-`:membros` node-list accessor (graph edges over graph
6626    /// nodes; every graph-shaped consumer reads both). Same "one
6627    /// typed dispatch on the substrate primitive, thin projections
6628    /// at each consumer" discipline. The last remaining `Vec`-carry
6629    /// axis still unlifted at the time of this lift —
6630    /// [`crate::UpgradeFromEntry::instructions`]
6631    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
6632    /// list) — inherits this accessor's discipline as future
6633    /// compounding runs migrate its consumers onto the shared slice-
6634    /// return shape. Second `&[T]`-return accessor on the top-level
6635    /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
6636    /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
6637    /// `:contratos` are the two `Vec` fields on the outer typed
6638    /// composition view — `:politicas`, `:placement`, `:entrada` are
6639    /// scalar/option-shaped and already route through their per-slot
6640    /// accessor families). Named `contratos()` to match the storage
6641    /// field's name verbatim and the tatara-lisp author-surface term
6642    /// (`:contratos`) the field's own docstring already carries; the
6643    /// accessor's identity maps onto the canonical MESH-COMPOSITION
6644    /// §III.1 vocabulary the slot's docstring already reaches for.
6645    /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
6646    /// every downstream consumer of the contract list treats it as a
6647    /// read-only sequence — the slice-view is the narrowest borrow
6648    /// that supports every present + roadmapped consumer
6649    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
6650    /// backing `Vec`'s grow/push/reserve surface that no consumer of
6651    /// the typed view reaches for (the storage-side `Vec` remains
6652    /// reachable through the `pub contratos` field for the mutation-
6653    /// carrying serde round-trip and per-test fixture-mutation paths).
6654    #[must_use]
6655    pub const fn contratos(&self) -> &[WitContract] {
6656        self.contratos.as_slice()
6657    }
6658
6659    /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
6660    /// per-Aplicacao mesh-policy composite-reference accessor every
6661    /// per-Aplicacao policy-block reader keys off — returns the author-
6662    /// declared `:politicas` composite verbatim as a `&MeshPolicy`
6663    /// reference over the same backing storage the raw `&self.politicas`
6664    /// field access borrows from.
6665    ///
6666    /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
6667    /// mesh-policy composite — the load-bearing container of every
6668    /// mesh-level operational-policy axis every downstream mesh-artifact
6669    /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
6670    /// mesh-policy overlay is the single typed surface a
6671    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
6672    /// from). Every per-`:politicas` axis threads through a lifted
6673    /// per-slot accessor on the [`MeshPolicy`] type: the
6674    /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
6675    /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
6676    /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
6677    /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
6678    /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
6679    /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
6680    /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
6681    /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
6682    /// accessor. Every downstream consumer that reaches for a policy
6683    /// axis first passes through this outer accessor onto the composite
6684    /// and then dispatches onto the per-axis accessor — the two-level
6685    /// dispatch means every per-`:politicas` reader now routes through
6686    /// a typed dispatch on the substrate primitive at both altitudes.
6687    ///
6688    /// Prior to this lift the `.politicas` `MeshPolicy` composite was
6689    /// accessed inline at four production sites — the
6690    /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
6691    /// &self.politicas;` traversal seed (which drives every per-axis
6692    /// zero-floor + upper-cap + canonical-form bracket dispatch through
6693    /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
6694    /// `p.rate_limit()` on the axis-level lifted accessors), the
6695    /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
6696    /// emitter's `spec.politicas.mtls_required()` field-then-accessor
6697    /// chain (which drives every per-`(:de, :para)` CNP
6698    /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
6699    /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
6700    /// timeout + retry overlay emitter's paired
6701    /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
6702    /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
6703    /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
6704    /// open-coded outer-field accesses that expressed no compile-time
6705    /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
6706    /// future extension of the `:politicas` outer axis to a richer
6707    /// author surface (a per-cluster policy overlay the operator pins
6708    /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
6709    /// §V federation roadmap acknowledges, a per-tenant policy-alias
6710    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
6711    /// resolves per-CR at admission time, a per-Aplicacao dynamic
6712    /// policy-composite derivation the future adaptive-placement engine
6713    /// computes from a per-cluster load-topology reader, a promotion of
6714    /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
6715    /// partition once virtual-actor-style dynamic-mesh-policy
6716    /// composition comes into typed scope) would have had to be threaded
6717    /// through all four open-coded copies in lockstep or one consumer
6718    /// would silently disagree with the peers on which mesh-policy
6719    /// composite a given Aplicacao resolves to — the validator's
6720    /// per-axis bracket-dispatch seed reading the raw slot while the
6721    /// peer CNP mTLS-overlay emitter read an operator-resolved slot
6722    /// would silently split the build-time policy-shape gate from the
6723    /// runtime CNP-emission gate, a four-consumer split at the
6724    /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
6725    /// the source `caixa.lisp` with no field naming the policy-drift
6726    /// root cause. Lifting the resolution rule to a typed method on the
6727    /// substrate primitive means every downstream consumer of the
6728    /// Aplicacao's per-`:politicas` mesh-policy composite surface
6729    /// reaches for exactly one typed dispatch — the resolver's accept-
6730    /// set migrates as a unit on any future axis addition.
6731    ///
6732    /// First `&Composite`-return accessor on the top-level M3 mesh-slot
6733    /// `AplicacaoSpec` type itself — sibling to the seed slice-return
6734    /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
6735    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
6736    /// close the two `Vec`-carry axes on the outer typed composition
6737    /// view; the outer `:politicas` composite-reference axis is the
6738    /// natural pair to the paired outer `Vec`-carry accessors on the
6739    /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
6740    /// emitter reads all four axes as one unit (graph nodes + graph
6741    /// edges + mesh policy + placement pool). Peer to the same
6742    /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
6743    /// slot: every M2 `SupervisorSpec`-scoped composite reader
6744    /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
6745    /// `restart_window`, `children`) already routes through the M2
6746    /// `SupervisorSpec` accessor family — this lift extends the same
6747    /// "one typed dispatch on the substrate primitive at the outer
6748    /// composition altitude" discipline to the M3 mesh-slot
6749    /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
6750    /// remaining peer outer-composite axes still unlifted at the time
6751    /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
6752    /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
6753    /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
6754    /// inherit this accessor's discipline as future compounding runs
6755    /// migrate their consumers onto the shared reference-return shape.
6756    /// Named `politicas()` to match the storage field's name verbatim
6757    /// and the tatara-lisp author-surface term (`:politicas`) the
6758    /// field's own docstring already carries; the accessor's identity
6759    /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
6760    /// slot's docstring already reaches for. Returns `&MeshPolicy`
6761    /// (not the owning composite by copy or clone) because every
6762    /// downstream consumer of the mesh-policy composite treats it as a
6763    /// read-only per-axis dispatch source — the reference-view is the
6764    /// narrowest borrow that supports every present + roadmapped
6765    /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
6766    /// emptiness probe) without cloning the composite through every
6767    /// consumer's fast path.
6768    #[must_use]
6769    pub const fn politicas(&self) -> &MeshPolicy {
6770        &self.politicas
6771    }
6772
6773    /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
6774    /// per-Aplicacao distribution-composite composite-reference accessor
6775    /// every per-Aplicacao placement-block reader keys off — returns the
6776    /// author-declared `:placement` composite verbatim as a `&Placement`
6777    /// reference over the same backing storage the raw `&self.placement`
6778    /// field access borrows from.
6779    ///
6780    /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
6781    /// distribution composite — the load-bearing container of every
6782    /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
6783    /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
6784    /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
6785    /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
6786    /// hosting-pool identity, §V for the `M3-Adaptive`-compression
6787    /// `:affinity` hint). Every per-`:placement` axis threads through a
6788    /// lifted per-slot accessor on the [`Placement`] type: the
6789    /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
6790    /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
6791    /// per-cluster distribution-target slice-return accessor, the
6792    /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
6793    /// optional-scalar accessor, and the [`Placement::shard_key`]
6794    /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
6795    /// downstream consumer that reaches for a placement axis first passes
6796    /// through this outer accessor onto the composite and then dispatches
6797    /// onto the per-axis accessor — the two-level dispatch means every
6798    /// per-`:placement` reader now routes through a typed dispatch on the
6799    /// substrate primitive at both altitudes.
6800    ///
6801    /// Prior to this lift the `.placement` `Placement` composite was
6802    /// accessed inline at three production sites — the
6803    /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
6804    /// seed (six `self.placement.<axis>()` field-then-inner-accessor
6805    /// chains: the pre-flight `.clusters().is_empty()` refusal probe
6806    /// paired with the `.estrategia()` diagnostic-carry copy, the per-
6807    /// cluster `.clusters()` validate-loop traversal head, the per-
6808    /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
6809    /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
6810    /// paired with the shape-gate cascade's `.shard_key()` /
6811    /// `.estrategia()` diagnostic-carry pair), the
6812    /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
6813    /// per-entry placement-block emitter's outer
6814    /// `serde_yaml::to_value(&spec.placement)` composite-serialization
6815    /// seed (which fans onto every per-cluster `programs[]` entry as a
6816    /// self-describing distribution overlay the aggregator filters by),
6817    /// and the `feira app graph` per-Aplicacao print line's paired
6818    /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
6819    /// then-inner-accessor chains (which drive the human-readable
6820    /// distribution summary of the typed Aplicacao view) — three open-
6821    /// coded outer-field accesses that expressed no compile-time link
6822    /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
6823    /// extension of the `:placement` outer axis to a richer author surface
6824    /// (a per-cluster placement overlay the operator pins through a
6825    /// future `:placement-overrides` slot the MESH-COMPOSITION §V
6826    /// federation roadmap acknowledges, a per-tenant placement-alias
6827    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
6828    /// resolves per-CR at admission time, a per-Aplicacao dynamic
6829    /// placement-composite derivation the future M5 adaptive-placement
6830    /// engine computes from a per-cluster load-topology reader, a
6831    /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
6832    /// partition once Orleans-style virtual-actor dynamic-placement comes
6833    /// into typed scope) would have had to be threaded through all three
6834    /// open-coded copies in lockstep or one consumer would silently
6835    /// disagree with the peers on which placement composite a given
6836    /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
6837    /// seed reading the raw slot while the peer
6838    /// `programs_for_aplicacao` emitter read an operator-resolved slot
6839    /// would silently split the build-time distribution-shape gate from
6840    /// the runtime programs.yaml distribution-annotation gate, a three-
6841    /// consumer split at the validator, the programs.yaml emitter, and
6842    /// the `feira app graph` printer far from the source `caixa.lisp`
6843    /// with no field naming the placement-drift root cause. Lifting the
6844    /// resolution rule to a typed method on the substrate primitive
6845    /// means every downstream consumer of the Aplicacao's per-
6846    /// `:placement` distribution composite surface reaches for exactly
6847    /// one typed dispatch — the resolver's accept-set migrates as a unit
6848    /// on any future axis addition.
6849    ///
6850    /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
6851    /// `AplicacaoSpec` type itself — sibling to the seed
6852    /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
6853    /// composite-reference accessor on the peer per-`:politicas` outer-
6854    /// composite axis, and to the paired slice-return accessors
6855    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
6856    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
6857    /// the two `Vec`-carry axes on the outer typed composition view; the
6858    /// outer `:placement` composite-reference axis is the natural pair
6859    /// to the peer `:politicas` composite-reference axis on the two
6860    /// operationally-symmetric M3 mesh slots (`:politicas` carries the
6861    /// how-to-run policy overlay, `:placement` carries the where-to-run
6862    /// distribution composite — every whole-Aplicacao mesh-artifact
6863    /// emitter reads both as one unit). Same "one typed dispatch on the
6864    /// substrate primitive, thin projections at each consumer"
6865    /// discipline the peer per-`:politicas` composite-reference axis
6866    /// already routes through. The one remaining outer-composite axis
6867    /// still unlifted at the time of this lift —
6868    /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
6869    /// external-gateway composite) — inherits this accessor's discipline
6870    /// as the next compounding run migrates its consumers onto the shared
6871    /// reference-return shape, closing the outer-composite altitude on
6872    /// every M3 mesh-slot axis. Named `placement()` to match the storage
6873    /// field's name verbatim and the tatara-lisp author-surface term
6874    /// (`:placement`) the field's own docstring already carries; the
6875    /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
6876    /// vocabulary the slot's docstring already reaches for. Returns
6877    /// `&Placement` (not the owning composite by copy or clone) because
6878    /// every downstream consumer of the placement composite treats it as
6879    /// a read-only per-axis dispatch source — the reference-view is the
6880    /// narrowest borrow that supports every present + roadmapped consumer
6881    /// (per-axis accessor dispatch, serde composite-serialization) without
6882    /// cloning the composite through every consumer's fast path.
6883    #[must_use]
6884    pub const fn placement(&self) -> &Placement {
6885        &self.placement
6886    }
6887
6888    /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
6889    /// per-Aplicacao external-gateway composite optional-composite-
6890    /// reference accessor every per-Aplicacao gateway-block reader
6891    /// keys off — returns the author-declared `:entrada` composite
6892    /// verbatim as an `Option<&Entrada>` reference over the same
6893    /// backing storage the raw `self.entrada.as_ref()` field access
6894    /// borrows from, with `None` naming the internal-only mesh shape
6895    /// (the author-omitted `:entrada` slot the K8s Gateway API v1
6896    /// gateway_routes emitter treats as "emit nothing" and the peer
6897    /// `feira app graph` printer treats as "internal-only mesh").
6898    ///
6899    /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
6900    /// external-gateway composite — the load-bearing container of
6901    /// every does-this-Aplicacao-expose-a-public-endpoint axis every
6902    /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
6903    /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
6904    /// hostname axis, §III.4 for the `:para` destination-Servico
6905    /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
6906    /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
6907    /// axis threads through a lifted per-slot accessor on the
6908    /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
6909    /// Gateway-API `Listener.hostname` scalar accessor, the paired
6910    /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
6911    /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
6912    /// backendRefs destination-Servico scalar accessor, the
6913    /// [`Entrada::resolved_paths`] path-fallback resolver, and the
6914    /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
6915    /// scalar accessor. Every downstream consumer that reaches for
6916    /// an entrada axis first passes through this outer accessor onto
6917    /// the composite and then dispatches onto the per-axis accessor
6918    /// — the two-level dispatch means every per-`:entrada` reader
6919    /// now routes through a typed dispatch on the substrate primitive
6920    /// at both altitudes.
6921    ///
6922    /// Prior to this lift the `.entrada` `Option<Entrada>` composite
6923    /// was accessed inline at four production sites — the
6924    /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
6925    /// gate's `if let Some(e) = &self.entrada { … }` traversal head
6926    /// (which drives every per-axis refusal on the composite: the
6927    /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
6928    /// `EntradaMemberMissing` membership lookup against the
6929    /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
6930    /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
6931    /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
6932    /// per-path shape gate on each entry of `e.paths`), the
6933    /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
6934    /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
6935    /// composite-projection seed (which drives the destination-
6936    /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
6937    /// backendRefs port emitter fans on), the
6938    /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
6939    /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
6940    /// early-return seed (which drives the "no `:entrada` ⇒ no
6941    /// external artifacts" partition on the whole-Aplicacao Gateway-
6942    /// API emitter's fan-out), and the `feira app graph` per-
6943    /// Aplicacao print line's `if let Some(e) = &spec.entrada`
6944    /// external-gateway summary emitter (which drives the human-
6945    /// readable `entrada: host → para (paths=…, port=…)` /
6946    /// `entrada: (internal-only mesh)` partition on the typed
6947    /// Aplicacao view) — four open-coded outer-field accesses that
6948    /// expressed no compile-time link back to the typed slot at the
6949    /// [`AplicacaoSpec`] altitude. A future extension of the
6950    /// `:entrada` outer axis to a richer author surface (a
6951    /// multi-`:entrada` list the M4 CR materializer resolves per-CR
6952    /// at admission time so an Aplicacao can expose a public-web +
6953    /// admin-web pair, a per-cluster `:entrada-overrides` slot the
6954    /// MESH-COMPOSITION §V federation roadmap acknowledges so an
6955    /// operator can pin a per-cluster hostname override without
6956    /// re-authoring the `caixa.lisp`, a promotion of the plain
6957    /// `Option<Entrada>` to a richer `{single, multi}` partition once
6958    /// the multi-`:entrada` roadmap lands) would have had to be
6959    /// threaded through all four open-coded copies in lockstep or one
6960    /// consumer would silently disagree with the peers on which
6961    /// entrada composite a given Aplicacao resolves to — the
6962    /// validator's per-axis bracket-dispatch seed reading the raw
6963    /// slot while the peer `gateway_routes` emitter read an
6964    /// operator-resolved slot would silently split the build-time
6965    /// gateway-shape gate from the runtime Gateway + HTTPRoute
6966    /// emission gate, a four-consumer split at the validator, the
6967    /// `port_for_destination` L4-port resolver, the `gateway_routes`
6968    /// emitter, and the `feira app graph` printer far from the
6969    /// source `caixa.lisp` with no field naming the entrada-drift
6970    /// root cause. Lifting the resolution rule to a typed method on
6971    /// the substrate primitive means every downstream consumer of
6972    /// the Aplicacao's per-`:entrada` external-gateway composite
6973    /// surface reaches for exactly one typed dispatch — the
6974    /// resolver's accept-set migrates as a unit on any future axis
6975    /// addition.
6976    ///
6977    /// Third and final `&Composite`-return accessor on the top-level
6978    /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
6979    /// unlifted outer-composite axis on the outer typed composition
6980    /// view, sibling to the seed [`AplicacaoSpec::politicas`]
6981    /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
6982    /// accessor on the per-`:politicas` outer-composite axis and to
6983    /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
6984    /// distribution-composite composite-reference accessor on the
6985    /// per-`:placement` outer-composite axis; extends the outer-
6986    /// composite reference-return discipline the two peers already
6987    /// route through onto the last unlifted per-`AplicacaoSpec`
6988    /// outer-composite axis. The `:entrada` outer-composite axis is
6989    /// the natural pair to the two peer outer-composite axes on the
6990    /// three operationally-symmetric M3 mesh-slot outer composites
6991    /// (`:politicas` carries the how-to-run policy overlay,
6992    /// `:placement` carries the where-to-run distribution composite,
6993    /// `:entrada` carries the who-can-reach-it external-gateway
6994    /// composite — every whole-Aplicacao mesh-artifact emitter reads
6995    /// all three as one unit). Same "one typed dispatch on the
6996    /// substrate primitive, thin projections at each consumer"
6997    /// discipline the peer outer-composite axes already route through.
6998    /// Named `entrada()` to match the storage field's name verbatim
6999    /// and the tatara-lisp author-surface term (`:entrada`) the
7000    /// field's own docstring already carries; the accessor's
7001    /// identity maps onto the canonical MESH-COMPOSITION §III.4
7002    /// vocabulary the slot's docstring already reaches for. Returns
7003    /// `Option<&Entrada>` (not the owning composite by copy or
7004    /// clone) because every downstream consumer of the entrada
7005    /// composite treats it as a read-only per-axis dispatch source
7006    /// — the reference-view is the narrowest borrow that supports
7007    /// every present + roadmapped consumer (per-axis accessor
7008    /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
7009    /// port-fallback projection, early-return partition on the
7010    /// `None` arm) without cloning the composite through every
7011    /// consumer's fast path. The `Option` half of the return-type
7012    /// preserves the load-bearing "author-omitted `:entrada` ⇒
7013    /// internal-only mesh" partition (not a default composite the
7014    /// downstream must reject on emptiness) — the accessor projects
7015    /// the raw `Option<Entrada>` slot's presence bit through the
7016    /// reference-return unchanged.
7017    #[must_use]
7018    pub const fn entrada(&self) -> Option<&Entrada> {
7019        self.entrada.as_ref()
7020    }
7021
7022    /// Validate the typed shape:
7023    ///   - `:membros` is non-empty; every entry has a non-empty `:caixa`
7024    ///     and a non-empty `:versao`; no two entries share the same
7025    ///     `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
7026    ///     not a multiset)
7027    ///   - every `:contratos` :de + :para must be in `:membros`
7028    ///   - no `:contratos` edge is a self-edge (`:de == :para`) — a
7029    ///     contract is an inter-Servico edge, so a Servico contracting
7030    ///     with itself is a build error under every WIT shape
7031    ///     (MESH-COMPOSITION §III.1)
7032    ///   - no two `:contratos` entries agree on
7033    ///     `(de, para, wit, endpoint, subject, slot)` — the typed-graph
7034    ///     edges are a set, not a multiset (peer of the `:membros` /
7035    ///     `:placement :clusters` / `:entrada :paths` duplicate gates)
7036    ///   - `:entrada :para` must be in `:membros`
7037    ///   - `:placement Sharded` must declare `:shard-key` (non-empty);
7038    ///     `:placement Replicated`/`SingleNode` must NOT declare
7039    ///     `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
7040    ///     consumes it (MESH-COMPOSITION §II.4), and the typed partition
7041    ///     between strategy and shard-key is symmetric: every validated
7042    ///     `Placement` has `shard_key.is_some()` iff `estrategia ==
7043    ///     Sharded`
7044    ///   - every `:placement` strategy must declare ≥1 `:clusters` entry —
7045    ///     `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
7046    ///     the shard pool (MESH-COMPOSITION §III.1)
7047    ///   - every `:clusters` entry is non-empty and unique
7048    ///   - `:placement :affinity`, when set, is non-empty
7049    ///   - the synchronous-`:contratos` subgraph is acyclic
7050    ///     (MESH-COMPOSITION §III.3)
7051    ///   - every declared `:politicas` value is operationally meaningful
7052    ///     (zero timeout, zero retries, zero breaker thresholds, zero rate
7053    ///     limit are all build errors — MESH-COMPOSITION §V CSE invariants;
7054    ///     omit the field instead to express "no policy on this axis")
7055    pub fn validate(&self) -> Result<(), AplicacaoError> {
7056        self.validate_membros()?;
7057        let names: std::collections::HashSet<&str> =
7058            self.membros().iter().map(Membro::nome).collect();
7059
7060        // Identity key for the typed-edge duplicate gate below: every
7061        // field that distinguishes one contract from another. Two
7062        // entries that agree on all six are *the same edge declared
7063        // twice*, the typed-graph analogue of duplicate `:membros` /
7064        // `:placement :clusters` / `:entrada :paths` entries (which
7065        // are already build errors at this layer). Rejecting it at the
7066        // validate gate closes a renderer-side footgun: caixa-mesh's
7067        // `cilium_network_policies` keys each emitted policy by
7068        // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
7069        // (de, para) and identical payload would land as two K8s
7070        // objects with colliding `metadata.name`, rejected at apply
7071        // time far from the source caixa.lisp.
7072        let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
7073            std::collections::HashSet::new();
7074        for c in self.contratos() {
7075            // Per-axis value-shape gate on every `:contratos` name
7076            // reference, before any graph-membership lookup. Empty +
7077            // DNS-1123-malformed `:de`/`:para` values silently fell
7078            // through to `ContratoMemberMissing` at the lookup arm
7079            // because every `:membros :caixa` is shape-validated
7080            // (3f9d7a0), so the `names` set structurally cannot contain
7081            // an empty / malformed string and the membership-lookup
7082            // diagnostic always misframed the root cause as
7083            // "this caixa is not in `:membros`". The shape gate runs
7084            // ahead of the lookup so structurally-impossible-to-match
7085            // inputs route through the narrower self-locating
7086            // diagnostic, preserving the legitimate "well-shaped
7087            // phantom reference" arm. `:de` runs before `:para` per
7088            // the canonical edge-direction order the existing
7089            // membership lookup, self-edge check, target dispatch,
7090            // and diagnostic strings already use.
7091            // Route the per-`:contratos` per-arm DNS-1123 shape-gate arg
7092            // + the paired [`AplicacaoError::ContratoMemberMissing`]
7093            // diagnostic's `caixa:` carrier through the lifted
7094            // [`WitContract::source`] / [`WitContract::destination`]
7095            // scalar accessors rather than the raw `&c.de` / `&c.para`
7096            // `&String`-borrow arg site + the raw `c.de.clone()` /
7097            // `c.para.clone()` field-access `String`-carry sites — the
7098            // last unlifted per-`:contratos` raw-field-access sites in
7099            // the M3 mesh-slot validator's per-edge per-arm shape-gate
7100            // arg + phantom-name diagnostic wrap-envelope emit surface.
7101            // `c.source()` is byte-identical to `&c.de` (pinned by the
7102            // sibling `wit_contract_source_returns_de_byte_equal_across_permutations`
7103            // + `wit_contract_source_borrows_from_de_storage` accessor
7104            // tests) and `c.destination()` is byte-identical to `&c.para`
7105            // (pinned by the sibling
7106            // `wit_contract_destination_returns_para_byte_equal_across_permutations`
7107            // + `wit_contract_destination_borrows_from_para_storage`
7108            // accessor tests) — so a future rebrand of either underlying
7109            // storage flows through the accessor's one body without a
7110            // coordinated per-consumer rewrite across the M3 mesh
7111            // validator's per-edge shape-gate + phantom-name refusal
7112            // arms. Peer of the sibling per-`:contratos` self-loop
7113            // arm's `.source().to_string()` / `.world_ref().to_string()`
7114            // `String`-carry sites the earlier convergence lifted onto
7115            // the same accessor pair.
7116            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
7117            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
7118            if !names.contains(c.source()) {
7119                return Err(AplicacaoError::ContratoMemberMissing {
7120                    caixa: c.source().to_string(),
7121                });
7122            }
7123            if !names.contains(c.destination()) {
7124                return Err(AplicacaoError::ContratoMemberMissing {
7125                    caixa: c.destination().to_string(),
7126                });
7127            }
7128            // A `:contratos` entry is an *inter*-Servico contract
7129            // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
7130            // typed edge between two distinct graph nodes. An edge whose
7131            // `:de` equals its `:para` is a Servico contracting with
7132            // itself — a degenerate edge under every WIT shape. The
7133            // synchronous shapes were caught only incidentally, and with
7134            // a misleading diagnostic: `detect_sync_cycles` reported
7135            // `cart → cart` as a `ContratoCycle` whose path is
7136            // `["cart", "cart"]` — framing a self-edge as a multi-node
7137            // deadlock. The pub-sub shape slipped through entirely
7138            // (`detect_sync_cycles` excludes `WitTarget::PubSub`, so a
7139            // `nats:pub-sub` edge from a member to itself silently
7140            // validated, then rendered a `CiliumNetworkPolicy` whose
7141            // endpointSelector and fromEndpoints both name the same
7142            // program — a self-allow rule that is a no-op, since
7143            // intra-pod traffic never traverses the mesh). A self-edge's
7144            // runtime meaning is an in-process call, which doesn't go
7145            // through the mesh at all, so no `:contratos` edge can carry
7146            // it. Firing the gate before the `:wit`/`target()` shape
7147            // checks means the structural "this edge can't exist" error
7148            // precedes the narrower payload-shape diagnostics, and shape-
7149            // agnostically covers all four `WitTarget` arms (HTTP / Store
7150            // / Capability / PubSub) at one point — closing the pub-sub
7151            // hole and replacing the misleading cycle diagnostic in one
7152            // gate. Peer of the duplicate-`:contratos` / duplicate-
7153            // `:membros` set gates: both reject a structurally
7154            // ill-formed graph at the typed surface, before the renderer
7155            // emits a K8s object that fails or no-ops far from the source
7156            // caixa.lisp.
7157            // Route the per-`:contratos` structural self-edge probe
7158            // through the lifted [`WitContract::is_self_loop`] typed
7159            // predicate rather than the raw `c.de == c.para` field-
7160            // equality check — the one production consumer of the per-
7161            // `:contratos` caller-equals-callee endpoint-equality axis
7162            // now keys off exactly one typed dispatch on the substrate
7163            // primitive, so any future rebrand of the axis (an M4-typed-
7164            // caller enum whose identity comparison rule the predicate
7165            // could route through, a per-cluster caller/callee-alias
7166            // table the M4 CR materializer resolves per-CR before the
7167            // equality probe) migrates as a single caixa-core edit
7168            // rather than a coordinated rewrite of the gate + every
7169            // downstream self-edge consumer. Peer of the sibling
7170            // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
7171            // [`WitContract::is_store`] shape-predicate routing on the
7172            // `:wit` world-ref axis, extended onto the per-edge
7173            // endpoint-equality axis.
7174            //
7175            // Route the paired [`AplicacaoError::ContratoSelfLoop`]
7176            // diagnostic's `caixa:` / `wit:` carriers through the
7177            // lifted [`WitContract::source`] / [`WitContract::world_ref`]
7178            // scalar accessors rather than the raw `c.de.clone()` /
7179            // `c.wit.clone()` field-access `String`-carry sites — the
7180            // last unlifted per-`:contratos` raw-field-access
7181            // `.clone()` sites in the M3 mesh-slot validator's self-
7182            // edge refusal arm. `.source().to_string()` is byte-
7183            // identical to `.de.clone()` (pinned by the sibling
7184            // `source_returns_de_byte_equal_across_permutations` accessor
7185            // test), and `.world_ref().to_string()` is byte-identical
7186            // to `.wit.clone()` (pinned by the sibling
7187            // `world_ref_returns_wit_byte_equal_across_permutations`
7188            // accessor test) — so a future rebrand of either underlying
7189            // storage flows through the accessor's one body without a
7190            // coordinated per-consumer rewrite across the M3 mesh
7191            // validator.
7192            if c.is_self_loop() {
7193                return Err(AplicacaoError::ContratoSelfLoop {
7194                    caixa: c.source().to_string(),
7195                    wit: c.world_ref().to_string(),
7196                });
7197            }
7198            if c.world_ref().is_empty() {
7199                let (de, para) = c.edge_pair();
7200                return Err(AplicacaoError::EmptyWit { de, para });
7201            }
7202            // Shape ↔ target consistency — surfaces "HTTP wit without
7203            // :endpoint", "NATS wit with :endpoint set", etc. as named
7204            // build errors instead of silent renderer drops. Threaded
7205            // through the duplicate-edge diagnostic below (via
7206            // [`WitTarget::label`]) so the "which typed target arm did
7207            // the duplicate carry" question is answered by the typed
7208            // enum's variant discriminator, not by re-probing the raw
7209            // `Option<String>` payload fields.
7210            let target_view = c.target()?;
7211            // Contract identity: (de, para, wit, endpoint, subject, slot).
7212            // Two contracts that match on all six are the same typed edge
7213            // declared twice — author error, not a legitimate variant of
7214            // "same caller-callee pair, different payload" (e.g.
7215            // cart→catalog at /products vs /search), which keeps distinct
7216            // identity keys via the differing endpoint payloads.
7217            //
7218            // Route the six-axis dedup key through the lifted
7219            // [`WitContract::identity`] composite-projection accessor
7220            // rather than the inline six-tuple builder — the two
7221            // substrate primitives on the per-`:contratos` identity axis
7222            // (the [`ContratoIdentity`] type alias's six axes, this
7223            // dedup-key's six tuple arms) now migrate as a unit on any
7224            // future axis addition. Peer of the sibling per-`:contratos`
7225            // composite-projection [`WitContract::edge_pair`] /
7226            // [`WitContract::edge_triple`] accessors on the
7227            // caller-callee / caller-callee-wit prefix axes; extends
7228            // the discipline onto the full-identity axis that carries
7229            // the three payload-shape arms too.
7230            let key = c.identity();
7231            crate::render::insert_first_seen(&mut seen_contracts, key, || {
7232                // Route the per-`:contratos` duplicate-gate diagnostic's
7233                // `(de, para, wit)` triple through the lifted
7234                // [`WitContract::edge_triple`] typed accessor rather
7235                // than pairing `edge_pair()` for the `(de, para)` prefix
7236                // with a raw `c.wit.clone()` for the `wit:` tail — the
7237                // paired-with-raw-field-access shape was the last
7238                // per-`:contratos` diagnostic constructor bypassing the
7239                // substrate-primitive composite projection, sibling to
7240                // the eight [`AplicacaoError::Contrato*`] triple-
7241                // carrying constructors [`WitContract::target`]'s edge
7242                // closure feeds through the same accessor.
7243                let (de, para, wit) = c.edge_triple();
7244                AplicacaoError::ContratoDuplicate {
7245                    de,
7246                    para,
7247                    wit,
7248                    target: target_view.label(),
7249                }
7250            })?;
7251        }
7252
7253        // Cycles in the synchronous-edge subgraph are build errors
7254        // (MESH-COMPOSITION §III.3). Pub-sub edges are excluded — they
7255        // are "acyclic by construction" because the publisher fires
7256        // and forgets, so no caller blocks on a downstream that loops
7257        // back to it.
7258        self.detect_sync_cycles()?;
7259
7260        if let Some(e) = self.entrada() {
7261            // Route the per-`:entrada` composite-reference read
7262            // through the lifted [`AplicacaoSpec::entrada`] accessor
7263            // rather than the raw `&self.entrada` field access — the
7264            // shape-and-membership gate's traversal head is now the
7265            // canonical read-side surface every per-Aplicacao entrada
7266            // consumer routes through, closing the fourth of four
7267            // open-coded outer-field accesses on the per-`:entrada`
7268            // outer-composite axis.
7269            //
7270            // Shape gate on `:entrada :para` runs ahead of the
7271            // membership lookup. Every `:membros :caixa` past
7272            // `validate_membro_caixa` is a valid DNS-1123 label
7273            // (3f9d7a0), so the `names` set structurally cannot
7274            // contain an empty / malformed string and the membership-
7275            // lookup diagnostic always misframed the root cause as
7276            // "this caixa is not in `:membros`". The shape gate
7277            // routes structurally-impossible-to-match inputs through
7278            // the narrower self-locating diagnostic, preserving the
7279            // legitimate "well-shaped phantom reference" arm — the
7280            // same trajectory the peer `:membros :caixa` (3f9d7a0),
7281            // `:placement :clusters` (6c8c00b), and `:contratos :de`
7282            // / `:para` (8d5af6b) axes already follow. This closes
7283            // the fourth and last Aplicacao-level Servico-name
7284            // reference axis on the canonical DNS-1123 floor.
7285            // Route the per-`:entrada :para` byte-string reads through
7286            // the lifted [`Entrada::destination`] accessor rather than
7287            // the raw `e.para` field access — the three
7288            // per-`AplicacaoSpec::validate` `:entrada :para` consumers
7289            // (shape-gate `validate_entrada_para` arg, membership
7290            // lookup, `EntradaMemberMissing` diagnostic carry) now key
7291            // off exactly one typed dispatch on the substrate
7292            // primitive, closing the last unlifted per-`:entrada :para`
7293            // raw-field-access axis on the M3 mesh-slot validator.
7294            // The `.destination().to_string()` at the diagnostic site
7295            // is byte-identical to `.para.clone()` — pinned by the
7296            // sibling `destination_returns_entrada_para_byte_equal` +
7297            // `destination_borrows_from_entrada_para_storage` accessor
7298            // tests — so a future rebrand of the underlying `:para`
7299            // storage (a lift from `String` to a typed
7300            // `ServicoName(String)` newtype, a per-Aplicacao interning
7301            // arena the M4 CR materializer authors, a
7302            // `smol_str::SmolStr` inline-buffer swap) flows through
7303            // the accessor's one body without a coordinated
7304            // per-consumer rewrite across the M3 mesh validator.
7305            validate_entrada_para(e.destination())?;
7306            if !names.contains(e.destination()) {
7307                return Err(AplicacaoError::EntradaMemberMissing {
7308                    para: e.destination().to_string(),
7309                });
7310            }
7311            // Route the per-`:entrada :host` byte-string reads through
7312            // the lifted [`Entrada::hostname`] accessor rather than
7313            // the raw `e.host` field access — the emptiness gate and
7314            // the shape-gate `validate_entrada_host` arg now key off
7315            // exactly one typed dispatch on the substrate primitive,
7316            // closing the last unlifted per-`:entrada :host` raw-
7317            // field-access axis on the M3 mesh-slot validator. Peer
7318            // of the sibling per-`:entrada :para` convergence above
7319            // and pinned by the existing
7320            // `hostname_returns_entrada_host_byte_equal` +
7321            // `hostnames_returns_singleton_of_hostname_accessor`
7322            // accessor tests, so any future
7323            // Gateway-API-shaped host renormalization (a wildcard-
7324            // label lift, a trailing-`.` FQDN substitution, an IDNA
7325            // Punycode round-trip the SNI fan-out overlay authors)
7326            // flows through the accessor's one body without a
7327            // coordinated per-consumer rewrite across the M3 mesh
7328            // validator.
7329            if e.hostname().is_empty() {
7330                return Err(AplicacaoError::EmptyEntradaHost);
7331            }
7332            // The `:host` lands verbatim as a K8s Gateway API v1
7333            // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
7334            // both apiserver-validated against the same restrictive
7335            // pattern: lowercase RFC 1123 DNS subdomain, optional
7336            // single leading wildcard label (`*.`), max length 253,
7337            // per-label max length 63, no IP literals, no scheme,
7338            // no port. Until this gate landed `validate()` only
7339            // refused the empty string (`EmptyEntradaHost`); a
7340            // structurally invalid hostname (`"https://example.com"`,
7341            // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
7342            // `"_underscored.example.com"`, `"FOO.example.com"`,
7343            // `"checkout.quero.cloud."`) silently passed validate
7344            // and the apiserver `field is invalid` error surfaced at
7345            // `kubectl apply` time, far from the source caixa.lisp.
7346            // Lifting the gate to caixa-build time mirrors the
7347            // `:entrada :paths` value-shape trajectory (eb3456d) and
7348            // closes the last unstructured `:entrada` axis.
7349            validate_entrada_host(e.hostname())?;
7350            // Structural-floor gate on `:entrada :port`: every
7351            // validated `Entrada::port` past this gate lies in
7352            // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
7353            // type-inferred ceiling closes the top edge, so no companion
7354            // upper-cap arm is needed here — unlike the peer capped-
7355            // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
7356            // `require_positive_bounded_u32` bracket covers both edges).
7357            // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
7358            // accept-set-floor const rather than the prior inline
7359            // `if e.port == 0` byte-check so a future rebrand of the
7360            // accept-set floor (a hypothetical unprivileged-only
7361            // migration lifting the floor to `1024`, a per-cluster
7362            // scoping the operator pins through a future
7363            // `:placement :port-floor` slot as the M4 typed-slot
7364            // trajectory adds it, the future
7365            // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7366            // per-Aplicacao gateway resolver reaching for the same
7367            // floor) is a one-line edit on the canonical
7368            // [`SERVICO_PORT_MIN`] declaration, not a coordinated
7369            // rewrite across the emit site + the pin test + every
7370            // future per-target renderer the substrate adds.
7371            if e.port() < SERVICO_PORT_MIN {
7372                return Err(AplicacaoError::EntradaPortZero);
7373            }
7374            // Each `:entrada :paths` entry becomes a K8s Gateway API
7375            // HTTPRoute `matches[].path.value`. The Gateway API rejects
7376            // values that don't start with `/` for `type: PathPrefix`,
7377            // and an empty value is meaningless. Surface those as build
7378            // errors (MESH-COMPOSITION §III.3) rather than apply-time
7379            // failures. Empty `:paths` itself is fine — caixa-mesh
7380            // falls back to a single `/` catch-all.
7381            let mut seen = std::collections::HashSet::new();
7382            // Route the per-entry value-shape gate's traversal head
7383            // through the lifted [`Entrada::paths`] slice accessor
7384            // rather than the raw `&e.paths` field access — the
7385            // per-Aplicacao `:entrada :paths` validate loop now keys
7386            // off the canonical raw-slot surface every downstream
7387            // per-`:entrada` path-list consumer (the sibling
7388            // [`Entrada::resolved_paths`] fallback-applying resolver
7389            // internal reads, `feira app graph`'s per-Aplicacao entrada
7390            // summary line's `{:?}` Debug print) routes through, so any
7391            // future rebrand on the typed slot's raw-slot reader lands
7392            // at exactly one place. Same convergence discipline as the
7393            // sibling [`Placement::clusters`] (a6e18d7) reader-site
7394            // convergences on the peer M3 mesh-slot `Vec<String>`-carry
7395            // axis.
7396            for p in e.paths() {
7397                if p.is_empty() {
7398                    return Err(AplicacaoError::EntradaPathEmpty);
7399                }
7400                if !p.starts_with('/') {
7401                    return Err(AplicacaoError::EntradaPathNotAbsolute { path: p.clone() });
7402                }
7403                // Per-entry value-shape gate: the path lands verbatim
7404                // as a K8s Gateway API HTTPRoute `matches[].path.value`
7405                // (caixa-mesh/src/lib.rs:498), apiserver-validated
7406                // against `maxLength: 1024` + the Gateway API webhook's
7407                // path-grammar rules (no `//`, no `/./`, no `/../`, no
7408                // query/fragment separators, no whitespace, no control
7409                // characters, no non-ASCII bytes). Until this gate
7410                // landed `validate` only refused the empty string and
7411                // missing-leading-slash (eb3456d); a structurally
7412                // invalid path (`"/api?q=1"`, `"/api#frag"`,
7413                // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
7414                // 1025-byte URL-shaped slug) silently passed validate
7415                // and the failure surfaced at `kubectl apply` time as
7416                // a Gateway API webhook rejection, far from the source
7417                // caixa.lisp, with no field naming the offending
7418                // `:paths` entry. Lifting the gate to caixa-build time
7419                // mirrors the `:entrada :host` value-shape trajectory
7420                // (c7d05ec) on the sibling axis — every author surface
7421                // that emits a Gateway API field now matches the
7422                // apiserver's accepted set at validate time.
7423                validate_entrada_path(p)?;
7424                crate::render::insert_first_seen(&mut seen, p.as_str(), || {
7425                    AplicacaoError::EntradaPathDuplicate { path: p.clone() }
7426                })?;
7427            }
7428        }
7429
7430        self.validate_placement()?;
7431
7432        self.validate_politicas()?;
7433
7434        Ok(())
7435    }
7436
7437    /// Reject `:membros` values that are operationally meaningless. The
7438    /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
7439    /// every entry names a Servico that participates in the Aplicacao,
7440    /// and the rendered programs.yaml fan-out emits one entry per
7441    /// `:membros`. Three authoring footguns are closed here:
7442    ///
7443    ///   - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
7444    ///     a `programs:` entry whose `name:` is the empty string, which
7445    ///     downstream `lareira-fleet-programs` rejects at template time
7446    ///     with a non-localized error;
7447    ///   - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
7448    ///     an empty semver constraint, so the failure surfaces far from
7449    ///     the source caixa.lisp;
7450    ///   - duplicate `:caixa` names — two entries with the same name
7451    ///     produce duplicate programs.yaml entries (one silently
7452    ///     overwrites the other in the cluster's HelmRelease values), and
7453    ///     contract membership lookups against `:contratos` collapse the
7454    ///     two onto one node, masking authoring mistakes.
7455    ///
7456    /// Same value-shape discipline as `:placement :clusters` (where empty
7457    /// + duplicate cluster names are rejected) and `:entrada :paths`
7458    /// (where empty + duplicate path entries are rejected). Lifting these
7459    /// invariants to the typed surface mirrors the MESH-COMPOSITION
7460    /// §III.3 promise that the `:membros` set — the load-bearing identity
7461    /// of the application graph — is well-formed by construction.
7462    fn validate_membros(&self) -> Result<(), AplicacaoError> {
7463        if self.membros().is_empty() {
7464            return Err(AplicacaoError::NoMembros);
7465        }
7466        let mut seen = std::collections::HashSet::new();
7467        for m in self.membros() {
7468            // Route the `MembroCaixaEmpty` refusal-arm's per-member
7469            // empty-`:caixa` shape-gate through the typed
7470            // [`Membro::nome`] accessor rather than the raw `.caixa`
7471            // field access — the last un-lifted `.caixa` production-
7472            // code read site on the per-`:membros` member-caixa `:nome`
7473            // axis, sibling to the six caixa-core validator read sites
7474            // (member-set collector, per-member value-shape gate,
7475            // duplicate dedup key, cycle-detector adjacency-map seed,
7476            // self-loop gate) the 4a32abf lift already routed through
7477            // the accessor and the peer 54bf2f3 caixa-mesh emit-side
7478            // per-`programs[]` entry-`name:` `String`-carry converge.
7479            // Prior to this converge the `MembroCaixaEmpty` refusal
7480            // arm was the solitary consumer bypassing the typed
7481            // dispatch — the same-loop iteration's very next call
7482            // `validate_membro_caixa(m.nome())` already routed through
7483            // the accessor, so an author landing an empty-`:caixa`
7484            // entry hit the accessor on the shape-gate line but
7485            // bypassed it on the emptiness line one line above. A
7486            // future extension of the `:membros :caixa` axis to a
7487            // richer author surface (a per-cluster alias table pinned
7488            // through a future `:placement`-scoped slot, a namespace-
7489            // qualified rewrite the M4 CR materializer applies per-CR,
7490            // a per-member overlay from the future `:membros
7491            // :nome-suffix` slot MESH-COMPOSITION §III.2 acknowledges)
7492            // that lands on the accessor would silently disagree
7493            // between the emptiness gate and every peer consumer —
7494            // an author-declared `:caixa "checkout"` value the
7495            // accessor rewrote to `""` under a future alias arm would
7496            // pass the raw `.is_empty()` gate here while the peer
7497            // `validate_membro_caixa(m.nome())` call one line below
7498            // (and every downstream emit-side consumer routing through
7499            // the accessor) tripped on the empty-value shape far from
7500            // this diagnostic. Pinned by the drift-detection test
7501            // [`validate_membros_empty_gate_routes_through_nome_accessor`]
7502            // below.
7503            if m.nome().is_empty() {
7504                return Err(AplicacaoError::MembroCaixaEmpty);
7505            }
7506            // Every emitted cluster artifact's `metadata.name` derives
7507            // from a `:membros :caixa` value verbatim — the rendered
7508            // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
7509            // the [`crate::LABEL_PROGRAM`] label value on every CNP
7510            // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
7511            // 272), the composed `CiliumNetworkPolicy` `metadata.name`
7512            // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
7513            // `metadata.name` when the member is the `:entrada :para`
7514            // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
7515            // schema enforces the DNS-1123 label rule on admission;
7516            // a structurally invalid member name (`"Cart"`, `"my_cart"`,
7517            // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
7518            // mistaken-identity slug) silently passes the prior empty-/
7519            // duplicate-only gate and the failure surfaces at `kubectl
7520            // apply` time as a `metadata.name: Invalid value` rejection,
7521            // far from the source caixa.lisp, with no field naming the
7522            // offending `:membros` entry. Lifting the gate to caixa-build
7523            // time mirrors the `:entrada :host` value-shape trajectory
7524            // (c7d05ec) on the peer axis — every author surface that
7525            // emits a K8s name now matches the apiserver's accepted set
7526            // at validate time.
7527            validate_membro_caixa(m.nome())?;
7528            // The author surface for `:versao` is the same Cargo-shaped
7529            // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
7530            // `"*"`) every `:deps` entry carries — and the lacre pipeline
7531            // resolves both axes through the same
7532            // [`crate::version::parse_requirement`] entry-point. The
7533            // shared [`crate::render::require_valid_versao_requirement`]
7534            // helper brackets the empty-first + parse cascade both peer
7535            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
7536            // [`crate::SupervisorSpec::validate`] on `:children :versao`)
7537            // route through, so drift between the three axes' accepted
7538            // requirement sets is structurally impossible and the parse-
7539            // side no-op the empty-first arm closes (semver's empty
7540            // parse yields an implicit `*`) lives in exactly one
7541            // predicate.
7542            crate::render::require_valid_versao_requirement(
7543                m.versao_requirement(),
7544                || AplicacaoError::MembroVersaoEmpty {
7545                    caixa: m.nome().to_string(),
7546                },
7547                |reason| AplicacaoError::MembroVersaoInvalid {
7548                    caixa: m.nome().to_string(),
7549                    versao: m.versao_requirement().to_string(),
7550                    reason,
7551                },
7552            )?;
7553            crate::render::insert_first_seen(&mut seen, m.nome(), || {
7554                AplicacaoError::MembroDuplicate {
7555                    caixa: m.nome().to_string(),
7556                }
7557            })?;
7558        }
7559        Ok(())
7560    }
7561
7562    /// Reject `:placement` values that are operationally meaningless or
7563    /// internally contradictory. Each strategy variant has the same
7564    /// invariants on `:clusters` (non-empty list, non-empty unique
7565    /// entries) — the §III.1 author surface is uniform on this axis,
7566    /// even though the *meaning* of the list differs by strategy
7567    /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
7568    /// shard pool).
7569    ///
7570    /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
7571    /// are the same authoring footgun closed for `:politicas` zero
7572    /// values and `:entrada` empty paths: the field is *declared* but
7573    /// carries no meaning, so downstream renderers either skip it
7574    /// silently (cluster-fanout drops the empty entry, no diagnostic)
7575    /// or apply it literally and fail at admission time. Lifting both
7576    /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
7577    /// violation is a build error" promise.
7578    ///
7579    /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
7580    /// is required exactly when `:estrategia Sharded` (hash-keyed
7581    /// distribution, Akka cluster-sharding convention, §II.4) and
7582    /// refused on `:estrategia Replicated`/`SingleNode` (where no
7583    /// hash-keyed routing axis consumes it). The partition closes the
7584    /// "I think I configured sharding" footgun where an author writes
7585    /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
7586    /// the typed slot's value silently vanishes at the renderer layer
7587    /// — every validated `Placement` past this call satisfies
7588    /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
7589    fn validate_placement(&self) -> Result<(), AplicacaoError> {
7590        // Every strategy needs at least one named cluster: `Replicated`
7591        // and `SingleNode` use the list as hosting/takeover candidates
7592        // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
7593        // §II.1), while `Sharded` uses it as the shard pool
7594        // (Akka cluster-sharding convention — §II.4). An empty list is
7595        // meaningless under any of the three.
7596        //
7597        // Route the paired pre-flight `.is_empty()` refusal probe and
7598        // the per-cluster validate loop's traversal head through the
7599        // lifted [`Placement::clusters`] slice-return accessor rather
7600        // than the raw `self.placement.clusters` field access — the
7601        // two production consumers of the per-`:placement` cluster-
7602        // pool `Vec`-carry now key off exactly one typed dispatch on
7603        // the substrate primitive, so any future rebrand on the axis
7604        // (a per-tenant cluster-pool overlay the operator pins through
7605        // a future `:placement :clusters-overrides` slot, a per-
7606        // Aplicacao dynamic cluster-pool derivation the future M5
7607        // adaptive-placement engine computes from `:affinity` weights)
7608        // migrates as a single caixa-core edit rather than a
7609        // coordinated rewrite of the paired arms — sibling of the
7610        // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
7611        // arm migration on the per-`:supervisor` static-child-list
7612        // `Vec`-carry axis.
7613        //
7614        // Route the per-`:placement` outer-composite reference read
7615        // through the lifted [`AplicacaoSpec::placement`] outer accessor
7616        // rather than the raw `&self.placement` field access — the
7617        // per-axis bracket-dispatch fan-out below (`p.clusters()`,
7618        // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
7619        // axis-level lifted accessor family) now routes through the
7620        // substrate-primitive typed dispatch at the outer composition
7621        // altitude, the same shape the peer caixa-mesh
7622        // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
7623        // and the sibling `feira app graph` per-Aplicacao print line
7624        // now key off after this accessor lift.
7625        let p = self.placement();
7626        if p.clusters().is_empty() {
7627            return Err(AplicacaoError::PlacementWithoutClusters {
7628                estrategia: p.estrategia(),
7629            });
7630        }
7631        let mut seen = std::collections::HashSet::new();
7632        for c in p.clusters() {
7633            // Per-entry value-shape gate: the cluster name lands in
7634            // every K8s context / `lareira-fleet-programs` aggregator
7635            // filter / future M4 CR materializer's per-cluster axis
7636            // a validated `:clusters` entry passes through, each
7637            // enforcing the DNS-1123 label rule on admission. Same
7638            // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
7639            // on the peer name axis — both axes' validated values
7640            // are guaranteed-accepted by the apiserver without
7641            // re-validation at any downstream renderer or admission
7642            // layer.
7643            validate_placement_cluster(c)?;
7644            crate::render::insert_first_seen(&mut seen, c.as_str(), || {
7645                AplicacaoError::PlacementClusterDuplicate { cluster: c.clone() }
7646            })?;
7647        }
7648        // Route the per-`:placement :affinity` per-hint value-shape
7649        // gate through the typed [`Placement::affinity`] accessor rather
7650        // than the raw `&self.placement.affinity` field access — the
7651        // sole open-coded field-access site on the per-`:placement`
7652        // M3-Adaptive-compression-hint axis the accessor lift now owns.
7653        // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
7654        // the accessor's `Option<&str>` return type;
7655        // [`validate_placement_affinity`]'s `&str` parameter accepts
7656        // the narrower borrow without a re-allocation, so the routing
7657        // change is byte-for-byte in the pass arm and remains
7658        // byte-for-byte in every failure diagnostic
7659        // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
7660        // String` field is populated inside
7661        // [`validate_placement_affinity`] via the peer `.to_string()`
7662        // path on the same borrowed slice). Peer of the sibling
7663        // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
7664        // routing through [`Placement::shard_key`] at the caixa-core
7665        // site above — extends the "read `:placement` optional-scalars
7666        // through the typed accessor" discipline to the second
7667        // `Option<String>`-shape slot on the M3 mesh-slot family.
7668        //
7669        // Per-hint value-shape gate: the `:affinity` value lands
7670        // verbatim in the M3 Adaptive compression overlay
7671        // (caixa-mesh's `placement.affinity` emission) and every
7672        // future M4 placement-engine routing axis keying off the
7673        // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
7674        // selector — each enforces the DNS-1123 label rule on
7675        // admission. Same typed-shape trajectory as `:placement
7676        // :clusters` (6c8c00b) on the sibling slot and the four
7677        // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
7678        // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
7679        // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
7680        // on the Aplicacao surface to land on the canonical
7681        // [`crate::render::is_dns_1123_label`] floor.
7682        if let Some(a) = p.affinity() {
7683            validate_placement_affinity(a)?;
7684        }
7685        match p.estrategia() {
7686            // Route the `Sharded`-arm shape-gate cascade through the
7687            // typed [`Placement::shard_key`] accessor rather than the
7688            // raw `&self.placement.shard_key` field access — one of the
7689            // two open-coded field-access sites on the per-`:placement`
7690            // Akka-cluster-sharding-key axis the accessor lift now
7691            // owns. The `Some(k)`-bound `k` narrows from `&String` to
7692            // `&str` under the accessor's `Option<&str>` return type;
7693            // `str::is_empty` and [`validate_placement_shard_key`]'s
7694            // `&str` parameter both accept the narrower borrow without
7695            // a re-allocation.
7696            PlacementStrategy::Sharded => match p.shard_key() {
7697                None => return Err(AplicacaoError::ShardedWithoutKey),
7698                Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
7699                // Per-axis value-shape gate on the Akka-cluster-sharding
7700                // `:shard-key` extractor expression. The shape gate runs
7701                // after the more self-locating `ShardedKeyEmpty` arm so
7702                // a `:shard-key ""` surfaces the narrower empty
7703                // diagnostic first; every non-empty `:shard-key` past
7704                // this call is guaranteed to be a printable-ASCII
7705                // single-token reference the future M4 Akka-style
7706                // cluster-sharding reconciler can hash without
7707                // re-validating at the runtime layer. Mirrors the
7708                // payload-axis shape gates on the peer `:contratos`
7709                // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
7710                // 63e18a0 / c4213a4) — each lifts the runtime parser's
7711                // intersection-floor to a caixa-build-time gate.
7712                Some(k) => validate_placement_shard_key(k)?,
7713            },
7714            // `:shard-key` is the Akka-cluster-sharding axis
7715            // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
7716            // across the cluster pool. `Replicated` (active-active across
7717            // every named cluster) and `SingleNode` (Erlang/OTP
7718            // distributed-app takeover/failover, §II.1) have no hash-keyed
7719            // routing axis to consume the slot; downstream renderers
7720            // (caixa-mesh's `placement.shardKey` overlay at
7721            // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
7722            // sharding reconciler) ignore `:shard-key` outside the
7723            // `Sharded` arm by construction. Until this gate landed an
7724            // author who wrote `:placement (:estrategia Replicated
7725            // :shard-key "tenantId")` (an off-by-one strategy typo, a
7726            // copy-paste from a Sharded sibling caixa, the "I think I
7727            // configured sharding" footgun) silently passed validate and
7728            // the typed slot's value vanished at the renderer layer with
7729            // no diagnostic — the canonical "declared-but-inert" footgun
7730            // the empty-:affinity / empty-shard-key / zero-:politicas /
7731            // empty-:contratos-target gates already close on every other
7732            // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
7733            // Lifting the rejection to a build-time gate closes the
7734            // Sharded ↔ non-Sharded partition over the typed
7735            // `:placement` slot: every validated `Placement` past this
7736            // call has `shard_key.is_some()` iff `estrategia ==
7737            // Sharded`, structurally — the future Akka reconciler can
7738            // reach for `placement.shard_key` knowing it's `Some` exactly
7739            // when the strategy consumes it, without re-deriving the
7740            // partition from inline strategy probes.
7741            PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
7742                // Route the non-`Sharded`-arm declared-but-inert refusal
7743                // through the typed [`Placement::shard_key`] accessor —
7744                // the second of the two open-coded field-access sites the
7745                // accessor lift now owns. The `Some(k)`-bound `k` narrows
7746                // from `&String` to `&str`; the `AplicacaoError::
7747                // ShardKeyOnNonSharded { shard_key: String }` diagnostic
7748                // materializes the owned `String` via `k.to_string()`
7749                // (peer to the sibling per-Membro `String`-carry sites
7750                // 4127bb6 routed through `m.nome().to_string()` /
7751                // `m.versao_requirement().to_string()`), so the whole
7752                // `Sharded` ↔ non-`Sharded` partition on the
7753                // `:shard-key` axis now flows through the same typed
7754                // dispatch as the sibling `Sharded`-arm shape gate.
7755                if let Some(k) = p.shard_key() {
7756                    return Err(AplicacaoError::ShardKeyOnNonSharded {
7757                        estrategia: p.estrategia(),
7758                        shard_key: k.to_string(),
7759                    });
7760                }
7761            }
7762        }
7763        Ok(())
7764    }
7765
7766    /// Reject `:politicas` values that are operationally meaningless.
7767    /// Each axis is optional — omitting it expresses "no policy on this
7768    /// axis". Carrying a *zero* value for a declared axis is the bug
7769    /// this function rejects: zero is either
7770    ///
7771    ///   - re-interpreted as "infinite" by downstream proxies (Envoy's
7772    ///     `RouteAction.timeout = 0s` disables the timeout entirely),
7773    ///     directly contradicting MESH-COMPOSITION §V CSE invariant
7774    ///     "every Aplicacao declares :politicas :timeout (no infinite
7775    ///     blocking)", or
7776    ///   - a renderer footgun (a 0-failure circuit breaker trips on the
7777    ///     first call; a 0-rate rate-limit denies every request).
7778    ///
7779    /// Lifting these "0 means the opposite of what you think" idioms to
7780    /// the typed Aplicacao surface as build errors mirrors the §III.3
7781    /// promise that contract drift, capability leaks, and cycles are all
7782    /// build errors — not runtime surprises.
7783    fn validate_politicas(&self) -> Result<(), AplicacaoError> {
7784        // Route the per-`:politicas` composite-reference read through
7785        // the lifted [`AplicacaoSpec::politicas`] outer accessor rather
7786        // than the raw `&self.politicas` field access — the per-axis
7787        // bracket-dispatch fan-out below (`p.timeout()`, `p.retries()`,
7788        // `p.circuit_breaker()`, `p.rate_limit()`) now routes through
7789        // the substrate-primitive typed dispatch at the outer
7790        // composition altitude AND at every per-axis altitude, matching
7791        // the peer caixa-mesh CNP mTLS-overlay + HTTPRoute
7792        // timeout/retry-overlay emitters that already key off the same
7793        // per-axis accessor family. The four-axis fan-out is now
7794        // uniformly `p.<axis>()` — the last two raw `p.timeout` /
7795        // `p.retries` field-access sites (co-resident with the peer
7796        // `p.circuit_breaker()` / `p.rate_limit()` accessor sites that
7797        // b0e741a / 21a6c3b already lifted) now route through
7798        // [`MeshPolicy::timeout`] / [`MeshPolicy::retries`], closing
7799        // the per-`:politicas` bracket-dispatch fan-out's raw-field-
7800        // access axis on the M3 mesh-slot family.
7801        let p = self.politicas();
7802        if let Some(t) = p.timeout() {
7803            // Zero-floor + integer-millisecond canonical-form +
7804            // upper-cap bracket on the typed `:timeout` axis. See
7805            // [`crate::render::require_positive_canonical_bounded_duration`]
7806            // for the full three-arm ordering discipline (zero-floor
7807            // strictly precedes the canonical-form arm so
7808            // `Duration::ZERO` surfaces the self-locating
7809            // `PolicyTimeoutZero` diagnostic naming the omit-axis
7810            // remediation; canonical-form strictly precedes the cap
7811            // arm so a sub-millisecond above-cap `Duration` surfaces
7812            // the more fundamental round-trip-shape diagnostic first)
7813            // and the four peer typed-`Duration` sites that now share
7814            // this canonical bracket. Every validated value lies in
7815            // `1ms..=POLICY_TIMEOUT_MAX` (1ms..=1h), integer-millisecond
7816            // granularity — the same top-and-bottom-edge discipline
7817            // [`POLICY_RETRIES_MAX`] and
7818            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] apply on the sibling
7819            // capped-`u32` `:politicas` axes.
7820            crate::render::require_positive_canonical_bounded_duration(
7821                t,
7822                POLICY_TIMEOUT_MAX,
7823                || AplicacaoError::PolicyTimeoutZero,
7824                |timeout| AplicacaoError::PolicyTimeoutNotCanonical { timeout },
7825                |timeout| AplicacaoError::PolicyTimeoutExceedsCap { timeout },
7826            )?;
7827        }
7828        if let Some(r) = p.retries() {
7829            // Zero-floor + upper-cap bracket on the typed `:retries`
7830            // axis. See [`crate::render::require_positive_bounded_u32`]
7831            // for the ordering discipline (zero-floor arm strictly
7832            // precedes cap arm so `Some(0)` surfaces the self-locating
7833            // `PolicyRetriesZero` diagnostic with its omit-axis
7834            // remediation directly named, not the misleading
7835            // `0 > POLICY_RETRIES_MAX == false` cap-arm miss). Until
7836            // this bracket landed the top edge ran all the way to
7837            // `u32::MAX` and a struct-literal `MeshPolicy { retries:
7838            // Some(100_000), .. }` (or the equivalent author-surface
7839            // `(:retries 100000)` / `(:retries 4294967295)` typo
7840            // landing in the slot) silently passed validate. The
7841            // runtime substrate consuming the value (Envoy's
7842            // `retry_policy.num_retries`, the future
7843            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7844            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7845            // policy into a thundering-herd amplification vector —
7846            // the caller's one request fans out to `retries`
7847            // server-side calls per edge per traversal, multiplying
7848            // load by `(retries+1)^depth` across the
7849            // synchronous-`:contratos` subgraph at the precise moment
7850            // the substrate is already failing (transient failure is
7851            // the trigger), exactly the failure mode AWS App Mesh's
7852            // explicit `maxRetries ≤ 10` schema cap exists to prevent.
7853            // The bracket set is `1..=POLICY_RETRIES_MAX`. Peer with
7854            // the sibling capped-`u32` `:politicas` axes
7855            // (`max_failures`, `rate_limit.rate`) and the peer capped-
7856            // `u32` axes in `:supervisor :max-restarts` +
7857            // `:limits :cpu`; all five now route through the same
7858            // canonical bracket helper.
7859            crate::render::require_positive_bounded_u32(
7860                r,
7861                POLICY_RETRIES_MAX,
7862                || AplicacaoError::PolicyRetriesZero,
7863                |retries| AplicacaoError::PolicyRetriesExceedsCap { retries },
7864            )?;
7865        }
7866        if let Some(cb) = p.circuit_breaker() {
7867            // Zero-floor + upper-cap bracket on the typed
7868            // `:max-failures` axis. See
7869            // [`crate::render::require_positive_bounded_u32`] for the
7870            // ordering discipline (zero-floor arm strictly precedes
7871            // cap arm so `max_failures == 0` surfaces the
7872            // self-locating `PolicyBreakerZeroFailures` diagnostic
7873            // with its omit-axis remediation directly named, not the
7874            // misleading `0 > POLICY_BREAKER_MAX_FAILURES_MAX ==
7875            // false` cap-arm miss). Until this bracket landed the top
7876            // edge ran all the way to `u32::MAX` and a struct-literal
7877            // `CircuitBreaker { max_failures: 100_000, .. }` (or the
7878            // equivalent author-surface `(:max-failures 100000)` /
7879            // `(:max-failures 4294967295)` typo landing in the slot)
7880            // silently passed validate. The runtime substrate
7881            // consuming the value (Envoy's
7882            // `outlier_detection.consecutive_5xx`, the future
7883            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7884            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7885            // breaker policy into a no-op — the trip threshold is
7886            // structurally so high that no realistic
7887            // failures-per-`:window` traffic shape can reach it, the
7888            // breaker never trips, and every typed-slot consumer
7889            // emits an Envoy / Cilium L7 overlay carrying a
7890            // protection that is structurally never enforced. The
7891            // bracket set is `1..=POLICY_BREAKER_MAX_FAILURES_MAX`;
7892            // peer with `retries` and `rate_limit.rate` on the same
7893            // helper.
7894            crate::render::require_positive_bounded_u32(
7895                cb.max_failures(),
7896                POLICY_BREAKER_MAX_FAILURES_MAX,
7897                || AplicacaoError::PolicyBreakerZeroFailures,
7898                |max_failures| AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
7899            )?;
7900            // Zero-floor + integer-millisecond canonical-form +
7901            // upper-cap bracket on the typed `:window` axis. See
7902            // [`crate::render::require_positive_canonical_bounded_duration`]
7903            // for the full three-arm ordering discipline (peer to the
7904            // `:timeout` site immediately above); every validated
7905            // value lies in `1ms..=POLICY_BREAKER_WINDOW_MAX`
7906            // (1ms..=1h), integer-millisecond granularity — the same
7907            // top-and-bottom-edge discipline
7908            // [`POLICY_TIMEOUT_MAX`] applies on the sibling
7909            // duration-typed `:politicas :timeout` axis.
7910            crate::render::require_positive_canonical_bounded_duration(
7911                cb.window(),
7912                POLICY_BREAKER_WINDOW_MAX,
7913                || AplicacaoError::PolicyBreakerZeroWindow,
7914                |window| AplicacaoError::PolicyBreakerWindowNotCanonical { window },
7915                |window| AplicacaoError::PolicyBreakerWindowExceedsCap { window },
7916            )?;
7917        }
7918        if let Some(rl) = p.rate_limit() {
7919            // Zero-floor + upper-cap bracket on the typed
7920            // `:rate-limit` rate axis. See
7921            // [`crate::render::require_positive_bounded_u32`] for the
7922            // ordering discipline (zero-floor arm strictly precedes
7923            // cap arm so `rl.rate == 0` surfaces the self-locating
7924            // `PolicyRateLimitZero` diagnostic with its omit-axis
7925            // remediation directly named, not the misleading
7926            // `0 > POLICY_RATE_LIMIT_MAX == false` cap-arm miss).
7927            // Until this bracket landed the top edge ran all the way
7928            // to `u32::MAX` and a struct-literal
7929            // `RateLimit { rate: u32::MAX, .. }` (or the equivalent
7930            // author-surface `(:rate-limit "4294967295/s")` /
7931            // `(:rate-limit "100000000/m")` typo landing in the slot)
7932            // silently passed validate. The runtime substrate
7933            // consuming the value (Envoy's
7934            // `local_rate_limit.token_bucket.max_tokens`, the future
7935            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7936            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7937            // rate-limit policy into a no-op limiter: the bucket
7938            // capacity is structurally so high that no realistic
7939            // per-edge traffic shape can drain it, the limiter never
7940            // trips, and every typed-slot consumer emits a "rate
7941            // declared" L7 overlay carrying enforcement that is
7942            // structurally never reached — the canonical
7943            // declared-but-inert footgun the sibling
7944            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap arm closes on
7945            // the peer no-op-breaker shape. The bracket set is
7946            // `1..=POLICY_RATE_LIMIT_MAX`; peer with `retries` and
7947            // `max_failures` on the same helper. The rate bracket
7948            // strictly precedes the window-canonical gate so a
7949            // structurally absurd rate magnitude surfaces the more
7950            // fundamental amplification-shape diagnostic before the
7951            // narrower codec-round-trip-shape diagnostic on `:window`.
7952            crate::render::require_positive_bounded_u32(
7953                rl.rate(),
7954                POLICY_RATE_LIMIT_MAX,
7955                || AplicacaoError::PolicyRateLimitZero,
7956                |rate| AplicacaoError::PolicyRateLimitExceedsCap { rate },
7957            )?;
7958            // The `:rate-limit` author surface is the canonical
7959            // `"<n>/<s|m|h>"` form, and the [`rate_limit_codec`] parser
7960            // accepts exactly the three-unit set (1s/60s/3600s) the
7961            // [`rate_limit_codec::render`] formatter emits the canonical
7962            // unit suffix for. A `RateLimit` whose `:window` is anything
7963            // else (zero, 30s, 45s, 120s, 86400s, …) is constructible
7964            // programmatically (struct literals in Rust + the typed
7965            // `Duration` field) but renders to a `<n>/<k>s` fragment
7966            // (the codec's fall-through) the parser then rejects on
7967            // round-trip — silently breaking the THEORY.md §V.2.7
7968            // render-determinism contract for any consumer that
7969            // serializes-then-deserializes the typed slot. Lifting the
7970            // canonical-window invariant to a build-time gate at
7971            // `validate_politicas` makes the codec's round-trip property
7972            // a structural property of the validated typed value:
7973            // every `RateLimit` past `AplicacaoSpec::validate` has a
7974            // window the codec round-trips losslessly, so the next
7975            // typed-slot wiring (the future `CiliumClusterwideEnvoyConfig`
7976            // emitter for `:politicas :rate-limit`, MESH-COMPOSITION
7977            // §III.2 #3) reaches for `rate_limit.window` knowing the
7978            // value is in the codec's accepted set without re-validating
7979            // at the renderer layer. Same trajectory as c4213a4 (typed
7980            // WitContract endpoint/subject/slot value-shape gates) and
7981            // the b0c8389 :behavior + :upgrade-from script-path lifts:
7982            // the typed slot's valid set matches its codec's accepted
7983            // set, structurally.
7984            // Route the canonical-window shape-gate through the substrate
7985            // primitive [`RateLimit::canonical_unit`] rather than the free
7986            // module-private [`is_canonical_rate_limit_window`] predicate:
7987            // both projections resolve `Duration → Option<RateLimitUnit>`
7988            // through [`RateLimitUnit::from_window`] (the sole `Duration → Self`
7989            // arm on the closed-set typed enum), but the accessor is the
7990            // typed method every downstream consumer of the validated slot
7991            // ([`rate_limit_codec::render`]'s canonical arm above, the
7992            // future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7993            // per-`:politicas :rate-limit` admission webhook, the future
7994            // per-`:contratos`-edge rate-limit-override overlay
7995            // MESH-COMPOSITION §III.2 #3 acknowledges) already reads. Two
7996            // production consumers of the canonical-unit axis (the codec
7997            // render and this validate gate) now key off exactly one typed
7998            // dispatch on the substrate primitive, so any future extension
7999            // to `canonical_unit` (a per-cluster canonical-window overlay
8000            // the operator pins through a future `:contratos :rate-limit
8001            // -unit-overrides` slot, a per-tenant unit-alias table the M4
8002            // CR materializer resolves per-CR) reaches both consumers by
8003            // construction rather than a coordinated rewrite of every
8004            // free-helper call site.
8005            if rl.canonical_unit().is_none() {
8006                return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical {
8007                    window: rl.window(),
8008                });
8009            }
8010        }
8011        Ok(())
8012    }
8013
8014    /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
8015    /// A synchronous edge is any contract whose typed [`WitTarget`] is
8016    /// `Http`, `Store`, or `Capability` — the caller blocks on the
8017    /// callee, so a cycle would deadlock at runtime. Pub-sub edges
8018    /// (`WitTarget::PubSub`) are skipped: an event publisher does not
8019    /// block on its subscribers, so they can never close a sync loop.
8020    ///
8021    /// Iterative DFS with three-coloring; the reported cycle is the
8022    /// path of caixa names traversed from the back-edge target around
8023    /// to itself, in declaration order. Adjacency lists and DFS roots
8024    /// are visited in `BTreeMap` key order so the diagnostic is
8025    /// deterministic across runs.
8026    fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
8027        use std::collections::{BTreeMap, BTreeSet};
8028
8029        #[derive(Clone, Copy, PartialEq, Eq)]
8030        enum Mark {
8031            White,
8032            Gray,
8033            Black,
8034        }
8035
8036        let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
8037        for m in self.membros() {
8038            adj.entry(m.nome()).or_default();
8039        }
8040        for c in self.contratos() {
8041            // target() was already called by validate(); re-running here
8042            // keeps detect_sync_cycles self-contained for callers that
8043            // reuse it (M4 per-edge policy resolver) without revalidating.
8044            //
8045            // The pub-sub-arm check routes through the lifted
8046            // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
8047            // arm-discriminator predicate rather than a raw `matches!(…,
8048            // WitTarget::PubSub { .. })` on the variant so a future
8049            // rebrand on the axis (an M4 per-edge WIT registry split of
8050            // [`WitTarget::PubSub`] into shape-specific peers, a
8051            // per-consumer rename that the accept-set already carries)
8052            // reaches this call site through the derive rather than a
8053            // scattered per-arm `matches!` rewrite — same
8054            // `IsVariant`-derived-arm-discriminator discipline the
8055            // peer closed-set typed enums ([`crate::CaixaKind`] via
8056            // f5bba80, [`PlacementStrategy`] via 766ec63,
8057            // [`crate::supervisor::RestartStrategy`] +
8058            // [`crate::supervisor::RestartPolicy`],
8059            // [`crate::upgrade::UpgradeInstruction`] via 915a934)
8060            // already route through on the substrate's other typed-enum
8061            // arm-discriminator axes.
8062            if c.target()?.is_pubsub() {
8063                continue;
8064            }
8065            adj.entry(c.source()).or_default().insert(c.destination());
8066        }
8067
8068        let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
8069        let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
8070
8071        // Stable DFS root order — BTreeMap iteration is sorted by key.
8072        let roots: Vec<&str> = adj.keys().copied().collect();
8073
8074        // Frame: (node, sorted-neighbours snapshot, next-edge index).
8075        for root in roots {
8076            if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
8077                continue;
8078            }
8079            let root_neighbors: Vec<&str> = adj
8080                .get(root)
8081                .map(|s| s.iter().copied().collect())
8082                .unwrap_or_default();
8083            let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
8084            color.insert(root, Mark::Gray);
8085
8086            loop {
8087                // Read+advance the top frame in one borrow scope so we
8088                // can later mutate the stack (push/pop) without holding
8089                // a borrow across.
8090                let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
8091                    let node = top.0;
8092                    if top.2 >= top.1.len() {
8093                        (node, None)
8094                    } else {
8095                        let nxt = top.1[top.2];
8096                        top.2 += 1;
8097                        (node, Some(nxt))
8098                    }
8099                });
8100                let Some((node, nxt_opt)) = step else { break };
8101                let Some(nxt) = nxt_opt else {
8102                    color.insert(node, Mark::Black);
8103                    stack.pop();
8104                    continue;
8105                };
8106                let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
8107                match nxt_color {
8108                    Mark::Gray => {
8109                        // Reconstruct the cycle from `node` back through
8110                        // the parent chain to `nxt`, then close.
8111                        let mut cycle = Vec::new();
8112                        let mut cur = node;
8113                        cycle.push(cur.to_string());
8114                        while cur != nxt {
8115                            match parent.get(cur).copied() {
8116                                Some(p) => {
8117                                    cur = p;
8118                                    cycle.push(cur.to_string());
8119                                }
8120                                None => break,
8121                            }
8122                        }
8123                        cycle.reverse();
8124                        cycle.push(nxt.to_string());
8125                        return Err(AplicacaoError::ContratoCycle { cycle });
8126                    }
8127                    Mark::White => {
8128                        parent.insert(nxt, node);
8129                        color.insert(nxt, Mark::Gray);
8130                        let nxt_neighbors: Vec<&str> = adj
8131                            .get(nxt)
8132                            .map(|s| s.iter().copied().collect())
8133                            .unwrap_or_default();
8134                        stack.push((nxt, nxt_neighbors, 0));
8135                    }
8136                    Mark::Black => {}
8137                }
8138            }
8139        }
8140        Ok(())
8141    }
8142
8143    /// Substrate-canonical destination-facing TCP port every emitted
8144    /// per-Aplicacao artifact must key `destination`-shaped port axes
8145    /// off. Returns the typed `:entrada :port` scalar when this
8146    /// Aplicacao's `:entrada` block names `destination` under its
8147    /// `:para` axis (the destination Servico *is* the ingress apex, so
8148    /// the substrate honors the author-declared listener port
8149    /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
8150    /// fallback otherwise (every non-apex destination — the internal
8151    /// mesh Servicos `:contratos` reach across, the future per-edge
8152    /// policy resolver's per-destination probe targets, the
8153    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
8154    /// L4 port resolver — reads the same substrate-canonical port floor
8155    /// by construction).
8156    ///
8157    /// Prior to this lift the "if :entrada matches this destination use
8158    /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
8159    /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
8160    /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
8161    /// prior to this lift), with no typed method on the substrate primitive
8162    /// that named the rule. A future per-destination port axis addition
8163    /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
8164    /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
8165    /// per-Servico listener ports land, a per-cluster override the operator
8166    /// pins through a future `:placement :default-port` slot — would have
8167    /// to be threaded through every renderer's inline cascade in lockstep
8168    /// or one consumer would silently disagree on which port a given
8169    /// destination Servico's ingress lands at. Lifting the rule to a
8170    /// typed method on the substrate primitive means the M4 CR
8171    /// materializer, the future per-edge policy resolver, and every
8172    /// downstream test-fixture navigator reach for exactly one typed
8173    /// dispatch — the resolver's accept-set moves as a unit on any
8174    /// future axis addition.
8175    ///
8176    /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
8177    /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
8178    /// the typed primitive, thin projections at each consumer"
8179    /// discipline lifts on the sibling `:contratos` payload / `:politicas
8180    /// :rate-limit` unit-suffix axes; extends the discipline onto the
8181    /// destination-facing port-resolution axis every per-Aplicacao
8182    /// L4-fallback renderer consumes.
8183    #[must_use]
8184    pub fn port_for_destination(&self, destination: &str) -> u16 {
8185        // Route the per-`:entrada` composite-reference read through
8186        // the lifted [`AplicacaoSpec::entrada`] accessor rather than
8187        // the raw `self.entrada.as_ref()` field access — the
8188        // per-destination L4-port fallback resolver's composite-
8189        // projection seed is now the canonical read-side surface
8190        // every per-Aplicacao entrada consumer routes through, peer
8191        // of the sibling `validate` per-`:entrada` shape-and-
8192        // membership gate migration on the same outer-composite
8193        // axis.
8194        // Route the per-`:entrada` apex-destination membership probe
8195        // through the lifted [`Entrada::destination`] accessor rather
8196        // than the raw `e.para == destination` field access — the last
8197        // un-lifted `.para` production-code read site on the per-
8198        // `:entrada` `:para` axis, sibling to the four caixa-core
8199        // consumer sites the peer 15ddd8c converge already routed
8200        // through the accessor (the three
8201        // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
8202        // membership gate sites: the `validate_entrada_para` DNS-1123
8203        // shape gate, the per-`:membros` membership lookup, and the
8204        // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
8205        // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
8206        // `entrada.para`-projection converge at
8207        // caixa-core/src/render.rs (the `gateway_api_http_route_name`
8208        // route-name projection site). Prior to this converge the
8209        // `port_for_destination` resolver was the solitary consumer
8210        // bypassing the typed dispatch on the `.para` axis — the two
8211        // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
8212        // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
8213        // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
8214        // reach through the same accessor family compose with this
8215        // resolver at the emit boundary via the apex-identity
8216        // invariant `spec.port_for_destination(entrada.destination())
8217        // == entrada.port` the sibling
8218        // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
8219        // pin pins across four permutations. A future extension of the
8220        // `:entrada :para` axis to a richer author surface (a per-
8221        // cluster alias overlay the operator pins through a future
8222        // `:placement`-scoped slot, a namespace-qualified rewrite the
8223        // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
8224        // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
8225        // §III.2 acknowledges) that lands on the accessor would silently
8226        // disagree between this resolver and the two `caixa-mesh` emit
8227        // sites — an author-declared `:para "cart"` value the accessor
8228        // rewrote to `"cart-v2"` under a future canary arm would leave
8229        // the resolver's membership arm falling through to
8230        // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
8231        // `.para`) while the peer emit-site consumers landed on the
8232        // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
8233        // silently disagreed on which destination port a given typed
8234        // `:entrada` resolves to at cluster-apply time. Pinned by the
8235        // drift-detection test
8236        // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
8237        // below.
8238        self.entrada()
8239            .filter(|e| e.destination() == destination)
8240            .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
8241    }
8242}
8243
8244/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
8245/// entry may name the Aplicacao's own `:nome`.
8246///
8247/// An Aplicacao that lists itself as a member is a degenerate self-edge in
8248/// the typed graph — the application graph is a DAG rooted at the Aplicacao
8249/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
8250/// Servicos that compose the app; an Aplicacao is never its own constituent),
8251/// and the lacre pipeline's closure-resolution would otherwise be handed a
8252/// node that is its own parent: a one-node cycle it either rejects far from
8253/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
8254/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
8255/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
8256/// label + lacre closure root), a member whose `:caixa` equals the
8257/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
8258/// peer.
8259///
8260/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
8261/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
8262/// gate `validate_upgrade_from_against_versao` and the supervision-tree
8263/// self-parent gate `crate::supervisor::validate_no_self_supervision`
8264/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
8265/// not a tree/mesh edge" discipline, here on the second typed-graph axis
8266/// (the Aplicacao :membros set; the supervision-tree :children list was the
8267/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
8268/// every validated Supervisor's children are distinct from its `:nome`,
8269/// every validated Aplicacao's membros are distinct from its `:nome`. The
8270/// transitive consequence is that `:entrada :para` and `:contratos`
8271/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
8272/// name the Aplicacao itself, without re-deriving the partition.
8273pub fn validate_no_self_membership(
8274    membros: &[Membro],
8275    parent_nome: &str,
8276) -> Result<(), AplicacaoError> {
8277    for m in membros {
8278        if m.nome() == parent_nome {
8279            return Err(AplicacaoError::MembroIsSelfAplicacao {
8280                caixa: parent_nome.to_string(),
8281            });
8282        }
8283    }
8284    Ok(())
8285}
8286
8287#[derive(Debug, Error, PartialEq, Eq)]
8288pub enum AplicacaoError {
8289    #[error("Aplicacao must declare at least one :membros entry")]
8290    NoMembros,
8291    #[error(
8292        ":membros entry has empty :caixa (every member must name a Servico; \
8293         omit the entry instead of carrying an empty name)"
8294    )]
8295    MembroCaixaEmpty,
8296    #[error(
8297        ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
8298         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
8299         name / label value the member name lands in; use a lowercase \
8300         alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
8301    )]
8302    MembroCaixaInvalid { caixa: String, reason: String },
8303    #[error(
8304        ":membros entry {caixa:?} has empty :versao (every member must pin a \
8305         semver constraint that resolves through the lacre pipeline)"
8306    )]
8307    MembroVersaoEmpty { caixa: String },
8308    #[error(
8309        ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
8310         requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
8311         `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
8312         carries; the lacre pipeline resolves both through the same parser)"
8313    )]
8314    MembroVersaoInvalid {
8315        caixa: String,
8316        versao: String,
8317        reason: String,
8318    },
8319    #[error(
8320        ":membros entry {caixa:?} appears more than once (the graph node set \
8321         is a set, not a multiset; duplicate members produce duplicate \
8322         programs.yaml entries and ambiguous :contratos membership lookups)"
8323    )]
8324    MembroDuplicate { caixa: String },
8325    #[error(
8326        "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
8327         never its own constituent Servico (the application graph is a DAG rooted \
8328         at the Aplicacao; :membros names the *other* caixas that compose the \
8329         app, not the app itself). Since every :nome is a globally-unique \
8330         substrate identity, a member naming the Aplicacao's own :nome is a \
8331         one-node lacre-closure recursion, not a coincidentally-named peer; \
8332         drop the self-referential :membros entry or rename it to the actual \
8333         constituent caixa."
8334    )]
8335    MembroIsSelfAplicacao { caixa: String },
8336    #[error(
8337        "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
8338         caixa declared in :membros; omit the contract or fill the {slot} field with a \
8339         member name)"
8340    )]
8341    ContratoCaixaEmpty { slot: &'static str },
8342    #[error(
8343        "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
8344         :contratos {slot} value names a member of :membros, which is itself a \
8345         DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
8346         object the member name lands in — Service, Pod, identity-based Cilium \
8347         selector; use a lowercase alphanumeric + hyphen identifier like \
8348         `\"checkout\"` or `\"cart-v2\"`)"
8349    )]
8350    ContratoCaixaInvalid {
8351        slot: &'static str,
8352        caixa: String,
8353        reason: String,
8354    },
8355    #[error("contrato references caixa {caixa:?} not declared in :membros")]
8356    ContratoMemberMissing { caixa: String },
8357    #[error(
8358        "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
8359         entry is an inter-Servico contract whose :de and :para must name distinct \
8360         :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
8361         the contract, or point :para at the member it actually calls)"
8362    )]
8363    ContratoSelfLoop { caixa: String, wit: String },
8364    #[error("contrato {de:?} → {para:?} has empty :wit")]
8365    EmptyWit { de: String, para: String },
8366    #[error(
8367        "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
8368         {reason} (the substrate dispatches `:wit` values on the canonical \
8369         lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
8370         `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
8371         demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
8372         kebab-case identifier per segment)"
8373    )]
8374    ContratoWitInvalid {
8375        de: String,
8376        para: String,
8377        wit: String,
8378        reason: String,
8379    },
8380    #[error(
8381        ":entrada :para is empty (every :entrada must route to a caixa declared in \
8382         :membros; fill the :para field with a member name)"
8383    )]
8384    EntradaParaEmpty,
8385    #[error(
8386        ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
8387         :entrada :para value names a member of :membros, which is itself a DNS-1123 \
8388         label per the K8s apiserver's `metadata.name` rule on every object the \
8389         member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
8390         Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
8391         `\"checkout\"` or `\"cart-v2\"`)"
8392    )]
8393    EntradaParaInvalid { para: String, reason: String },
8394    #[error(":entrada routes to caixa {para:?} not declared in :membros")]
8395    EntradaMemberMissing { para: String },
8396    #[error(":entrada must declare a non-empty :host")]
8397    EmptyEntradaHost,
8398    #[error(
8399        ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
8400         (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
8401         `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
8402         like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
8403    )]
8404    EntradaHostInvalid { host: String, reason: String },
8405    #[error(":entrada :port must be in 1..=65535, got 0")]
8406    EntradaPortZero,
8407    #[error(":entrada :paths entry is empty (use the empty list to match all)")]
8408    EntradaPathEmpty,
8409    #[error(
8410        ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
8411    )]
8412    EntradaPathNotAbsolute { path: String },
8413    #[error(
8414        ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
8415         value: {reason} (the K8s apiserver enforces the same shape on \
8416         `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
8417         single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
8418         requires percent-encoding `%XX` for non-ASCII and whitespace)"
8419    )]
8420    EntradaPathInvalid { path: String, reason: String },
8421    #[error(":entrada :paths entry {path:?} appears more than once")]
8422    EntradaPathDuplicate { path: String },
8423    #[error(
8424        ":placement {estrategia} requires at least one :clusters entry \
8425         (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
8426    )]
8427    PlacementWithoutClusters { estrategia: PlacementStrategy },
8428    #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
8429    PlacementClusterEmpty,
8430    #[error(
8431        ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
8432         (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
8433         in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
8434         future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
8435         — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
8436         identifier like `\"rio\"` or `\"mar-east\"`)"
8437    )]
8438    PlacementClusterInvalid { cluster: String, reason: String },
8439    #[error(":placement :clusters entry {cluster:?} appears more than once")]
8440    PlacementClusterDuplicate { cluster: String },
8441    #[error(
8442        ":placement :affinity must be non-empty when set (omit :affinity to express \
8443         `no placement hint`)"
8444    )]
8445    PlacementAffinityEmpty,
8446    #[error(
8447        ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
8448         (placement hints land verbatim in the M3 Adaptive compression overlay's \
8449         `placement.affinity` field and in every future M4 placement-engine routing \
8450         axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
8451         selector — both enforce the DNS-1123 label rule on admission; use a \
8452         lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
8453         `\"low-latency\"`, or `\"anti-affinity\"`)"
8454    )]
8455    PlacementAffinityInvalid { affinity: String, reason: String },
8456    #[error(":placement Sharded requires :shard-key")]
8457    ShardedWithoutKey,
8458    #[error(
8459        ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
8460         hashes every entity onto the same shard, defeating sharding entirely)"
8461    )]
8462    ShardedKeyEmpty,
8463    #[error(
8464        ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
8465         entity-id extractor expression: {reason} (the future M4 Akka-style \
8466         cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
8467         as a single-token property reference and hashes the extracted entity ID \
8468         to compute shard placement; use a printable-ASCII extractor expression \
8469         like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
8470         `\"${{tenant}}\"`)"
8471    )]
8472    ShardKeyInvalid { shard_key: String, reason: String },
8473    #[error(
8474        ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
8475         Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
8476         convention); :estrategia Replicated runs every cluster active-active and \
8477         :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
8478         distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
8479         to :estrategia Sharded if hash-keyed routing is the intent"
8480    )]
8481    ShardKeyOnNonSharded {
8482        estrategia: PlacementStrategy,
8483        shard_key: String,
8484    },
8485    #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
8486    ContratoMissingTarget {
8487        de: String,
8488        para: String,
8489        wit: String,
8490        expected: &'static str,
8491    },
8492    #[error(
8493        "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
8494         expected `:{expected}` only"
8495    )]
8496    ContratoWrongTarget {
8497        de: String,
8498        para: String,
8499        wit: String,
8500        expected: &'static str,
8501    },
8502    #[error(
8503        "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
8504         like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
8505         that matches no traffic and silently drops every request)"
8506    )]
8507    ContratoEndpointEmpty { de: String, para: String },
8508    #[error(
8509        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
8510         (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
8511         :entrada :paths)"
8512    )]
8513    ContratoEndpointNotAbsolute {
8514        de: String,
8515        para: String,
8516        endpoint: String,
8517    },
8518    #[error(
8519        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
8520         Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
8521         emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
8522         caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
8523         shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
8524         like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
8525         and whitespace)"
8526    )]
8527    ContratoEndpointInvalid {
8528        de: String,
8529        para: String,
8530        endpoint: String,
8531        reason: String,
8532    },
8533    #[error(
8534        "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
8535         subject is a no-op subscribe; omit :subject only if the WIT world is not \
8536         pub-sub-shaped)"
8537    )]
8538    ContratoSubjectEmpty { de: String, para: String },
8539    #[error(
8540        "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
8541         NATS subject: {reason} (the NATS server's subject parser enforces the \
8542         same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
8543         single-token and `>` multi-token wildcards — at publish/subscribe time; \
8544         use a token-by-token form like `\"checkout.events.charge.failed\"` or \
8545         `\"orders.*.completed\"` — a malformed subject silently drops every \
8546         message at runtime far from the source caixa.lisp)"
8547    )]
8548    ContratoSubjectInvalid {
8549        de: String,
8550        para: String,
8551        subject: String,
8552        reason: String,
8553    },
8554    #[error(
8555        "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
8556         addresses the bucket root, defeating the per-key isolation the slot exists \
8557         for; omit :slot only if the WIT world is not store-shaped)"
8558    )]
8559    ContratoSlotEmpty { de: String, para: String },
8560    #[error(
8561        "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
8562         WASI keyvalue store slot template: {reason} (the substrate enforces \
8563         the printable-ASCII intersection-floor every kv backend admits — \
8564         use a single-token path / template expression like `\"checkout/$orderId\"`, \
8565         `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
8566         percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
8567         slot either gets rejected on write by strict backends or silently \
8568         corrupts the next read on permissive ones, far from the source caixa.lisp)"
8569    )]
8570    ContratoSlotInvalid {
8571        de: String,
8572        para: String,
8573        slot: String,
8574        reason: String,
8575    },
8576    #[error(
8577        "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
8578         or an event-sourced indirection (MESH-COMPOSITION §III.3)",
8579        cycle.join(" → ")
8580    )]
8581    ContratoCycle { cycle: Vec<String> },
8582    #[error(
8583        ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
8584         than once (the typed graph edges are a set, not a multiset; duplicate \
8585         contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
8586         values that K8s admission rejects far from the source caixa.lisp)"
8587    )]
8588    ContratoDuplicate {
8589        de: String,
8590        para: String,
8591        wit: String,
8592        target: String,
8593    },
8594    #[error(
8595        ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
8596         contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
8597         express `no per-call deadline on this axis`"
8598    )]
8599    PolicyTimeoutZero,
8600    #[error(
8601        ":politicas :retries must be > 0 when set; omit :retries to express \
8602         `no retries on transient failure`"
8603    )]
8604    PolicyRetriesZero,
8605    #[error(
8606        ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
8607         (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
8608         retry policy into a thundering-herd amplification vector on transient \
8609         failure (one caller request fans out to `(retries+1)^depth` server-side \
8610         calls across the synchronous-:contratos subgraph), exactly the failure \
8611         mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
8612         Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
8613         or omit :retries to disable retries entirely"
8614    )]
8615    PolicyRetriesExceedsCap { retries: u32 },
8616    #[error(
8617        ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
8618         breaker trips on the first call); omit :circuit-breaker to disable it"
8619    )]
8620    PolicyBreakerZeroFailures,
8621    #[error(
8622        ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
8623         mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
8624         above this cap turns the typed breaker policy into a no-op: the trip \
8625         threshold is structurally so high that no realistic failures-per-:window \
8626         traffic shape can reach it, so the breaker never trips and every typed-slot \
8627         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
8628         Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
8629         structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
8630         Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
8631         omit :circuit-breaker to disable the breaker entirely"
8632    )]
8633    PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
8634    #[error(
8635        ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
8636         tracks no failures); omit :circuit-breaker to disable it"
8637    )]
8638    PolicyBreakerZeroWindow,
8639    #[error(
8640        ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
8641         request); omit :rate-limit to disable rate limiting"
8642    )]
8643    PolicyRateLimitZero,
8644    #[error(
8645        ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
8646         (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
8647         rate-limit policy into a no-op limiter: the token-bucket capacity is \
8648         structurally so high that no realistic per-edge traffic shape can drain it, \
8649         so the limiter never trips and every typed-slot consumer (the future \
8650         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
8651         local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
8652         that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
8653         Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
8654         Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
8655         Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
8656         to disable rate limiting entirely"
8657    )]
8658    PolicyRateLimitExceedsCap { rate: u32 },
8659    #[error(
8660        ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
8661         the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
8662         rate-limit codec round-trips losslessly; got {window:?} which renders to a \
8663         non-round-trippable form (omit :rate-limit to disable, or pick one of the \
8664         three canonical windows)"
8665    )]
8666    PolicyRateLimitWindowNotCanonical { window: Duration },
8667    #[error(
8668        ":politicas :timeout must be an integer number of milliseconds — the canonical \
8669         authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
8670         duration codec round-trips losslessly; got {timeout:?} which carries a \
8671         sub-millisecond residue that either truncates to a different `Duration` on \
8672         re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
8673         to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
8674         zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
8675         (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
8676    )]
8677    PolicyTimeoutNotCanonical { timeout: Duration },
8678    #[error(
8679        ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
8680         (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
8681         per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
8682         overlays carry a deadline so long no realistic synchronous-:contratos \
8683         traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
8684         CSE invariant degenerates to enforcement only at the per-Servico \
8685         `:limits :wall-clock` layer — far above the per-edge granularity the typed \
8686         `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
8687         (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
8688         ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
8689         maxes out at the same `3600s` ceiling) or omit :timeout to express \
8690         `no per-call deadline on this axis` (the synchronous-call deadline then \
8691         relies entirely on the per-Servico `:limits :wall-clock` axis)"
8692    )]
8693    PolicyTimeoutExceedsCap { timeout: Duration },
8694    #[error(
8695        ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
8696         the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
8697         the shared duration codec round-trips losslessly; got {window:?} which carries a \
8698         sub-millisecond residue that either truncates to a different `Duration` on \
8699         re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
8700         Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
8701    )]
8702    PolicyBreakerWindowNotCanonical { window: Duration },
8703    #[error(
8704        ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
8705         (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
8706         rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
8707         is structurally so long that transient failures are never forgotten, the breaker \
8708         trips once and stays tripped for the lifetime of the component, and every typed-slot \
8709         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
8710         outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
8711         Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
8712         default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
8713         the breaker entirely"
8714    )]
8715    PolicyBreakerWindowExceedsCap { window: Duration },
8716}
8717
8718#[cfg(test)]
8719mod tests {
8720    use super::*;
8721
8722    fn membro(name: &str, ver: &str) -> Membro {
8723        Membro {
8724            caixa: name.into(),
8725            versao: ver.into(),
8726        }
8727    }
8728
8729    fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
8730        WitContract {
8731            de: de.into(),
8732            para: para.into(),
8733            wit: "wasi:http/proxy".into(),
8734            endpoint: Some(ep.into()),
8735            subject: None,
8736            slot: None,
8737        }
8738    }
8739
8740    fn three_member_spec() -> AplicacaoSpec {
8741        AplicacaoSpec {
8742            membros: vec![
8743                membro("catalog", "^0.1"),
8744                membro("cart", "^0.1"),
8745                membro("payment", "^0.2"),
8746            ],
8747            contratos: vec![
8748                contract_http("cart", "catalog", "/products/:id"),
8749                contract_http("cart", "payment", "/charge"),
8750            ],
8751            politicas: MeshPolicy {
8752                timeout: Some(Duration::from_secs(30)),
8753                retries: Some(3),
8754                mtls_required: Some(true),
8755                ..Default::default()
8756            },
8757            placement: Placement {
8758                estrategia: PlacementStrategy::Replicated,
8759                clusters: vec!["rio".into(), "mar".into()],
8760                affinity: Some("data-locality".into()),
8761                shard_key: None,
8762            },
8763            entrada: Some(Entrada {
8764                host: "checkout.quero.cloud".into(),
8765                para: "cart".into(),
8766                paths: vec!["/api/cart".into(), "/api/products".into()],
8767                port: 8080,
8768            }),
8769        }
8770    }
8771
8772    #[test]
8773    fn happy_path_validates() {
8774        three_member_spec().validate().unwrap();
8775    }
8776
8777    #[test]
8778    fn rejects_empty_membros() {
8779        let mut s = three_member_spec();
8780        s.membros = vec![];
8781        assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
8782    }
8783
8784    #[test]
8785    fn rejects_empty_membro_caixa() {
8786        // A `:caixa ""` entry has no name to render into programs.yaml
8787        // and no caixa.lisp to resolve at lacre time.
8788        let mut s = three_member_spec();
8789        s.membros[1].caixa = String::new();
8790        assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
8791    }
8792
8793    #[test]
8794    fn rejects_empty_membro_versao() {
8795        // A `:versao ""` entry can't pin a semver constraint, so the
8796        // lacre pipeline fails far from the source.
8797        let mut s = three_member_spec();
8798        s.membros[2].versao = String::new();
8799        let err = s.validate().unwrap_err();
8800        assert!(
8801            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
8802            "got {err:?}"
8803        );
8804    }
8805
8806    #[test]
8807    fn rejects_duplicate_membro_caixa() {
8808        // Two `:membros` entries with the same `:caixa` collapse to one
8809        // node in the membership HashSet, which masks `:contratos`
8810        // membership errors and produces duplicate programs.yaml entries.
8811        let mut s = three_member_spec();
8812        s.membros.push(membro("cart", "^0.2"));
8813        let err = s.validate().unwrap_err();
8814        assert!(
8815            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
8816            "got {err:?}"
8817        );
8818    }
8819
8820    #[test]
8821    fn rejects_invalid_membro_versao_requirement() {
8822        // The fail-before-pass-after pin: a non-empty but malformed
8823        // semver requirement (`"^bad-version"`) silently passed
8824        // `validate()` on every pre-gate codebase because the prior
8825        // shape only refused the empty string. The parse failure
8826        // surfaced far downstream at lacre-resolve time with a
8827        // `semver::Error` that didn't name which `:membros` entry
8828        // carried the typo. The new gate moves the check to caixa-build
8829        // time at the source caixa.lisp.
8830        let mut s = three_member_spec();
8831        s.membros[2].versao = "^bad-version".into();
8832        let err = s.validate().unwrap_err();
8833        assert!(
8834            matches!(
8835                err,
8836                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8837                    if caixa == "payment" && versao == "^bad-version"
8838            ),
8839            "got {err:?}"
8840        );
8841    }
8842
8843    #[test]
8844    fn rejects_membro_versao_with_double_caret_typo() {
8845        // `"^^0.1"` is the canonical doubled-caret typo — looks like a
8846        // Cargo-shaped requirement on first glance but fails the parser
8847        // because semver doesn't accept stacked operators. Pin this
8848        // adjacent-shape footgun explicitly so a future relaxation that
8849        // accepts "looks-canonical-but-isn't" forms surfaces here.
8850        let mut s = three_member_spec();
8851        s.membros[0].versao = "^^0.1".into();
8852        let err = s.validate().unwrap_err();
8853        assert!(
8854            matches!(
8855                err,
8856                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8857                    if caixa == "catalog" && versao == "^^0.1"
8858            ),
8859            "got {err:?}"
8860        );
8861    }
8862
8863    #[test]
8864    fn rejects_membro_versao_with_v_prefixed_tag() {
8865        // `"v0.1"` is the canonical "git-tag-shape leaking into the
8866        // semver requirement slot" typo — an author copies the
8867        // publish-side git-tag string verbatim into `:versao`, but
8868        // Cargo's semver parser rejects the leading `v` (only digits +
8869        // canonical operators are valid in the major-version
8870        // position). The gate's diagnostic names which member entry
8871        // carried the v-prefix so the fix is one edit, not a grep
8872        // through every member's `:versao`. (Note: bare `x`-glob
8873        // shorthands like `^0.1.x` are *accepted* by the semver crate
8874        // as an `*` wildcard on the patch axis — they're a Cargo-side
8875        // valid shape, not a typo, so the gate intentionally lets them
8876        // through.)
8877        let mut s = three_member_spec();
8878        s.membros[1].versao = "v0.1".into();
8879        let err = s.validate().unwrap_err();
8880        assert!(
8881            matches!(
8882                err,
8883                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8884                    if caixa == "cart" && versao == "v0.1"
8885            ),
8886            "got {err:?}"
8887        );
8888    }
8889
8890    #[test]
8891    fn accepts_canonical_membro_versao_forms() {
8892        // The four Cargo-shaped requirement forms `:deps :versao`
8893        // already accepts via `crate::parse_requirement` must pass the
8894        // membros gate without re-validating at the resolver layer.
8895        // Pin every leg so a future tightening of the canonical set
8896        // surfaces here as a test failure.
8897        for form in [
8898            "^0.1",      // caret — minor-range pin (the most common shape)
8899            "~0.1.2",    // tilde — patch-range pin
8900            "0.1.0",     // exact — single-version pin
8901            "*",         // wildcard — explicitly any-version (semver::VersionReq::STAR)
8902            ">=0.1, <2", // multi-range — comma-separated comparators
8903        ] {
8904            let mut s = three_member_spec();
8905            for m in &mut s.membros {
8906                m.versao = form.into();
8907            }
8908            s.validate()
8909                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
8910        }
8911    }
8912
8913    #[test]
8914    fn membro_versao_empty_takes_precedence_over_invalid() {
8915        // Order pin: the existing `MembroVersaoEmpty` diagnostic
8916        // (which doesn't try to parse) fires before the new
8917        // `MembroVersaoInvalid` parse-side diagnostic, so an empty
8918        // `:versao` keeps its narrower error message — `parse_requirement`
8919        // would also reject `""`, but the empty-string arm is the more
8920        // self-locating diagnostic for the author.
8921        let mut s = three_member_spec();
8922        s.membros[1].versao = String::new();
8923        let err = s.validate().unwrap_err();
8924        assert!(
8925            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
8926            "got {err:?}"
8927        );
8928    }
8929
8930    #[test]
8931    fn membro_versao_invalid_fires_before_duplicate_check() {
8932        // Order pin: a malformed requirement on a non-duplicate entry
8933        // surfaces *its own* diagnostic (which names the offending
8934        // `:versao` string), even when a later entry would otherwise
8935        // collapse onto an earlier name. The per-entry shape gate runs
8936        // inline before the duplicate-key insert, parallel to
8937        // `membros_validation_runs_before_contratos_membership_check`
8938        // and `duplicate_contrato_gate_runs_after_target_shape_check`.
8939        let mut s = three_member_spec();
8940        s.membros[0].versao = "^bad".into();
8941        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
8942        let err = s.validate().unwrap_err();
8943        assert!(
8944            matches!(
8945                err,
8946                AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
8947            ),
8948            "got {err:?}"
8949        );
8950    }
8951
8952    #[test]
8953    fn membro_versao_invalid_diagnostic_carries_offending_versao() {
8954        // The diagnostic-shape pin: the error names the offending
8955        // `:versao` value verbatim so the author can grep their
8956        // caixa.lisp without re-running the build, and carries a
8957        // non-empty `reason` from `semver::VersionReq::parse` so the
8958        // parser's own wording flows through to the diagnostic.
8959        let mut s = three_member_spec();
8960        s.membros[2].versao = "not-a-req".into();
8961        let err = s.validate().unwrap_err();
8962        let AplicacaoError::MembroVersaoInvalid {
8963            caixa,
8964            versao,
8965            reason,
8966        } = err
8967        else {
8968            panic!("expected MembroVersaoInvalid, got other variant");
8969        };
8970        assert_eq!(caixa, "payment");
8971        assert_eq!(versao, "not-a-req");
8972        assert!(
8973            !reason.is_empty(),
8974            "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
8975        );
8976    }
8977
8978    #[test]
8979    fn membro_versao_invalid_runs_before_contratos_check() {
8980        // A malformed `:versao` on any member must surface its own
8981        // diagnostic (which names *which* member to fix) before any
8982        // `:contratos` membership lookup raises `ContratoMemberMissing`.
8983        // The `:contratos` gate runs after `validate_membros`, so this
8984        // is structurally guaranteed — pin it explicitly so a future
8985        // refactor that reorders the gates surfaces here.
8986        let mut s = three_member_spec();
8987        s.membros[1].versao = "^^0.1".into();
8988        // Add a contrato whose `:para` doesn't exist — would normally
8989        // raise ContratoMemberMissing at the membership lookup, but
8990        // the membros gate must fire first.
8991        s.contratos
8992            .push(contract_http("cart", "phantom", "/never-reached"));
8993        let err = s.validate().unwrap_err();
8994        assert!(
8995            matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
8996            "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
8997        );
8998    }
8999
9000    #[test]
9001    fn membros_validation_runs_before_contratos_membership_check() {
9002        // If `:membros` carries a duplicate, the membership-collapse
9003        // would silently accept a `:contratos :para "phantom"` so long
9004        // as some entry hashes to "phantom". Pinning order: the
9005        // duplicate-membros error fires first, regardless of whether
9006        // contratos reference real members.
9007        let mut s = three_member_spec();
9008        s.membros = vec![
9009            membro("cart", "^0.1"),
9010            membro("cart", "^0.2"),
9011            membro("catalog", "^0.1"),
9012            membro("payment", "^0.1"),
9013        ];
9014        let err = s.validate().unwrap_err();
9015        assert!(
9016            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
9017            "got {err:?}"
9018        );
9019    }
9020
9021    #[test]
9022    fn distinct_membros_validate() {
9023        // Pin the happy-path: every `:membros` entry has a non-empty
9024        // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
9025        // The fixture already satisfies this; this test makes the
9026        // invariant explicit so a future refactor of the fixture can't
9027        // silently break the guarantee.
9028        three_member_spec().validate().unwrap();
9029    }
9030
9031    // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
9032
9033    #[test]
9034    fn rejects_membro_caixa_with_uppercase() {
9035        // The canonical "I copied the Servico's display name verbatim"
9036        // typo — caixa names are lowercase per K8s DNS-1123 label rule,
9037        // but author tools often round-trip a TitleCase or CamelCase
9038        // identifier from an ADR or a sketch. Pin the diagnostic names
9039        // the offending name and suggests the lower-cased fix in one
9040        // edit, mirroring the `rejects_entrada_host_with_uppercase`
9041        // gate's shape (c7d05ec).
9042        let mut s = three_member_spec();
9043        s.membros[1].caixa = "Cart".into();
9044        let err = s.validate().unwrap_err();
9045        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
9046            panic!("expected MembroCaixaInvalid, got other variant");
9047        };
9048        assert_eq!(caixa, "Cart");
9049        assert!(
9050            reason.contains("uppercase"),
9051            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9052        );
9053        assert!(
9054            reason.contains("\"cart\""),
9055            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
9056        );
9057    }
9058
9059    #[test]
9060    fn rejects_membro_caixa_with_underscore() {
9061        // The canonical "I'm thinking of a Python module / Postgres
9062        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
9063        // label schema. K8s rejects `metadata.name: my_cart` at admission
9064        // time with an opaque `field is invalid` (no source-citing
9065        // diagnostic). The gate moves it to caixa-build time.
9066        let mut s = three_member_spec();
9067        s.membros[0].caixa = "my_cart".into();
9068        let err = s.validate().unwrap_err();
9069        assert!(
9070            matches!(
9071                err,
9072                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
9073                    if caixa == "my_cart" && reason.contains('_')
9074            ),
9075            "got {err:?}"
9076        );
9077    }
9078
9079    #[test]
9080    fn rejects_membro_caixa_with_dot() {
9081        // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
9082        // subdomain — even though K8s `metadata.name` itself accepts
9083        // dots (DNS-1123 subdomain rule), this string also lands as a
9084        // K8s Service name (DNS-1035 label — no dots) and as a label
9085        // value on identity-based Cilium selectors. The strictest floor
9086        // among the use sites wins. The "I want to namespace my member
9087        // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
9088        let mut s = three_member_spec();
9089        s.membros[2].caixa = "team.cart".into();
9090        let err = s.validate().unwrap_err();
9091        assert!(
9092            matches!(
9093                err,
9094                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
9095                    if caixa == "team.cart" && reason.contains('.')
9096            ),
9097            "got {err:?}"
9098        );
9099    }
9100
9101    #[test]
9102    fn rejects_membro_caixa_with_leading_hyphen() {
9103        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
9104        // with an alphanumeric. The K8s apiserver rejects `-cart`
9105        // outright; the renderer would emit a `metadata.name: "-cart"`
9106        // that fails admission far from the source caixa.lisp.
9107        let mut s = three_member_spec();
9108        s.membros[0].caixa = "-cart".into();
9109        let err = s.validate().unwrap_err();
9110        assert!(
9111            matches!(
9112                err,
9113                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
9114                    if caixa == "-cart" && reason.contains("start and end")
9115            ),
9116            "got {err:?}"
9117        );
9118    }
9119
9120    #[test]
9121    fn rejects_membro_caixa_with_trailing_hyphen() {
9122        // The symmetric arm of the boundary rule. Pin separately so
9123        // both ends of the label are covered against a future relaxation
9124        // that only checks one boundary.
9125        let mut s = three_member_spec();
9126        s.membros[1].caixa = "cart-".into();
9127        let err = s.validate().unwrap_err();
9128        assert!(
9129            matches!(
9130                err,
9131                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
9132                    if caixa == "cart-"
9133            ),
9134            "got {err:?}"
9135        );
9136    }
9137
9138    #[test]
9139    fn rejects_membro_caixa_with_unicode() {
9140        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9141        // (`xn--…`) by the author before it reaches K8s. The byte-by-
9142        // byte ASCII validity check rejects multi-byte UTF-8 sequences
9143        // by the first byte that fails the `[a-z0-9-]` predicate.
9144        let mut s = three_member_spec();
9145        s.membros[2].caixa = "café".into();
9146        let err = s.validate().unwrap_err();
9147        assert!(
9148            matches!(
9149                err,
9150                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
9151                    if caixa == "café"
9152            ),
9153            "got {err:?}"
9154        );
9155    }
9156
9157    #[test]
9158    fn rejects_membro_caixa_with_whitespace() {
9159        // Whitespace is the canonical "I pasted from a sketch / doc"
9160        // footgun. The apiserver rejects every `metadata.name` value
9161        // carrying whitespace; pin the gate fires at the right boundary.
9162        let mut s = three_member_spec();
9163        s.membros[0].caixa = "my cart".into();
9164        let err = s.validate().unwrap_err();
9165        assert!(
9166            matches!(
9167                err,
9168                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
9169                    if caixa == "my cart"
9170            ),
9171            "got {err:?}"
9172        );
9173    }
9174
9175    #[test]
9176    fn rejects_membro_caixa_too_long() {
9177        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
9178        // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
9179        // exactly. The gate's reason names both the cap and the actual
9180        // length so the author can shorten in one edit.
9181        let mut s = three_member_spec();
9182        let too_long = "a".repeat(64);
9183        s.membros[1].caixa = too_long.clone();
9184        let err = s.validate().unwrap_err();
9185        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
9186            panic!("expected MembroCaixaInvalid");
9187        };
9188        assert_eq!(caixa, too_long);
9189        assert!(
9190            reason.contains("63") && reason.contains("64"),
9191            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
9192        );
9193    }
9194
9195    #[test]
9196    fn membro_caixa_max_length_validates() {
9197        // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
9198        // so a future tightening (e.g. dropping to 62) surfaces here as
9199        // a regression, mirroring `entrada_host_max_length_validates`
9200        // (c7d05ec).
9201        let mut s = three_member_spec();
9202        s.membros[2].caixa = "a".repeat(63);
9203        s.entrada.as_mut().unwrap().para = "a".repeat(63);
9204        // remove contratos referencing the renamed member; they'd
9205        // raise ContratoMemberMissing otherwise
9206        s.contratos
9207            .retain(|c| c.de != "payment" && c.para != "payment");
9208        s.validate().unwrap();
9209    }
9210
9211    #[test]
9212    fn accepts_canonical_membro_caixa_forms() {
9213        // The DNS-1123 label shapes a caixa author is realistically
9214        // going to write: single-word lowercase, hyphen-joined, ending
9215        // in a digit-suffixed version (`cart-v2`), starting with a
9216        // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
9217        // DNS-1035 which requires a letter at position 0), single-
9218        // character (`a` — boundary). Pin every leg so a future
9219        // tightening that bans (e.g.) digit-start identifiers surfaces
9220        // here.
9221        for form in [
9222            "checkout",
9223            "cart",
9224            "cart-v2",
9225            "a",
9226            "c0",
9227            "3rd-party-shim",
9228            "x-1-2-3-4",
9229        ] {
9230            let mut s = three_member_spec();
9231            // Renaming a member also requires updating downstream refs;
9232            // drop everything else and rebuild a minimal spec around
9233            // just the one renamed member.
9234            s.membros = vec![membro(form, "^0.1")];
9235            s.contratos = vec![];
9236            s.entrada = None;
9237            s.validate()
9238                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
9239        }
9240    }
9241
9242    #[test]
9243    fn membro_caixa_empty_takes_precedence_over_invalid() {
9244        // Order pin: the existing `MembroCaixaEmpty` diagnostic
9245        // (which doesn't try to parse) fires before the new
9246        // `MembroCaixaInvalid` parse-side diagnostic, so an empty
9247        // `:caixa` keeps its narrower error message — the new gate
9248        // would also reject `""`, but the empty-string arm is the more
9249        // self-locating diagnostic for the author. Mirrors the
9250        // `entrada_host_empty_takes_precedence_over_invalid` pin
9251        // (c7d05ec).
9252        let mut s = three_member_spec();
9253        s.membros[1].caixa = String::new();
9254        let err = s.validate().unwrap_err();
9255        assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
9256    }
9257
9258    #[test]
9259    fn membro_caixa_invalid_fires_before_versao_check() {
9260        // Order pin: an invalid-shape `:caixa` surfaces *its own*
9261        // diagnostic (which names the offending caixa name), even when
9262        // the same entry's `:versao` is also empty/invalid. The shape
9263        // gate runs first because the diagnostic is more self-locating —
9264        // an empty/invalid `:versao` on an invalid-shape caixa name is
9265        // a downstream-fix-after-the-caixa-rename concern.
9266        let mut s = three_member_spec();
9267        s.membros[1].caixa = "Cart".into();
9268        s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
9269        let err = s.validate().unwrap_err();
9270        assert!(
9271            matches!(
9272                err,
9273                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
9274            ),
9275            "got {err:?}"
9276        );
9277    }
9278
9279    #[test]
9280    fn membro_caixa_invalid_fires_before_duplicate_check() {
9281        // Order pin: a malformed-shape `:caixa` on an earlier entry
9282        // surfaces *its own* diagnostic, even when a later entry would
9283        // otherwise collapse onto a duplicate name. The per-entry shape
9284        // gate runs inline before the duplicate-key insert, parallel
9285        // to `membro_versao_invalid_fires_before_duplicate_check`.
9286        let mut s = three_member_spec();
9287        s.membros[0].caixa = "Catalog".into();
9288        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
9289        let err = s.validate().unwrap_err();
9290        assert!(
9291            matches!(
9292                err,
9293                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
9294            ),
9295            "got {err:?}"
9296        );
9297    }
9298
9299    #[test]
9300    fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
9301        // The diagnostic-shape pin: the error names the offending
9302        // `:caixa` value verbatim so the author can grep their
9303        // caixa.lisp without re-running the build, and carries a
9304        // non-empty `reason` naming the specific violation. Same
9305        // shape every typed-shape gate enshrines (c7d05ec's
9306        // `entrada_host_diagnostic_carries_offending_host`,
9307        // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
9308        let mut s = three_member_spec();
9309        s.membros[2].caixa = "BAD_NAME".into();
9310        let err = s.validate().unwrap_err();
9311        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
9312            panic!("expected MembroCaixaInvalid");
9313        };
9314        assert_eq!(caixa, "BAD_NAME");
9315        assert!(
9316            !reason.is_empty(),
9317            "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
9318        );
9319    }
9320
9321    #[test]
9322    fn rejects_contrato_with_unknown_de() {
9323        let mut s = three_member_spec();
9324        s.contratos.push(contract_http("phantom", "catalog", "/x"));
9325        let err = s.validate().unwrap_err();
9326        assert!(
9327            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
9328        );
9329    }
9330
9331    #[test]
9332    fn rejects_contrato_with_unknown_para() {
9333        let mut s = three_member_spec();
9334        s.contratos.push(contract_http("cart", "phantom", "/x"));
9335        let err = s.validate().unwrap_err();
9336        assert!(
9337            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
9338        );
9339    }
9340
9341    #[test]
9342    fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
9343        // The read-path pin: the phantom-`:de` refusal arm's
9344        // `ContratoMemberMissing.caixa` carrier must be observed through
9345        // the lifted [`WitContract::source`] accessor, not the raw
9346        // `.de.clone()` field-access `String`-carry. Peer of the sibling
9347        // per-`:contratos` self-loop arm's `.source().to_string()` /
9348        // `.world_ref().to_string()` `String`-carry sites the earlier
9349        // convergence lifted onto the same accessor pair. A future
9350        // silent detour that reintroduced the raw `.de.clone()` at the
9351        // wrap envelope while the shape-gate and membership lookup
9352        // routed through the accessor would surface here as a byte-equal
9353        // miss between the fired diagnostic's `caixa:` field and the
9354        // offending edge's `.source()` — pinning the accessor as the
9355        // sole read path across the phantom-name refusal arm's arg +
9356        // wrap-envelope emit surface.
9357        let mut s = three_member_spec();
9358        let phantom = contract_http("phantom", "catalog", "/x");
9359        s.contratos.push(phantom.clone());
9360        let err = s.validate().unwrap_err();
9361        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
9362            panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
9363        };
9364        assert_eq!(
9365            caixa,
9366            phantom.source(),
9367            "ContratoMemberMissing.caixa on the phantom-:de arm must \
9368             byte-equal WitContract::source — the wrap envelope must \
9369             route through the lifted accessor rather than the raw \
9370             .de.clone() field-access String-carry"
9371        );
9372    }
9373
9374    #[test]
9375    fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
9376        // The symmetric read-path pin on the `:para` phantom-name
9377        // refusal arm — same shape as the sibling `:de` pin above but
9378        // on the callee-Servico axis. Pins the wrap envelope's
9379        // `caixa:` field is observed through the lifted
9380        // [`WitContract::destination`] accessor, not the raw
9381        // `.para.clone()` field-access `String`-carry.
9382        let mut s = three_member_spec();
9383        let phantom = contract_http("cart", "phantom", "/x");
9384        s.contratos.push(phantom.clone());
9385        let err = s.validate().unwrap_err();
9386        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
9387            panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
9388        };
9389        assert_eq!(
9390            caixa,
9391            phantom.destination(),
9392            "ContratoMemberMissing.caixa on the phantom-:para arm must \
9393             byte-equal WitContract::destination — the wrap envelope \
9394             must route through the lifted accessor rather than the raw \
9395             .para.clone() field-access String-carry"
9396        );
9397    }
9398
9399    #[test]
9400    fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
9401        // The read-path pin on the `:de` DNS-1123-malformed shape-gate
9402        // refusal arm — the `validate_contrato_caixa` arg must be
9403        // observed through the lifted [`WitContract::source`] accessor,
9404        // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
9405        // value routes through the shared
9406        // [`crate::render::require_valid_dns_1123_label`] floor with the
9407        // accessor-projected value; the fired
9408        // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
9409        // the offending edge's `.source()`, pinning that the arg + the
9410        // downstream `caixa: caixa.to_string()` wrap route through the
9411        // same accessor's read path.
9412        let mut s = three_member_spec();
9413        let malformed = contract_http("BAD_NAME", "catalog", "/x");
9414        s.contratos.push(malformed.clone());
9415        let err = s.validate().unwrap_err();
9416        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
9417            panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
9418        };
9419        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
9420        assert_eq!(
9421            caixa,
9422            malformed.source(),
9423            "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
9424             byte-equal WitContract::source — the shape-gate arg + wrap \
9425             envelope must route through the lifted accessor rather \
9426             than the raw &c.de &String-borrow"
9427        );
9428    }
9429
9430    #[test]
9431    fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
9432        // Symmetric arm to the sibling `:de` malformed-shape pin above,
9433        // on the `:para` axis. Pins the shape-gate arg + wrap envelope
9434        // route through the lifted [`WitContract::destination`]
9435        // accessor. `:para` runs after the `:de` shape gate in the
9436        // canonical edge-direction order, so the `:de` value must be
9437        // well-shaped for the `:para` gate to fire — the `cart` :de is
9438        // canonical.
9439        let mut s = three_member_spec();
9440        let malformed = contract_http("cart", "BAD_NAME", "/x");
9441        s.contratos.push(malformed.clone());
9442        let err = s.validate().unwrap_err();
9443        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
9444            panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
9445        };
9446        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
9447        assert_eq!(
9448            caixa,
9449            malformed.destination(),
9450            "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
9451             byte-equal WitContract::destination — the shape-gate arg + \
9452             wrap envelope must route through the lifted accessor \
9453             rather than the raw &c.para &String-borrow"
9454        );
9455    }
9456
9457    // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
9458
9459    #[test]
9460    fn rejects_contrato_de_empty() {
9461        // `:de ""` previously fell through to `ContratoMemberMissing`
9462        // (with `caixa: ""`) because the validated `:membros :caixa`
9463        // set never contains the empty string. The narrower
9464        // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
9465        // the offending slot.
9466        let mut s = three_member_spec();
9467        s.contratos.push(contract_http("", "catalog", "/x"));
9468        let err = s.validate().unwrap_err();
9469        assert_eq!(
9470            err,
9471            AplicacaoError::ContratoCaixaEmpty {
9472                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9473            },
9474            "got {err:?}"
9475        );
9476    }
9477
9478    #[test]
9479    fn rejects_contrato_para_empty() {
9480        // Symmetric arm to `:de ""` — `:para ""` previously fell
9481        // through to `ContratoMemberMissing { caixa: "" }`.
9482        let mut s = three_member_spec();
9483        s.contratos.push(contract_http("cart", "", "/x"));
9484        let err = s.validate().unwrap_err();
9485        assert_eq!(
9486            err,
9487            AplicacaoError::ContratoCaixaEmpty {
9488                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
9489            },
9490            "got {err:?}"
9491        );
9492    }
9493
9494    #[test]
9495    fn rejects_contrato_de_with_uppercase() {
9496        // The canonical "I copied the Servico's TitleCase display
9497        // name from an ADR" typo. Until this gate landed `:de "Cart"`
9498        // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
9499        // as "this caixa isn't in `:membros`" when the root cause is
9500        // "this `:de` value's shape can never legitimately match a
9501        // validated member (DNS-1123 labels are lowercase)". The
9502        // narrower diagnostic names the offending slot, the value
9503        // verbatim, and the parser-shaped reason.
9504        let mut s = three_member_spec();
9505        s.contratos.push(contract_http("Cart", "catalog", "/x"));
9506        let err = s.validate().unwrap_err();
9507        let AplicacaoError::ContratoCaixaInvalid {
9508            slot,
9509            caixa,
9510            reason,
9511        } = err
9512        else {
9513            panic!("expected ContratoCaixaInvalid, got other variant");
9514        };
9515        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
9516        assert_eq!(caixa, "Cart");
9517        assert!(
9518            reason.contains("uppercase"),
9519            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9520        );
9521    }
9522
9523    #[test]
9524    fn rejects_contrato_para_with_underscore() {
9525        // The canonical "I'm thinking of a Python module" leak —
9526        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
9527        // Pin the `:para` axis surfaces the same diagnostic shape as
9528        // the `:de` axis on the underscore violation.
9529        let mut s = three_member_spec();
9530        s.contratos.push(contract_http("cart", "my_catalog", "/x"));
9531        let err = s.validate().unwrap_err();
9532        assert!(
9533            matches!(
9534                err,
9535                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9536                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
9537            ),
9538            "got {err:?}"
9539        );
9540    }
9541
9542    #[test]
9543    fn rejects_contrato_de_with_dot() {
9544        // A `:contratos :de` value is a single DNS-1123 *label*, not
9545        // a subdomain — mirroring the `:membros :caixa` floor. The
9546        // strictest floor among the use sites wins.
9547        let mut s = three_member_spec();
9548        s.contratos
9549            .push(contract_http("team.cart", "catalog", "/x"));
9550        let err = s.validate().unwrap_err();
9551        assert!(
9552            matches!(
9553                err,
9554                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9555                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
9556            ),
9557            "got {err:?}"
9558        );
9559    }
9560
9561    #[test]
9562    fn rejects_contrato_para_with_unicode() {
9563        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9564        // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
9565        // validity check rejects multi-byte UTF-8 by the first
9566        // non-`[a-z0-9-]` byte.
9567        let mut s = three_member_spec();
9568        s.contratos.push(contract_http("cart", "café", "/x"));
9569        let err = s.validate().unwrap_err();
9570        assert!(
9571            matches!(
9572                err,
9573                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9574                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
9575            ),
9576            "got {err:?}"
9577        );
9578    }
9579
9580    #[test]
9581    fn rejects_contrato_de_with_leading_hyphen() {
9582        // DNS-1123 boundary rule: labels must start and end with an
9583        // alphanumeric. K8s rejects `-cart` outright; the narrower
9584        // shape diagnostic now names the violation at caixa-build
9585        // time rather than the misframed membership-lookup arm.
9586        let mut s = three_member_spec();
9587        s.contratos.push(contract_http("-cart", "catalog", "/x"));
9588        let err = s.validate().unwrap_err();
9589        assert!(
9590            matches!(
9591                err,
9592                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9593                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
9594            ),
9595            "got {err:?}"
9596        );
9597    }
9598
9599    #[test]
9600    fn contrato_de_empty_takes_precedence_over_invalid() {
9601        // Order pin: the `ContratoCaixaEmpty` arm fires before the
9602        // `ContratoCaixaInvalid` parse-side arm — same empty-first
9603        // cascade `validate_membro_caixa` / `validate_placement_cluster`
9604        // / `validate_entrada_host` already establish on their peer
9605        // name axes. The empty string is a structurally distinct
9606        // authoring footgun (the author left the field blank, vs.
9607        // typed a malformed value), so it gets its own diagnostic.
9608        let mut s = three_member_spec();
9609        s.contratos.push(contract_http("", "catalog", "/x"));
9610        let err = s.validate().unwrap_err();
9611        assert_eq!(
9612            err,
9613            AplicacaoError::ContratoCaixaEmpty {
9614                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9615            }
9616        );
9617    }
9618
9619    #[test]
9620    fn contrato_de_shape_fires_before_para_shape() {
9621        // Per-axis order pin: within one `:contratos` entry, the `:de`
9622        // shape gate fires before the `:para` shape gate — same
9623        // edge-direction order the existing `ContratoMemberMissing` /
9624        // `ContratoSelfLoop` / target-dispatch checks use, so the
9625        // diagnostic for a contract with both `:de` and `:para`
9626        // malformed is stable. Authors fixing the surfaced `:de`
9627        // first will see `:para`'s diagnostic on re-run.
9628        let mut s = three_member_spec();
9629        s.contratos.push(contract_http("Cart", "Catalog", "/x"));
9630        let err = s.validate().unwrap_err();
9631        assert!(
9632            matches!(
9633                err,
9634                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9635                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
9636            ),
9637            "got {err:?}"
9638        );
9639    }
9640
9641    #[test]
9642    fn contrato_shape_fires_before_membership_lookup() {
9643        // The load-bearing pin: an invalid-shape `:de` surfaces its
9644        // *own* diagnostic, not the misframed `ContratoMemberMissing`.
9645        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
9646        // an invalid-shape `:de` could never legitimately match any
9647        // member — the prior `ContratoMemberMissing` diagnostic was
9648        // a structural impossibility framed as a graph-membership
9649        // failure. The shape gate now routes every such input through
9650        // the narrower self-locating diagnostic.
9651        let mut s = three_member_spec();
9652        s.contratos.push(contract_http("Cart", "catalog", "/x"));
9653        let err = s.validate().unwrap_err();
9654        assert!(
9655            matches!(
9656                err,
9657                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
9658            ),
9659            "got {err:?}"
9660        );
9661        // And the symmetric case: an invalid-shape `:para` surfaces
9662        // its own diagnostic too, even when `:de` is well-shaped.
9663        let mut s = three_member_spec();
9664        s.contratos.push(contract_http("cart", "Catalog", "/x"));
9665        let err = s.validate().unwrap_err();
9666        assert!(
9667            matches!(
9668                err,
9669                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
9670            ),
9671            "got {err:?}"
9672        );
9673    }
9674
9675    #[test]
9676    fn contrato_shape_fires_before_self_edge_check() {
9677        // A `:de "Cart" :para "Cart"` entry is two distinct authoring
9678        // bugs: the shape violation (uppercase) and the self-edge
9679        // violation. The narrower per-axis shape diagnostic surfaces
9680        // first because fixing the shape may reveal that the author
9681        // also meant to point `:para` at a different member — the
9682        // self-edge framing is only useful once both endpoints have
9683        // valid shape.
9684        let mut s = three_member_spec();
9685        s.contratos.push(contract_http("Cart", "Cart", "/x"));
9686        let err = s.validate().unwrap_err();
9687        assert!(
9688            matches!(
9689                err,
9690                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9691                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
9692            ),
9693            "got {err:?}"
9694        );
9695    }
9696
9697    #[test]
9698    fn contrato_well_shaped_phantom_still_raises_member_missing() {
9699        // Strict-improvement pin: a well-shaped `:de` that simply
9700        // isn't in `:membros` (a phantom reference — author meant
9701        // to add the member but didn't, or renamed and missed an
9702        // update) still surfaces `ContratoMemberMissing`, unchanged.
9703        // The shape gate only intercepts inputs that could never
9704        // legitimately match a validated member; legitimately-shaped
9705        // phantom references remain on the graph-membership axis.
9706        let mut s = three_member_spec();
9707        s.contratos
9708            .push(contract_http("phantom-shim", "catalog", "/x"));
9709        let err = s.validate().unwrap_err();
9710        assert!(
9711            matches!(
9712                err,
9713                AplicacaoError::ContratoMemberMissing { ref caixa }
9714                    if caixa == "phantom-shim"
9715            ),
9716            "got {err:?}"
9717        );
9718    }
9719
9720    #[test]
9721    fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
9722        // The diagnostic-shape pin: the error names the offending
9723        // slot (`:de` or `:para`) verbatim and the offending value
9724        // verbatim plus a non-empty parser-shaped reason, so the
9725        // author can grep their caixa.lisp for `:de "<name>"` /
9726        // `:para "<name>"` and fix it in one edit. Same diagnostic
9727        // shape as `MembroCaixaInvalid` (3f9d7a0) and
9728        // `PlacementClusterInvalid` (6c8c00b).
9729        let mut s = three_member_spec();
9730        s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
9731        let err = s.validate().unwrap_err();
9732        let AplicacaoError::ContratoCaixaInvalid {
9733            slot,
9734            caixa,
9735            reason,
9736        } = err
9737        else {
9738            panic!("expected ContratoCaixaInvalid, got {err:?}");
9739        };
9740        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
9741        assert_eq!(caixa, "BAD_NAME");
9742        assert!(
9743            !reason.is_empty(),
9744            "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
9745        );
9746    }
9747
9748    #[test]
9749    fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
9750        // Scalar-value pin: the two author-facing kebab-case labels the
9751        // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
9752        // admits on the `:contratos` per-entry endpoint-shape axis,
9753        // one arm per typed sub-slot. Mirrors the peer scalar-value
9754        // pin the sibling top-level M2 / M3 / Supervisor
9755        // author-facing-label consts carry
9756        // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
9757        // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
9758        // slot itself), so every altitude of the typed-slot algebra
9759        // shares the same "one canonical byte-string per arm"
9760        // discipline. A future rebrand (`:de` → `:from` matching the
9761        // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
9762        // sibling, `:para` → `:to` matching the same, or
9763        // `:de`/`:para` → `:source`/`:target` matching the WIT
9764        // world's `import`/`export` half-vocabulary) lands as an
9765        // edit to exactly one const, and every consumer that reaches
9766        // for the label picks it up at build time rather than at
9767        // runtime as a downstream `ContratoCaixaEmpty` /
9768        // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
9769        // diagnostic mismatch far from the rename's commit.
9770        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
9771        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
9772    }
9773
9774    #[test]
9775    fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
9776        // Production-through-const pin: the two per-axis labels the
9777        // per-`:contratos` entry endpoint-shape gate at
9778        // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
9779        // argument to [`validate_contrato_caixa`] route through the
9780        // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
9781        // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
9782        // future rebrand that reaches the const but not the gate (or
9783        // vice versa) surfaces here at build time rather than at
9784        // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
9785        // `slot: <stale-kebab-case>` diagnostic far from the rename's
9786        // commit. Mirror of the peer
9787        // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
9788        // pin (882f498) on the sibling M3 top-level slot axis.
9789        let mut s = three_member_spec();
9790        s.contratos.push(contract_http("", "catalog", "/x"));
9791        assert_eq!(
9792            s.validate().unwrap_err(),
9793            AplicacaoError::ContratoCaixaEmpty {
9794                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9795            }
9796        );
9797        let mut s = three_member_spec();
9798        s.contratos.push(contract_http("cart", "", "/x"));
9799        assert_eq!(
9800            s.validate().unwrap_err(),
9801            AplicacaoError::ContratoCaixaEmpty {
9802                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
9803            }
9804        );
9805    }
9806
9807    #[test]
9808    fn accepts_canonical_contrato_caixa_forms() {
9809        // The DNS-1123 label shapes a caixa author is realistically
9810        // going to write on a `:contratos :de` / `:para`. Pin every
9811        // leg so a future tightening that bans (e.g.) digit-start
9812        // identifiers surfaces here, mirroring
9813        // `accepts_canonical_membro_caixa_forms` on the peer name
9814        // axis.
9815        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
9816            let mut s = three_member_spec();
9817            s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
9818            s.contratos = vec![contract_http("checkout", form, "/x")];
9819            s.entrada = None;
9820            s.validate().unwrap_or_else(|e| {
9821                panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
9822            });
9823
9824            let mut s = three_member_spec();
9825            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
9826            s.contratos = vec![contract_http(form, "catalog", "/x")];
9827            s.entrada = None;
9828            s.validate().unwrap_or_else(|e| {
9829                panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
9830            });
9831        }
9832    }
9833
9834    #[test]
9835    fn rejects_empty_wit() {
9836        let mut s = three_member_spec();
9837        s.contratos.push(WitContract {
9838            de: "cart".into(),
9839            para: "catalog".into(),
9840            wit: "".into(),
9841            endpoint: None,
9842            subject: None,
9843            slot: None,
9844        });
9845        let err = s.validate().unwrap_err();
9846        assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
9847    }
9848
9849    #[test]
9850    fn rejects_entrada_to_unknown_member() {
9851        let mut s = three_member_spec();
9852        s.entrada.as_mut().unwrap().para = "phantom".into();
9853        assert!(matches!(
9854            s.validate().unwrap_err(),
9855            AplicacaoError::EntradaMemberMissing { .. }
9856        ));
9857    }
9858
9859    // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
9860
9861    #[test]
9862    fn rejects_entrada_para_empty() {
9863        // `:para ""` previously fell through to
9864        // `EntradaMemberMissing { para: "" }` because the validated
9865        // `:membros :caixa` set never contains the empty string. The
9866        // narrower `EntradaParaEmpty` diagnostic now names the
9867        // offending slot directly — same empty-first cascade
9868        // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
9869        // `ContratoCaixaEmpty` establish on the peer name axes.
9870        let mut s = three_member_spec();
9871        s.entrada.as_mut().unwrap().para = String::new();
9872        let err = s.validate().unwrap_err();
9873        assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
9874    }
9875
9876    #[test]
9877    fn rejects_entrada_para_with_uppercase() {
9878        // The canonical "I copied the Servico's TitleCase display
9879        // name from an ADR" typo. Until this gate landed `:para "Cart"`
9880        // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
9881        // as "this caixa isn't in `:membros`" when the root cause is
9882        // "this `:para` value's shape can never legitimately match a
9883        // validated member (DNS-1123 labels are lowercase)". The
9884        // narrower diagnostic names the value verbatim plus the
9885        // parser-shaped reason.
9886        let mut s = three_member_spec();
9887        s.entrada.as_mut().unwrap().para = "Cart".into();
9888        let err = s.validate().unwrap_err();
9889        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
9890            panic!("expected EntradaParaInvalid, got other variant");
9891        };
9892        assert_eq!(para, "Cart");
9893        assert!(
9894            reason.contains("uppercase"),
9895            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9896        );
9897    }
9898
9899    #[test]
9900    fn rejects_entrada_para_with_underscore() {
9901        // The canonical "I'm thinking of a Python module" leak —
9902        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
9903        let mut s = three_member_spec();
9904        s.entrada.as_mut().unwrap().para = "my_cart".into();
9905        let err = s.validate().unwrap_err();
9906        assert!(
9907            matches!(
9908                err,
9909                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9910                    if para == "my_cart" && reason.contains('_')
9911            ),
9912            "got {err:?}"
9913        );
9914    }
9915
9916    #[test]
9917    fn rejects_entrada_para_with_dot() {
9918        // An `:entrada :para` value is a single DNS-1123 *label*, not
9919        // a subdomain — mirroring the `:membros :caixa` floor. The
9920        // strictest floor among the use sites wins.
9921        let mut s = three_member_spec();
9922        s.entrada.as_mut().unwrap().para = "team.cart".into();
9923        let err = s.validate().unwrap_err();
9924        assert!(
9925            matches!(
9926                err,
9927                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9928                    if para == "team.cart" && reason.contains('.')
9929            ),
9930            "got {err:?}"
9931        );
9932    }
9933
9934    #[test]
9935    fn rejects_entrada_para_with_unicode() {
9936        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9937        // (`xn--…`) before it reaches K8s.
9938        let mut s = three_member_spec();
9939        s.entrada.as_mut().unwrap().para = "café".into();
9940        let err = s.validate().unwrap_err();
9941        assert!(
9942            matches!(
9943                err,
9944                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
9945            ),
9946            "got {err:?}"
9947        );
9948    }
9949
9950    #[test]
9951    fn rejects_entrada_para_with_leading_hyphen() {
9952        // DNS-1123 boundary rule: labels must start and end with an
9953        // alphanumeric. K8s rejects `-cart` outright.
9954        let mut s = three_member_spec();
9955        s.entrada.as_mut().unwrap().para = "-cart".into();
9956        let err = s.validate().unwrap_err();
9957        assert!(
9958            matches!(
9959                err,
9960                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9961                    if para == "-cart" && reason.contains("start and end")
9962            ),
9963            "got {err:?}"
9964        );
9965    }
9966
9967    #[test]
9968    fn rejects_entrada_para_with_trailing_hyphen() {
9969        // Symmetric boundary arm.
9970        let mut s = three_member_spec();
9971        s.entrada.as_mut().unwrap().para = "cart-".into();
9972        let err = s.validate().unwrap_err();
9973        assert!(
9974            matches!(
9975                err,
9976                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9977                    if para == "cart-" && reason.contains("start and end")
9978            ),
9979            "got {err:?}"
9980        );
9981    }
9982
9983    #[test]
9984    fn rejects_entrada_para_too_long() {
9985        // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
9986        // bytes per label. K8s rejects longer names at admission on
9987        // every `metadata.name` axis.
9988        let mut s = three_member_spec();
9989        s.entrada.as_mut().unwrap().para = "a".repeat(64);
9990        let err = s.validate().unwrap_err();
9991        assert!(
9992            matches!(
9993                err,
9994                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9995                    if para.len() == 64 && reason.contains("max length")
9996            ),
9997            "got {err:?}"
9998        );
9999    }
10000
10001    #[test]
10002    fn entrada_para_empty_takes_precedence_over_invalid() {
10003        // Order pin: the `EntradaParaEmpty` arm fires before the
10004        // `EntradaParaInvalid` parse-side arm — same empty-first
10005        // cascade `validate_membro_caixa` / `validate_placement_cluster`
10006        // / `validate_contrato_caixa` already establish.
10007        let mut s = three_member_spec();
10008        s.entrada.as_mut().unwrap().para = String::new();
10009        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
10010    }
10011
10012    #[test]
10013    fn entrada_para_shape_fires_before_membership_lookup() {
10014        // The load-bearing pin: an invalid-shape `:para` surfaces its
10015        // *own* diagnostic, not the misframed `EntradaMemberMissing`.
10016        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
10017        // an invalid-shape `:para` could never legitimately match any
10018        // member — the prior `EntradaMemberMissing` diagnostic framed
10019        // a structural impossibility as a graph-membership failure.
10020        let mut s = three_member_spec();
10021        s.entrada.as_mut().unwrap().para = "Cart".into();
10022        let err = s.validate().unwrap_err();
10023        assert!(
10024            matches!(
10025                err,
10026                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
10027            ),
10028            "got {err:?}"
10029        );
10030    }
10031
10032    #[test]
10033    fn entrada_para_shape_fires_before_host_gate() {
10034        // Per-`:entrada` order pin: the `:para` shape gate fires
10035        // before the `:host` gate, mirroring the existing
10036        // `entrada_host_member_missing_takes_precedence_over_host_invalid`
10037        // ordering where the member-lookup arm preceded the host gate.
10038        // The shape gate slots ahead of that, so a malformed `:para`
10039        // surfaces its own diagnostic even when `:host` is also wrong.
10040        let mut s = three_member_spec();
10041        let e = s.entrada.as_mut().unwrap();
10042        e.para = "Cart".into();
10043        e.host = "BAD HOST".into();
10044        let err = s.validate().unwrap_err();
10045        assert!(
10046            matches!(
10047                err,
10048                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
10049            ),
10050            "got {err:?}"
10051        );
10052    }
10053
10054    #[test]
10055    fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
10056        // Strict-improvement pin: a well-shaped `:para` that simply
10057        // isn't in `:membros` (a phantom reference — author meant to
10058        // add the member but didn't, or renamed and missed an
10059        // update) still surfaces `EntradaMemberMissing`, unchanged.
10060        // The shape gate only intercepts inputs that could never
10061        // legitimately match a validated member.
10062        let mut s = three_member_spec();
10063        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
10064        let err = s.validate().unwrap_err();
10065        assert!(
10066            matches!(
10067                err,
10068                AplicacaoError::EntradaMemberMissing { ref para }
10069                    if para == "phantom-shim"
10070            ),
10071            "got {err:?}"
10072        );
10073    }
10074
10075    #[test]
10076    fn entrada_para_invalid_diagnostic_carries_offending_para() {
10077        // The diagnostic-shape pin: the error names the offending
10078        // `:para` value verbatim plus a non-empty parser-shaped
10079        // reason, so the author can grep their caixa.lisp for
10080        // `:para "<name>"` and fix it in one edit. Same diagnostic
10081        // shape as `MembroCaixaInvalid` (3f9d7a0),
10082        // `PlacementClusterInvalid` (6c8c00b), and
10083        // `ContratoCaixaInvalid` (8d5af6b).
10084        let mut s = three_member_spec();
10085        s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
10086        let err = s.validate().unwrap_err();
10087        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
10088            panic!("expected EntradaParaInvalid, got {err:?}");
10089        };
10090        assert_eq!(para, "BAD_NAME");
10091        assert!(
10092            !reason.is_empty(),
10093            "EntradaParaInvalid `reason` must carry a parser-shaped wording"
10094        );
10095    }
10096
10097    #[test]
10098    fn accepts_canonical_entrada_para_forms() {
10099        // Positive-control sweep covering the DNS-1123 label shapes a
10100        // caixa author is realistically going to write on `:entrada
10101        // :para`. Pin every leg so a future tightening that bans
10102        // (e.g.) digit-start identifiers surfaces here, mirroring
10103        // `accepts_canonical_membro_caixa_forms` and
10104        // `accepts_canonical_contrato_caixa_forms` on the peer name
10105        // axes.
10106        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
10107            let mut s = three_member_spec();
10108            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
10109            s.contratos = vec![contract_http(form, "catalog", "/x")];
10110            s.entrada = Some(Entrada {
10111                host: "checkout.quero.cloud".into(),
10112                para: form.into(),
10113                paths: vec!["/api".into()],
10114                port: 8080,
10115            });
10116            s.validate().unwrap_or_else(|e| {
10117                panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
10118            });
10119        }
10120    }
10121
10122    #[test]
10123    fn rejects_replicated_without_clusters() {
10124        let mut s = three_member_spec();
10125        s.placement.clusters = vec![];
10126        assert!(matches!(
10127            s.validate().unwrap_err(),
10128            AplicacaoError::PlacementWithoutClusters { .. }
10129        ));
10130    }
10131
10132    #[test]
10133    fn rejects_sharded_without_key() {
10134        let mut s = three_member_spec();
10135        s.placement.estrategia = PlacementStrategy::Sharded;
10136        s.placement.shard_key = None;
10137        s.placement.clusters = vec!["rio".into()];
10138        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
10139    }
10140
10141    #[test]
10142    fn sharded_with_key_validates() {
10143        let mut s = three_member_spec();
10144        s.placement.estrategia = PlacementStrategy::Sharded;
10145        s.placement.shard_key = Some("$tenantId".into());
10146        s.validate().unwrap();
10147    }
10148
10149    #[test]
10150    fn round_trip_via_json_preserves_shape() {
10151        let s = three_member_spec();
10152        let json = serde_json::to_string(&s.membros).unwrap();
10153        let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
10154        assert_eq!(back, s.membros);
10155
10156        let json = serde_json::to_string(&s.contratos).unwrap();
10157        let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
10158        assert_eq!(back, s.contratos);
10159
10160        let json = serde_json::to_string(&s.placement).unwrap();
10161        let back: Placement = serde_json::from_str(&json).unwrap();
10162        assert_eq!(back, s.placement);
10163
10164        let json = serde_json::to_string(&s.entrada).unwrap();
10165        let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
10166        assert_eq!(back, s.entrada);
10167    }
10168
10169    #[test]
10170    fn rate_limit_round_trip_seconds() {
10171        let policy = MeshPolicy {
10172            rate_limit: Some(RateLimit {
10173                rate: 100,
10174                window: Duration::from_secs(1),
10175            }),
10176            ..Default::default()
10177        };
10178        let json = serde_json::to_string(&policy).unwrap();
10179        assert!(json.contains("\"100/s\""));
10180        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
10181        assert_eq!(back.rate_limit.unwrap().rate, 100);
10182        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
10183    }
10184
10185    #[test]
10186    fn rate_limit_round_trip_minutes() {
10187        let policy = MeshPolicy {
10188            rate_limit: Some(RateLimit {
10189                rate: 5000,
10190                window: Duration::from_secs(60),
10191            }),
10192            ..Default::default()
10193        };
10194        let json = serde_json::to_string(&policy).unwrap();
10195        assert!(json.contains("\"5000/m\""));
10196    }
10197
10198    #[test]
10199    fn circuit_breaker_round_trip() {
10200        let policy = MeshPolicy {
10201            circuit_breaker: Some(CircuitBreaker {
10202                max_failures: 5,
10203                window: Duration::from_secs(60),
10204            }),
10205            ..Default::default()
10206        };
10207        let json = serde_json::to_string(&policy).unwrap();
10208        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
10209        assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
10210        assert_eq!(
10211            back.circuit_breaker.unwrap().window,
10212            Duration::from_secs(60)
10213        );
10214    }
10215
10216    #[test]
10217    fn rejects_http_contrato_without_endpoint() {
10218        let mut s = three_member_spec();
10219        s.contratos.push(WitContract {
10220            de: "cart".into(),
10221            para: "catalog".into(),
10222            wit: "wasi:http/proxy".into(),
10223            endpoint: None,
10224            subject: None,
10225            slot: None,
10226        });
10227        let err = s.validate().unwrap_err();
10228        assert!(matches!(
10229            err,
10230            AplicacaoError::ContratoMissingTarget {
10231                expected: WitTarget::HTTP_FIELD_NAME,
10232                ..
10233            }
10234        ));
10235    }
10236
10237    #[test]
10238    fn rejects_http_contrato_with_subject() {
10239        let mut s = three_member_spec();
10240        s.contratos.push(WitContract {
10241            de: "cart".into(),
10242            para: "catalog".into(),
10243            wit: "wasi:http/proxy".into(),
10244            endpoint: Some("/x".into()),
10245            subject: Some("not.allowed.here".into()),
10246            slot: None,
10247        });
10248        let err = s.validate().unwrap_err();
10249        assert!(matches!(
10250            err,
10251            AplicacaoError::ContratoWrongTarget {
10252                expected: WitTarget::HTTP_FIELD_NAME,
10253                ..
10254            }
10255        ));
10256    }
10257
10258    #[test]
10259    fn rejects_pubsub_contrato_without_subject() {
10260        let mut s = three_member_spec();
10261        s.contratos.push(WitContract {
10262            de: "cart".into(),
10263            para: "catalog".into(),
10264            wit: "nats:pub-sub".into(),
10265            endpoint: None,
10266            subject: None,
10267            slot: None,
10268        });
10269        let err = s.validate().unwrap_err();
10270        assert!(matches!(
10271            err,
10272            AplicacaoError::ContratoMissingTarget {
10273                expected: WitTarget::PUBSUB_FIELD_NAME,
10274                ..
10275            }
10276        ));
10277    }
10278
10279    #[test]
10280    fn rejects_pubsub_contrato_with_endpoint() {
10281        let mut s = three_member_spec();
10282        s.contratos.push(WitContract {
10283            de: "cart".into(),
10284            para: "catalog".into(),
10285            wit: "kafka:topic".into(),
10286            endpoint: Some("/wrong".into()),
10287            subject: Some("topic.x".into()),
10288            slot: None,
10289        });
10290        let err = s.validate().unwrap_err();
10291        assert!(matches!(
10292            err,
10293            AplicacaoError::ContratoWrongTarget {
10294                expected: WitTarget::PUBSUB_FIELD_NAME,
10295                ..
10296            }
10297        ));
10298    }
10299
10300    #[test]
10301    fn rejects_store_contrato_without_slot() {
10302        let mut s = three_member_spec();
10303        s.contratos.push(WitContract {
10304            de: "cart".into(),
10305            para: "catalog".into(),
10306            wit: "wasi:keyvalue/store".into(),
10307            endpoint: None,
10308            subject: None,
10309            slot: None,
10310        });
10311        let err = s.validate().unwrap_err();
10312        assert!(matches!(
10313            err,
10314            AplicacaoError::ContratoMissingTarget {
10315                expected: WitTarget::STORE_FIELD_NAME,
10316                ..
10317            }
10318        ));
10319    }
10320
10321    // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
10322
10323    #[test]
10324    fn rejects_http_contrato_with_empty_endpoint() {
10325        // `Some("")` for an HTTP endpoint passes the presence check
10326        // (target() previously returned WitTarget::Http { endpoint: "" })
10327        // but renders as a `path: ""` Cilium L7 rule that matches no
10328        // traffic. Same value-shape footgun closed for :entrada :paths
10329        // entries (eb3456d).
10330        let mut s = three_member_spec();
10331        s.contratos.push(WitContract {
10332            de: "cart".into(),
10333            para: "catalog".into(),
10334            wit: "wasi:http/proxy".into(),
10335            endpoint: Some(String::new()),
10336            subject: None,
10337            slot: None,
10338        });
10339        let err = s.validate().unwrap_err();
10340        assert!(
10341            matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
10342                if de == "cart" && para == "catalog"),
10343            "got {err:?}"
10344        );
10345    }
10346
10347    #[test]
10348    fn rejects_http_contrato_with_relative_endpoint() {
10349        // Cilium L7 :path + Gateway API PathPrefix both require a
10350        // leading `/`. Same shape required of :entrada :paths
10351        // (eb3456d). Lifted into target() so every consumer of the
10352        // typed WitTarget view inherits the guarantee.
10353        let mut s = three_member_spec();
10354        s.contratos.push(WitContract {
10355            de: "cart".into(),
10356            para: "catalog".into(),
10357            wit: "wasi:http/proxy".into(),
10358            endpoint: Some("products/:id".into()),
10359            subject: None,
10360            slot: None,
10361        });
10362        let err = s.validate().unwrap_err();
10363        assert!(
10364            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
10365                if endpoint == "products/:id"),
10366            "got {err:?}"
10367        );
10368    }
10369
10370    #[test]
10371    fn rejects_pubsub_contrato_with_empty_subject() {
10372        // NATS / Kafka publish without a subject is a no-op subscribe;
10373        // never the author's intent. Same empty-string rejection as
10374        // :membros :caixa, :placement :clusters entries, :entrada
10375        // :paths entries — every value carried by every typed slot is
10376        // value-shape-checked at validate().
10377        let mut s = three_member_spec();
10378        s.contratos.push(WitContract {
10379            de: "cart".into(),
10380            para: "catalog".into(),
10381            wit: "nats:pub-sub".into(),
10382            endpoint: None,
10383            subject: Some(String::new()),
10384            slot: None,
10385        });
10386        let err = s.validate().unwrap_err();
10387        assert!(
10388            matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
10389                if de == "cart" && para == "catalog"),
10390            "got {err:?}"
10391        );
10392    }
10393
10394    #[test]
10395    fn rejects_store_contrato_with_empty_slot() {
10396        // An empty slot template addresses the bucket root, defeating
10397        // the per-key isolation the slot exists for — a footgun on
10398        // `wasi:keyvalue/store` whose closest analog is the empty
10399        // shard-key rejected on :placement Sharded (c7c7799).
10400        let mut s = three_member_spec();
10401        s.contratos.push(WitContract {
10402            de: "cart".into(),
10403            para: "catalog".into(),
10404            wit: "wasi:keyvalue/store".into(),
10405            endpoint: None,
10406            subject: None,
10407            slot: Some(String::new()),
10408        });
10409        let err = s.validate().unwrap_err();
10410        assert!(
10411            matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
10412                if de == "cart" && para == "catalog"),
10413            "got {err:?}"
10414        );
10415    }
10416
10417    #[test]
10418    fn http_contrato_root_endpoint_validates() {
10419        // Pin the boundary case: a single-`/` endpoint is the catch-all
10420        // form the Gateway HTTPRoute renderer falls back to when
10421        // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
10422        // must remain a valid contrato endpoint too.
10423        let mut s = three_member_spec();
10424        s.contratos.push(contract_http("cart", "catalog", "/"));
10425        s.validate().unwrap();
10426    }
10427
10428    // ── :contratos :endpoint value-shape gate ────────────────────────────
10429    //
10430    // Mirrors the `:entrada :paths` value-shape suite on the peer
10431    // HTTP-path axis. Until this gate landed `WitContract::target()`
10432    // only refused the empty string + the missing-leading-`/` form
10433    // (c4213a4); a structurally invalid endpoint passed validate and
10434    // landed verbatim as a Cilium L7 `path:` rule
10435    // (caixa-mesh/src/lib.rs:311) that either silently dropped all
10436    // traffic or was rejected at apply time by Cilium policy admission.
10437    // Every authoring footgun the K8s Gateway API webhook / Cilium
10438    // policy validator would catch on admission now becomes a caixa-
10439    // build-time `ContratoEndpointInvalid` with the offending
10440    // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
10441    // shape as `EntradaPathInvalid` on the sibling axis; same shared
10442    // predicate (`crate::render::is_gateway_api_http_path`) ensures
10443    // drift between the two axes' rule enforcement is a build error
10444    // at the predicate.
10445
10446    fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
10447        // Fresh spec per call so the would-be-duplicate edge
10448        // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
10449        // `three_member_spec`'s pre-existing
10450        // `(cart, catalog, …, /products/:id)` entry — only the
10451        // endpoint payload differs.
10452        let mut s = three_member_spec();
10453        s.contratos.push(contract_http("cart", "catalog", ep));
10454        s.validate().unwrap_err()
10455    }
10456
10457    #[test]
10458    fn rejects_http_contrato_endpoint_with_query() {
10459        // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
10460        // silently rendered as a Cilium L7 `path: "/charge?token=X"`
10461        // rule the L7 matcher would never satisfy.
10462        let err = contrato_endpoint_err("/charge?token=X");
10463        assert!(
10464            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10465                if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
10466            "got {err:?}"
10467        );
10468    }
10469
10470    #[test]
10471    fn rejects_http_contrato_endpoint_with_fragment() {
10472        let err = contrato_endpoint_err("/charge#frag");
10473        assert!(
10474            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10475                if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
10476            "got {err:?}"
10477        );
10478    }
10479
10480    #[test]
10481    fn rejects_http_contrato_endpoint_with_whitespace() {
10482        let err = contrato_endpoint_err("/foo bar");
10483        assert!(
10484            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10485                if endpoint == "/foo bar" && reason.contains("whitespace")),
10486            "got {err:?}"
10487        );
10488    }
10489
10490    #[test]
10491    fn rejects_http_contrato_endpoint_with_control_char() {
10492        let err = contrato_endpoint_err("/api/\x01bar");
10493        assert!(
10494            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10495                if endpoint == "/api/\x01bar" && reason.contains("control character")),
10496            "got {err:?}"
10497        );
10498    }
10499
10500    #[test]
10501    fn rejects_http_contrato_endpoint_with_non_ascii() {
10502        let err = contrato_endpoint_err("/api/café");
10503        assert!(
10504            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10505                if endpoint == "/api/café" && reason.contains("non-ASCII")),
10506            "got {err:?}"
10507        );
10508    }
10509
10510    #[test]
10511    fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
10512        let err = contrato_endpoint_err("/api//cart");
10513        assert!(
10514            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10515                if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
10516            "got {err:?}"
10517        );
10518    }
10519
10520    #[test]
10521    fn rejects_http_contrato_endpoint_with_dot_segment() {
10522        let err = contrato_endpoint_err("/api/./cart");
10523        assert!(
10524            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10525                if endpoint == "/api/./cart" && reason.contains("`.` segment")),
10526            "got {err:?}"
10527        );
10528    }
10529
10530    #[test]
10531    fn rejects_http_contrato_endpoint_with_parent_segment() {
10532        // Path-traversal in a contrato endpoint is the canonical
10533        // "L7 rule that the workload's HTTP server's path-resolution
10534        // logic interprets differently than the policy enforcer"
10535        // footgun. Rejected outright at validate time.
10536        let err = contrato_endpoint_err("/api/../etc");
10537        assert!(
10538            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10539                if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
10540            "got {err:?}"
10541        );
10542    }
10543
10544    #[test]
10545    fn rejects_http_contrato_endpoint_too_long() {
10546        // 1025-byte endpoint — one over the Gateway API
10547        // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
10548        // path matcher has no inherent length limit but the policy
10549        // CR itself rides through the K8s apiserver, which enforces
10550        // ConfigMap-shaped limits; sharing the Gateway API cap is the
10551        // conservative floor.
10552        let big = format!("/api/{}", "a".repeat(1020));
10553        assert_eq!(big.len(), 1025);
10554        let err = contrato_endpoint_err(&big);
10555        assert!(
10556            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10557                if endpoint == &big && reason.contains("max length of 1024")),
10558            "got {err:?}"
10559        );
10560    }
10561
10562    #[test]
10563    fn http_contrato_endpoint_max_length_validates() {
10564        // 1024-byte endpoint — exactly the cap. Boundary pin: drift
10565        // in the cap surfaces here and at
10566        // `rejects_http_contrato_endpoint_too_long` simultaneously,
10567        // mirroring `entrada_path_max_length_validates` on the peer
10568        // axis.
10569        let big = format!("/api/{}", "a".repeat(1019));
10570        assert_eq!(big.len(), 1024);
10571        let mut s = three_member_spec();
10572        s.contratos.push(contract_http("cart", "catalog", &big));
10573        s.validate().unwrap();
10574    }
10575
10576    #[test]
10577    fn http_contrato_endpoint_accepts_canonical_forms() {
10578        // Positive-set sweep: every canonical HTTP-path shape the
10579        // sibling `:entrada :paths` axis accepts (the bare-root `/`,
10580        // plain paths, hidden-file-style `.config` segments distinct
10581        // from the `.` segment, digit-bearing segments, the canonical
10582        // route-template `:param` form, trailing-slash form,
10583        // percent-encoded segments, the `/foo..bar` interior-`..`-
10584        // substring forms that are NOT `..` segments) must remain a
10585        // valid contrato endpoint too. Drift between this list and
10586        // the entrada path positive sweep surfaces at the shared
10587        // `is_gateway_api_http_path` substrate-side suite — one
10588        // source of truth. Uses a fresh `(payment, catalog)` edge so
10589        // none of the swept endpoints collide with the pre-existing
10590        // `(cart, catalog, /products/:id)` / `(cart, payment,
10591        // /charge)` entries in `three_member_spec`.
10592        for ep in [
10593            "/",
10594            "/charge",
10595            "/v1/charge",
10596            "/api/.config",
10597            "/products/:id",
10598            "/api/cart/",
10599            "/api/caf%C3%A9",
10600            "/foo..bar",
10601            "/...",
10602        ] {
10603            let mut s = three_member_spec();
10604            s.contratos.push(contract_http("payment", "catalog", ep));
10605            s.validate()
10606                .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
10607        }
10608    }
10609
10610    #[test]
10611    fn contrato_endpoint_empty_takes_precedence_over_invalid() {
10612        // Ordering pin: `ContratoEndpointEmpty` is the more self-
10613        // locating diagnostic on `""` and must lead — the value-
10614        // shape gate is only reached after the empty-check fires.
10615        // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
10616        // on the peer axis.
10617        let mut s = three_member_spec();
10618        s.contratos.push(WitContract {
10619            de: "cart".into(),
10620            para: "catalog".into(),
10621            wit: "wasi:http/proxy".into(),
10622            endpoint: Some(String::new()),
10623            subject: None,
10624            slot: None,
10625        });
10626        let err = s.validate().unwrap_err();
10627        assert!(
10628            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
10629            "got {err:?}"
10630        );
10631    }
10632
10633    #[test]
10634    fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
10635        // Ordering pin: an endpoint without a leading `/` surfaces the
10636        // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
10637        // value-shape gate is only consulted on endpoints that already
10638        // satisfy the absolute-prefix invariant. Mirrors
10639        // `entrada_path_not_absolute_takes_precedence_over_invalid`.
10640        let err = contrato_endpoint_err("bad path");
10641        assert!(
10642            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
10643                if endpoint == "bad path"),
10644            "got {err:?}"
10645        );
10646    }
10647
10648    #[test]
10649    fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
10650        // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
10651        // `:para` + a non-empty reason flow through verbatim so the
10652        // author can grep their caixa.lisp for the offending contrato
10653        // block and fix it in one edit. Same shape as
10654        // `entrada_path_diagnostic_carries_offending_path`.
10655        let err = contrato_endpoint_err("/api?q=1");
10656        match err {
10657            AplicacaoError::ContratoEndpointInvalid {
10658                de,
10659                para,
10660                endpoint,
10661                reason,
10662            } => {
10663                assert_eq!(de, "cart");
10664                assert_eq!(para, "catalog");
10665                assert_eq!(endpoint, "/api?q=1");
10666                assert!(!reason.is_empty(), "reason field must be non-empty");
10667            }
10668            other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
10669        }
10670    }
10671
10672    #[test]
10673    fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
10674        // The compounding theorem: every &str inside a WitTarget
10675        // returned by target() is non-empty (and absolute, for Http).
10676        // Renderers downstream of typed_view() can rely on this
10677        // without re-checking — the type system carries the proof.
10678        let http = contract_http("cart", "catalog", "/x");
10679        match http.target().unwrap() {
10680            WitTarget::Http { endpoint } => {
10681                assert!(!endpoint.is_empty());
10682                assert!(endpoint.starts_with('/'));
10683            }
10684            other => panic!("expected Http, got {other:?}"),
10685        }
10686        let nats = WitContract {
10687            de: "a".into(),
10688            para: "b".into(),
10689            wit: "nats:pub-sub".into(),
10690            endpoint: None,
10691            subject: Some("topic.x".into()),
10692            slot: None,
10693        };
10694        match nats.target().unwrap() {
10695            WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
10696            other => panic!("expected PubSub, got {other:?}"),
10697        }
10698        let kv = WitContract {
10699            de: "a".into(),
10700            para: "b".into(),
10701            wit: "wasi:keyvalue/store".into(),
10702            endpoint: None,
10703            subject: None,
10704            slot: Some("checkout/$orderId".into()),
10705        };
10706        match kv.target().unwrap() {
10707            WitTarget::Store { slot } => assert!(!slot.is_empty()),
10708            other => panic!("expected Store, got {other:?}"),
10709        }
10710    }
10711
10712    #[test]
10713    fn target_diagnostic_names_offending_endpoint_value() {
10714        // When the malformed endpoint string is non-trivial, the
10715        // diagnostic carries the actual value back to the author —
10716        // not a generic "endpoint malformed" error.
10717        let bad = WitContract {
10718            de: "src".into(),
10719            para: "dst".into(),
10720            wit: "wasi:http/proxy".into(),
10721            endpoint: Some("api/v1/charge".into()),
10722            subject: None,
10723            slot: None,
10724        };
10725        match bad.target().unwrap_err() {
10726            AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
10727                assert_eq!(de, "src");
10728                assert_eq!(para, "dst");
10729                assert_eq!(endpoint, "api/v1/charge");
10730            }
10731            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
10732        }
10733    }
10734
10735    #[test]
10736    fn rejects_unknown_wit_with_target_set() {
10737        let mut s = three_member_spec();
10738        s.contratos.push(WitContract {
10739            de: "cart".into(),
10740            para: "catalog".into(),
10741            wit: "custom:exchange".into(),
10742            endpoint: Some("/leaked".into()),
10743            subject: None,
10744            slot: None,
10745        });
10746        let err = s.validate().unwrap_err();
10747        assert!(matches!(
10748            err,
10749            AplicacaoError::ContratoWrongTarget {
10750                expected: WitTarget::CAPABILITY_EXPECTED,
10751                ..
10752            }
10753        ));
10754    }
10755
10756    #[test]
10757    fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
10758        // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
10759        // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
10760        // fourth arm of the same "which payload field name goes in the
10761        // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
10762        // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
10763        // consts cover on the peer HTTP / PubSub / Store arms
10764        // (`wit_target_field_name_pins_per_variant`). Until this lift
10765        // landed the byte-string sat twice — once inline in the
10766        // [`WitContract::target`] Capability-arm rejection at the
10767        // production dispatch, once in `rejects_unknown_wit_with_target_set`
10768        // pinning against the same literal — with no compile-time link
10769        // between them. Same "one canonical declaration, next to the
10770        // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
10771        // lift established for the payload-less arm's human-readable
10772        // label axis; this test is the shape peer of
10773        // `wit_target_label_pins_per_variant`'s Capability-arm assertion
10774        // pair (routes-through-const + scalar-value pin) on the
10775        // wrong-target diagnostic-scalar axis.
10776        //
10777        // Fail-before-pass-after was verified locally by mutating the
10778        // const declaration to `"capability"` — the scalar-value pin
10779        // below fires (`"capability" != "none"`) and the routes-through
10780        // assertion below still holds (production and const walk in
10781        // lockstep), which is the correct behavior: a rename on the
10782        // const drifts here first, not at a downstream consumer.
10783        assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
10784
10785        let mut s = three_member_spec();
10786        s.contratos.push(WitContract {
10787            de: "cart".into(),
10788            para: "catalog".into(),
10789            wit: "custom:exchange".into(),
10790            endpoint: Some("/leaked".into()),
10791            subject: None,
10792            slot: None,
10793        });
10794        match s.validate().unwrap_err() {
10795            AplicacaoError::ContratoWrongTarget { expected, .. } => {
10796                assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
10797            }
10798            other => panic!("expected ContratoWrongTarget, got {other:?}"),
10799        }
10800    }
10801
10802    #[test]
10803    fn unknown_wit_capability_only_validates() {
10804        let mut s = three_member_spec();
10805        s.contratos.push(WitContract {
10806            de: "cart".into(),
10807            para: "catalog".into(),
10808            // A WIT world we haven't yet shaped — accept it as a typed
10809            // capability edge so authors aren't blocked while the WIT
10810            // registry catches up. No payload field may be carried.
10811            wit: "custom:exchange".into(),
10812            endpoint: None,
10813            subject: None,
10814            slot: None,
10815        });
10816        s.validate().unwrap();
10817        let added = s.contratos.last().unwrap();
10818        assert_eq!(added.target().unwrap(), WitTarget::Capability);
10819    }
10820
10821    #[test]
10822    fn target_typed_view_round_trips_each_shape() {
10823        let http = contract_http("cart", "catalog", "/products/:id");
10824        assert_eq!(
10825            http.target().unwrap(),
10826            WitTarget::Http {
10827                endpoint: "/products/:id"
10828            }
10829        );
10830        let nats = WitContract {
10831            de: "a".into(),
10832            para: "b".into(),
10833            wit: "nats:pub-sub".into(),
10834            endpoint: None,
10835            subject: Some("topic.x".into()),
10836            slot: None,
10837        };
10838        assert_eq!(
10839            nats.target().unwrap(),
10840            WitTarget::PubSub { subject: "topic.x" }
10841        );
10842        let kv = WitContract {
10843            de: "a".into(),
10844            para: "b".into(),
10845            wit: "wasi:keyvalue/store".into(),
10846            endpoint: None,
10847            subject: None,
10848            slot: Some("checkout/$orderId".into()),
10849        };
10850        assert_eq!(
10851            kv.target().unwrap(),
10852            WitTarget::Store {
10853                slot: "checkout/$orderId"
10854            }
10855        );
10856    }
10857
10858    #[test]
10859    fn wit_contract_kind_predicates() {
10860        let http = contract_http("a", "b", "/x");
10861        assert!(http.is_http());
10862        assert!(!http.is_pubsub());
10863        assert!(!http.is_store());
10864        assert!(!http.is_capability());
10865
10866        let nats = WitContract {
10867            de: "a".into(),
10868            para: "b".into(),
10869            wit: "nats:pub-sub".into(),
10870            endpoint: None,
10871            subject: Some("topic.x".into()),
10872            slot: None,
10873        };
10874        assert!(nats.is_pubsub());
10875        assert!(!nats.is_http());
10876        assert!(!nats.is_capability());
10877
10878        let kv = WitContract {
10879            de: "a".into(),
10880            para: "b".into(),
10881            wit: "wasi:keyvalue/store".into(),
10882            endpoint: None,
10883            subject: None,
10884            slot: Some("checkout/$orderId".into()),
10885        };
10886        assert!(kv.is_store());
10887        assert!(!kv.is_http());
10888        assert!(!kv.is_capability());
10889
10890        // Fourth arm on the paired closed-set predicate family: the
10891        // payload-less capability edge that projects to the payload-
10892        // less [`WitTarget::Capability`] arm under [`WitContract::target`].
10893        // Extends the 3-arm predicate sweep this test opened to cover
10894        // the closed 4-way partition [`WitContract::is_capability`]
10895        // closes on the pre-projection WIT-shape axis, matched with the
10896        // sibling post-projection [`WitTarget`]-side `IsVariant`-derived
10897        // 4-arm predicate set.
10898        let cap = WitContract {
10899            de: "a".into(),
10900            para: "b".into(),
10901            wit: "custom:capability-only".into(),
10902            endpoint: None,
10903            subject: None,
10904            slot: None,
10905        };
10906        assert!(cap.is_capability());
10907        assert!(!cap.is_http());
10908        assert!(!cap.is_pubsub());
10909        assert!(!cap.is_store());
10910    }
10911
10912    // ── :contratos :wit value-shape gate ─────────────────────────────────
10913    //
10914    // Mirrors the `:contratos :endpoint` value-shape suite on the peer
10915    // dispatch-discriminator axis. Until this gate landed
10916    // `WitContract::target()` accepted any non-empty string and
10917    // silently demoted unrecognized shapes to a capability-only L4
10918    // edge — the canonical "I thought I had L7 HTTP routing, got
10919    // L4-only" footgun. Every authoring footgun the WIT registry's
10920    // own grammar rejects (uppercase, hyphen-for-colon typo,
10921    // whitespace, empty package, doubled `@`, …) now becomes a
10922    // caixa-build-time `ContratoWitInvalid` with the offending
10923    // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
10924    // as `ContratoEndpointInvalid` on the sibling axis; same shared
10925    // predicate (`crate::render::is_wit_world_ref`) ensures drift
10926    // between any two axes' rule enforcement is a build error at the
10927    // predicate, not piecemeal across renderers.
10928
10929    fn contrato_wit_err(wit: &str) -> AplicacaoError {
10930        // Fresh spec per call so the new contract doesn't collide on
10931        // identity with `three_member_spec`'s pre-existing entries.
10932        // The new edge uses `(payment, catalog)` — a pair the fixture
10933        // doesn't already declare — with no payload field set, so the
10934        // wit-shape gate fires before any payload-shape arm.
10935        let mut s = three_member_spec();
10936        s.contratos.push(WitContract {
10937            de: "payment".into(),
10938            para: "catalog".into(),
10939            wit: wit.into(),
10940            endpoint: None,
10941            subject: None,
10942            slot: None,
10943        });
10944        s.validate().unwrap_err()
10945    }
10946
10947    #[test]
10948    fn rejects_wit_with_uppercase_namespace() {
10949        // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
10950        // didn't match the lowercase `wasi:http/` prefix is_http() keys
10951        // off, so the dispatch fell through to the capability arm and
10952        // the contract silently rendered as an L4-only Cilium edge.
10953        // The new gate surfaces the uppercase typo at validate time
10954        // with the offending `:wit` named.
10955        let err = contrato_wit_err("WASI:http/proxy");
10956        assert!(
10957            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10958                if wit == "WASI:http/proxy" && reason.contains("lowercase")),
10959            "got {err:?}"
10960        );
10961    }
10962
10963    #[test]
10964    fn rejects_wit_with_hyphen_for_colon_typo() {
10965        // The canonical "I forgot the `:` separator" typo — pre-gate
10966        // this passed as Capability silently, so the renderer emitted
10967        // an L4-only policy where the author expected L7 HTTP rules.
10968        let err = contrato_wit_err("wasi-http/proxy");
10969        assert!(
10970            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10971                if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
10972            "got {err:?}"
10973        );
10974    }
10975
10976    #[test]
10977    fn rejects_wit_with_multiple_colons() {
10978        // Doubled `:` — the namespace/package split has nowhere to
10979        // anchor, so the dispatch silently demotes to Capability.
10980        let err = contrato_wit_err("wasi:http:proxy");
10981        assert!(
10982            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10983                if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
10984            "got {err:?}"
10985        );
10986    }
10987
10988    #[test]
10989    fn rejects_wit_with_empty_package() {
10990        // `wasi:` — namespace alone with no package. Pre-gate this
10991        // failed neither the is_http nor is_pubsub nor is_store
10992        // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
10993        // a bare `wasi:`), so it silently demoted to Capability.
10994        let err = contrato_wit_err("wasi:");
10995        assert!(
10996            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10997                if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
10998            "got {err:?}"
10999        );
11000    }
11001
11002    #[test]
11003    fn rejects_wit_with_underscore() {
11004        // Underscore — WIT identifiers are kebab-case, same rule
11005        // DNS-1123 enforces on its peer axes. The diagnostic carries
11006        // the explicit "use `-` instead" remediation.
11007        let err = contrato_wit_err("wasi:http_proxy");
11008        assert!(
11009            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11010                if wit == "wasi:http_proxy" && reason.contains('_')),
11011            "got {err:?}"
11012        );
11013    }
11014
11015    #[test]
11016    fn rejects_wit_with_whitespace() {
11017        // Whitespace mid-token — the prefix check matches but the
11018        // package-and-onward parse silently demoted to Capability.
11019        let err = contrato_wit_err("wasi:http proxy");
11020        assert!(
11021            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11022                if wit == "wasi:http proxy" && reason.contains("whitespace")),
11023            "got {err:?}"
11024        );
11025    }
11026
11027    #[test]
11028    fn rejects_wit_with_non_ascii() {
11029        // Un-percent-encoded non-ASCII byte — the canonical "I copied
11030        // the package name from a doc with smart quotes / accented
11031        // characters" footgun.
11032        let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
11033        assert!(
11034            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11035                if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
11036            "got {err:?}"
11037        );
11038    }
11039
11040    #[test]
11041    fn rejects_wit_with_consecutive_hyphens() {
11042        // `pub--sub` — WIT identifiers join words with single hyphens.
11043        let err = contrato_wit_err("nats:pub--sub");
11044        assert!(
11045            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11046                if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
11047            "got {err:?}"
11048        );
11049    }
11050
11051    #[test]
11052    fn rejects_wit_with_trailing_at_no_version() {
11053        // `wasi:http/proxy@` — the version-suffix author started to
11054        // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
11055        // parser would reject this; surface it at validate time.
11056        let err = contrato_wit_err("wasi:http/proxy@");
11057        assert!(
11058            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11059                if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
11060            "got {err:?}"
11061        );
11062    }
11063
11064    #[test]
11065    fn rejects_wit_too_long() {
11066        // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
11067        // The legitimate-shape arms all pass (lowercase, single `:`,
11068        // kebab-case identifiers); only the cap arm fires. Surfaces
11069        // the paste-from-binary / accidental-multi-line-blob landing
11070        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
11071        // on the peer axis.
11072        let big = format!("wasi:{}", "a".repeat(124));
11073        assert_eq!(big.len(), 129);
11074        let err = contrato_wit_err(&big);
11075        assert!(
11076            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11077                if wit == &big && reason.contains("max length of 128")),
11078            "got {err:?}"
11079        );
11080    }
11081
11082    #[test]
11083    fn wit_max_length_validates() {
11084        // 128-byte WIT reference — exactly the cap. Boundary pin:
11085        // drift in the cap surfaces here and at `rejects_wit_too_long`
11086        // simultaneously, mirroring
11087        // `http_contrato_endpoint_max_length_validates` on the peer
11088        // axis.
11089        let big = format!("wasi:{}", "a".repeat(123));
11090        assert_eq!(big.len(), 128);
11091        let mut s = three_member_spec();
11092        s.contratos.push(WitContract {
11093            de: "payment".into(),
11094            para: "catalog".into(),
11095            wit: big,
11096            endpoint: None,
11097            subject: None,
11098            slot: None,
11099        });
11100        s.validate().unwrap();
11101    }
11102
11103    #[test]
11104    fn wit_accepts_canonical_forms_at_aplicacao_layer() {
11105        // Positive-set sweep through the AplicacaoSpec::validate
11106        // surface (rather than the substrate-side predicate directly)
11107        // — pins every shape the existing test fixtures + the
11108        // checkout-aplicacao example carry, so the gate's accept-set
11109        // matches the substrate's emit-set. Drift between this list
11110        // and `render::tests::wit_world_ref_accepts_canonical_forms`
11111        // surfaces at the substrate layer's positive sweep — one
11112        // source of truth for the rule.
11113        for wit in [
11114            "wasi:http/proxy",
11115            "wasi:keyvalue/store",
11116            "nats:pub-sub",
11117            "kafka:topic",
11118            "custom:exchange",
11119            "pleme:cap/audit",
11120            "wasi:http/proxy@0.2.0",
11121        ] {
11122            // Payload field paired to the dispatched WIT shape so the
11123            // shape-↔-target arm doesn't fire instead of the wit-shape
11124            // arm we're exercising. Routes off the same
11125            // `wit_shape_is_http` / `wit_shape_is_pubsub` /
11126            // `wit_shape_is_store` free functions the production
11127            // `WitContract::is_http` / `is_pubsub` / `is_store`
11128            // methods delegate to (both consult the lifted
11129            // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
11130            // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
11131            // future prefix addition to the routing accept-set
11132            // reaches this test's payload-dispatch arm by
11133            // construction — no per-test-site drift can hide a
11134            // shape-→-target-slot mismatch that would silently
11135            // demote a canonical `:wit` value to the
11136            // `(None, None, None)` capability-only arm and let the
11137            // `AplicacaoSpec::validate` positive sweep pass on a
11138            // shape it should exercise as HTTP / pub-sub / store.
11139            let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
11140                (Some("/x".into()), None, None)
11141            } else if wit_shape_is_pubsub(wit) {
11142                (None, Some("topic.x".into()), None)
11143            } else if wit_shape_is_store(wit) {
11144                (None, None, Some("bucket/$key".into()))
11145            } else {
11146                (None, None, None)
11147            };
11148            let mut s = three_member_spec();
11149            s.contratos.push(WitContract {
11150                de: "payment".into(),
11151                para: "catalog".into(),
11152                wit: wit.into(),
11153                endpoint,
11154                subject,
11155                slot,
11156            });
11157            s.validate()
11158                .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
11159        }
11160    }
11161
11162    #[test]
11163    fn wit_shape_predicates_accept_canonical_prefix_set() {
11164        // Positive-set sweep pinning every prefix in
11165        // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
11166        // WIT_STORE_SHAPE_PREFIXES against the three free-function
11167        // dispatch predicates. The six prefixes are the load-bearing
11168        // routing keys the substrate's WIT-shape dispatch consults
11169        // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
11170        // key/value-store-slot admission); any drift between the
11171        // free-function accept-set and this list surfaces here
11172        // rather than at apply time as a silent
11173        // shape-→-capability-only demotion.
11174        assert!(wit_shape_is_http("wasi:http/proxy"));
11175        assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
11176        assert!(wit_shape_is_http("http:incoming"));
11177
11178        assert!(wit_shape_is_pubsub("nats:pub-sub"));
11179        assert!(wit_shape_is_pubsub("kafka:topic"));
11180
11181        assert!(wit_shape_is_store("wasi:keyvalue/store"));
11182        assert!(wit_shape_is_store("kv:cache/session"));
11183    }
11184
11185    #[test]
11186    fn wit_shape_predicates_reject_uncanonical_forms() {
11187        // Negative-set pin: the six canonical prefixes are
11188        // lowercase-only (mirrors the `is_wit_world_ref` substrate
11189        // predicate's lowercase invariant — see its docstring on the
11190        // "I thought I had L7 HTTP routing, got L4-only" footgun).
11191        // The empty string, an uppercase-prefixed form, a hyphen-
11192        // instead-of-colon typo, and a bare kebab identifier all miss
11193        // every shape arm — reachable-by-construction only via the
11194        // `is_wit_world_ref` gate that admission-checks the `:wit`
11195        // value first, but pinned here so any future
11196        // free-function change (e.g. a case-insensitive
11197        // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
11198        // this unit level.
11199        for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
11200            assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
11201            assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
11202            assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
11203        }
11204    }
11205
11206    #[test]
11207    fn wit_shape_predicates_partition_canonical_set() {
11208        // Every canonical prefix routes to exactly one shape arm —
11209        // the three prefix sets are pairwise disjoint. Pins the
11210        // routing property [`WitContract::target`] relies on: an
11211        // `is_http()` return of `true` guarantees `is_pubsub()` and
11212        // `is_store()` return `false`, so the shape-→-target-slot
11213        // dispatch (endpoint vs subject vs slot) is unambiguous.
11214        // Drift (e.g. a future `"kv:"` moved into the HTTP set
11215        // without removal from the store set) would silently route
11216        // one prefix to two arms and the first-matching-arm order
11217        // becomes load-bearing — this pin surfaces it as a build
11218        // error instead.
11219        for prefix in WIT_HTTP_SHAPE_PREFIXES {
11220            let sample = format!("{prefix}x");
11221            assert!(wit_shape_is_http(&sample));
11222            assert!(!wit_shape_is_pubsub(&sample));
11223            assert!(!wit_shape_is_store(&sample));
11224        }
11225        for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
11226            let sample = format!("{prefix}x");
11227            assert!(!wit_shape_is_http(&sample));
11228            assert!(wit_shape_is_pubsub(&sample));
11229            assert!(!wit_shape_is_store(&sample));
11230        }
11231        for prefix in WIT_STORE_SHAPE_PREFIXES {
11232            let sample = format!("{prefix}x");
11233            assert!(!wit_shape_is_http(&sample));
11234            assert!(!wit_shape_is_pubsub(&sample));
11235            assert!(wit_shape_is_store(&sample));
11236        }
11237    }
11238
11239    #[test]
11240    fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
11241        // Positive pin: [`wit_shape_matches`] is exactly the
11242        // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
11243        // parameterized on the accept-set. Two-prefix accept-set,
11244        // one-prefix accept-set, and empty accept-set (which must
11245        // reject everything, including the empty string — an empty
11246        // `any()` fold returns `false`) all pinned so a future
11247        // reimplementation that swaps `starts_with` for `contains`,
11248        // `==`, or a case-folded comparator surfaces at unit-test
11249        // time.
11250        let two = &["wasi:http/", "http:"];
11251        assert!(wit_shape_matches("wasi:http/proxy", two));
11252        assert!(wit_shape_matches("http:incoming", two));
11253        assert!(!wit_shape_matches("wasi:keyvalue/store", two));
11254
11255        let one = &["nats:"];
11256        assert!(wit_shape_matches("nats:pub-sub", one));
11257        assert!(!wit_shape_matches("kafka:topic", one));
11258
11259        // Empty accept-set matches nothing — the identity element
11260        // for the disjunctive `any()` fold across the prefix set.
11261        // Reachable via a future `wit_shape_is_<name>` const paired
11262        // to a still-empty prefix table on a nascent shape-arm draft.
11263        let empty: &[&str] = &[];
11264        assert!(!wit_shape_matches("wasi:http/proxy", empty));
11265        assert!(!wit_shape_matches("", empty));
11266
11267        // starts_with, not contains: a prefix embedded mid-string
11268        // never matches. Pins the routing invariant [`WitContract::target`]
11269        // relies on (an authored `:wit "custom:wasi:http/"` string
11270        // does not silently route through the HTTP arm just because
11271        // it happens to contain the canonical HTTP prefix).
11272        assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
11273    }
11274
11275    #[test]
11276    fn wit_shape_predicates_delegate_to_wit_shape_matches() {
11277        // Equivalence pin: each per-shape predicate is exactly
11278        // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
11279        // every canonical prefix + the empty string + one negative
11280        // sample against every peer so a future predicate that grew
11281        // its own inline `iter().any(starts_with)` (rather than
11282        // delegating through the lifted combinator) drifts loudly here
11283        // — the peer-const table's contents must agree with the
11284        // predicate's accept-set by construction.
11285        let samples = [
11286            String::new(),
11287            "wasi:http/proxy".to_string(),
11288            "http:incoming".to_string(),
11289            "nats:pub-sub".to_string(),
11290            "kafka:topic".to_string(),
11291            "wasi:keyvalue/store".to_string(),
11292            "kv:cache/session".to_string(),
11293            "custom-shape".to_string(),
11294            "WASI:HTTP/proxy".to_string(),
11295        ];
11296        for wit in &samples {
11297            assert_eq!(
11298                wit_shape_is_http(wit),
11299                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
11300                "wit_shape_is_http drifted from combinator on {wit:?}",
11301            );
11302            assert_eq!(
11303                wit_shape_is_pubsub(wit),
11304                wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
11305                "wit_shape_is_pubsub drifted from combinator on {wit:?}",
11306            );
11307            assert_eq!(
11308                wit_shape_is_store(wit),
11309                wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
11310                "wit_shape_is_store drifted from combinator on {wit:?}",
11311            );
11312        }
11313    }
11314
11315    #[test]
11316    fn wit_contract_shape_methods_delegate_to_free_functions() {
11317        // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
11318        // `is_store` are `&self` conveniences on top of the free
11319        // functions — for every canonical prefix the method's return
11320        // matches its free-function peer. Sweeps the union of the
11321        // three prefix sets so a future method that grew its own
11322        // inline prefix logic (rather than delegating) drifts loudly
11323        // here on the first prefix the free function accepts and the
11324        // method doesn't.
11325        for shape_set in [
11326            WIT_HTTP_SHAPE_PREFIXES,
11327            WIT_PUBSUB_SHAPE_PREFIXES,
11328            WIT_STORE_SHAPE_PREFIXES,
11329        ] {
11330            for prefix in shape_set {
11331                let c = WitContract {
11332                    de: "cart".into(),
11333                    para: "catalog".into(),
11334                    wit: format!("{prefix}x"),
11335                    endpoint: None,
11336                    subject: None,
11337                    slot: None,
11338                };
11339                assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
11340                assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
11341                assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
11342                assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
11343            }
11344        }
11345        // Capability-arm delegation sweep: two representative
11346        // Capability-shaped `:wit` values (a bare non-prefix-matching
11347        // WIT world, the deliberately-shaped empty string
11348        // [`WitContract::is_capability`]'s docstring calls out as
11349        // syntactically Capability). Extends the free-function
11350        // delegation pin onto the fourth arm so a future
11351        // [`WitContract::is_capability`] rewrite that grew an inline
11352        // prefix-set scan (rather than delegating through
11353        // [`wit_shape_is_capability`]) drifts loudly here on the first
11354        // Capability-shaped sample.
11355        for wit in ["custom:capability-only", ""] {
11356            let c = WitContract {
11357                de: "cart".into(),
11358                para: "catalog".into(),
11359                wit: wit.into(),
11360                endpoint: None,
11361                subject: None,
11362                slot: None,
11363            };
11364            assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
11365        }
11366    }
11367
11368    #[test]
11369    fn wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis() {
11370        // 4-way partition-witness pin on the raw `&str` axis: for every
11371        // canonical prefix in the three payload-arm accept-sets,
11372        // exactly one of the four [`wit_shape_is_http`] /
11373        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
11374        // [`wit_shape_is_capability`] free functions returns `true` and
11375        // the other three return `false` — the four-arm partition
11376        // witness that locks the free-function WIT-shape-classifier
11377        // family into a partition of the `:contratos :wit` axis
11378        // load-bearing. Peer of the sibling [`WitContract`]-surface
11379        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
11380        // partition pin — extends the discipline onto the raw `&str`
11381        // axis so any future arm addition (a hypothetical
11382        // `wasi:sockets/*` transport-layer shape, an `oci:*`
11383        // capability-import carrier per the sibling
11384        // [`wit_shape_matches`] docstring's trajectory bullet) that
11385        // landed on one of the payload-arm free functions without
11386        // shrinking [`wit_shape_is_capability`]'s accept-set surfaces
11387        // here as two arms returning `true` simultaneously at
11388        // caixa-core build time rather than a silent per-consumer
11389        // misclassification at renderer emit time.
11390        for shape_set in [
11391            WIT_HTTP_SHAPE_PREFIXES,
11392            WIT_PUBSUB_SHAPE_PREFIXES,
11393            WIT_STORE_SHAPE_PREFIXES,
11394        ] {
11395            for prefix in shape_set {
11396                let wit = format!("{prefix}x");
11397                let hits = [
11398                    wit_shape_is_http(&wit),
11399                    wit_shape_is_pubsub(&wit),
11400                    wit_shape_is_store(&wit),
11401                    wit_shape_is_capability(&wit),
11402                ]
11403                .iter()
11404                .filter(|&&b| b)
11405                .count();
11406                assert_eq!(
11407                    hits,
11408                    1,
11409                    "raw-&str WIT-shape 4-way predicate partition must \
11410                     admit exactly one arm per canonical prefix; got {hits} \
11411                     hits at wit={wit:?} (is_http={}, is_pubsub={}, is_store={}, \
11412                     is_capability={})",
11413                    wit_shape_is_http(&wit),
11414                    wit_shape_is_pubsub(&wit),
11415                    wit_shape_is_store(&wit),
11416                    wit_shape_is_capability(&wit),
11417                );
11418            }
11419        }
11420        // Capability-arm sweep on the raw `&str` axis: two
11421        // representative Capability-shaped `:wit` values (a bare non-
11422        // prefix-matching WIT world, the deliberately-shaped empty
11423        // string the pure classifier still admits per
11424        // [`wit_shape_is_capability`]'s docstring). Both must land on
11425        // the fourth arm exclusively so the partition witness holds
11426        // across the full 4-arm closure on the raw `&str` axis.
11427        for wit in ["custom:capability-only", ""] {
11428            let hits = [
11429                wit_shape_is_http(wit),
11430                wit_shape_is_pubsub(wit),
11431                wit_shape_is_store(wit),
11432                wit_shape_is_capability(wit),
11433            ]
11434            .iter()
11435            .filter(|&&b| b)
11436            .count();
11437            assert_eq!(
11438                hits, 1,
11439                "raw-&str WIT-shape 4-way predicate partition must \
11440                 admit exactly one arm on Capability-shaped wit={wit:?}"
11441            );
11442            assert!(
11443                wit_shape_is_capability(wit),
11444                "wit={wit:?} must project onto the Capability arm on the raw-&str axis"
11445            );
11446        }
11447    }
11448
11449    #[test]
11450    fn wit_shape_is_capability_composes_through_payload_arm_predicate_negation() {
11451        // Composition-witness pin: [`wit_shape_is_capability`] is the
11452        // exact-inverse disjunction of the sibling payload-arm free-
11453        // function trio [`wit_shape_is_http`] / [`wit_shape_is_pubsub`]
11454        // / [`wit_shape_is_store`]. A future reimplementation that
11455        // grew its own prefix-set scan (e.g. inlining a fourth
11456        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does
11457        // not own today) rather than delegating to the sibling trio
11458        // would drift loudly here — the composition contract binds the
11459        // fourth-arm free-function predicate to the exact-inverse of
11460        // the three payload-arm free-function predicates, so any
11461        // rebrand of any prefix-set const flows through
11462        // [`wit_shape_is_capability`] by construction without a
11463        // coordinated per-consumer rewrite. Peer of the sibling
11464        // [`WitContract`]-surface
11465        // [`wit_contract_is_capability_composes_through_shape_predicate_negation`]
11466        // composition pin — extends the discipline onto the raw
11467        // `&str` axis.
11468        let mut cases: Vec<String> = Vec::new();
11469        for shape_set in [
11470            WIT_HTTP_SHAPE_PREFIXES,
11471            WIT_PUBSUB_SHAPE_PREFIXES,
11472            WIT_STORE_SHAPE_PREFIXES,
11473        ] {
11474            for prefix in shape_set {
11475                cases.push(format!("{prefix}x"));
11476            }
11477        }
11478        cases.push("custom:capability-only".to_string());
11479        cases.push(String::new());
11480        for wit in cases {
11481            assert_eq!(
11482                wit_shape_is_capability(&wit),
11483                !wit_shape_is_http(&wit) && !wit_shape_is_pubsub(&wit) && !wit_shape_is_store(&wit),
11484                "wit_shape_is_capability must equal \
11485                 !wit_shape_is_http() && !wit_shape_is_pubsub() && !wit_shape_is_store() \
11486                 at wit={wit:?}"
11487            );
11488        }
11489    }
11490
11491    #[test]
11492    fn wit_shape_classifier_family_is_const_fn() {
11493        // Fail-before-pass-after pin on the 4-arm free-function WIT-
11494        // shape classifier family's `const`-eval posture. Each of the
11495        // four peer classifiers ([`wit_shape_is_http`] /
11496        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
11497        // [`wit_shape_is_capability`]) and the underlying combinator
11498        // [`wit_shape_matches`] must be `pub const fn` — any future
11499        // accidental downgrade to non-`const` fails the `const fn`
11500        // wrappers below at caixa-core build time with E0015
11501        // (`cannot call non-const function`), strictly stronger than
11502        // a runtime `assert!` and strictly stronger than the module-
11503        // scope `const _: () = assert!(…)` pins immediately after the
11504        // classifier declarations (those anchor specific accept-set
11505        // truth-table entries; this pin anchors the `const` posture
11506        // itself via `const fn` wrappers that are only well-formed
11507        // when the callee is itself `const fn`).
11508        //
11509        // Verified fail-before-pass-after by locally reverting
11510        // `pub const fn` → `pub fn` on each classifier and observing
11511        // E0015 at every corresponding wrapper call site (build
11512        // error, no test-time surface), then restoring `pub const fn`
11513        // and observing the pin pass at test time. Peer of the
11514        // sibling M3
11515        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
11516        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
11517        // M2
11518        // [`child_spec_restart_accessor_is_const_fn`] /
11519        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
11520        // and M3
11521        // [`placement_estrategia_accessor_is_const_fn`] /
11522        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
11523        // sibling `const`-eval-surface-pass axes.
11524        const fn matches_via_const_fn(wit: &str, prefixes: &[&str]) -> bool {
11525            wit_shape_matches(wit, prefixes)
11526        }
11527        const fn http_via_const_fn(wit: &str) -> bool {
11528            wit_shape_is_http(wit)
11529        }
11530        const fn pubsub_via_const_fn(wit: &str) -> bool {
11531            wit_shape_is_pubsub(wit)
11532        }
11533        const fn store_via_const_fn(wit: &str) -> bool {
11534            wit_shape_is_store(wit)
11535        }
11536        const fn capability_via_const_fn(wit: &str) -> bool {
11537            wit_shape_is_capability(wit)
11538        }
11539        // Sweep one canonical accept-set sample per arm plus the
11540        // payload-less/empty capability samples, asserting the
11541        // wrapper and direct dispatches agree byte-for-byte across
11542        // the closed 4-arm partition.
11543        let cases: [(&str, bool, bool, bool, bool); 6] = [
11544            ("wasi:http/proxy", true, false, false, false),
11545            ("http:incoming", true, false, false, false),
11546            ("nats:events", false, true, false, false),
11547            ("kafka:topic", false, true, false, false),
11548            ("wasi:keyvalue/store", false, false, true, false),
11549            ("kv:cache", false, false, true, false),
11550        ];
11551        for (wit, is_http, is_pubsub, is_store, _is_capability) in cases {
11552            assert_eq!(
11553                matches_via_const_fn(wit, WIT_HTTP_SHAPE_PREFIXES),
11554                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
11555                "wit_shape_matches const fn wrapper disagrees at wit={wit:?}",
11556            );
11557            assert_eq!(http_via_const_fn(wit), wit_shape_is_http(wit));
11558            assert_eq!(pubsub_via_const_fn(wit), wit_shape_is_pubsub(wit));
11559            assert_eq!(store_via_const_fn(wit), wit_shape_is_store(wit));
11560            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
11561            assert_eq!(wit_shape_is_http(wit), is_http);
11562            assert_eq!(wit_shape_is_pubsub(wit), is_pubsub);
11563            assert_eq!(wit_shape_is_store(wit), is_store);
11564        }
11565        // Payload-less capability arm (the 4th partition arm).
11566        let capability_samples: [&str; 3] =
11567            ["wasi:filesystem/preopens", "custom:capability-only", ""];
11568        for wit in capability_samples {
11569            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
11570            assert!(wit_shape_is_capability(wit));
11571            assert!(!wit_shape_is_http(wit));
11572            assert!(!wit_shape_is_pubsub(wit));
11573            assert!(!wit_shape_is_store(wit));
11574        }
11575    }
11576
11577    #[test]
11578    fn wit_shape_matches_composes_through_bytes_starts_with_across_boundary_lengths() {
11579        // Composition-witness pin: [`wit_shape_matches`] agrees with
11580        // the reference `prefixes.iter().any(|p| wit.starts_with(p))`
11581        // dispatch (the prior non-`const` implementation) across
11582        // boundary lengths — empty `wit`, empty prefix, one-byte
11583        // slack, prefix longer than `wit`, one-byte trailing slack.
11584        // The rewrite to a byte-level manual starts_with loop (the
11585        // enabler for the `pub const fn` posture) must not change any
11586        // truth-table entry on the canonical accept-set — this pin
11587        // sweeps a targeted boundary corpus and asserts byte-for-byte
11588        // agreement, locking the const-fn rewrite's semantics against
11589        // the prior iterator body by construction.
11590        let prefixes = &["wasi:http/", "http:"][..];
11591        let cases: [(&str, bool); 12] = [
11592            ("wasi:http/proxy", true),
11593            ("wasi:http/", true), // exact-length match on prefix
11594            ("wasi:http", false), // one byte short
11595            ("http:", true),
11596            ("http:incoming", true),
11597            ("http", false), // one byte short
11598            ("", false),
11599            ("wasi:https/proxy", false),
11600            ("nats:events", false),
11601            ("HTTPS:", false), // uppercase — no case-fold in classifier
11602            ("wasi:HTTP/proxy", false),
11603            ("wasi:http", false),
11604        ];
11605        for (wit, expected) in cases {
11606            assert_eq!(
11607                wit_shape_matches(wit, prefixes),
11608                expected,
11609                "wit_shape_matches disagrees with reference at wit={wit:?}",
11610            );
11611            // Byte-equal to the iterator body it replaced.
11612            let via_iter = prefixes.iter().any(|p| wit.starts_with(p));
11613            assert_eq!(
11614                wit_shape_matches(wit, prefixes),
11615                via_iter,
11616                "wit_shape_matches must byte-equal iter().any(starts_with) at wit={wit:?}",
11617            );
11618        }
11619        // Empty prefix set → always false regardless of `wit`.
11620        let empty: &[&str] = &[];
11621        assert!(!wit_shape_matches("", empty));
11622        assert!(!wit_shape_matches("wasi:http/proxy", empty));
11623        // Empty prefix inside a non-empty set → always true (every
11624        // string starts with the empty string, matching the
11625        // iterator body's semantics on `str::starts_with("")`).
11626        let contains_empty: &[&str] = &["nats:", ""];
11627        assert!(wit_shape_matches("", contains_empty));
11628        assert!(wit_shape_matches("wasi:http/proxy", contains_empty));
11629    }
11630
11631    #[test]
11632    fn wit_contract_is_capability_partitions_the_wit_shape_space() {
11633        // 4-way partition-witness pin: for every canonical prefix in
11634        // the payload-arm accept-sets, exactly one of the four
11635        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
11636        // [`WitContract::is_store`] / [`WitContract::is_capability`]
11637        // predicates returns `true` and the other three return `false`
11638        // — the four-arm partition witness that locks the substrate's
11639        // WIT-shape-space closure on the pre-projection axis load-
11640        // bearing. A future arm addition (a hypothetical fourth
11641        // payload-shape prefix set, a `wasi:sockets/*` transport-layer
11642        // shape) that landed on one of the payload-arm predicates
11643        // without shrinking [`WitContract::is_capability`]'s accept-set
11644        // would surface here as two arms returning `true` simultaneously
11645        // — a partition-witness break the pin catches at caixa-core
11646        // build time rather than a silent per-consumer misclassification
11647        // at renderer emit time. Peer of the sibling `WitTarget`-side
11648        // [`tests::wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`]
11649        // partition-witness pin on the post-projection payload-scalar
11650        // arm-set — extends the discipline onto the pre-projection
11651        // 4-arm shape-space.
11652        for shape_set in [
11653            WIT_HTTP_SHAPE_PREFIXES,
11654            WIT_PUBSUB_SHAPE_PREFIXES,
11655            WIT_STORE_SHAPE_PREFIXES,
11656        ] {
11657            for prefix in shape_set {
11658                let c = WitContract {
11659                    de: "cart".into(),
11660                    para: "catalog".into(),
11661                    wit: format!("{prefix}x"),
11662                    endpoint: None,
11663                    subject: None,
11664                    slot: None,
11665                };
11666                let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
11667                    .iter()
11668                    .filter(|&&b| b)
11669                    .count();
11670                assert_eq!(
11671                    hits,
11672                    1,
11673                    "WitContract WIT-shape 4-way predicate partition must \
11674                     admit exactly one arm per canonical prefix; got {hits} \
11675                     hits at wit={:?} (is_http={}, is_pubsub={}, is_store={}, \
11676                     is_capability={})",
11677                    c.wit,
11678                    c.is_http(),
11679                    c.is_pubsub(),
11680                    c.is_store(),
11681                    c.is_capability(),
11682                );
11683            }
11684        }
11685        // Capability-arm sweep: two representative capability shapes
11686        // (a bare WIT world outside the three payload-arm prefix sets,
11687        // and the deliberately-shaped empty string that
11688        // [`crate::render::is_wit_world_ref`] rejects at
11689        // [`WitContract::target`] time but which the pure classifier
11690        // still admits — see the method docstring's "purely syntactic
11691        // classification" note). Both must land on the fourth arm
11692        // exclusively, so the partition witness holds across the full
11693        // 4-arm closure.
11694        for wit in ["custom:capability-only", ""] {
11695            let c = WitContract {
11696                de: "cart".into(),
11697                para: "catalog".into(),
11698                wit: wit.into(),
11699                endpoint: None,
11700                subject: None,
11701                slot: None,
11702            };
11703            let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
11704                .iter()
11705                .filter(|&&b| b)
11706                .count();
11707            assert_eq!(
11708                hits, 1,
11709                "WitContract WIT-shape 4-way predicate partition must \
11710                 admit exactly one arm on Capability-shaped wit={wit:?}"
11711            );
11712            assert!(
11713                c.is_capability(),
11714                "wit={wit:?} must project onto the Capability arm"
11715            );
11716        }
11717    }
11718
11719    #[test]
11720    fn wit_contract_is_capability_composes_through_shape_predicate_negation() {
11721        // Composition-witness pin: [`WitContract::is_capability`] is the
11722        // exact-inverse disjunction of the sibling payload-arm predicate
11723        // trio [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
11724        // [`WitContract::is_store`]. A future reimplementation that
11725        // grew its own prefix-set scan (e.g. inlining a fourth
11726        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does not
11727        // own today) rather than delegating to the sibling trio would
11728        // drift loudly here — the composition contract binds the
11729        // fourth-arm predicate to the exact-inverse of the three
11730        // payload-arm predicates, so any rebrand of any prefix-set const
11731        // flows through this method by construction without a
11732        // coordinated per-consumer rewrite. Sweeps the union of the
11733        // three payload-arm prefix sets plus two Capability-shaped
11734        // shapes (a bare non-prefix-matching WIT world, the deliberately-
11735        // empty string the pure classifier still admits per the method
11736        // docstring's "purely syntactic classification" note).
11737        let mut cases: Vec<String> = Vec::new();
11738        for shape_set in [
11739            WIT_HTTP_SHAPE_PREFIXES,
11740            WIT_PUBSUB_SHAPE_PREFIXES,
11741            WIT_STORE_SHAPE_PREFIXES,
11742        ] {
11743            for prefix in shape_set {
11744                cases.push(format!("{prefix}x"));
11745            }
11746        }
11747        cases.push("custom:capability-only".to_string());
11748        cases.push(String::new());
11749        for wit in cases {
11750            let c = WitContract {
11751                de: "cart".into(),
11752                para: "catalog".into(),
11753                wit: wit.clone(),
11754                endpoint: None,
11755                subject: None,
11756                slot: None,
11757            };
11758            assert_eq!(
11759                c.is_capability(),
11760                !c.is_http() && !c.is_pubsub() && !c.is_store(),
11761                "WitContract::is_capability must equal \
11762                 !is_http() && !is_pubsub() && !is_store() at wit={wit:?}"
11763            );
11764        }
11765    }
11766
11767    #[test]
11768    fn wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant() {
11769        // Cross-projection-witness pin: whenever [`WitContract::target`]
11770        // succeeds, the pre-projection [`WitContract::is_capability`]
11771        // classification agrees with the post-projection
11772        // [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
11773        // predicate — the 4-arm typed partition on the substrate's
11774        // typed-view surface (7f6aa98 IsVariant lift) and the peer 4-arm
11775        // partition on the pre-projection axis line up by construction.
11776        // A future divergence between the two axes (a peer
11777        // [`WitTarget`] variant addition that landed on the typed-view
11778        // surface without a peer prefix-set + [`WitContract`] predicate
11779        // extension, or vice versa) would surface here at caixa-core
11780        // build time rather than a silent per-consumer split at renderer
11781        // emit time. Peer of the sibling pre-/post-projection
11782        // agreement pins the payload-carrier trio
11783        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
11784        // [`WitContract::slot`] on pre-projection; [`WitTarget::http_endpoint`]
11785        // / [`WitTarget::pubsub_subject`] / [`WitTarget::store_slot`] on
11786        // post-projection — b11bb49 trio lift) already carry across the
11787        // three payload arms — this pin closes the pair on the fourth
11788        // payload-less arm.
11789        let http = WitContract {
11790            de: "cart".into(),
11791            para: "catalog".into(),
11792            wit: "wasi:http/proxy".into(),
11793            endpoint: Some("/x".into()),
11794            subject: None,
11795            slot: None,
11796        };
11797        assert!(!http.is_capability());
11798        assert!(!http.target().unwrap().is_capability());
11799
11800        let nats = WitContract {
11801            de: "cart".into(),
11802            para: "catalog".into(),
11803            wit: "nats:pub-sub".into(),
11804            endpoint: None,
11805            subject: Some("events.x".into()),
11806            slot: None,
11807        };
11808        assert!(!nats.is_capability());
11809        assert!(!nats.target().unwrap().is_capability());
11810
11811        let kv = WitContract {
11812            de: "cart".into(),
11813            para: "catalog".into(),
11814            wit: "wasi:keyvalue/store".into(),
11815            endpoint: None,
11816            subject: None,
11817            slot: Some("checkout/$orderId".into()),
11818        };
11819        assert!(!kv.is_capability());
11820        assert!(!kv.target().unwrap().is_capability());
11821
11822        let cap = WitContract {
11823            de: "cart".into(),
11824            para: "catalog".into(),
11825            wit: "custom:capability-only".into(),
11826            endpoint: None,
11827            subject: None,
11828            slot: None,
11829        };
11830        assert!(cap.is_capability());
11831        assert!(cap.target().unwrap().is_capability());
11832    }
11833
11834    #[test]
11835    fn wit_contract_pre_projection_accessor_family_is_const_fn() {
11836        // Fail-before-pass-after pin on the [`WitContract`] pre-
11837        // projection accessor family's `const`-eval-surface posture.
11838        // Each of the three per-`:contratos` byte-string scalar
11839        // accessors ([`WitContract::source`] / [`WitContract::destination`]
11840        // / [`WitContract::world_ref`], each projecting through
11841        // `String::as_str` — const-stable since Rust 1.87, well within
11842        // the workspace MSRV) and each of the four peer WIT-shape
11843        // predicates ([`WitContract::is_http`] /
11844        // [`WitContract::is_pubsub`] / [`WitContract::is_store`] /
11845        // [`WitContract::is_capability`], each composing
11846        // `wit_shape_is_<arm>(self.world_ref())` on the `pub const fn`
11847        // free-function classifier family the sibling
11848        // [`wit_shape_classifier_family_is_const_fn`] pin already
11849        // anchors on the raw `&str → bool` axis) must be `pub const fn`
11850        // — any future accidental downgrade to non-`const` fails the
11851        // `const fn` wrappers below at caixa-core build time with E0015
11852        // (`cannot call non-const function`), strictly stronger than a
11853        // runtime `assert!` and strictly stronger than a
11854        // module-scope `const _: () = assert!(…)` pin (which cannot be
11855        // formed on a `&WitContract` fixture because the type's
11856        // `String` / `Option<String>` carriers rule out `const`-context
11857        // construction; the `const fn` wrapper is the load-bearing
11858        // shape that side-steps the destructor-in-const restriction on
11859        // the value axis while still pinning the `const`-fn posture on
11860        // the callee).
11861        //
11862        // Peer of the sibling free-function classifier pin
11863        // [`wit_shape_classifier_family_is_const_fn`] (d46420c) on the
11864        // raw `&str → bool` axis — this pin extends the same
11865        // `const`-eval-surface discipline onto the peer method surface
11866        // that composes through those free-function classifiers, and
11867        // simultaneously onto the underlying per-`:contratos`
11868        // byte-string scalar-accessor trio each predicate reads
11869        // through. Sibling of the peer M3
11870        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
11871        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
11872        // M2
11873        // [`child_spec_restart_accessor_is_const_fn`] /
11874        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
11875        // and M3
11876        // [`placement_estrategia_accessor_is_const_fn`] /
11877        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
11878        // sibling `const`-eval-surface-pass axes.
11879        const fn source_via_const_fn(c: &WitContract) -> &str {
11880            c.source()
11881        }
11882        const fn destination_via_const_fn(c: &WitContract) -> &str {
11883            c.destination()
11884        }
11885        const fn world_ref_via_const_fn(c: &WitContract) -> &str {
11886            c.world_ref()
11887        }
11888        const fn is_http_via_const_fn(c: &WitContract) -> bool {
11889            c.is_http()
11890        }
11891        const fn is_pubsub_via_const_fn(c: &WitContract) -> bool {
11892            c.is_pubsub()
11893        }
11894        const fn is_store_via_const_fn(c: &WitContract) -> bool {
11895            c.is_store()
11896        }
11897        const fn is_capability_via_const_fn(c: &WitContract) -> bool {
11898            c.is_capability()
11899        }
11900        // Sweep one canonical accept-set sample per WIT-shape arm plus
11901        // a payload-less capability sample, asserting the wrapper and
11902        // direct dispatches agree byte-for-byte across the closed
11903        // 4-arm partition on both the scalar-accessor trio and the
11904        // WIT-shape-predicate family.
11905        for (wit, is_http, is_pubsub, is_store, is_capability) in [
11906            ("wasi:http/proxy", true, false, false, false),
11907            ("http:incoming", true, false, false, false),
11908            ("nats:events", false, true, false, false),
11909            ("kafka:topic", false, true, false, false),
11910            ("wasi:keyvalue/store", false, false, true, false),
11911            ("kv:cache", false, false, true, false),
11912            ("custom:capability-only", false, false, false, true),
11913            ("", false, false, false, true),
11914        ] {
11915            let c = WitContract {
11916                de: "cart".into(),
11917                para: "catalog".into(),
11918                wit: wit.into(),
11919                endpoint: None,
11920                subject: None,
11921                slot: None,
11922            };
11923            assert_eq!(source_via_const_fn(&c), c.source());
11924            assert_eq!(destination_via_const_fn(&c), c.destination());
11925            assert_eq!(world_ref_via_const_fn(&c), c.world_ref());
11926            assert_eq!(is_http_via_const_fn(&c), c.is_http());
11927            assert_eq!(is_pubsub_via_const_fn(&c), c.is_pubsub());
11928            assert_eq!(is_store_via_const_fn(&c), c.is_store());
11929            assert_eq!(is_capability_via_const_fn(&c), c.is_capability());
11930            assert_eq!(c.source(), "cart");
11931            assert_eq!(c.destination(), "catalog");
11932            assert_eq!(c.world_ref(), wit);
11933            assert_eq!(c.is_http(), is_http);
11934            assert_eq!(c.is_pubsub(), is_pubsub);
11935            assert_eq!(c.is_store(), is_store);
11936            assert_eq!(c.is_capability(), is_capability);
11937        }
11938    }
11939
11940    #[test]
11941    fn wit_contract_identity_projection_accessor_is_const_fn() {
11942        // Fail-before-pass-after pin on the [`WitContract::identity`]
11943        // six-arm composite-projection accessor's `const`-eval-surface
11944        // posture. The accessor projects the typed edge's six identity
11945        // arms (`:de` / `:para` / `:wit` / `:endpoint` / `:subject` /
11946        // `:slot`) as a borrowed [`ContratoIdentity<'_>`] six-tuple —
11947        // every callee is itself `pub const fn` ([`WitContract::source`]
11948        // / [`WitContract::destination`] / [`WitContract::world_ref`]
11949        // through `String::as_str`, const-stable since Rust 1.87;
11950        // [`WitContract::endpoint`] / [`WitContract::subject`] /
11951        // [`WitContract::slot`] through the sibling `match &self
11952        // .<field> { Some(s) => Some(s.as_str()), None => None }` shape
11953        // 0650f64 closed the const-eval surface on) and the tuple
11954        // constructor from borrowed-reference / `Option`-of-borrowed-
11955        // reference arms is trivially const. Any future accidental
11956        // downgrade fails the `identity_via_const_fn` wrapper at
11957        // caixa-core build time with E0015 (`cannot call non-const
11958        // method`), strictly stronger than a runtime `assert!` and
11959        // strictly stronger than a module-scope `const _: () =
11960        // assert!(…)` pin (which cannot be formed on a `&WitContract`
11961        // fixture because the type's `String` / `Option<String>`
11962        // carriers rule out `const`-context value construction; the
11963        // `const fn` wrapper is the load-bearing shape that side-steps
11964        // the destructor-in-const restriction on the value axis while
11965        // still pinning the `const`-fn posture on the callee — mirror
11966        // of the sibling
11967        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
11968        // pin's discipline verbatim on the peer scalar-accessor
11969        // surface).
11970        //
11971        // Peer of the sibling
11972        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
11973        // (279823b) pin on the six per-`:contratos` scalar-accessor
11974        // callees this composite-projection reads through — where that
11975        // pin anchors the const-eval surface at the six individual
11976        // scalar-accessor arms, this pin extends the same posture onto
11977        // the composite six-tuple projection every consumer that dedups
11978        // typed edges on the [`ContratoIdentity`] axis keys off (the
11979        // [`AplicacaoSpec::validate`]-side duplicate-`:contratos`
11980        // scanner + its BTreeMap dedup key; a future per-Aplicacao CR
11981        // materializer's per-edge identity-based admission webhook; a
11982        // future L7 policy-emitter that shards CNPs by identity-tuple
11983        // rather than by name). Same fail-before-pass-after wrapper
11984        // discipline as the peer M2 / M3 accessor-family pins on the
11985        // sibling `const`-eval-surface passes.
11986        const fn identity_via_const_fn(c: &WitContract) -> ContratoIdentity<'_> {
11987            c.identity()
11988        }
11989        // Sweep one canonical WIT-shape sample per payload-carrier arm
11990        // plus a payload-less capability sample so the pin exercises
11991        // both `Some(_)`-carrying and `None`-carrying arms on all three
11992        // `Option<String>` payload-carrier axes (`:endpoint` / `:subject`
11993        // / `:slot`) — every wrapper dispatch must agree byte-for-byte
11994        // with the direct method call on every arm of the closed WIT-
11995        // shape partition.
11996        for (wit, endpoint, subject, slot) in [
11997            ("wasi:http/proxy", Some("/checkout"), None, None),
11998            ("http:incoming", Some("/api"), None, None),
11999            ("nats:events", None, Some("orders.placed"), None),
12000            ("kafka:topic", None, Some("orders.stream"), None),
12001            ("wasi:keyvalue/store", None, None, Some("carts/{id}")),
12002            ("kv:cache", None, None, Some("session/{token}")),
12003            ("custom:capability-only", None, None, None),
12004        ] {
12005            let c = WitContract {
12006                de: "cart".into(),
12007                para: "catalog".into(),
12008                wit: wit.into(),
12009                endpoint: endpoint.map(str::to_string),
12010                subject: subject.map(str::to_string),
12011                slot: slot.map(str::to_string),
12012            };
12013            assert_eq!(identity_via_const_fn(&c), c.identity());
12014            assert_eq!(
12015                c.identity(),
12016                ("cart", "catalog", wit, endpoint, subject, slot,),
12017            );
12018        }
12019    }
12020
12021    #[test]
12022    fn m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn() {
12023        // Fail-before-pass-after pin on the four M3 mesh-slot
12024        // `String → &str` scalar accessors ([`Membro::nome`] /
12025        // [`Membro::versao_requirement`] on the per-`:membros` axis,
12026        // [`Entrada::hostname`] / [`Entrada::destination`] on the
12027        // per-`:entrada` axis) — each projects the typed slot's
12028        // [`String`] storage through the `pub const fn`
12029        // [`String::as_str`] (const-stable since Rust 1.87, well
12030        // within the workspace MSRV) and any future accidental
12031        // downgrade to non-`const` fails the corresponding
12032        // `<name>_via_const_fn` wrapper at caixa-core build time with
12033        // E0015 (`cannot call non-const method`), strictly stronger
12034        // than a runtime `assert!` and strictly stronger than a
12035        // module-scope `const _: () = assert!(…)` pin (which cannot
12036        // be formed on `&Membro` / `&Entrada` fixtures because the
12037        // types' `String` carriers rule out `const`-context value
12038        // construction; the `const fn` wrapper is the load-bearing
12039        // shape that side-steps the destructor-in-const restriction
12040        // on the value axis while still pinning the `const`-fn
12041        // posture on the callee — mirror of the sibling
12042        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
12043        // (279823b) pin on the per-`:contratos` axis). Peer of the
12044        // sibling per-M2/M3/universal-axis `String → &str` accessor
12045        // family pins on the sibling `const`-eval-surface passes
12046        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
12047        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
12048        // typed-newtype wrapper,
12049        // [`crate::supervisor::ChildSpec::nome`] /
12050        // [`crate::supervisor::ChildSpec::versao_requirement`] at the
12051        // M2 supervisor-tree axis,
12052        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
12053        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
12054        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
12055        // axis, and the sibling per-`:contratos`
12056        // [`WitContract::source`] / [`WitContract::destination`] /
12057        // [`WitContract::world_ref`] trio at 279823b).
12058        const fn membro_nome_via_const_fn(m: &Membro) -> &str {
12059            m.nome()
12060        }
12061        const fn membro_versao_via_const_fn(m: &Membro) -> &str {
12062            m.versao_requirement()
12063        }
12064        const fn entrada_hostname_via_const_fn(e: &Entrada) -> &str {
12065            e.hostname()
12066        }
12067        const fn entrada_destination_via_const_fn(e: &Entrada) -> &str {
12068            e.destination()
12069        }
12070        for (caixa, versao) in [
12071            ("cart", "^0.1"),
12072            ("catalog-v2", "~0.2.3"),
12073            ("checkout", "*"),
12074        ] {
12075            let m = Membro {
12076                caixa: caixa.into(),
12077                versao: versao.into(),
12078            };
12079            assert_eq!(membro_nome_via_const_fn(&m), m.nome());
12080            assert_eq!(membro_versao_via_const_fn(&m), m.versao_requirement());
12081            assert_eq!(m.nome(), caixa);
12082            assert_eq!(m.versao_requirement(), versao);
12083        }
12084        for (host, para) in [
12085            ("cart.example.com", "cart"),
12086            ("api.checkout.io", "checkout"),
12087        ] {
12088            let e = Entrada {
12089                host: host.into(),
12090                para: para.into(),
12091                paths: vec![],
12092                port: DEFAULT_SERVICO_PORT,
12093            };
12094            assert_eq!(entrada_hostname_via_const_fn(&e), e.hostname());
12095            assert_eq!(entrada_destination_via_const_fn(&e), e.destination());
12096            assert_eq!(e.hostname(), host);
12097            assert_eq!(e.destination(), para);
12098        }
12099    }
12100
12101    #[test]
12102    fn m3_option_string_scalar_accessor_family_is_const_fn() {
12103        // Fail-before-pass-after pin on the five M3 mesh-slot
12104        // `Option<String> → Option<&str>` scalar accessors
12105        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
12106        // [`WitContract::slot`] on the per-`:contratos` HTTP /
12107        // pub-sub / key-value payload-carrier trio,
12108        // [`Placement::shard_key`] / [`Placement::affinity`] on the
12109        // per-`:placement` Akka-sharding-key + Adaptive-compression-
12110        // hint pair). Each accessor destructures the typed slot's
12111        // `Option<String>` storage through the `match &self.<field> {
12112        // Some(s) => Some(s.as_str()), None => None }` shape —
12113        // routing through [`String::as_str`] (const-stable since Rust
12114        // 1.87, well within the workspace MSRV) rather than the
12115        // non-const [`Option::as_deref`] the pre-lift bodies carried
12116        // — and any future accidental downgrade to non-`const` fails
12117        // the corresponding `<name>_via_const_fn` wrapper at
12118        // caixa-core build time with E0015 (`cannot call non-const
12119        // method`), strictly stronger than a runtime `assert!` and
12120        // strictly stronger than a module-scope `const _: () =
12121        // assert!(…)` pin (which cannot be formed on `&WitContract`
12122        // / `&Placement` fixtures because the types' `String` /
12123        // `Option<String>` carriers rule out `const`-context value
12124        // construction; the `const fn` wrapper is the load-bearing
12125        // shape that side-steps the destructor-in-const restriction
12126        // on the value axis while still pinning the `const`-fn
12127        // posture on the callee — mirror of the sibling
12128        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
12129        // (279823b) and
12130        // [`m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn`]
12131        // (29c5d7e) pins on the peer `String → &str` axes at the same
12132        // structs).
12133        //
12134        // Peer of the sibling per-`Caixa` `Option<String> →
12135        // Option<&str>` accessor family pin
12136        // [`crate::manifest::tests::caixa_option_string_scalar_accessor_family_is_const_fn`]
12137        // on the top-level manifest's optional universal-axis surface
12138        // (`:licenca` / `:repositorio` / `:descricao` / `:edicao` /
12139        // `:restart-window`).
12140        const fn wit_endpoint_via_const_fn(w: &WitContract) -> Option<&str> {
12141            w.endpoint()
12142        }
12143        const fn wit_subject_via_const_fn(w: &WitContract) -> Option<&str> {
12144            w.subject()
12145        }
12146        const fn wit_slot_via_const_fn(w: &WitContract) -> Option<&str> {
12147            w.slot()
12148        }
12149        const fn placement_shard_key_via_const_fn(p: &Placement) -> Option<&str> {
12150            p.shard_key()
12151        }
12152        const fn placement_affinity_via_const_fn(p: &Placement) -> Option<&str> {
12153            p.affinity()
12154        }
12155        // Sweep every closed shape-arm partition on the
12156        // per-`:contratos` payload-carrier trio: HTTP (`:endpoint`
12157        // Some, sibling pair None), pub-sub (`:subject` Some, sibling
12158        // pair None), key-value (`:slot` Some, sibling pair None),
12159        // and Capability (all three None) so each accessor's
12160        // Some/None arm carries a pin through the const dispatch.
12161        for (wit, endpoint, subject, slot) in [
12162            ("wasi:http/proxy", Some("/api"), None, None),
12163            ("nats:pub-sub", None, Some("orders.paid"), None),
12164            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
12165            ("custom:capability-only", None, None, None),
12166        ] {
12167            let c = WitContract {
12168                de: "cart".into(),
12169                para: "catalog".into(),
12170                wit: wit.into(),
12171                endpoint: endpoint.map(str::to_string),
12172                subject: subject.map(str::to_string),
12173                slot: slot.map(str::to_string),
12174            };
12175            assert_eq!(wit_endpoint_via_const_fn(&c), c.endpoint());
12176            assert_eq!(wit_subject_via_const_fn(&c), c.subject());
12177            assert_eq!(wit_slot_via_const_fn(&c), c.slot());
12178            assert_eq!(c.endpoint(), endpoint);
12179            assert_eq!(c.subject(), subject);
12180            assert_eq!(c.slot(), slot);
12181        }
12182        // Sweep both `Some`/`None` arms on each per-`:placement`
12183        // optional-scalar so the shard-key + affinity pair carries a
12184        // const-dispatch pin on both arms.
12185        for (shard_key, affinity) in [
12186            (Some("tenantId"), Some("data-locality")),
12187            (Some("$tenantId"), None),
12188            (None, Some("low-latency")),
12189            (None, None),
12190        ] {
12191            let p = Placement {
12192                estrategia: PlacementStrategy::default(),
12193                clusters: vec![],
12194                affinity: affinity.map(str::to_string),
12195                shard_key: shard_key.map(str::to_string),
12196            };
12197            assert_eq!(placement_shard_key_via_const_fn(&p), p.shard_key());
12198            assert_eq!(placement_affinity_via_const_fn(&p), p.affinity());
12199            assert_eq!(p.shard_key(), shard_key);
12200            assert_eq!(p.affinity(), affinity);
12201        }
12202    }
12203
12204    #[test]
12205    fn m3_placement_entrada_slice_return_accessor_pair_is_const_fn() {
12206        // Fail-before-pass-after pin on the two M3-mesh-slot inner-
12207        // composite `Vec → &[String]` slice-return accessors on
12208        // [`Placement::clusters`] and [`Entrada::paths`]. Each
12209        // destructures the typed slot's `Vec<String>` storage through
12210        // the `pub const fn` [`Vec::as_slice`] (const-stable since Rust
12211        // 1.66, well within the workspace MSRV) — any future accidental
12212        // downgrade to non-`const` fails the corresponding
12213        // `<name>_via_const_fn` wrapper at caixa-core build time with
12214        // E0015 (`cannot call non-const method`), strictly stronger
12215        // than a runtime `assert!`. Sibling of the peer
12216        // [`m3_aplicacao_spec_reference_return_accessor_family_is_const_fn`]
12217        // pin on the outer-`AplicacaoSpec` reference-return family
12218        // (`:membros` / `:contratos` slice-return + `:politicas` /
12219        // `:placement` / `:entrada` composite-reference), and of the
12220        // peer M2 slice-return axis pins
12221        // [`crate::supervisor::tests::supervisor_children_slice_return_accessor_is_const_fn`]
12222        // (on `SupervisorSpec::children`) and
12223        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
12224        // (on `UpgradeFromEntry::instructions`). Together the four
12225        // pins close the last unlifted reference-return accessor
12226        // family across the substrate primitive.
12227        const fn placement_clusters_via_const_fn(p: &Placement) -> &[String] {
12228            p.clusters()
12229        }
12230        const fn entrada_paths_via_const_fn(e: &Entrada) -> &[String] {
12231            e.paths()
12232        }
12233        // Sweep both the empty-Vec (no author-declared entries) and
12234        // the populated-Vec arms on every slice-return accessor so
12235        // each carries a const-dispatch pin on both arms.
12236        let p_empty = Placement {
12237            estrategia: PlacementStrategy::default(),
12238            clusters: vec![],
12239            affinity: None,
12240            shard_key: None,
12241        };
12242        let p_full = Placement {
12243            estrategia: PlacementStrategy::default(),
12244            clusters: vec!["prod-a".into(), "prod-b".into()],
12245            affinity: None,
12246            shard_key: None,
12247        };
12248        assert_eq!(
12249            placement_clusters_via_const_fn(&p_empty),
12250            p_empty.clusters()
12251        );
12252        assert_eq!(placement_clusters_via_const_fn(&p_full), p_full.clusters());
12253        assert!(p_empty.clusters().is_empty());
12254        assert_eq!(p_full.clusters(), &["prod-a", "prod-b"]);
12255        let e_empty = Entrada {
12256            host: "web.example.com".into(),
12257            para: "web".into(),
12258            paths: vec![],
12259            port: DEFAULT_SERVICO_PORT,
12260        };
12261        let e_full = Entrada {
12262            host: "web.example.com".into(),
12263            para: "web".into(),
12264            paths: vec!["/api".into(), "/health".into()],
12265            port: DEFAULT_SERVICO_PORT,
12266        };
12267        assert_eq!(entrada_paths_via_const_fn(&e_empty), e_empty.paths());
12268        assert_eq!(entrada_paths_via_const_fn(&e_full), e_full.paths());
12269        assert!(e_empty.paths().is_empty());
12270        assert_eq!(e_full.paths(), &["/api", "/health"]);
12271    }
12272
12273    #[test]
12274    fn m3_aplicacao_spec_reference_return_accessor_family_is_const_fn() {
12275        // Fail-before-pass-after pin on the five outer-`AplicacaoSpec`
12276        // reference-return accessors — the two `Vec → &[T]` slice-
12277        // return accessors on [`AplicacaoSpec::membros`] and
12278        // [`AplicacaoSpec::contratos`] (each routes through the
12279        // `pub const fn` [`Vec::as_slice`], const-stable since Rust
12280        // 1.66), the two `&Composite` composite-reference accessors
12281        // on [`AplicacaoSpec::politicas`] and
12282        // [`AplicacaoSpec::placement`] (each routes through a raw
12283        // `&self.<field>` borrow, trivially const), and the one
12284        // `Option<&Composite>` optional-composite-reference accessor
12285        // on [`AplicacaoSpec::entrada`] (routes through the
12286        // `pub const fn` [`Option::as_ref`], const-stable since Rust
12287        // 1.83). Any future accidental downgrade to non-`const` fails
12288        // the corresponding `<name>_via_const_fn` wrapper at caixa-
12289        // core build time with E0015 (`cannot call non-const
12290        // method`), strictly stronger than a runtime `assert!`.
12291        // Sibling of the peer inner-composite pin
12292        // [`m3_placement_entrada_slice_return_accessor_pair_is_const_fn`]
12293        // on the `Placement::clusters` + `Entrada::paths` slice-
12294        // return pair, and of the peer M2 axis pins on
12295        // [`crate::supervisor::SupervisorSpec::children`] and
12296        // [`crate::upgrade::UpgradeFromEntry::instructions`].
12297        const fn aplicacao_membros_via_const_fn(s: &AplicacaoSpec) -> &[Membro] {
12298            s.membros()
12299        }
12300        const fn aplicacao_contratos_via_const_fn(s: &AplicacaoSpec) -> &[WitContract] {
12301            s.contratos()
12302        }
12303        const fn aplicacao_politicas_via_const_fn(s: &AplicacaoSpec) -> &MeshPolicy {
12304            s.politicas()
12305        }
12306        const fn aplicacao_placement_via_const_fn(s: &AplicacaoSpec) -> &Placement {
12307            s.placement()
12308        }
12309        const fn aplicacao_entrada_via_const_fn(s: &AplicacaoSpec) -> Option<&Entrada> {
12310            s.entrada()
12311        }
12312        // Construct both a minimal "no :entrada" (internal-only
12313        // mesh) and a full "with :entrada" (external-gateway)
12314        // fixture so the family pins both the `None`-arm (author-
12315        // omitted `:entrada`) and the `Some`-arm (author-declared
12316        // `:entrada`) on the optional-composite axis.
12317        let membro = Membro {
12318            caixa: "web".into(),
12319            versao: "^0.1".into(),
12320        };
12321        let entrada_full = Entrada {
12322            host: "web.example.com".into(),
12323            para: "web".into(),
12324            paths: vec!["/api".into()],
12325            port: DEFAULT_SERVICO_PORT,
12326        };
12327        let internal_only = AplicacaoSpec {
12328            membros: vec![membro.clone()],
12329            contratos: vec![],
12330            politicas: MeshPolicy::default(),
12331            placement: Placement::default(),
12332            entrada: None,
12333        };
12334        let with_entrada = AplicacaoSpec {
12335            membros: vec![membro],
12336            contratos: vec![],
12337            politicas: MeshPolicy::default(),
12338            placement: Placement::default(),
12339            entrada: Some(entrada_full),
12340        };
12341        assert_eq!(
12342            aplicacao_membros_via_const_fn(&internal_only),
12343            internal_only.membros()
12344        );
12345        assert_eq!(
12346            aplicacao_membros_via_const_fn(&with_entrada),
12347            with_entrada.membros()
12348        );
12349        assert_eq!(
12350            aplicacao_contratos_via_const_fn(&internal_only),
12351            internal_only.contratos()
12352        );
12353        assert!(std::ptr::eq(
12354            aplicacao_politicas_via_const_fn(&internal_only),
12355            internal_only.politicas(),
12356        ));
12357        assert!(std::ptr::eq(
12358            aplicacao_placement_via_const_fn(&internal_only),
12359            internal_only.placement(),
12360        ));
12361        assert!(aplicacao_entrada_via_const_fn(&internal_only).is_none());
12362        match (
12363            aplicacao_entrada_via_const_fn(&with_entrada),
12364            with_entrada.entrada(),
12365        ) {
12366            (Some(a), Some(b)) => assert!(std::ptr::eq(a, b)),
12367            _ => panic!(
12368                "aplicacao_entrada_via_const_fn must agree with \
12369                 AplicacaoSpec::entrada on the Some-arm reference"
12370            ),
12371        }
12372    }
12373
12374    #[test]
12375    fn target_projected_returns_byte_equal_typed_view_across_all_four_arms() {
12376        // Load-bearing contract pin: on every canonical
12377        // `(:wit, :endpoint/:subject/:slot)` shape the substrate admits,
12378        // [`WitContract::target_projected`] returns byte-equal to
12379        // [`WitContract::target`]`().unwrap()` — the post-validation
12380        // projection accessor is a thin panicking wrapper over the
12381        // pre-validation validator, no extra work in the projection
12382        // path. Any future divergence (a validator-side normalization
12383        // the projection doesn't route through, an accessor-side
12384        // caching layer the validator doesn't populate) would surface
12385        // here at caixa-core build time rather than a silent per-consumer
12386        // split at renderer emit time. Sweeps the closed 4-arm
12387        // [`WitTarget`] partition ([`WitTarget::Http`] /
12388        // [`WitTarget::PubSub`] / [`WitTarget::Store`] /
12389        // [`WitTarget::Capability`]) so every arm carries a byte-equality
12390        // pin on the two-accessor pair.
12391        for (wit, endpoint, subject, slot) in [
12392            ("wasi:http/proxy", Some("/x"), None, None),
12393            ("nats:pub-sub", None, Some("events.x"), None),
12394            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
12395            ("custom:capability-only", None, None, None),
12396        ] {
12397            let c = WitContract {
12398                de: "cart".into(),
12399                para: "catalog".into(),
12400                wit: wit.into(),
12401                endpoint: endpoint.map(str::to_string),
12402                subject: subject.map(str::to_string),
12403                slot: slot.map(str::to_string),
12404            };
12405            assert_eq!(
12406                c.target_projected(),
12407                c.target().unwrap(),
12408                "target_projected must return byte-equal to target().unwrap() at wit={wit:?}"
12409            );
12410        }
12411    }
12412
12413    #[test]
12414    #[should_panic(expected = "validated by typed_view")]
12415    fn target_projected_panics_with_canonical_message_on_unvalidated_contract() {
12416        // Panic-path pin: [`WitContract::target_projected`] threads the
12417        // canonical [`WitContract::PROJECTED_INVARIANT_MSG`] byte-string
12418        // through its expect-panic when called on a contract whose
12419        // (`:wit`, payload) shape has not been crossed by
12420        // [`AplicacaoSpec::validate`] — a contract with a structurally-
12421        // invalid `:wit` (hyphen-for-colon typo) that would surface
12422        // [`AplicacaoError::ContratoWitInvalid`] at the validator gate.
12423        // A future rebrand on the panic-message axis would land at one
12424        // caixa-core edit on [`WitContract::PROJECTED_INVARIANT_MSG`]
12425        // and this pin's [`should_panic(expected = …)`] literal would
12426        // migrate alongside — the pin catches drift between the const
12427        // and the accessor's `expect(…)` call by construction.
12428        let c = WitContract {
12429            de: "cart".into(),
12430            para: "catalog".into(),
12431            // Hyphen-for-colon typo: `WitContract::target` returns
12432            // [`AplicacaoError::ContratoWitInvalid`] on this shape,
12433            // driving the [`WitContract::target_projected`] expect-panic.
12434            wit: "wasi-http/proxy".into(),
12435            endpoint: Some("/x".into()),
12436            subject: None,
12437            slot: None,
12438        };
12439        let _ = c.target_projected();
12440    }
12441
12442    #[test]
12443    fn target_projected_invariant_msg_matches_prior_inline_call_site_literal() {
12444        // Byte-equivalence pin: [`WitContract::PROJECTED_INVARIANT_MSG`]
12445        // carries the exact byte-string the two prior open-coded
12446        // `.target().expect("validated by typed_view")` production
12447        // consumers threaded through inline before this lift converged
12448        // them onto [`WitContract::target_projected`] — the caixa-mesh
12449        // per-`(:de, :para)` CNP L7 introspection branch at
12450        // `caixa-mesh/src/lib.rs:2825` and the caixa-feira `feira app
12451        // graph` per-`:contratos` payload-column printer at
12452        // `caixa-feira/src/cmd/app.rs:110`. Locks the panic-message
12453        // byte-string load-bearing so a well-meaning const-side rebrand
12454        // that didn't carry a matched pin migration would surface here
12455        // at caixa-core build time rather than a silent per-consumer
12456        // panic-message drift at cluster-apply time. Peer of the
12457        // sibling [`WitTarget::CAPABILITY_LABEL`] /
12458        // [`WitTarget::CAPABILITY_EXPECTED`] /
12459        // [`WitTarget::CAPABILITY_GRAPH_LABEL`] byte-equivalence pins on
12460        // the paired payload-less-arm scalar-const family.
12461        assert_eq!(
12462            WitContract::PROJECTED_INVARIANT_MSG,
12463            "validated by typed_view"
12464        );
12465    }
12466
12467    #[test]
12468    fn empty_wit_takes_precedence_over_invalid() {
12469        // Ordering pin: `EmptyWit` is the more self-locating
12470        // diagnostic on `""` and must lead — the value-shape gate is
12471        // only reached after the empty-check fires. Mirrors
12472        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
12473        // the peer payload axis.
12474        let mut s = three_member_spec();
12475        s.contratos.push(WitContract {
12476            de: "payment".into(),
12477            para: "catalog".into(),
12478            wit: String::new(),
12479            endpoint: None,
12480            subject: None,
12481            slot: None,
12482        });
12483        let err = s.validate().unwrap_err();
12484        assert!(
12485            matches!(err, AplicacaoError::EmptyWit { .. }),
12486            "got {err:?}"
12487        );
12488    }
12489
12490    #[test]
12491    fn wit_invalid_fires_before_payload_shape_arm() {
12492        // Ordering pin: a malformed `:wit` surfaces *its own*
12493        // diagnostic (which names the offending wit verbatim) before
12494        // any payload-field check — a contrato whose wit is
12495        // structurally invalid AND carries a wrong target field
12496        // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
12497        // because the dispatch on the wit is what decides which
12498        // payload field is "right" in the first place. Without this
12499        // ordering, the author would see "wrong target field" for a
12500        // wit that hasn't even been parsed, which doesn't name the
12501        // root cause.
12502        let mut s = three_member_spec();
12503        s.contratos.push(WitContract {
12504            de: "payment".into(),
12505            para: "catalog".into(),
12506            // Hyphen-for-colon typo + endpoint set: pre-gate this
12507            // raised `ContratoWrongTarget { expected: "none" }` (the
12508            // Capability arm rejecting the endpoint), masking the
12509            // real authoring mistake (the wit isn't `wasi:http/proxy`).
12510            wit: "wasi-http/proxy".into(),
12511            endpoint: Some("/x".into()),
12512            subject: None,
12513            slot: None,
12514        });
12515        let err = s.validate().unwrap_err();
12516        assert!(
12517            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
12518                if wit == "wasi-http/proxy"),
12519            "got {err:?}"
12520        );
12521    }
12522
12523    #[test]
12524    fn wit_invalid_diagnostic_carries_offending_wit() {
12525        // Diagnostic-shape pin — the offending `:wit` + `:de` +
12526        // `:para` + a non-empty reason flow through verbatim so the
12527        // author can grep their caixa.lisp for the offending contrato
12528        // block and fix it in one edit. Same shape as
12529        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
12530        let err = contrato_wit_err("WASI:HTTP/proxy");
12531        match err {
12532            AplicacaoError::ContratoWitInvalid {
12533                de,
12534                para,
12535                wit,
12536                reason,
12537            } => {
12538                assert_eq!(de, "payment");
12539                assert_eq!(para, "catalog");
12540                assert_eq!(wit, "WASI:HTTP/proxy");
12541                assert!(!reason.is_empty(), "reason field must be non-empty");
12542            }
12543            other => panic!("expected ContratoWitInvalid, got {other:?}"),
12544        }
12545    }
12546
12547    // ── :contratos :subject value-shape gate ─────────────────────────────
12548    //
12549    // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
12550    // suites on the peer payload axes. Until this gate landed
12551    // `WitContract::target()` only refused the empty string; a
12552    // structurally invalid subject silently passed validate and the
12553    // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
12554    // Subject'` on publish / subscribe, or as a silent message drop,
12555    // far from the source caixa.lisp. Every authoring footgun the
12556    // NATS server's subject parser would catch on admission now
12557    // becomes a caixa-build-time `ContratoSubjectInvalid` with the
12558    // offending `:subject` + `:de` + `:para` named verbatim. Same
12559    // diagnostic shape as `ContratoEndpointInvalid` /
12560    // `ContratoWitInvalid` on the peer payload axes; same shared
12561    // predicate (`crate::render::is_nats_subject`) ensures drift
12562    // between any two axes' rule enforcement is a build error at the
12563    // predicate, not piecemeal across renderers.
12564
12565    fn contrato_subject_err(subject: &str) -> AplicacaoError {
12566        // Fresh spec per call so the new contract doesn't collide on
12567        // identity with `three_member_spec`'s pre-existing entries.
12568        // The new edge uses `(payment, catalog)` — a pair the fixture
12569        // doesn't already declare — with `:wit "nats:pub-sub"` and the
12570        // varying `:subject`, so the subject-shape gate fires cleanly
12571        // after the wit-shape gate (which `"nats:pub-sub"` passes).
12572        let mut s = three_member_spec();
12573        s.contratos.push(WitContract {
12574            de: "payment".into(),
12575            para: "catalog".into(),
12576            wit: "nats:pub-sub".into(),
12577            endpoint: None,
12578            subject: Some(subject.into()),
12579            slot: None,
12580        });
12581        s.validate().unwrap_err()
12582    }
12583
12584    #[test]
12585    fn rejects_pubsub_contrato_subject_with_whitespace() {
12586        // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
12587        // landed at the NATS server as a malformed subject the parser
12588        // rejects with `-ERR 'Invalid Subject'`. Now caught at the
12589        // source caixa.lisp.
12590        let err = contrato_subject_err("foo bar");
12591        assert!(
12592            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12593                if subject == "foo bar" && reason.contains("whitespace")),
12594            "got {err:?}"
12595        );
12596    }
12597
12598    #[test]
12599    fn rejects_pubsub_contrato_subject_with_control_char() {
12600        let err = contrato_subject_err("foo\x01bar");
12601        assert!(
12602            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12603                if subject == "foo\x01bar" && reason.contains("control character")),
12604            "got {err:?}"
12605        );
12606    }
12607
12608    #[test]
12609    fn rejects_pubsub_contrato_subject_with_non_ascii() {
12610        // Un-percent-encoded non-ASCII byte — the canonical "I copied
12611        // the subject from a doc with smart quotes / accented
12612        // characters" footgun.
12613        let err = contrato_subject_err("foo.caf\u{e9}");
12614        assert!(
12615            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12616                if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
12617            "got {err:?}"
12618        );
12619    }
12620
12621    #[test]
12622    fn rejects_pubsub_contrato_subject_with_leading_dot() {
12623        // Empty leading token — NATS rejects.
12624        let err = contrato_subject_err(".foo");
12625        assert!(
12626            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12627                if subject == ".foo" && reason.contains("must not start with `.`")),
12628            "got {err:?}"
12629        );
12630    }
12631
12632    #[test]
12633    fn rejects_pubsub_contrato_subject_with_trailing_dot() {
12634        // Empty trailing token — NATS rejects. The remediation
12635        // (use `>` instead) is in the reason string.
12636        let err = contrato_subject_err("foo.");
12637        assert!(
12638            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12639                if subject == "foo." && reason.contains("must not end with `.`")),
12640            "got {err:?}"
12641        );
12642    }
12643
12644    #[test]
12645    fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
12646        // The canonical "I forgot to fill in the middle segment"
12647        // typo — `"foo..bar"`. NATS rejects empty tokens.
12648        let err = contrato_subject_err("foo..bar");
12649        assert!(
12650            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12651                if subject == "foo..bar" && reason.contains("consecutive `.`")),
12652            "got {err:?}"
12653        );
12654    }
12655
12656    #[test]
12657    fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
12658        // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
12659        // as the final segment. Pre-gate this passed as a typed edge
12660        // and surfaced at runtime as a NATS subscribe rejection.
12661        let err = contrato_subject_err("foo.>.bar");
12662        assert!(
12663            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12664                if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
12665            "got {err:?}"
12666        );
12667    }
12668
12669    #[test]
12670    fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
12671        // `foo*.bar` — NATS wildcards are standalone tokens. The
12672        // remediation is in the reason string.
12673        let err = contrato_subject_err("foo*.bar");
12674        assert!(
12675            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12676                if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
12677            "got {err:?}"
12678        );
12679    }
12680
12681    #[test]
12682    fn rejects_pubsub_contrato_subject_with_invalid_char() {
12683        // `foo,bar` — comma is not a valid NATS subject character.
12684        // Pinned separately from the wildcard arms so the invalid-
12685        // character diagnostic is in force.
12686        let err = contrato_subject_err("foo,bar");
12687        assert!(
12688            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12689                if subject == "foo,bar" && reason.contains("invalid character")),
12690            "got {err:?}"
12691        );
12692    }
12693
12694    #[test]
12695    fn rejects_pubsub_contrato_subject_too_long() {
12696        // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
12697        // The legitimate-shape arms all pass (one all-`a` token, no
12698        // `.`, no wildcards); only the cap arm fires. Surfaces the
12699        // paste-from-binary / accidental-multi-line-blob landing
12700        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
12701        // on the peer axis.
12702        let big = "a".repeat(257);
12703        assert_eq!(big.len(), 257);
12704        let err = contrato_subject_err(&big);
12705        assert!(
12706            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12707                if subject == &big && reason.contains("max length of 256")),
12708            "got {err:?}"
12709        );
12710    }
12711
12712    #[test]
12713    fn pubsub_contrato_subject_max_length_validates() {
12714        // 256-byte subject — exactly the cap. Boundary pin: drift in
12715        // the cap surfaces here and at
12716        // `rejects_pubsub_contrato_subject_too_long` simultaneously,
12717        // mirroring `http_contrato_endpoint_max_length_validates` and
12718        // `wit_max_length_validates` on the peer axes.
12719        let big = "a".repeat(256);
12720        assert_eq!(big.len(), 256);
12721        let mut s = three_member_spec();
12722        s.contratos.push(WitContract {
12723            de: "payment".into(),
12724            para: "catalog".into(),
12725            wit: "nats:pub-sub".into(),
12726            endpoint: None,
12727            subject: Some(big),
12728            slot: None,
12729        });
12730        s.validate().unwrap();
12731    }
12732
12733    #[test]
12734    fn pubsub_contrato_subject_accepts_canonical_forms() {
12735        // Positive-set sweep: every canonical NATS subject shape the
12736        // substrate-side `is_nats_subject` predicate accepts (the
12737        // multi-dot `events.order.charged`, the snake_case / kebab-
12738        // case / mixed-case tokens, the digit-bearing tokens, the
12739        // single-token wildcard `*` at every segment position, and
12740        // the trailing `>` multi-token wildcard) must remain a valid
12741        // contrato subject too. Drift between this list and the
12742        // substrate-side `nats_subject_accepts_canonical_forms` sweep
12743        // surfaces at the shared predicate — one source of truth.
12744        // Uses a fresh `(payment, catalog)` edge so none of the swept
12745        // subjects collide with the pre-existing entries in
12746        // `three_member_spec`.
12747        for subject in [
12748            "checkout.events.charge.failed",
12749            "rio.events.order.charged",
12750            "orders",
12751            "orders.123",
12752            "snake_case.token",
12753            "kebab-case.token",
12754            "MixedCase.Token",
12755            "orders.*.charged",
12756            "*.events.*",
12757            "orders.>",
12758        ] {
12759            let mut s = three_member_spec();
12760            s.contratos.push(WitContract {
12761                de: "payment".into(),
12762                para: "catalog".into(),
12763                wit: "nats:pub-sub".into(),
12764                endpoint: None,
12765                subject: Some(subject.into()),
12766                slot: None,
12767            });
12768            s.validate()
12769                .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
12770        }
12771    }
12772
12773    #[test]
12774    fn contrato_subject_empty_takes_precedence_over_invalid() {
12775        // Ordering pin: `ContratoSubjectEmpty` is the more self-
12776        // locating diagnostic on `""` and must lead — the value-shape
12777        // gate is only reached after the empty-check fires. Mirrors
12778        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
12779        // the peer payload axis.
12780        let mut s = three_member_spec();
12781        s.contratos.push(WitContract {
12782            de: "payment".into(),
12783            para: "catalog".into(),
12784            wit: "nats:pub-sub".into(),
12785            endpoint: None,
12786            subject: Some(String::new()),
12787            slot: None,
12788        });
12789        let err = s.validate().unwrap_err();
12790        assert!(
12791            matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
12792            "got {err:?}"
12793        );
12794    }
12795
12796    #[test]
12797    fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
12798        // Diagnostic-shape pin — the offending `:subject` + `:de` +
12799        // `:para` + a non-empty reason flow through verbatim so the
12800        // author can grep their caixa.lisp for the offending contrato
12801        // block and fix it in one edit. Same shape as
12802        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
12803        // and `wit_invalid_diagnostic_carries_offending_wit`.
12804        let err = contrato_subject_err("foo..bar");
12805        match err {
12806            AplicacaoError::ContratoSubjectInvalid {
12807                de,
12808                para,
12809                subject,
12810                reason,
12811            } => {
12812                assert_eq!(de, "payment");
12813                assert_eq!(para, "catalog");
12814                assert_eq!(subject, "foo..bar");
12815                assert!(!reason.is_empty(), "reason field must be non-empty");
12816            }
12817            other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
12818        }
12819    }
12820
12821    #[test]
12822    fn target_view_pubsub_subject_passes_through_to_typed_view() {
12823        // The compounding theorem on the pub-sub axis: every
12824        // `WitTarget::PubSub { subject }` returned by `target()` carries
12825        // a NATS-server-accepted subject. Renderers downstream of
12826        // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
12827        // NATS Stream/Consumer CR emitter, the future `feira app graph`
12828        // view's subject labeller) can rely on this without re-checking
12829        // — the type system carries the proof. Mirrors
12830        // `target_view_payload_is_guaranteed_nonempty_after_target_call`
12831        // on the peer axes.
12832        let nats = WitContract {
12833            de: "a".into(),
12834            para: "b".into(),
12835            wit: "nats:pub-sub".into(),
12836            endpoint: None,
12837            subject: Some("orders.events.*.charged".into()),
12838            slot: None,
12839        };
12840        match nats.target().unwrap() {
12841            WitTarget::PubSub { subject } => {
12842                assert_eq!(subject, "orders.events.*.charged");
12843            }
12844            other => panic!("expected PubSub, got {other:?}"),
12845        }
12846    }
12847
12848    // ── :contratos :slot value-shape gate ────────────────────────────────
12849    //
12850    // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
12851    // (63e18a0) value-shape suites on the peer payload axes. Until this
12852    // gate landed `WitContract::target()` only refused the empty string
12853    // for the Store arm; a structurally invalid slot (raw whitespace,
12854    // control character, non-ASCII byte, paste-from-binary multi-line
12855    // blob) silently passed validate and surfaced at runtime as a
12856    // per-backend kv write rejection or a silent next-read corruption,
12857    // far from the source caixa.lisp with no field naming which
12858    // `:contratos` edge carried the typo. Every authoring footgun the
12859    // kv backend intersection-floor would catch on write now becomes a
12860    // caixa-build-time `ContratoSlotInvalid` with the offending
12861    // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
12862    // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
12863    // peer payload axes; same shared predicate
12864    // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
12865    // any two axes' rule enforcement is a build error at the
12866    // predicate, not piecemeal across renderers. Closes the typed
12867    // payload-axis value-shape trajectory across all three legs of the
12868    // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
12869
12870    fn contrato_slot_err(slot: &str) -> AplicacaoError {
12871        // Fresh spec per call so the new contract doesn't collide on
12872        // identity with `three_member_spec`'s pre-existing entries
12873        // and doesn't close a synchronous cycle the cycle detector
12874        // would reject before the slot-shape gate fires. The new edge
12875        // uses `(payment, catalog)` — a pair the fixture doesn't
12876        // already declare in either direction (the fixture carries
12877        // `cart -> catalog` and `cart -> payment`, so `payment ->
12878        // catalog` doesn't form a cycle on the sync subgraph) — with
12879        // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
12880        // slot-shape gate fires cleanly after the wit-shape gate
12881        // (which `"wasi:keyvalue/store"` passes). Same edge pair the
12882        // peer `contrato_subject_err` helper uses (63e18a0).
12883        let mut s = three_member_spec();
12884        s.contratos.push(WitContract {
12885            de: "payment".into(),
12886            para: "catalog".into(),
12887            wit: "wasi:keyvalue/store".into(),
12888            endpoint: None,
12889            subject: None,
12890            slot: Some(slot.into()),
12891        });
12892        s.validate().unwrap_err()
12893    }
12894
12895    #[test]
12896    fn rejects_store_contrato_slot_with_whitespace() {
12897        // Fail-before-pass-after pin — pre-gate `"check out/$order"`
12898        // silently landed at the kv backend with whitespace whose
12899        // runtime behavior varies unpredictably across backends (etcd
12900        // accepts, Redis accepts then breaks on next CLI op, DynamoDB
12901        // rejects on write). Now caught at the source caixa.lisp.
12902        let err = contrato_slot_err("check out/$order");
12903        assert!(
12904            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12905                if slot == "check out/$order" && reason.contains("whitespace")),
12906            "got {err:?}"
12907        );
12908    }
12909
12910    #[test]
12911    fn rejects_store_contrato_slot_with_tab() {
12912        // Tab byte arm-pinned separately from the space arm so a
12913        // future relaxation that admits one but not the other surfaces
12914        // here.
12915        let err = contrato_slot_err("check\tout");
12916        assert!(
12917            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12918                if slot == "check\tout" && reason.contains("whitespace")),
12919            "got {err:?}"
12920        );
12921    }
12922
12923    #[test]
12924    fn rejects_store_contrato_slot_with_control_char() {
12925        // SOH (0x01) — distinct from the whitespace arm. Redis admits
12926        // and corrupts on RESP protocol framing; DynamoDB rejects on
12927        // write.
12928        let err = contrato_slot_err("checkout/\x01order");
12929        assert!(
12930            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12931                if slot == "checkout/\x01order" && reason.contains("control character")),
12932            "got {err:?}"
12933        );
12934    }
12935
12936    #[test]
12937    fn rejects_store_contrato_slot_with_newline() {
12938        // Embedded newline — the canonical "the paste-from-binary slug
12939        // spans multiple lines" footgun. Distinct from the whitespace
12940        // arm because `\n` is a control character (0x0A).
12941        let err = contrato_slot_err("checkout\norder");
12942        assert!(
12943            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12944                if slot == "checkout\norder" && reason.contains("control character")),
12945            "got {err:?}"
12946        );
12947    }
12948
12949    #[test]
12950    fn rejects_store_contrato_slot_with_non_ascii() {
12951        // Un-percent-encoded non-ASCII byte — the canonical "I copied
12952        // the slot from a doc with accented characters" footgun. Each
12953        // kv backend re-encodes non-ASCII differently (etcd preserves
12954        // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
12955        // rejects), so the typed slot's value set is the intersection-
12956        // floor every backend admits identically (printable ASCII).
12957        let err = contrato_slot_err("ch\u{e9}ckout/$order");
12958        assert!(
12959            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12960                if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
12961            "got {err:?}"
12962        );
12963    }
12964
12965    #[test]
12966    fn rejects_store_contrato_slot_too_long() {
12967        // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
12968        // legitimate-shape arms all pass (a single all-`a` token, no
12969        // separators); only the cap arm fires. Surfaces the paste-
12970        // from-binary / accidental-multi-line-blob landing footgun.
12971        // Mirrors `rejects_pubsub_contrato_subject_too_long` and
12972        // `rejects_http_contrato_endpoint_too_long` on the peer
12973        // payload axes.
12974        let big = "a".repeat(513);
12975        assert_eq!(big.len(), 513);
12976        let err = contrato_slot_err(&big);
12977        assert!(
12978            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12979                if slot == &big && reason.contains("max length of 512")),
12980            "got {err:?}"
12981        );
12982    }
12983
12984    #[test]
12985    fn store_contrato_slot_max_length_validates() {
12986        // 512-byte slot — exactly the cap. Boundary pin: drift in the
12987        // cap surfaces here and at `rejects_store_contrato_slot_too_long`
12988        // simultaneously, mirroring
12989        // `pubsub_contrato_subject_max_length_validates` and
12990        // `http_contrato_endpoint_max_length_validates` on the peer
12991        // payload axes.
12992        let big = "a".repeat(512);
12993        assert_eq!(big.len(), 512);
12994        let mut s = three_member_spec();
12995        s.contratos.push(WitContract {
12996            de: "payment".into(),
12997            para: "catalog".into(),
12998            wit: "wasi:keyvalue/store".into(),
12999            endpoint: None,
13000            subject: None,
13001            slot: Some(big),
13002        });
13003        s.validate().unwrap();
13004    }
13005
13006    #[test]
13007    fn store_contrato_slot_accepts_canonical_forms() {
13008        // Positive-set sweep: every canonical kv slot template the
13009        // substrate-side `is_wasi_keyvalue_slot` predicate accepts
13010        // (single-token identifiers, path-namespaced `$`-templates,
13011        // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
13012        // snake_case / kebab-case / MixedCase tokens, digit-bearing
13013        // tokens, percent-encoded fragments) must remain valid
13014        // contrato slots too. Drift between this list and the
13015        // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
13016        // surfaces at the shared predicate — one source of truth.
13017        // Uses a fresh `(payment, catalog)` edge so none of the swept
13018        // slots collide with the pre-existing entries in
13019        // `three_member_spec`.
13020        for slot in [
13021            "checkout",
13022            "checkout/$orderId",
13023            "users:{tenant}/{id}",
13024            "session.<sid>",
13025            "session.tokens.<sid>",
13026            "snake_case_key",
13027            "kebab-case-key",
13028            "MixedCase",
13029            "shard0",
13030            "v2/key",
13031            "users/caf%C3%A9",
13032        ] {
13033            let mut s = three_member_spec();
13034            s.contratos.push(WitContract {
13035                de: "payment".into(),
13036                para: "catalog".into(),
13037                wit: "wasi:keyvalue/store".into(),
13038                endpoint: None,
13039                subject: None,
13040                slot: Some(slot.into()),
13041            });
13042            s.validate()
13043                .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
13044        }
13045    }
13046
13047    #[test]
13048    fn contrato_slot_empty_takes_precedence_over_invalid() {
13049        // Ordering pin: `ContratoSlotEmpty` is the more self-locating
13050        // diagnostic on `""` and must lead — the value-shape gate is
13051        // only reached after the empty-check fires. Mirrors
13052        // `contrato_subject_empty_takes_precedence_over_invalid` and
13053        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
13054        // the peer payload axes.
13055        let mut s = three_member_spec();
13056        s.contratos.push(WitContract {
13057            de: "payment".into(),
13058            para: "catalog".into(),
13059            wit: "wasi:keyvalue/store".into(),
13060            endpoint: None,
13061            subject: None,
13062            slot: Some(String::new()),
13063        });
13064        let err = s.validate().unwrap_err();
13065        assert!(
13066            matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
13067            "got {err:?}"
13068        );
13069    }
13070
13071    #[test]
13072    fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
13073        // Diagnostic-shape pin — the offending `:slot` + `:de` +
13074        // `:para` + a non-empty reason flow through verbatim so the
13075        // author can grep their caixa.lisp for the offending contrato
13076        // block and fix it in one edit. Same shape as
13077        // `contrato_subject_invalid_diagnostic_carries_offending_subject`
13078        // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
13079        // on the peer payload axes.
13080        let err = contrato_slot_err("check out/$order");
13081        match err {
13082            AplicacaoError::ContratoSlotInvalid {
13083                de,
13084                para,
13085                slot,
13086                reason,
13087            } => {
13088                assert_eq!(de, "payment");
13089                assert_eq!(para, "catalog");
13090                assert_eq!(slot, "check out/$order");
13091                assert!(!reason.is_empty(), "reason field must be non-empty");
13092            }
13093            other => panic!("expected ContratoSlotInvalid, got {other:?}"),
13094        }
13095    }
13096
13097    #[test]
13098    fn target_view_store_slot_passes_through_to_typed_view() {
13099        // The compounding theorem on the store axis: every
13100        // `WitTarget::Store { slot }` returned by `target()` carries a
13101        // kv-backend-accepted slot template. Renderers downstream of
13102        // `typed_view()` (the future per-Servico `:capabilities
13103        // wasi:keyvalue/store` axis emitter, the future `feira app
13104        // graph` view's slot labeller, the future kv-provider CR
13105        // materializer) can rely on this without re-checking — the
13106        // type system carries the proof. Mirrors
13107        // `target_view_pubsub_subject_passes_through_to_typed_view` on
13108        // the peer payload axis.
13109        let store = WitContract {
13110            de: "a".into(),
13111            para: "b".into(),
13112            wit: "wasi:keyvalue/store".into(),
13113            endpoint: None,
13114            subject: None,
13115            slot: Some("checkout/$orderId".into()),
13116        };
13117        match store.target().unwrap() {
13118            WitTarget::Store { slot } => {
13119                assert_eq!(slot, "checkout/$orderId");
13120            }
13121            other => panic!("expected Store, got {other:?}"),
13122        }
13123    }
13124
13125    #[test]
13126    fn rejects_self_loop_in_synchronous_contratos() {
13127        // A synchronous self-edge (`cart → cart` over HTTP) is now
13128        // rejected by the dedicated `ContratoSelfLoop` gate — a precise
13129        // "this edge is degenerate" diagnostic — rather than incidentally
13130        // by the cycle detector framing it as a `["cart", "cart"]`
13131        // multi-node deadlock.
13132        let mut s = three_member_spec();
13133        s.contratos.push(contract_http("cart", "cart", "/loop"));
13134        let err = s.validate().unwrap_err();
13135        match err {
13136            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
13137                assert_eq!(caixa, "cart");
13138                assert_eq!(wit, "wasi:http/proxy");
13139            }
13140            other => panic!("expected ContratoSelfLoop, got {other:?}"),
13141        }
13142    }
13143
13144    #[test]
13145    fn rejects_self_loop_in_pubsub_contratos() {
13146        // The cycle detector excludes pub-sub edges (acyclic by
13147        // construction), so before the explicit gate a `nats:pub-sub`
13148        // self-edge silently validated and rendered a self-allow CNP.
13149        // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
13150        let mut s = three_member_spec();
13151        s.contratos.push(WitContract {
13152            de: "payment".into(),
13153            para: "payment".into(),
13154            wit: "nats:pub-sub".into(),
13155            endpoint: None,
13156            subject: Some("rio.events.payment".into()),
13157            slot: None,
13158        });
13159        let err = s.validate().unwrap_err();
13160        match err {
13161            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
13162                assert_eq!(caixa, "payment");
13163                assert_eq!(wit, "nats:pub-sub");
13164            }
13165            other => panic!("expected ContratoSelfLoop, got {other:?}"),
13166        }
13167    }
13168
13169    #[test]
13170    fn self_loop_fires_before_payload_shape_check() {
13171        // The structural "this edge can't exist" error precedes the
13172        // narrower payload-shape diagnostics: a self-edge carrying an
13173        // otherwise-malformed endpoint still reports ContratoSelfLoop,
13174        // not ContratoEndpointInvalid.
13175        let mut s = three_member_spec();
13176        s.contratos.push(WitContract {
13177            de: "cart".into(),
13178            para: "cart".into(),
13179            wit: "wasi:http/proxy".into(),
13180            endpoint: Some("not-absolute".into()),
13181            subject: None,
13182            slot: None,
13183        });
13184        match s.validate().unwrap_err() {
13185            AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
13186            other => panic!("expected ContratoSelfLoop, got {other:?}"),
13187        }
13188    }
13189
13190    #[test]
13191    fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
13192        // A self-edge naming a non-member reports the more fundamental
13193        // ContratoMemberMissing first (the member doesn't exist), so the
13194        // self-loop gate is reached only once both endpoints resolve.
13195        let mut s = three_member_spec();
13196        s.contratos.push(contract_http("ghost", "ghost", "/loop"));
13197        match s.validate().unwrap_err() {
13198            AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
13199            other => panic!("expected ContratoMemberMissing, got {other:?}"),
13200        }
13201    }
13202
13203    #[test]
13204    fn rejects_two_node_synchronous_cycle() {
13205        let mut s = three_member_spec();
13206        // existing edges: cart → catalog, cart → payment
13207        // adding catalog → cart closes a 2-cycle on the HTTP subgraph
13208        s.contratos
13209            .push(contract_http("catalog", "cart", "/refresh"));
13210        let err = s.validate().unwrap_err();
13211        match err {
13212            AplicacaoError::ContratoCycle { cycle } => {
13213                // Cycle traversal should mention both endpoints, with
13214                // the back-edge target appearing as both first and last
13215                // element to close the loop.
13216                assert!(cycle.len() >= 3);
13217                assert_eq!(cycle.first(), cycle.last());
13218                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
13219                assert!(body.contains("cart"));
13220                assert!(body.contains("catalog"));
13221            }
13222            other => panic!("expected ContratoCycle, got {other:?}"),
13223        }
13224    }
13225
13226    #[test]
13227    fn rejects_three_node_synchronous_cycle() {
13228        let mut s = three_member_spec();
13229        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
13230        s.contratos = vec![
13231            contract_http("catalog", "cart", "/x"),
13232            contract_http("cart", "payment", "/y"),
13233            contract_http("payment", "catalog", "/z"),
13234        ];
13235        let err = s.validate().unwrap_err();
13236        match err {
13237            AplicacaoError::ContratoCycle { cycle } => {
13238                assert_eq!(cycle.first(), cycle.last());
13239                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
13240                assert_eq!(body.len(), 3);
13241                assert!(body.contains("cart"));
13242                assert!(body.contains("catalog"));
13243                assert!(body.contains("payment"));
13244            }
13245            other => panic!("expected ContratoCycle, got {other:?}"),
13246        }
13247    }
13248
13249    #[test]
13250    fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
13251        // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
13252        // "acyclic by construction" — so a cycle whose closing edge
13253        // is pub-sub should NOT raise ContratoCycle.
13254        let mut s = three_member_spec();
13255        s.contratos = vec![
13256            contract_http("catalog", "cart", "/x"),
13257            contract_http("cart", "payment", "/y"),
13258            // Closing edge is pub-sub — async; not a sync deadlock.
13259            WitContract {
13260                de: "payment".into(),
13261                para: "catalog".into(),
13262                wit: "nats:pub-sub".into(),
13263                endpoint: None,
13264                subject: Some("checkout.events.charge.completed".into()),
13265                slot: None,
13266            },
13267        ];
13268        s.validate().expect("pub-sub edge breaks the sync cycle");
13269    }
13270
13271    #[test]
13272    fn store_edge_counts_as_synchronous_for_cycle_detection() {
13273        // wasi:keyvalue/store is request/response; a cycle through one
13274        // *is* a sync deadlock, just like HTTP.
13275        let mut s = three_member_spec();
13276        s.contratos = vec![
13277            contract_http("catalog", "cart", "/x"),
13278            WitContract {
13279                de: "cart".into(),
13280                para: "catalog".into(),
13281                wit: "wasi:keyvalue/store".into(),
13282                endpoint: None,
13283                subject: None,
13284                slot: Some("session/$id".into()),
13285            },
13286        ];
13287        let err = s.validate().unwrap_err();
13288        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
13289    }
13290
13291    #[test]
13292    fn capability_edge_counts_as_synchronous_for_cycle_detection() {
13293        // Capability-only edges (unknown WIT shape, no payload) default
13294        // to synchronous — safer; authors with truly async capability
13295        // semantics can model them as pub-sub explicitly.
13296        let mut s = three_member_spec();
13297        s.contratos = vec![
13298            contract_http("catalog", "cart", "/x"),
13299            WitContract {
13300                de: "cart".into(),
13301                para: "catalog".into(),
13302                wit: "custom:exchange".into(),
13303                endpoint: None,
13304                subject: None,
13305                slot: None,
13306            },
13307        ];
13308        let err = s.validate().unwrap_err();
13309        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
13310    }
13311
13312    #[test]
13313    fn long_acyclic_chain_validates() {
13314        // A long sync chain (no back-edges) must validate even when
13315        // every node is reachable from the first.
13316        let mut s = three_member_spec();
13317        s.membros = vec![
13318            membro("a", "^0.1"),
13319            membro("b", "^0.1"),
13320            membro("c", "^0.1"),
13321            membro("d", "^0.1"),
13322            membro("e", "^0.1"),
13323        ];
13324        s.contratos = vec![
13325            contract_http("a", "b", "/1"),
13326            contract_http("b", "c", "/2"),
13327            contract_http("c", "d", "/3"),
13328            contract_http("d", "e", "/4"),
13329        ];
13330        s.entrada.as_mut().unwrap().para = "a".into();
13331        s.validate().unwrap();
13332    }
13333
13334    #[test]
13335    fn diamond_acyclic_validates() {
13336        // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
13337        let mut s = three_member_spec();
13338        s.membros = vec![
13339            membro("a", "^0.1"),
13340            membro("b", "^0.1"),
13341            membro("c", "^0.1"),
13342            membro("d", "^0.1"),
13343        ];
13344        s.contratos = vec![
13345            contract_http("a", "b", "/1"),
13346            contract_http("a", "c", "/2"),
13347            contract_http("b", "d", "/3"),
13348            contract_http("c", "d", "/4"),
13349        ];
13350        s.entrada.as_mut().unwrap().para = "a".into();
13351        s.validate().unwrap();
13352    }
13353
13354    // ── duplicate-`:contratos` build-error gate ──────────────────────────
13355
13356    #[test]
13357    fn rejects_duplicate_http_contrato() {
13358        // Fail-before-pass-after pin: the fixture's `cart → catalog`
13359        // HTTP edge appears once. Push an identical entry — same
13360        // (de, para, wit, endpoint) — and validate() must reject it.
13361        // Until this gate landed the typed surface accepted the
13362        // duplicate silently and caixa-mesh's `cilium_network_policies`
13363        // emitted two ``CiliumNetworkPolicy`` objects with identical
13364        // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
13365        // admission rejects on `kubectl apply` far from the source.
13366        let mut s = three_member_spec();
13367        s.contratos
13368            .push(contract_http("cart", "catalog", "/products/:id"));
13369        let err = s.validate().unwrap_err();
13370        assert!(
13371            matches!(
13372                err,
13373                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
13374                    if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
13375            ),
13376            "got {err:?}"
13377        );
13378    }
13379
13380    #[test]
13381    fn rejects_duplicate_pubsub_contrato() {
13382        // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
13383        // edges with identical (de, para, subject) are degenerate;
13384        // pin that the typed surface refuses both at validate time.
13385        let mut s = three_member_spec();
13386        let pubsub = WitContract {
13387            de: "payment".into(),
13388            para: "cart".into(),
13389            wit: "nats:pub-sub".into(),
13390            endpoint: None,
13391            subject: Some("checkout.events.charge.failed".into()),
13392            slot: None,
13393        };
13394        s.contratos.push(pubsub.clone());
13395        s.contratos.push(pubsub);
13396        let err = s.validate().unwrap_err();
13397        assert!(
13398            matches!(
13399                err,
13400                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
13401                    if de == "payment" && para == "cart" && wit == "nats:pub-sub"
13402            ),
13403            "got {err:?}"
13404        );
13405    }
13406
13407    #[test]
13408    fn rejects_duplicate_store_contrato() {
13409        // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
13410        // edges with identical (de, para, slot) collapse to one mesh-
13411        // policy edge; pin the build error.
13412        let mut s = three_member_spec();
13413        let store = WitContract {
13414            de: "cart".into(),
13415            para: "payment".into(),
13416            wit: "wasi:keyvalue/store".into(),
13417            endpoint: None,
13418            subject: None,
13419            slot: Some("checkout/$orderId".into()),
13420        };
13421        // Drop the conflicting HTTP `cart → payment` edge from the
13422        // fixture so the duplicate-store pair is the only one
13423        // distinguishable on this pair.
13424        s.contratos
13425            .retain(|c| !(c.de == "cart" && c.para == "payment"));
13426        s.contratos.push(store.clone());
13427        s.contratos.push(store);
13428        let err = s.validate().unwrap_err();
13429        assert!(
13430            matches!(
13431                err,
13432                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
13433                    if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
13434            ),
13435            "got {err:?}"
13436        );
13437    }
13438
13439    #[test]
13440    fn rejects_duplicate_capability_contrato() {
13441        // Same gate on the pure-capability axis (no payload selector).
13442        // Two contracts with identical (de, para, wit) and no
13443        // endpoint/subject/slot are duplicate edges; pin so a future
13444        // `target_label` change can't accidentally collapse the
13445        // capability arm into a None-shaped key that compares equal
13446        // to a populated one.
13447        let mut s = three_member_spec();
13448        let capability = WitContract {
13449            de: "cart".into(),
13450            para: "catalog".into(),
13451            wit: "pleme:cap/audit".into(),
13452            endpoint: None,
13453            subject: None,
13454            slot: None,
13455        };
13456        s.contratos.push(capability.clone());
13457        s.contratos.push(capability);
13458        let err = s.validate().unwrap_err();
13459        match err {
13460            AplicacaoError::ContratoDuplicate {
13461                de,
13462                para,
13463                wit,
13464                target,
13465            } => {
13466                assert_eq!(de, "cart");
13467                assert_eq!(para, "catalog");
13468                assert_eq!(wit, "pleme:cap/audit");
13469                assert!(
13470                    target.contains("capability"),
13471                    "capability-edge duplicate diagnostic must surface the \
13472                     no-payload shape (got target = {target:?})"
13473                );
13474            }
13475            other => panic!("expected ContratoDuplicate, got {other:?}"),
13476        }
13477    }
13478
13479    #[test]
13480    fn accepts_distinct_http_paths_between_same_pair() {
13481        // Negative pin: two HTTP contracts cart → catalog at distinct
13482        // endpoints (`/products/:id` and `/search`) are *not*
13483        // duplicates — they're distinct typed edges differing on the
13484        // payload axis. The duplicate-gate must not over-match here,
13485        // since the cart-calls-catalog-on-multiple-paths shape is the
13486        // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
13487        // example: cart calls catalog at /products/:id, payment at
13488        // /charge — same shape extends to two paths on one para).
13489        let mut s = three_member_spec();
13490        s.contratos
13491            .push(contract_http("cart", "catalog", "/search"));
13492        s.validate()
13493            .expect("distinct endpoints between same (de, para) must validate");
13494    }
13495
13496    #[test]
13497    fn accepts_same_endpoint_on_different_pairs() {
13498        // Negative pin: the same `/charge` endpoint reused on two
13499        // different (de, para) pairs is two distinct edges, not a
13500        // duplicate. Pinning this shape so the gate's identity key
13501        // includes both `de` and `para` (not just `(wit, endpoint)`).
13502        let mut s = three_member_spec();
13503        s.contratos
13504            .push(contract_http("payment", "catalog", "/charge"));
13505        s.validate()
13506            .expect("same endpoint reused on distinct (de, para) must validate");
13507    }
13508
13509    #[test]
13510    fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
13511        // Pin the diagnostic shape: the duplicate-edge error names
13512        // *which* target field carried the conflict, so the author
13513        // doesn't have to re-grep the source caixa.lisp to find it.
13514        // Same self-locating diagnostic discipline as
13515        // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
13516        let mut s = three_member_spec();
13517        s.contratos
13518            .push(contract_http("cart", "catalog", "/products/:id"));
13519        let err = s.validate().unwrap_err();
13520        let msg = format!("{err}");
13521        assert!(
13522            msg.contains("\"/products/:id\""),
13523            "duplicate-contrato diagnostic must name the offending \
13524             :endpoint payload (got: {msg:?})"
13525        );
13526        assert!(
13527            msg.contains("cart") && msg.contains("catalog"),
13528            "diagnostic must name both endpoints of the duplicate edge \
13529             (got: {msg:?})"
13530        );
13531    }
13532
13533    #[test]
13534    fn duplicate_contrato_gate_runs_after_membership_check() {
13535        // Order pin: a duplicate contract whose `:de` is *also* not in
13536        // `:membros` surfaces the membership error first — the
13537        // missing-member diagnostic is more locating than the
13538        // duplicate-edge one (the author has to fix the membership
13539        // before the duplicate is meaningful). Same ordering
13540        // discipline as `membros_validation_runs_before_contratos_membership_check`.
13541        let mut s = three_member_spec();
13542        s.contratos.push(contract_http("phantom", "catalog", "/x"));
13543        s.contratos.push(contract_http("phantom", "catalog", "/x"));
13544        let err = s.validate().unwrap_err();
13545        assert!(
13546            matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
13547            "membership-missing must fire before duplicate-edge (got {err:?})"
13548        );
13549    }
13550
13551    #[test]
13552    fn duplicate_contrato_gate_runs_after_target_shape_check() {
13553        // Order pin: a contract with a malformed target (e.g. an HTTP
13554        // wit world with an empty :endpoint) surfaces the target-shape
13555        // error first, not the duplicate one. Even when two such
13556        // malformed entries are identical, the per-contract `target()`
13557        // check fires inside the loop *before* the duplicate-key
13558        // insert, so the diagnostic remains the most-locating one.
13559        let mut s = three_member_spec();
13560        let malformed = WitContract {
13561            de: "cart".into(),
13562            para: "catalog".into(),
13563            wit: "wasi:http/proxy".into(),
13564            endpoint: Some(String::new()),
13565            subject: None,
13566            slot: None,
13567        };
13568        s.contratos.push(malformed.clone());
13569        s.contratos.push(malformed);
13570        let err = s.validate().unwrap_err();
13571        assert!(
13572            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
13573            "endpoint-empty must fire before duplicate-edge (got {err:?})"
13574        );
13575    }
13576
13577    #[test]
13578    fn wit_target_label_pins_per_variant_format() {
13579        // Label format is the single source of truth every duplicate-
13580        // `:contratos` diagnostic + every future `feira app graph`
13581        // consumer routes through. Pin the shape per variant so a
13582        // future edit to `WitTarget::label` (e.g. a JSON emitter that
13583        // strips the leading `:`, or a rename from `endpoint` →
13584        // `path`) surfaces as a red-red test rather than as a silent
13585        // downstream diagnostic drift. Together with the exhaustive
13586        // `match` on `WitTarget` inside `label()`, adding a future
13587        // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
13588        // peer, per-edge WIT registry variants) is a compile error at
13589        // the label site — not a fall-through into the `Capability`
13590        // "no payload" default the prior raw-field-probe helper
13591        // silently landed on.
13592        assert_eq!(
13593            WitTarget::Http {
13594                endpoint: "/charge",
13595            }
13596            .label(),
13597            "\
13598:endpoint \"/charge\""
13599        );
13600        assert_eq!(
13601            WitTarget::PubSub {
13602                subject: "events.checkout.paid",
13603            }
13604            .label(),
13605            "\
13606:subject \"events.checkout.paid\""
13607        );
13608        assert_eq!(
13609            WitTarget::Store {
13610                slot: "checkout/$order",
13611            }
13612            .label(),
13613            "\
13614:slot \"checkout/$order\""
13615        );
13616        assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
13617        // Capability-arm label routes through the lifted
13618        // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
13619        // declaration per arm, next to the variant" discipline the
13620        // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
13621        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13622        // consts already carry extends to the payload-less arm; the
13623        // byte-string equality pin below plus this label-routes-
13624        // through-the-const pin make a future rebrand on either the
13625        // const declaration or the `label()` template a build error
13626        // here rather than a downstream consumer surprise.
13627        assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
13628        assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
13629    }
13630
13631    #[test]
13632    fn wit_target_display_routes_through_label_helper() {
13633        // Fail-before-pass-after pin on the fourth (and only remaining)
13634        // typed-shape-discriminator axis to converge onto the
13635        // three-path-convergence discipline the sibling M3
13636        // [`PlacementStrategy`] (0a2f653) and M2
13637        // [`crate::supervisor::RestartStrategy`] /
13638        // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
13639        // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
13640        // through [`WitTarget::label`], so every consumer reaching for
13641        // `format!("{v}")` on a typed payload target lands on the same
13642        // stable author-facing byte-string [`WitTarget::label`] returns
13643        // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
13644        // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
13645        // `:contratos` gate seeds via [`WitTarget::label`] at
13646        // aplicacao.rs:5491 already threads through.
13647        //
13648        // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
13649        // through to the `Debug` derive's structural output
13650        // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
13651        // rather than the [`WitTarget::label`] helper's stable byte-
13652        // string (`:endpoint "/charge"` — the author-facing `:contratos`
13653        // keyword form). Every future consumer that reaches for
13654        // `format!("{target}")` — the canonical shape every user-facing
13655        // pretty-print site on the sibling typed-enum axes
13656        // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
13657        // [`crate::supervisor::RestartPolicy`]) already uses — would
13658        // silently land under a different byte-string than the
13659        // [`WitTarget::label`] callers that the duplicate-`:contratos`
13660        // diagnostic already threads through, with the mismatch
13661        // surfacing as a downstream diagnostic / graph / audit line
13662        // reading one spelling while the substrate's own gate emitted
13663        // another.
13664        //
13665        // Pin the routing here so a future
13666        // `impl std::fmt::Display for WitTarget<'_>` reimplementation
13667        // that hand-rolls the per-arm formatting instead of delegating
13668        // to [`WitTarget::label`] fails at caixa-core build time.
13669        for variant in [
13670            WitTarget::Http {
13671                endpoint: "/charge",
13672            },
13673            WitTarget::PubSub {
13674                subject: "events.checkout.paid",
13675            },
13676            WitTarget::Store {
13677                slot: "checkout/$order",
13678            },
13679            WitTarget::Capability,
13680        ] {
13681            assert_eq!(
13682                variant.to_string(),
13683                variant.label(),
13684                "WitTarget::{variant:?} Display must route through \
13685                 WitTarget::label (single source of truth: the lifted \
13686                 payload_pair 4-arm dispatch the label helper already \
13687                 threads through)"
13688            );
13689        }
13690    }
13691
13692    #[test]
13693    fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
13694        // Consumer-side pin on the three-path convergence:
13695        // [`std::fmt::Display`] agrees byte-for-byte with the
13696        // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
13697        // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
13698        // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
13699        // Pre-lift the two paths were structurally independent — the
13700        // substrate-side gate reached for `target_view.label()` while a
13701        // future downstream diagnostic / graph / audit line reaching
13702        // for `format!("{target}")` would silently land on the `Debug`
13703        // derive's structural output. Pin the two paths byte-for-byte
13704        // here so any future variant addition (M4 `Rest`/`Grpc` split
13705        // of [`WitTarget::Http`], `Queue`-shaped peer of
13706        // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
13707        // match error at [`WitTarget::payload_pair`] rather than a
13708        // silent per-consumer dispatch miss.
13709        for variant in [
13710            WitTarget::Http {
13711                endpoint: "/charge",
13712            },
13713            WitTarget::PubSub {
13714                subject: "events.checkout.paid",
13715            },
13716            WitTarget::Store {
13717                slot: "checkout/$order",
13718            },
13719            WitTarget::Capability,
13720        ] {
13721            assert_eq!(
13722                format!("{variant}"),
13723                variant.label(),
13724                "WitTarget::{variant:?} Display byte-string must match \
13725                 the AplicacaoError::ContratoDuplicate `target:` carrier \
13726                 the AplicacaoSpec::validate duplicate-`:contratos` gate \
13727                 seeds via WitTarget::label — three-path convergence: \
13728                 Display + label + payload_pair all resolve to the same \
13729                 per-arm byte-string"
13730            );
13731        }
13732    }
13733
13734    #[test]
13735    fn wit_target_payload_pair_pins_per_variant() {
13736        // Pin the per-arm `(field-name, payload)` pair single-sourced
13737        // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
13738        // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
13739        // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
13740        // and [`WitTarget::field_name`] (returns the first component)
13741        // route through. Until this lift landed [`WitTarget::label`]
13742        // dispatched on the same three arms with a per-arm
13743        // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
13744        // paired [`WitTarget::HTTP_FIELD_NAME`] /
13745        // [`WitTarget::PUBSUB_FIELD_NAME`] /
13746        // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
13747        // canonical "same shape, written N times" duplication
13748        // THEORY.md §I.3.5 promotes to a build-time concern. A future
13749        // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
13750        // [`WitTarget::Http`], `Queue`-shaped peer of
13751        // [`WitTarget::Store`]) is one match-arm edit at
13752        // [`WitTarget::payload_pair`], visible here as a compile-time
13753        // exhaustiveness error on both this pin and the label-format
13754        // pin above.
13755        assert_eq!(
13756            WitTarget::Http {
13757                endpoint: "/charge"
13758            }
13759            .payload_pair(),
13760            Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
13761        );
13762        assert_eq!(
13763            WitTarget::PubSub {
13764                subject: "events.x",
13765            }
13766            .payload_pair(),
13767            Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
13768        );
13769        assert_eq!(
13770            WitTarget::Store {
13771                slot: "checkout/$order",
13772            }
13773            .payload_pair(),
13774            Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
13775        );
13776        assert_eq!(WitTarget::Capability.payload_pair(), None);
13777    }
13778
13779    #[test]
13780    fn wit_target_field_name_pins_per_variant() {
13781        // Pin the per-arm author-facing `:contratos` payload field
13782        // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
13783        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13784        // + returned by [`WitTarget::field_name`]. Every downstream
13785        // consumer (the [`WitContract::target`] gate's `expected:`
13786        // scalar, the [`WitTarget::label`] template's keyword prefix,
13787        // the `feira app graph` verb's `endpoint=…` prefix) routes
13788        // through the same three peer consts, so a rename on the
13789        // author-surface `(defcaixa … :contratos ((:de … :para …
13790        // :wit … :endpoint …)))` field lands in exactly one place.
13791        assert_eq!(
13792            WitTarget::Http {
13793                endpoint: "/charge"
13794            }
13795            .field_name(),
13796            Some(WitTarget::HTTP_FIELD_NAME),
13797        );
13798        assert_eq!(
13799            WitTarget::PubSub {
13800                subject: "events.x",
13801            }
13802            .field_name(),
13803            Some(WitTarget::PUBSUB_FIELD_NAME),
13804        );
13805        assert_eq!(
13806            WitTarget::Store {
13807                slot: "checkout/$order",
13808            }
13809            .field_name(),
13810            Some(WitTarget::STORE_FIELD_NAME),
13811        );
13812        // Capability arm carries no payload field — the diagnostic
13813        // never reports `expected: "capability"` because the gate's
13814        // Capability arm accepts no payload at all (it fires the
13815        // "expected: none" WrongTarget error instead), so the field-
13816        // name method returns None here rather than a placeholder.
13817        assert_eq!(WitTarget::Capability.field_name(), None);
13818
13819        // Peer const scalar values pinned so a rename on either side
13820        // (author-surface field name in the `(defcaixa …)` DSL, or
13821        // the diagnostic's `expected:` scalar) can't drift without
13822        // failing here first.
13823        assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
13824        assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
13825        assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
13826    }
13827
13828    #[test]
13829    fn wit_target_payload_pins_per_variant() {
13830        // Pin the per-arm payload scalar single-sourced onto the
13831        // [`WitTarget::payload_pair`] 4-arm dispatch and surfaced through
13832        // [`WitTarget::payload`] — the peer per-half projection to
13833        // [`WitTarget::field_name`] on the paired sub-selector axis. The
13834        // three payload-carrying arms round-trip their author-declared
13835        // scalar verbatim (`Http` → `Some("/charge")`, `PubSub` →
13836        // `Some("events.x")`, `Store` → `Some("checkout/$order")`) and
13837        // the payload-less [`WitTarget::Capability`] arm returns `None`.
13838        // Same shape as the sibling `wit_target_field_name_pins_per_variant`
13839        // (c6ec2af) pin on the Component-0 projection axis, extended
13840        // onto the Component-1 projection axis so both per-half readers
13841        // on the paired dispatch carry their own byte-shape pin.
13842        assert_eq!(
13843            WitTarget::Http {
13844                endpoint: "/charge",
13845            }
13846            .payload(),
13847            Some("/charge"),
13848        );
13849        assert_eq!(
13850            WitTarget::PubSub {
13851                subject: "events.x",
13852            }
13853            .payload(),
13854            Some("events.x"),
13855        );
13856        assert_eq!(
13857            WitTarget::Store {
13858                slot: "checkout/$order",
13859            }
13860            .payload(),
13861            Some("checkout/$order"),
13862        );
13863        assert_eq!(WitTarget::Capability.payload(), None);
13864    }
13865
13866    #[test]
13867    fn wit_target_payload_matches_payload_pair_second_component_per_variant() {
13868        // Per-variant equivalence pin: for every arm of [`WitTarget`],
13869        // `.payload()` equals `.payload_pair().map(|(_, p)| p)`
13870        // byte-for-byte. Guards the drift surface where a future refactor
13871        // that split one accessor off the shared match onto its own
13872        // dispatch — a well-meaning "inline the pair back into per-half
13873        // fields for one crate-internal caller who only wanted one half"
13874        // or a scratch `impl` shadowing the derived projection — would
13875        // silently desynchronize [`WitTarget::payload`] from the
13876        // authoritative [`WitTarget::payload_pair`] dispatch, and every
13877        // downstream consumer that thinks "the payload half of the pair"
13878        // would drift from the diagnostic / graph consumers reading the
13879        // same match through [`WitTarget::label`] / [`WitTarget::graph_label`].
13880        // Sibling to the peer [`caixa_flux::GitRefSpec`] `ref_value`
13881        // per-half projection pin (`gitrefspec_ref_pair_projects_
13882        // ref_field_name_and_ref_value_per_variant`, 655a1c0) on the
13883        // FluxCD source-controller `spec.ref.<field>` axis — same "one
13884        // paired dispatch, both per-half projections agree byte-for-
13885        // byte" discipline extended onto the M3 `:contratos` payload-
13886        // arm surface.
13887        for variant in [
13888            WitTarget::Http {
13889                endpoint: "/charge",
13890            },
13891            WitTarget::PubSub {
13892                subject: "events.checkout.paid",
13893            },
13894            WitTarget::Store {
13895                slot: "checkout/$order",
13896            },
13897            WitTarget::Capability,
13898        ] {
13899            let via_projection = variant.payload();
13900            let via_pair = variant.payload_pair().map(|(_, p)| p);
13901            assert_eq!(
13902                via_projection, via_pair,
13903                "WitTarget::{variant:?} payload() must equal \
13904                 payload_pair().map(|(_, p)| p) byte-for-byte — a \
13905                 regression that splits the two per-half projections off \
13906                 their shared match would silently desynchronize the \
13907                 payload accessor from the paired dispatch every \
13908                 diagnostic / graph consumer reads through",
13909            );
13910        }
13911    }
13912
13913    #[test]
13914    fn wit_target_http_endpoint_pins_per_variant() {
13915        // Pin the per-arm HTTP-endpoint scalar single-sourced onto the
13916        // [`WitTarget::http_endpoint`] 2-arm dispatch — the
13917        // substrate-primitive per-arm post-projection accessor every
13918        // L7-HTTP-facing consumer routes through, sibling to the peer
13919        // WitContract pre-projection [`WitContract::endpoint`] (7020470)
13920        // scalar accessor on the raw-field axis. The [`WitTarget::Http`]
13921        // arm round-trips its author-declared endpoint verbatim as
13922        // `Some("/charge")`; the three sibling arms
13923        // ([`WitTarget::PubSub`] / [`WitTarget::Store`] /
13924        // [`WitTarget::Capability`]) each return `None` because they
13925        // carry no HTTP endpoint by definition. Same fail-before-pass-
13926        // after per-variant discipline as the sibling
13927        // `wit_target_payload_pins_per_variant` (5d6dc92) /
13928        // `wit_target_field_name_pins_per_variant` (c6ec2af) /
13929        // `wit_target_payload_pair_pins_per_variant` (6788ed6) pins on
13930        // the peer pan-arm / per-half projection axes — extended onto
13931        // the per-arm HTTP-shape post-projection axis so a future
13932        // [`WitTarget`] variant addition (a `Rest`/`Grpc` split of
13933        // [`WitTarget::Http`], a `Queue`-shaped peer of
13934        // [`WitTarget::Store`]) trips a compile-time exhaustiveness
13935        // error on the sibling [`WitTarget::http_endpoint`] match arms
13936        // whose payload the L7-HTTP-shape accept-set is meant to bound.
13937        assert_eq!(
13938            WitTarget::Http {
13939                endpoint: "/charge",
13940            }
13941            .http_endpoint(),
13942            Some("/charge"),
13943        );
13944        assert_eq!(
13945            WitTarget::PubSub {
13946                subject: "events.checkout.paid",
13947            }
13948            .http_endpoint(),
13949            None,
13950        );
13951        assert_eq!(
13952            WitTarget::Store {
13953                slot: "checkout/$order",
13954            }
13955            .http_endpoint(),
13956            None,
13957        );
13958        assert_eq!(WitTarget::Capability.http_endpoint(), None);
13959    }
13960
13961    #[test]
13962    fn wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere() {
13963        // Per-variant coherence pin: for every arm of [`WitTarget`],
13964        // `.http_endpoint()` equals `.payload()` on the [`WitTarget::Http`]
13965        // arm (both project the same author-declared request-path
13966        // scalar), and returns `None` on every sibling arm regardless of
13967        // whether [`WitTarget::payload`] itself returns `Some` (PubSub /
13968        // Store carry their own payload the pan-arm accessor surfaces,
13969        // but that payload is not an HTTP endpoint — the per-arm
13970        // accessor must not leak it through the HTTP-shape channel).
13971        // Guards the drift surface where a future refactor that
13972        // conflated the per-arm HTTP projection with the pan-arm
13973        // [`WitTarget::payload`] projection — a well-meaning "one
13974        // accessor for the L7 branch, one for the graph" collapse that
13975        // routes both through the same 4-arm dispatch — would silently
13976        // widen the L7-HTTP-shape accept-set onto pub-sub / store
13977        // payloads at the caixa-mesh L7 emit branch, admitting a
13978        // `nats:pub-sub` edge's `:subject` as a Cilium L7 HTTP `path:`
13979        // rule with the operator-side apply-time symptom (Cilium's
13980        // eBPF data-plane rejects every ingress edge whose L7 filter
13981        // doesn't match the wire-format HTTP request line) far from
13982        // the source refactor. Sibling to the peer
13983        // `wit_target_payload_matches_payload_pair_second_component_
13984        // per_variant` (5d6dc92) coherence pin on the pan-arm axis —
13985        // extended onto the per-arm HTTP specialization axis so both
13986        // the pan-arm and the per-arm projections carry their own
13987        // byte-shape coherence witness against the substrate's typed
13988        // arm-family accept-set.
13989        for variant in [
13990            WitTarget::Http {
13991                endpoint: "/charge",
13992            },
13993            WitTarget::PubSub {
13994                subject: "events.checkout.paid",
13995            },
13996            WitTarget::Store {
13997                slot: "checkout/$order",
13998            },
13999            WitTarget::Capability,
14000        ] {
14001            let per_arm = variant.http_endpoint();
14002            let pan_arm = variant.payload();
14003            if variant.is_http() {
14004                assert_eq!(
14005                    per_arm, pan_arm,
14006                    "WitTarget::{variant:?} http_endpoint() must equal \
14007                     payload() on the Http arm — a per-arm-vs-pan-arm \
14008                     split would silently drift the L7 emit branch's \
14009                     path-scalar source from the graph verb's payload \
14010                     scalar source",
14011                );
14012            } else {
14013                assert_eq!(
14014                    per_arm, None,
14015                    "WitTarget::{variant:?} http_endpoint() must return \
14016                     None on non-Http arms — a leak that surfaced a \
14017                     pub-sub :subject or a key/value :slot through the \
14018                     HTTP-endpoint accessor would silently widen the \
14019                     Cilium L7 HTTP `path:` rule accept-set onto \
14020                     protocol shapes Cilium's eBPF data-plane can't \
14021                     introspect",
14022                );
14023            }
14024        }
14025    }
14026
14027    #[test]
14028    fn wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant() {
14029        // Per-variant coherence pin: for every arm of [`WitTarget`],
14030        // `.http_endpoint().is_some()` iff `.is_http()`. Guards the
14031        // drift surface where a future extension of the
14032        // [`WitTarget::http_endpoint`] accessor's accept-set (e.g. a
14033        // `Rest`/`Grpc` split of [`WitTarget::Http`] that widened the
14034        // accessor to cover both peers) landed without a paired
14035        // extension of the [`gen_platform::IsVariant`]-derived
14036        // `is_http()` predicate's accept-set, or vice versa — a
14037        // regression that split the "which arms count as HTTP-shaped
14038        // for L7-path emission?" answer between two dispatch surfaces
14039        // the substrate ships. Sibling to the peer
14040        // `wit_target_field_name_pins_per_variant` (c6ec2af) discipline
14041        // on the paired dispatch axis — extended onto the per-arm
14042        // predicate-vs-accessor coherence axis so the gen-platform
14043        // IsVariant predicate and the substrate-lifted per-arm
14044        // accessor carry one shared answer to "is this the HTTP arm?".
14045        for variant in [
14046            WitTarget::Http {
14047                endpoint: "/charge",
14048            },
14049            WitTarget::PubSub {
14050                subject: "events.checkout.paid",
14051            },
14052            WitTarget::Store {
14053                slot: "checkout/$order",
14054            },
14055            WitTarget::Capability,
14056        ] {
14057            assert_eq!(
14058                variant.http_endpoint().is_some(),
14059                variant.is_http(),
14060                "WitTarget::{variant:?} http_endpoint().is_some() must \
14061                 equal is_http() — a drift would split the L7 emit \
14062                 branch's arm-set gate from the substrate-derived \
14063                 shape-discrimination predicate on the same axis",
14064            );
14065        }
14066    }
14067
14068    #[test]
14069    fn wit_target_pubsub_subject_pins_per_variant() {
14070        // Fail-before-pass-after pin: the substrate-canonical per-arm
14071        // pub-sub-subject scalar accessor [`WitTarget::pubsub_subject`]
14072        // is the single dispatch every future pub-sub-facing consumer
14073        // routes through, sibling to the peer [`WitContract::subject`]
14074        // (63e18a0) pre-projection scalar accessor on the raw-field
14075        // axis and to the peer [`WitTarget::http_endpoint`] (5d6dc92)
14076        // post-projection per-arm accessor on the sibling HTTP-shape
14077        // axis. The [`WitTarget::PubSub`] arm round-trips its
14078        // author-declared subject verbatim as
14079        // `Some("events.checkout.paid")`; the three sibling arms each
14080        // return `None` because they carry no NATS-shaped subject by
14081        // definition. Same fail-before-pass-after per-variant discipline
14082        // as the sibling `wit_target_http_endpoint_pins_per_variant`
14083        // pin on the peer per-arm axis — extended onto the per-arm
14084        // pub-sub-shape post-projection axis so a future [`WitTarget`]
14085        // variant addition (a `Rest`/`Grpc` split of [`WitTarget::Http`],
14086        // a `Queue`-shaped peer of [`WitTarget::Store`]) trips a
14087        // compile-time exhaustiveness error on the sibling
14088        // [`WitTarget::pubsub_subject`] match arms whose payload the
14089        // pub-sub-shape accept-set is meant to bound.
14090        assert_eq!(
14091            WitTarget::PubSub {
14092                subject: "events.checkout.paid",
14093            }
14094            .pubsub_subject(),
14095            Some("events.checkout.paid"),
14096        );
14097        assert_eq!(
14098            WitTarget::Http {
14099                endpoint: "/charge",
14100            }
14101            .pubsub_subject(),
14102            None,
14103        );
14104        assert_eq!(
14105            WitTarget::Store {
14106                slot: "checkout/$order",
14107            }
14108            .pubsub_subject(),
14109            None,
14110        );
14111        assert_eq!(WitTarget::Capability.pubsub_subject(), None);
14112    }
14113
14114    #[test]
14115    fn wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere() {
14116        // Per-variant coherence pin: for every arm of [`WitTarget`],
14117        // `.pubsub_subject()` equals `.payload()` on the
14118        // [`WitTarget::PubSub`] arm (both project the same
14119        // author-declared subject scalar), and returns `None` on every
14120        // sibling arm regardless of whether [`WitTarget::payload`]
14121        // itself returns `Some` (Http / Store carry their own payload
14122        // the pan-arm accessor surfaces, but that payload is not a
14123        // pub-sub subject — the per-arm accessor must not leak it
14124        // through the pub-sub-shape channel). Sibling to the peer
14125        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
14126        // coherence pin on the per-arm HTTP-shape axis — extended onto
14127        // the per-arm pub-sub specialization axis so both per-arm
14128        // projections carry their own byte-shape coherence witness
14129        // against the substrate's typed arm-family accept-set.
14130        for variant in [
14131            WitTarget::Http {
14132                endpoint: "/charge",
14133            },
14134            WitTarget::PubSub {
14135                subject: "events.checkout.paid",
14136            },
14137            WitTarget::Store {
14138                slot: "checkout/$order",
14139            },
14140            WitTarget::Capability,
14141        ] {
14142            let per_arm = variant.pubsub_subject();
14143            let pan_arm = variant.payload();
14144            if variant.is_pubsub() {
14145                assert_eq!(
14146                    per_arm, pan_arm,
14147                    "WitTarget::{variant:?} pubsub_subject() must equal \
14148                     payload() on the PubSub arm — a per-arm-vs-pan-arm \
14149                     split would silently drift the pub-sub-shape emit \
14150                     branch's subject-scalar source from the graph verb's \
14151                     payload scalar source",
14152                );
14153            } else {
14154                assert_eq!(
14155                    per_arm, None,
14156                    "WitTarget::{variant:?} pubsub_subject() must return \
14157                     None on non-PubSub arms — a leak that surfaced an \
14158                     HTTP :endpoint or a key/value :slot through the \
14159                     pub-sub-subject accessor would silently widen the \
14160                     downstream NATS-shape accept-set onto protocol \
14161                     shapes NATS servers can't route",
14162                );
14163            }
14164        }
14165    }
14166
14167    #[test]
14168    fn wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant() {
14169        // Per-variant coherence pin: for every arm of [`WitTarget`],
14170        // `.pubsub_subject().is_some()` iff `.is_pubsub()`. Guards the
14171        // drift surface where a future extension of the
14172        // [`WitTarget::pubsub_subject`] accessor's accept-set landed
14173        // without a paired extension of the [`gen_platform::IsVariant`]-
14174        // derived `is_pubsub()` predicate's accept-set, or vice versa
14175        // — a regression that split the "which arms count as pub-sub-
14176        // shaped for subject emission?" answer between two dispatch
14177        // surfaces the substrate ships. Sibling to the peer
14178        // `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
14179        // pin on the per-arm HTTP-shape axis — extended onto the
14180        // per-arm pub-sub predicate-vs-accessor coherence axis so the
14181        // gen-platform IsVariant predicate and the substrate-lifted
14182        // per-arm accessor carry one shared answer to "is this the
14183        // PubSub arm?".
14184        for variant in [
14185            WitTarget::Http {
14186                endpoint: "/charge",
14187            },
14188            WitTarget::PubSub {
14189                subject: "events.checkout.paid",
14190            },
14191            WitTarget::Store {
14192                slot: "checkout/$order",
14193            },
14194            WitTarget::Capability,
14195        ] {
14196            assert_eq!(
14197                variant.pubsub_subject().is_some(),
14198                variant.is_pubsub(),
14199                "WitTarget::{variant:?} pubsub_subject().is_some() must \
14200                 equal is_pubsub() — a drift would split the pub-sub \
14201                 emit branch's arm-set gate from the substrate-derived \
14202                 shape-discrimination predicate on the same axis",
14203            );
14204        }
14205    }
14206
14207    #[test]
14208    fn wit_target_store_slot_pins_per_variant() {
14209        // Fail-before-pass-after pin: the substrate-canonical per-arm
14210        // key/value-store-slot scalar accessor [`WitTarget::store_slot`]
14211        // is the single dispatch every future store-facing consumer
14212        // routes through, sibling to the peer [`WitContract::slot`]
14213        // pre-projection scalar accessor on the raw-field axis and to
14214        // the peer [`WitTarget::http_endpoint`] (5d6dc92) +
14215        // [`WitTarget::pubsub_subject`] post-projection per-arm
14216        // accessors on the sibling per-payload-arm axes. The
14217        // [`WitTarget::Store`] arm round-trips its author-declared
14218        // slot verbatim as `Some("checkout/$order")`; the three
14219        // sibling arms each return `None` because they carry no
14220        // WASI-key/value slot by definition. Same fail-before-pass-
14221        // after per-variant discipline as the sibling
14222        // `wit_target_http_endpoint_pins_per_variant` +
14223        // `wit_target_pubsub_subject_pins_per_variant` pins on the
14224        // peer per-arm axes — extended onto the per-arm store-shape
14225        // post-projection axis so a future [`WitTarget`] variant
14226        // addition trips a compile-time exhaustiveness error on the
14227        // sibling [`WitTarget::store_slot`] match arms whose payload
14228        // the store-shape accept-set is meant to bound.
14229        assert_eq!(
14230            WitTarget::Store {
14231                slot: "checkout/$order",
14232            }
14233            .store_slot(),
14234            Some("checkout/$order"),
14235        );
14236        assert_eq!(
14237            WitTarget::Http {
14238                endpoint: "/charge",
14239            }
14240            .store_slot(),
14241            None,
14242        );
14243        assert_eq!(
14244            WitTarget::PubSub {
14245                subject: "events.checkout.paid",
14246            }
14247            .store_slot(),
14248            None,
14249        );
14250        assert_eq!(WitTarget::Capability.store_slot(), None);
14251    }
14252
14253    #[test]
14254    fn wit_target_store_slot_matches_payload_on_store_arm_and_is_none_elsewhere() {
14255        // Per-variant coherence pin: for every arm of [`WitTarget`],
14256        // `.store_slot()` equals `.payload()` on the
14257        // [`WitTarget::Store`] arm (both project the same
14258        // author-declared slot scalar), and returns `None` on every
14259        // sibling arm regardless of whether [`WitTarget::payload`]
14260        // itself returns `Some`. Sibling to the peer
14261        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
14262        // and `wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere`
14263        // pins on the per-arm HTTP and PubSub axes — closes the
14264        // per-arm-vs-pan-arm byte-shape coherence trio across all
14265        // three payload arms.
14266        for variant in [
14267            WitTarget::Http {
14268                endpoint: "/charge",
14269            },
14270            WitTarget::PubSub {
14271                subject: "events.checkout.paid",
14272            },
14273            WitTarget::Store {
14274                slot: "checkout/$order",
14275            },
14276            WitTarget::Capability,
14277        ] {
14278            let per_arm = variant.store_slot();
14279            let pan_arm = variant.payload();
14280            if variant.is_store() {
14281                assert_eq!(
14282                    per_arm, pan_arm,
14283                    "WitTarget::{variant:?} store_slot() must equal \
14284                     payload() on the Store arm — a per-arm-vs-pan-arm \
14285                     split would silently drift the store-shape emit \
14286                     branch's slot-scalar source from the graph verb's \
14287                     payload scalar source",
14288                );
14289            } else {
14290                assert_eq!(
14291                    per_arm, None,
14292                    "WitTarget::{variant:?} store_slot() must return \
14293                     None on non-Store arms — a leak that surfaced an \
14294                     HTTP :endpoint or a NATS :subject through the \
14295                     key/value-slot accessor would silently widen the \
14296                     downstream WASI-key/value slot accept-set onto \
14297                     protocol shapes the kv backends can't route",
14298                );
14299            }
14300        }
14301    }
14302
14303    #[test]
14304    fn wit_target_store_slot_agrees_with_is_store_predicate_per_variant() {
14305        // Per-variant coherence pin: for every arm of [`WitTarget`],
14306        // `.store_slot().is_some()` iff `.is_store()`. Guards the
14307        // drift surface where a future extension of the
14308        // [`WitTarget::store_slot`] accessor's accept-set landed
14309        // without a paired extension of the [`gen_platform::IsVariant`]-
14310        // derived `is_store()` predicate's accept-set. Sibling to the
14311        // peer `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
14312        // and `wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant`
14313        // pins — closes the per-arm predicate-vs-accessor coherence
14314        // trio across all three payload arms so the gen-platform
14315        // IsVariant predicate and the substrate-lifted per-arm
14316        // accessor carry one shared answer to "is this the Store arm?".
14317        for variant in [
14318            WitTarget::Http {
14319                endpoint: "/charge",
14320            },
14321            WitTarget::PubSub {
14322                subject: "events.checkout.paid",
14323            },
14324            WitTarget::Store {
14325                slot: "checkout/$order",
14326            },
14327            WitTarget::Capability,
14328        ] {
14329            assert_eq!(
14330                variant.store_slot().is_some(),
14331                variant.is_store(),
14332                "WitTarget::{variant:?} store_slot().is_some() must \
14333                 equal is_store() — a drift would split the store-shape \
14334                 emit branch's arm-set gate from the substrate-derived \
14335                 shape-discrimination predicate on the same axis",
14336            );
14337        }
14338    }
14339
14340    #[test]
14341    fn wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set() {
14342        // Fail-before-pass-after cross-axis pin on the trio
14343        // (`http_endpoint`, `pubsub_subject`, `store_slot`): on every
14344        // payload-carrying arm of [`WitTarget`], exactly one per-arm
14345        // accessor returns `Some(payload)` and the two peers return
14346        // `None`; and on the payload-less [`WitTarget::Capability`]
14347        // arm, all three return `None`. Guards the drift surface where
14348        // a future extension of one per-arm accessor's accept-set (e.g.
14349        // a hypothetical `Rest`/`Grpc` split of [`WitTarget::Http`]
14350        // that widened `http_endpoint` to cover both peers without
14351        // narrowing the peer `pubsub_subject` / `store_slot` accept-
14352        // sets to keep the partition mutually exclusive) landed without
14353        // threading through the peer per-arm accessors — the resulting
14354        // silent overlap would land the same edge's payload on two
14355        // downstream per-shape emit branches at once, or leak a
14356        // pub-sub subject through the store-slot channel, at renderer
14357        // emit time far from the substrate primitive's arm-widening
14358        // commit. Peer of the sibling `wit_target_field_names_are_pairwise_distinct`
14359        // 3-way pin on the payload-field-name axis — extended onto the
14360        // per-arm-accessor payload-projection axis so the substrate-
14361        // owned partition invariant is load-bearing at every per-arm
14362        // consumer's read site.
14363        let payload_variants = [
14364            (
14365                WitTarget::Http {
14366                    endpoint: "/charge",
14367                },
14368                "http",
14369            ),
14370            (
14371                WitTarget::PubSub {
14372                    subject: "events.checkout.paid",
14373                },
14374                "pubsub",
14375            ),
14376            (
14377                WitTarget::Store {
14378                    slot: "checkout/$order",
14379                },
14380                "store",
14381            ),
14382        ];
14383        for (variant, own_arm_label) in payload_variants {
14384            let own_arm_hit = match own_arm_label {
14385                "http" => variant.is_http(),
14386                "pubsub" => variant.is_pubsub(),
14387                "store" => variant.is_store(),
14388                other => panic!("unknown own-arm label {other:?}"),
14389            };
14390            let per_arm_results = [
14391                ("http_endpoint", variant.http_endpoint()),
14392                ("pubsub_subject", variant.pubsub_subject()),
14393                ("store_slot", variant.store_slot()),
14394            ];
14395            let some_count = per_arm_results.iter().filter(|(_, v)| v.is_some()).count();
14396            assert_eq!(
14397                some_count, 1,
14398                "WitTarget::{variant:?} must land exactly one per-arm \
14399                 post-projection accessor's Some result — the trio \
14400                 (http_endpoint, pubsub_subject, store_slot) must \
14401                 partition the payload arm-set; got {per_arm_results:?}",
14402            );
14403            assert!(
14404                own_arm_hit,
14405                "WitTarget::{variant:?} own-arm gen-platform predicate \
14406                 must return true on its own arm — a partition failure \
14407                 upstream of this pin",
14408            );
14409            assert!(
14410                variant.payload().is_some(),
14411                "WitTarget::{variant:?} pan-arm payload() must return \
14412                 Some on every payload-carrying arm the trio partitions",
14413            );
14414        }
14415        // The payload-less Capability arm must return None on every
14416        // per-arm accessor — the partition's terminal-fallback shape.
14417        let cap = WitTarget::Capability;
14418        assert_eq!(cap.http_endpoint(), None);
14419        assert_eq!(cap.pubsub_subject(), None);
14420        assert_eq!(cap.store_slot(), None);
14421        assert_eq!(
14422            cap.payload(),
14423            None,
14424            "WitTarget::Capability pan-arm payload() must return None — \
14425             the trio's payload-less-arm coherence witness",
14426        );
14427    }
14428
14429    #[test]
14430    fn wit_target_field_names_are_pairwise_distinct() {
14431        // Distinctness pin: if any two of the three payload-field-name
14432        // scalars ever collapse (e.g. an accidental `endpoint` copy-
14433        // paste over the `subject` const), the [`WitContract::target`]
14434        // gate's diagnostic would point authors at the wrong field —
14435        // an "expected `:endpoint`" error on a pub-sub edge would
14436        // silently misroute the fix. Same cross-axis-distinctness
14437        // discipline as the peer M3 `:placement :estrategia` variant-
14438        // discriminator scalar-value pins (cc8f749) applied to the
14439        // payload-field-name axis.
14440        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
14441        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
14442        assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
14443    }
14444
14445    #[test]
14446    fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
14447        // Fail-before-pass-after pin: the graph-verb payload column's
14448        // per-arm `{field}={payload}` byte-string is derived through the
14449        // single [`WitTarget::payload_pair`] 4-arm dispatch on the three
14450        // payload-carrying arms, not through a hand-rolled per-arm match
14451        // that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
14452        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
14453        // inline. A future variant addition — the M4-and-later per-edge
14454        // WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
14455        // peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
14456        // peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
14457        // and both [`WitTarget::label`] (duplicate-`:contratos`
14458        // diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
14459        // payload column) pick up the new arm from the same dispatch.
14460        // Prior to this lift the graph verb open-coded the 4-arm match
14461        // in caixa-feira, so a variant addition would have to be threaded
14462        // through both projections in lockstep or the graph verb would
14463        // silently drop the new arm to `(capability-only)`.
14464        for variant in [
14465            WitTarget::Http {
14466                endpoint: "/charge",
14467            },
14468            WitTarget::PubSub {
14469                subject: "events.checkout.paid",
14470            },
14471            WitTarget::Store {
14472                slot: "checkout/$order",
14473            },
14474        ] {
14475            let (field, payload) = variant
14476                .payload_pair()
14477                .expect("payload arm must expose (field, payload)");
14478            assert_eq!(
14479                variant.graph_label(),
14480                format!("{field}={payload}"),
14481                "WitTarget::{variant:?} graph_label must route the \
14482                 `{{field}}={{payload}}` template through payload_pair — \
14483                 a regression to a hand-rolled per-arm match at the graph \
14484                 verb would silently disagree with a future variant \
14485                 addition landed only at payload_pair"
14486            );
14487        }
14488    }
14489
14490    #[test]
14491    fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
14492        // Fail-before-pass-after pin on the payload-less arm: the graph
14493        // verb's `(capability-only)` byte-string routes through the
14494        // lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
14495        // [`WitTarget::Capability`] arm, not through an inline
14496        // `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
14497        // per-`:contratos` payload column. Peer of the sibling
14498        // [`wit_target_label_pins_per_variant_format`] Capability-arm
14499        // assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
14500        // extended here onto the third payload-less-arm consumer axis
14501        // (graph verb, sibling to the duplicate-`:contratos` diagnostic
14502        // axis and the wrong-target diagnostic axis).
14503        assert_eq!(
14504            WitTarget::Capability.graph_label(),
14505            WitTarget::CAPABILITY_GRAPH_LABEL,
14506        );
14507        assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
14508    }
14509
14510    #[test]
14511    fn wit_target_capability_graph_label_distinct_from_capability_label() {
14512        // Cross-consumer-axis distinctness pin: the graph-verb
14513        // payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
14514        // (`(capability-only)`) and the duplicate-`:contratos` diagnostic
14515        // label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
14516        // payload)`) surface the payload-less arm on two distinct
14517        // consumer axes; a collapse (an accidental rebrand that lands
14518        // one spelling on both consts, a copy-paste that unifies them
14519        // "for consistency") would silently merge the two byte-strings
14520        // and lose the vocabulary distinction the graph verb's
14521        // compact-column form and the diagnostic's descriptive-clause
14522        // form each carry on purpose. Peer of the sibling 4-way
14523        // [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
14524        // pin on the `ContratoWrongTarget::expected` scalar-value axis —
14525        // extended here onto the cross-consumer-axis distinctness of the
14526        // two payload-less-arm consts.
14527        assert_ne!(
14528            WitTarget::CAPABILITY_GRAPH_LABEL,
14529            WitTarget::CAPABILITY_LABEL,
14530            "WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
14531             and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
14532             diagnostic) must remain distinct — a collapse would silently \
14533             merge two consumer axes onto one spelling"
14534        );
14535    }
14536
14537    #[test]
14538    fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
14539        // 4-way distinctness pin extending the sibling
14540        // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
14541        // (which covers only the HTTP / PubSub / Store payload arms)
14542        // onto the fourth scalar the shared
14543        // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
14544        // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
14545        // (`"none"`), the payload-less Capability-arm rejection scalar.
14546        //
14547        // All four [`WitTarget::HTTP_FIELD_NAME`] /
14548        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
14549        // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
14550        // dispatch surface [`WitContract::target`] writes onto the
14551        // `ContratoWrongTarget::expected` field — the same `&'static
14552        // str` axis authors read as "this WIT world's shape admits
14553        // (only|not) `:<field>`". Pairwise-distinctness is the invariant
14554        // downstream consumers rely on: an `expected: "endpoint"`
14555        // diagnostic on a Capability-shaped edge tells the author to
14556        // add a `:endpoint "…"` slot to a WIT world that admits none,
14557        // silently misrouting the fix. Until this pin landed the three
14558        // payload-arm consts were distinctness-guarded by the sibling
14559        // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
14560        // scalar (d4f54f2) sat unguarded — a rebrand collision (the
14561        // author-facing vocabulary shift from `"none"` to `"endpoint"`
14562        // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
14563        // into per-shape peers) would have silently landed one
14564        // Capability-arm rejection on a payload-arm's `expected:` byte-
14565        // string and desynchronized the diagnostic from the author's
14566        // typed shape.
14567        //
14568        // Same 4-way pairwise-distinctness pin discipline as the peer
14569        // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
14570        // (cc8f749) applies on the sibling M3 closed-set typed-enum
14571        // scalar-value dispatch axis; extends the pin trajectory the
14572        // sibling `wit_target_field_names_are_pairwise_distinct`
14573        // 3-way pin opened to cover the last unguarded corner on the
14574        // `ContratoWrongTarget::expected` scalar-value axis.
14575        //
14576        // Fail-before-pass-after locally verified by mutating
14577        // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
14578        // — this pin fires as expected; restoring passes.
14579        let all = [
14580            WitTarget::HTTP_FIELD_NAME,
14581            WitTarget::PUBSUB_FIELD_NAME,
14582            WitTarget::STORE_FIELD_NAME,
14583            WitTarget::CAPABILITY_EXPECTED,
14584        ];
14585        for (i, a) in all.iter().enumerate() {
14586            for (j, b) in all.iter().enumerate() {
14587                if i != j {
14588                    assert_ne!(
14589                        a, b,
14590                        "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
14591                         STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
14592                         pairwise distinct — got duplicate {a:?} at indices \
14593                         {i} and {j}; all four scalars thread through the \
14594                         shared `AplicacaoError::ContratoWrongTarget::expected` \
14595                         &'static str axis, so a collapse silently misdirects \
14596                         the diagnostic on which typed shape the WIT world admits",
14597                    );
14598                }
14599            }
14600        }
14601    }
14602
14603    #[test]
14604    fn wit_target_is_variant_predicates_partition_the_arm_set() {
14605        // Fail-before-pass-after pin on the
14606        // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
14607        // each of the four variants exactly one of the generated
14608        // `is_http` / `is_pubsub` / `is_store` / `is_capability`
14609        // predicates returns `true` and the other three return
14610        // `false`. Prior to this derive the only production
14611        // arm-discriminator on [`WitTarget`] — the sync-cycle
14612        // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
14613        // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
14614        // the variant that expressed no compile-time link back to
14615        // the closed-set typed dispatch a future fifth
14616        // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
14617        // split of [`WitTarget::PubSub`] into shape-specific peers,
14618        // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
14619        // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
14620        // to thread through in lockstep or the DFS exclusion would
14621        // silently disagree with the peer diagnostic templates on
14622        // which arms carry sync-versus-async semantics. Peer of the
14623        // sibling [`crate::CaixaKind`] (f5bba80),
14624        // [`PlacementStrategy`] (766ec63),
14625        // [`crate::supervisor::RestartStrategy`],
14626        // [`crate::supervisor::RestartPolicy`], and
14627        // [`crate::upgrade::UpgradeInstruction`] (915a934)
14628        // `IsVariant` derives on the sibling closed-set typed-enum
14629        // discriminator axes — extends the same one-typed-dispatch-
14630        // per-variant discipline onto the last unlifted closed-set
14631        // typed-enum discriminator on the caixa surface (the M3
14632        // mesh-slot per-`:contratos` target-arm axis), closing the
14633        // arm-discriminator convergence trajectory across every
14634        // closed-set typed enum in caixa-core.
14635        let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
14636            (
14637                WitTarget::Http { endpoint: "/x" },
14638                [true, false, false, false],
14639            ),
14640            (
14641                WitTarget::PubSub {
14642                    subject: "events.x",
14643                },
14644                [false, true, false, false],
14645            ),
14646            (
14647                WitTarget::Store { slot: "kv/x" },
14648                [false, false, true, false],
14649            ),
14650            (WitTarget::Capability, [false, false, false, true]),
14651        ];
14652        for (variant, expected) in rows {
14653            let observed = [
14654                variant.is_http(),
14655                variant.is_pubsub(),
14656                variant.is_store(),
14657                variant.is_capability(),
14658            ];
14659            assert_eq!(
14660                observed, expected,
14661                "WitTarget::{variant:?} is_* predicates must partition \
14662                 the arm set (http, pubsub, store, capability); got {observed:?}"
14663            );
14664        }
14665    }
14666
14667    #[test]
14668    fn wit_target_is_variant_predicates_are_const_fn() {
14669        // The [`gen_platform::IsVariant`] derive emits `const fn`
14670        // predicates on the peer [`crate::CaixaKind`] +
14671        // [`crate::upgrade::UpgradeInstruction`] +
14672        // [`crate::supervisor::RestartStrategy`] +
14673        // [`crate::supervisor::RestartPolicy`] +
14674        // [`PlacementStrategy`] closed-set typed enums — pin the
14675        // same posture on [`WitTarget`] so a future accidental
14676        // downgrade to non-`const` (an added runtime helper reachable
14677        // only from a non-`const` context, a manual hand-rolled
14678        // `impl` that shadows the derive-generated method) trips at
14679        // caixa-core build time rather than surfacing as a downstream
14680        // `const`-context regression far from the derive declaration.
14681        //
14682        // Unlike the peer unit-variant enums (`CaixaKind` /
14683        // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
14684        // whose `const` constructors need no arguments, the three
14685        // payload-carrying [`WitTarget`] arms are const-constructed
14686        // through `&'static str` payloads — the same `'static`
14687        // lifetime the closed-set typed enum's four-arm partition
14688        // pin above already threads through.
14689        const HTTP: WitTarget<'static> = WitTarget::Http { endpoint: "/x" };
14690        const PUBSUB: WitTarget<'static> = WitTarget::PubSub { subject: "e" };
14691        const STORE: WitTarget<'static> = WitTarget::Store { slot: "kv/x" };
14692        const CAPABILITY: WitTarget<'static> = WitTarget::Capability;
14693        const IS_HTTP: bool = HTTP.is_http();
14694        const IS_PUBSUB: bool = PUBSUB.is_pubsub();
14695        const IS_STORE: bool = STORE.is_store();
14696        const IS_CAPABILITY: bool = CAPABILITY.is_capability();
14697        assert!(IS_HTTP);
14698        assert!(IS_PUBSUB);
14699        assert!(IS_STORE);
14700        assert!(IS_CAPABILITY);
14701    }
14702
14703    #[test]
14704    fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
14705        // Consumer-side pin on the sole production converge site:
14706        // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
14707        // edges from the synchronous-subgraph DFS via the lifted
14708        // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
14709        // predicate (rebound from the prior raw
14710        // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
14711        // variant). Byte-equivalent today (`is_pubsub` is the
14712        // derive-generated `matches!(self, Self::PubSub { .. })` by
14713        // construction, the `#[is_variant(name = "pubsub")]` override
14714        // aliasing the auto-derived `is_pub_sub` back to the sibling
14715        // [`WitContract::is_pubsub`] name); pin the behavior so a
14716        // future accidental drift (a rebind onto a peer arm
14717        // predicate, a manual hand-rolled `impl` that shadows the
14718        // derive-generated method with different semantics, a peer
14719        // arm rename that shifts which variant carries sync-versus-
14720        // async semantics) trips at caixa-core test time rather than
14721        // at some downstream operator's runtime dispatch far from the
14722        // rebind commit.
14723        //
14724        // The fixture constructs a two-Servico Aplicacao with one
14725        // pub-sub edge that would close a sync-cycle if the DFS did
14726        // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
14727        // pub-sub exclusion means the DFS sees only the `b → a` HTTP
14728        // edge, which is not a cycle. A regression in the converge
14729        // (a rebind that reads the pub-sub arm as sync) would report
14730        // `AplicacaoError::ContratoCycle`.
14731        let s = AplicacaoSpec {
14732            membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
14733            contratos: vec![
14734                // Pub-sub edge: DFS must skip via is_pubsub().
14735                WitContract {
14736                    de: "a".into(),
14737                    para: "b".into(),
14738                    wit: "nats:pub-sub".into(),
14739                    endpoint: None,
14740                    subject: Some("events.x".into()),
14741                    slot: None,
14742                },
14743                // HTTP edge: DFS must include.
14744                WitContract {
14745                    de: "b".into(),
14746                    para: "a".into(),
14747                    wit: "wasi:http/proxy".into(),
14748                    endpoint: Some("/x".into()),
14749                    subject: None,
14750                    slot: None,
14751                },
14752            ],
14753            politicas: MeshPolicy::default(),
14754            placement: Placement {
14755                estrategia: PlacementStrategy::Replicated,
14756                clusters: vec!["rio".into()],
14757                affinity: None,
14758                shard_key: None,
14759            },
14760            entrada: None,
14761        };
14762        s.validate()
14763            .expect("pub-sub edge must be excluded from sync-cycle DFS");
14764    }
14765
14766    #[test]
14767    fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
14768        // Consumer-side pin: the same three peer consts thread through
14769        // both the [`WitTarget::label`] template (leading-`:` keyword
14770        // prefix in the duplicate-`:contratos` diagnostic) and the
14771        // [`WitContract::target`] gate's [`AplicacaoError::
14772        // ContratoMissingTarget`] `expected:` scalar (the field the
14773        // author needs to add). Pin both routes at once so a future
14774        // refactor can't accidentally split them onto separate string
14775        // literals — the "one place, everywhere reaches for it"
14776        // invariant the peer const set carries.
14777        let http_label = WitTarget::Http { endpoint: "/x" }.label();
14778        assert!(
14779            http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
14780            "label must lead with :{} keyword (got {http_label:?})",
14781            WitTarget::HTTP_FIELD_NAME,
14782        );
14783
14784        let mut s = three_member_spec();
14785        s.contratos.push(WitContract {
14786            de: "cart".into(),
14787            para: "catalog".into(),
14788            wit: "kafka:topic".into(),
14789            endpoint: None,
14790            subject: None,
14791            slot: None,
14792        });
14793        match s.validate().unwrap_err() {
14794            AplicacaoError::ContratoMissingTarget { expected, .. } => {
14795                assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
14796            }
14797            other => panic!("expected ContratoMissingTarget, got {other:?}"),
14798        }
14799    }
14800
14801    #[test]
14802    fn duplicate_pubsub_diagnostic_names_offending_subject() {
14803        // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
14804        // on the pub-sub target axis: the duplicate-edge diagnostic
14805        // must name the `:subject` payload verbatim (not just the
14806        // `(de, para, wit)` triple). Prior to lifting the label onto
14807        // [`WitTarget::label`] the diagnostic derived the label from
14808        // raw [`WitContract`] `Option<String>` probes — a future
14809        // `WitTarget` variant addition (M4 per-edge WIT registry)
14810        // would silently fall through to the `Capability` "no
14811        // payload" default without a compiler warning. Pinning the
14812        // pub-sub arm's format closes the second of three
14813        // payload-carrying `WitTarget` arms this diagnostic threads
14814        // through.
14815        let mut s = three_member_spec();
14816        let pubsub = WitContract {
14817            de: "payment".into(),
14818            para: "cart".into(),
14819            wit: "nats:pub-sub".into(),
14820            endpoint: None,
14821            subject: Some("events.checkout.paid".into()),
14822            slot: None,
14823        };
14824        s.contratos.push(pubsub.clone());
14825        s.contratos.push(pubsub);
14826        let err = s.validate().unwrap_err();
14827        let msg = format!("{err}");
14828        assert!(
14829            msg.contains(":subject \"events.checkout.paid\""),
14830            "duplicate-pubsub diagnostic must name the offending \
14831             :subject payload (got: {msg:?})"
14832        );
14833    }
14834
14835    #[test]
14836    fn duplicate_store_diagnostic_names_offending_slot() {
14837        // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
14838        // key-value target axis: the diagnostic must name the `:slot`
14839        // payload verbatim. Third of three payload-carrying
14840        // `WitTarget` arms this diagnostic threads through, closing
14841        // the per-arm label pin trilogy (`Http` — 6841,
14842        // `PubSub` + `Store` — this test + peer above).
14843        let mut s = three_member_spec();
14844        let store = WitContract {
14845            de: "cart".into(),
14846            para: "payment".into(),
14847            wit: "wasi:keyvalue/store".into(),
14848            endpoint: None,
14849            subject: None,
14850            slot: Some("checkout/$orderId".into()),
14851        };
14852        s.contratos
14853            .retain(|c| !(c.de == "cart" && c.para == "payment"));
14854        s.contratos.push(store.clone());
14855        s.contratos.push(store);
14856        let err = s.validate().unwrap_err();
14857        let msg = format!("{err}");
14858        assert!(
14859            msg.contains(":slot \"checkout/$orderId\""),
14860            "duplicate-store diagnostic must name the offending :slot \
14861             payload (got: {msg:?})"
14862        );
14863    }
14864
14865    #[test]
14866    fn rejects_entrada_path_without_leading_slash() {
14867        let mut s = three_member_spec();
14868        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
14869        let err = s.validate().unwrap_err();
14870        assert!(
14871            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
14872            "got {err:?}"
14873        );
14874    }
14875
14876    #[test]
14877    fn rejects_empty_entrada_path() {
14878        let mut s = three_member_spec();
14879        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "".into()];
14880        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
14881    }
14882
14883    #[test]
14884    fn rejects_duplicate_entrada_paths() {
14885        let mut s = three_member_spec();
14886        s.entrada.as_mut().unwrap().paths = vec![
14887            "/api/cart".into(),
14888            "/api/products".into(),
14889            "/api/cart".into(),
14890        ];
14891        let err = s.validate().unwrap_err();
14892        assert!(
14893            matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
14894            "got {err:?}"
14895        );
14896    }
14897
14898    #[test]
14899    fn rejects_zero_entrada_port() {
14900        let mut s = three_member_spec();
14901        s.entrada.as_mut().unwrap().port = 0;
14902        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
14903    }
14904
14905    // ── :entrada :paths value-shape gate ─────────────────────────────
14906    //
14907    // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
14908    // sibling `:paths` axis. Every authoring footgun the K8s Gateway
14909    // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
14910    // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
14911    // time now becomes a caixa-build-time `EntradaPathInvalid` with
14912    // the offending `:paths` entry named verbatim.
14913
14914    #[test]
14915    fn rejects_entrada_path_with_query() {
14916        // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
14917        // silently passed validate and the Gateway API webhook
14918        // rejected it at apply time with no source citation.
14919        let mut s = three_member_spec();
14920        s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
14921        let err = s.validate().unwrap_err();
14922        assert!(
14923            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14924                if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
14925            "got {err:?}"
14926        );
14927    }
14928
14929    #[test]
14930    fn rejects_entrada_path_with_fragment() {
14931        let mut s = three_member_spec();
14932        s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
14933        let err = s.validate().unwrap_err();
14934        assert!(
14935            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14936                if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
14937            "got {err:?}"
14938        );
14939    }
14940
14941    #[test]
14942    fn rejects_entrada_path_with_space() {
14943        let mut s = three_member_spec();
14944        s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
14945        let err = s.validate().unwrap_err();
14946        assert!(
14947            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14948                if path == "/api/my cart" && reason.contains("whitespace")),
14949            "got {err:?}"
14950        );
14951    }
14952
14953    #[test]
14954    fn rejects_entrada_path_with_tab() {
14955        let mut s = three_member_spec();
14956        s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
14957        let err = s.validate().unwrap_err();
14958        assert!(
14959            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14960                if path == "/api/\tcart" && reason.contains("whitespace")),
14961            "got {err:?}"
14962        );
14963    }
14964
14965    #[test]
14966    fn rejects_entrada_path_with_control_char() {
14967        // 0x01 (SOH) — a non-whitespace control char surfaces the
14968        // distinct "control character" reason arm, separate from
14969        // the whitespace arm. Pinned so a future refactor that
14970        // collapses the two arms can't accidentally drop the more
14971        // self-locating diagnostic.
14972        let mut s = three_member_spec();
14973        s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
14974        let err = s.validate().unwrap_err();
14975        assert!(
14976            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14977                if path == "/api/\x01cart" && reason.contains("control character")),
14978            "got {err:?}"
14979        );
14980    }
14981
14982    #[test]
14983    fn rejects_entrada_path_with_non_ascii() {
14984        // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
14985        // unreserved-set rule rejects. The Gateway API webhook
14986        // rejects literal non-ASCII bytes; percent-encoding is the
14987        // only way to author non-ASCII in a path.
14988        let mut s = three_member_spec();
14989        s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
14990        let err = s.validate().unwrap_err();
14991        assert!(
14992            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14993                if path == "/api/café" && reason.contains("non-ASCII")),
14994            "got {err:?}"
14995        );
14996    }
14997
14998    #[test]
14999    fn rejects_entrada_path_with_consecutive_slashes() {
15000        let mut s = three_member_spec();
15001        s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
15002        let err = s.validate().unwrap_err();
15003        assert!(
15004            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15005                if path == "/api//cart" && reason.contains("consecutive `/`")),
15006            "got {err:?}"
15007        );
15008    }
15009
15010    #[test]
15011    fn rejects_entrada_path_with_dot_segment() {
15012        let mut s = three_member_spec();
15013        s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
15014        let err = s.validate().unwrap_err();
15015        assert!(
15016            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15017                if path == "/api/./cart" && reason.contains("`.` segment")),
15018            "got {err:?}"
15019        );
15020    }
15021
15022    #[test]
15023    fn rejects_entrada_path_with_trailing_dot_segment() {
15024        // The bare `/.` and the trailing `/foo/.` are both rejected
15025        // by the Gateway API webhook; pinned separately so a future
15026        // narrowing that catches only the inner form surfaces here.
15027        let mut s = three_member_spec();
15028        s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
15029        let err = s.validate().unwrap_err();
15030        assert!(
15031            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15032                if path == "/api/." && reason.contains("`.` segment")),
15033            "got {err:?}"
15034        );
15035    }
15036
15037    #[test]
15038    fn rejects_entrada_path_with_parent_segment() {
15039        let mut s = three_member_spec();
15040        s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
15041        let err = s.validate().unwrap_err();
15042        assert!(
15043            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15044                if path == "/api/../etc" && reason.contains("`..` parent-segment")),
15045            "got {err:?}"
15046        );
15047    }
15048
15049    #[test]
15050    fn rejects_entrada_path_with_trailing_parent_segment() {
15051        // Trailing `/..` — symmetric arm of the parent-segment rule,
15052        // pinned separately so a future relaxation that only checks
15053        // the inner form (`/../`) surfaces here.
15054        let mut s = three_member_spec();
15055        s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
15056        let err = s.validate().unwrap_err();
15057        assert!(
15058            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15059                if path == "/api/.." && reason.contains("`..` parent-segment")),
15060            "got {err:?}"
15061        );
15062    }
15063
15064    #[test]
15065    fn rejects_entrada_path_too_long() {
15066        // 1025-byte path — one over the Gateway API HTTPPathMatch.value
15067        // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
15068        // ASCII-alphanumeric body so only the length rule fires.
15069        let mut s = three_member_spec();
15070        let big = format!("/api/{}", "a".repeat(1020));
15071        assert_eq!(big.len(), 1025);
15072        s.entrada.as_mut().unwrap().paths = vec![big.clone()];
15073        let err = s.validate().unwrap_err();
15074        assert!(
15075            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15076                if path == &big && reason.contains("max length of 1024")),
15077            "got {err:?}"
15078        );
15079    }
15080
15081    #[test]
15082    fn entrada_path_max_length_validates() {
15083        // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
15084        // maxLength cap. Boundary pin: drift in the cap surfaces here
15085        // and at `rejects_entrada_path_too_long` simultaneously.
15086        let mut s = three_member_spec();
15087        let big = format!("/api/{}", "a".repeat(1019));
15088        assert_eq!(big.len(), 1024);
15089        s.entrada.as_mut().unwrap().paths = vec![big];
15090        s.validate().unwrap();
15091    }
15092
15093    #[test]
15094    fn entrada_accepts_canonical_paths() {
15095        // Positive-control sweep — every form the Gateway API
15096        // apiserver accepts must round-trip through validate. Covers
15097        // the root catch-all, plain paths, dot-prefixed segments
15098        // (hidden-file-style, distinct from `.` and `..` segments
15099        // which are rejected), digit-bearing segments, the canonical
15100        // route-template `:param` form (`:` is RFC 3986 reserved-set
15101        // valid in paths), trailing-slash form, percent-encoded
15102        // segments, and an interior `..` *substring* (`/foo..bar` is
15103        // not the `..` segment and is allowed).
15104        for path in [
15105            "/",
15106            "/api/cart",
15107            "/healthz",
15108            "/api/.config",
15109            "/v1/products",
15110            "/products/:id",
15111            "/api/cart/",
15112            "/api/caf%C3%A9",
15113            "/foo..bar",
15114            "/...",
15115        ] {
15116            let mut s = three_member_spec();
15117            s.entrada.as_mut().unwrap().paths = vec![path.into()];
15118            s.validate()
15119                .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
15120        }
15121    }
15122
15123    #[test]
15124    fn entrada_path_empty_takes_precedence_over_invalid() {
15125        // Ordering pin: `EntradaPathEmpty` is the more self-locating
15126        // diagnostic on `""` and must lead — `validate_entrada_path`
15127        // is only reached after the empty-check fires at the call
15128        // site. (The predicate itself defends against direct
15129        // invocation by returning the same error on `""`.)
15130        let mut s = three_member_spec();
15131        s.entrada.as_mut().unwrap().paths = vec!["".into()];
15132        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
15133    }
15134
15135    #[test]
15136    fn entrada_path_not_absolute_takes_precedence_over_invalid() {
15137        // Ordering pin: a path without a leading `/` surfaces the
15138        // narrower `EntradaPathNotAbsolute` diagnostic first; the
15139        // value-shape gate is only consulted on paths that already
15140        // satisfy the absolute-prefix invariant.
15141        let mut s = three_member_spec();
15142        // `bad path` would fire the whitespace rule under the
15143        // value-shape gate, but missing-leading-`/` is the more
15144        // self-locating diagnostic.
15145        s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
15146        let err = s.validate().unwrap_err();
15147        assert!(
15148            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
15149            "got {err:?}"
15150        );
15151    }
15152
15153    #[test]
15154    fn entrada_path_invalid_fires_before_duplicate_check() {
15155        // Ordering pin: a malformed path on the *first* entry of a
15156        // would-be duplicate pair fires the value-shape gate before
15157        // the duplicate gate, mirroring the
15158        // `placement_cluster_invalid_fires_before_duplicate_check`
15159        // (6cbb900) pattern on the peer axis.
15160        let mut s = three_member_spec();
15161        s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
15162        let err = s.validate().unwrap_err();
15163        assert!(
15164            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
15165            "got {err:?}"
15166        );
15167    }
15168
15169    #[test]
15170    fn entrada_path_diagnostic_carries_offending_path() {
15171        // Diagnostic-shape pin — the offending path + a non-empty
15172        // reason flow through verbatim so the author can grep their
15173        // caixa.lisp for `:paths` and fix it in one edit. Same shape
15174        // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
15175        let mut s = three_member_spec();
15176        s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
15177        let err = s.validate().unwrap_err();
15178        match err {
15179            AplicacaoError::EntradaPathInvalid { path, reason } => {
15180                assert_eq!(path, "/api?q=1");
15181                assert!(!reason.is_empty(), "reason field must be non-empty");
15182            }
15183            other => panic!("expected EntradaPathInvalid, got {other:?}"),
15184        }
15185    }
15186
15187    #[test]
15188    fn rejects_entrada_path_with_curly_brace_template_form() {
15189        // Per-axis pin on the shared `is_gateway_api_http_path`
15190        // reserved-byte arm: the canonical "I wrote an OpenAPI
15191        // path-template `{id}` instead of the Gateway API `:id` form"
15192        // footgun the K8s apiserver would otherwise catch at admission
15193        // time on every `HTTPRoute.spec.rules[].matches[].path.value`
15194        // landing site, far from the caixa.lisp. Surfaces as
15195        // `EntradaPathInvalid` carrying the offending path verbatim
15196        // plus the canonical `%7B`/`%7D` percent-encoding remediation
15197        // — the substrate-side `gateway_api_http_path_rejects_every_
15198        // reserved_printable_ascii_byte` predicate-level sweep pins the
15199        // full eleven-byte set; this per-axis pin confirms the
15200        // diagnostic flows through to the `EntradaPathInvalid` variant.
15201        let mut s = three_member_spec();
15202        s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
15203        let err = s.validate().unwrap_err();
15204        assert!(
15205            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15206                if path == "/api/cart/{id}"
15207                    && reason.contains("reserved character")
15208                    && reason.contains("'{'")
15209                    && reason.contains("%7B")),
15210            "got {err:?}"
15211        );
15212    }
15213
15214    #[test]
15215    fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
15216        // Per-axis peer of `rejects_entrada_path_with_curly_brace_
15217        // template_form` on the sibling `:contratos :endpoint` axis.
15218        // Same shared `is_gateway_api_http_path` reserved-byte arm
15219        // fires through `ContratoEndpointInvalid`, with the offending
15220        // endpoint + `:de` + `:para` + reason flowing through verbatim.
15221        // Pins that the lifted predicate's tightening lands on both
15222        // caller axes simultaneously — one source of truth for the
15223        // Gateway API HTTPPathMatch.value accepted set.
15224        let err = contrato_endpoint_err("/api/cart/{id}");
15225        assert!(
15226            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
15227                if endpoint == "/api/cart/{id}"
15228                    && reason.contains("reserved character")
15229                    && reason.contains("'{'")
15230                    && reason.contains("%7B")),
15231            "got {err:?}"
15232        );
15233    }
15234
15235    // ── :entrada :host value-shape gate ──────────────────────────────
15236    //
15237    // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
15238    // the sibling `:host` axis. Every authoring footgun the K8s
15239    // Gateway API v1 apiserver would catch at admission time becomes
15240    // a caixa-build-time `EntradaHostInvalid` with the offending
15241    // `:host` named verbatim. Same diagnostic shape as
15242    // `MembroVersaoInvalid` (9888b13).
15243
15244    #[test]
15245    fn rejects_entrada_host_with_scheme() {
15246        // Fail-before-pass-after pin — pre-gate codebases silently
15247        // accepted `https://…` and the apiserver rejected it at apply
15248        // time with no source citation.
15249        let mut s = three_member_spec();
15250        s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
15251        let err = s.validate().unwrap_err();
15252        assert!(
15253            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
15254                if host == "https://checkout.quero.cloud"),
15255            "got {err:?}"
15256        );
15257    }
15258
15259    #[test]
15260    fn rejects_entrada_host_with_port() {
15261        // The `:8080` port suffix is the canonical "I forgot the port
15262        // belongs in `:entrada :port`" footgun. The top-level `:` arm
15263        // (introduced after the per-label loop-only impl silently
15264        // surfaced a deep "label \"cloud:8080\" contains invalid
15265        // character ':'" leak) names the canonical fix verbatim — the
15266        // `:entrada :port` slot.
15267        let mut s = three_member_spec();
15268        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
15269        let err = s.validate().unwrap_err();
15270        assert!(
15271            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
15272                if host == "checkout.quero.cloud:8080"
15273                && reason.contains(":entrada :port")),
15274            "got {err:?}"
15275        );
15276    }
15277
15278    #[test]
15279    fn rejects_entrada_host_with_trailing_colon() {
15280        // Trailing `:` (e.g. an in-progress `:host "example.com:"`
15281        // edit) — the per-label loop would land it as a deep
15282        // "label \"com:\" must start and end with an alphanumeric"
15283        // / "contains invalid character ':'" leak. The top-level
15284        // `:` arm pre-empts with the canonical `:port` slot
15285        // diagnostic.
15286        let mut s = three_member_spec();
15287        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
15288        let err = s.validate().unwrap_err();
15289        assert!(
15290            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
15291                if host == "checkout.quero.cloud:"
15292                && reason.contains(":entrada :port")),
15293            "got {err:?}"
15294        );
15295    }
15296
15297    #[test]
15298    fn rejects_entrada_host_unbracketed_ipv6_literal() {
15299        // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
15300        // literals across the board (peer with `rejects_entrada_host_
15301        // ipv4_literal` above for the four-label-all-digit IPv4 arm).
15302        // Before this top-level `:` arm landed the per-label loop
15303        // surfaced a single-label byte-class diagnostic that named the
15304        // `:` byte but not the IP-literal prohibition. The top-level
15305        // `:` arm names both the `:port` slot and the IP-literal
15306        // prohibition verbatim, so an author whose `:host "2001:..."`
15307        // value lands here gets a self-locating fix either way.
15308        let mut s = three_member_spec();
15309        s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
15310        let err = s.validate().unwrap_err();
15311        assert!(
15312            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
15313                if host == "2001:db8::1"
15314                && reason.contains("IPv6")),
15315            "got {err:?}"
15316        );
15317    }
15318
15319    #[test]
15320    fn rejects_entrada_host_wildcard_with_port() {
15321        // Wildcard host with port suffix — the `*.` strip and the
15322        // per-label loop on `["foo", "quero", "cloud:8080"]` would
15323        // surface the deep byte-class leak. The top-level `:` arm sits
15324        // upstream of the `*.` strip, so it names the canonical `:port`
15325        // fix verbatim regardless of whether the host is wildcard-led.
15326        let mut s = three_member_spec();
15327        s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
15328        let err = s.validate().unwrap_err();
15329        assert!(
15330            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
15331                if host == "*.quero.cloud:8080"
15332                && reason.contains(":entrada :port")),
15333            "got {err:?}"
15334        );
15335    }
15336
15337    #[test]
15338    fn rejects_entrada_host_with_path() {
15339        let mut s = three_member_spec();
15340        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
15341        let err = s.validate().unwrap_err();
15342        assert!(
15343            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
15344                if host == "checkout.quero.cloud/api"),
15345            "got {err:?}"
15346        );
15347    }
15348
15349    #[test]
15350    fn rejects_entrada_host_with_uppercase() {
15351        // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
15352        // rejected, not silently lower-cased.
15353        let mut s = three_member_spec();
15354        s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
15355        let err = s.validate().unwrap_err();
15356        assert!(
15357            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15358                if reason.contains("uppercase")),
15359            "got {err:?}"
15360        );
15361    }
15362
15363    #[test]
15364    fn rejects_entrada_host_with_underscore() {
15365        // RFC 1123 allows `[a-z0-9-]` only; underscore is the
15366        // canonical "I'm thinking of HTTP cookies / SRV records" leak.
15367        let mut s = three_member_spec();
15368        s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
15369        let err = s.validate().unwrap_err();
15370        assert!(
15371            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15372                if reason.contains('_')),
15373            "got {err:?}"
15374        );
15375    }
15376
15377    #[test]
15378    fn rejects_entrada_host_ipv4_literal() {
15379        // Gateway API v1 explicitly forbids IP literals as Hostnames.
15380        let mut s = three_member_spec();
15381        s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
15382        let err = s.validate().unwrap_err();
15383        assert!(
15384            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15385                if reason.contains("IPv4")),
15386            "got {err:?}"
15387        );
15388    }
15389
15390    #[test]
15391    fn rejects_entrada_host_with_trailing_dot() {
15392        // The Gateway API regex anchors at end-of-string with no
15393        // trailing `.` allowance — the FQDN root-dot form is rejected.
15394        let mut s = three_member_spec();
15395        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
15396        let err = s.validate().unwrap_err();
15397        assert!(
15398            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
15399                if host == "checkout.quero.cloud."),
15400            "got {err:?}"
15401        );
15402    }
15403
15404    #[test]
15405    fn rejects_entrada_host_with_leading_dot() {
15406        let mut s = three_member_spec();
15407        s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
15408        let err = s.validate().unwrap_err();
15409        assert!(
15410            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15411                if reason.contains("empty label")),
15412            "got {err:?}"
15413        );
15414    }
15415
15416    #[test]
15417    fn rejects_entrada_host_with_consecutive_dots() {
15418        let mut s = three_member_spec();
15419        s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
15420        let err = s.validate().unwrap_err();
15421        assert!(
15422            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15423                if reason.contains("empty label")),
15424            "got {err:?}"
15425        );
15426    }
15427
15428    #[test]
15429    fn rejects_entrada_host_with_leading_hyphen_label() {
15430        let mut s = three_member_spec();
15431        s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
15432        let err = s.validate().unwrap_err();
15433        assert!(
15434            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15435                if reason.contains("alphanumeric")),
15436            "got {err:?}"
15437        );
15438    }
15439
15440    #[test]
15441    fn rejects_entrada_host_with_trailing_hyphen_label() {
15442        let mut s = three_member_spec();
15443        s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
15444        let err = s.validate().unwrap_err();
15445        assert!(
15446            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15447                if reason.contains("alphanumeric")),
15448            "got {err:?}"
15449        );
15450    }
15451
15452    #[test]
15453    fn rejects_entrada_host_with_inner_wildcard() {
15454        // Gateway API allows `*` only as the first label (`*.foo`);
15455        // any inner or trailing `*` is rejected.
15456        let mut s = three_member_spec();
15457        s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
15458        let err = s.validate().unwrap_err();
15459        assert!(
15460            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15461                if reason.contains("wildcard")),
15462            "got {err:?}"
15463        );
15464    }
15465
15466    #[test]
15467    fn rejects_entrada_host_bare_wildcard() {
15468        // `*.` with no domain is meaningless; Gateway API rejects it.
15469        let mut s = three_member_spec();
15470        s.entrada.as_mut().unwrap().host = "*.".into();
15471        let err = s.validate().unwrap_err();
15472        assert!(
15473            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15474                if reason.contains("wildcard")),
15475            "got {err:?}"
15476        );
15477    }
15478
15479    #[test]
15480    fn rejects_entrada_host_with_whitespace() {
15481        let mut s = three_member_spec();
15482        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
15483        let err = s.validate().unwrap_err();
15484        assert!(
15485            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15486                if reason.contains("whitespace")),
15487            "got {err:?}"
15488        );
15489    }
15490
15491    #[test]
15492    fn rejects_entrada_host_space_names_offending_byte() {
15493        // Embedded space in the `:entrada :host` axis surfaces the
15494        // byte-naming diagnostic through the lifted
15495        // `find_ascii_whitespace_byte` predicate. Peer with the
15496        // sibling `parse_rejects_leading_whitespace` pins on
15497        // `supervisor::duration_codec` (a7ae622) — same "the
15498        // diagnostic carries the offending byte's `0x{b:02x}` shape"
15499        // discipline extended from the shared duration codec to the
15500        // Gateway API v1 Hostname axis.
15501        let mut s = three_member_spec();
15502        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
15503        let err = s.validate().unwrap_err();
15504        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15505            panic!("expected EntradaHostInvalid, got {err:?}");
15506        };
15507        assert!(
15508            reason.contains("ASCII whitespace byte"),
15509            "expected byte-naming diagnostic, got {reason:?}"
15510        );
15511        assert!(
15512            reason.contains("0x20"),
15513            "expected offending space byte 0x20, got {reason:?}"
15514        );
15515    }
15516
15517    #[test]
15518    fn rejects_entrada_host_tab_names_offending_byte() {
15519        // Embedded tab byte in the `:entrada :host` axis — the
15520        // canonical paste-from-YAML-block-scalar / paste-from-
15521        // indented-doc footgun. Pins that the lifted predicate covers
15522        // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
15523        // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
15524        // not just the leading-space case the pre-lift `.bytes().any`
15525        // arm's opaque "must not contain whitespace" reason already
15526        // covered. Peer with `parse_rejects_tab_byte` on
15527        // `supervisor::duration_codec` (a7ae622).
15528        let mut s = three_member_spec();
15529        s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
15530        let err = s.validate().unwrap_err();
15531        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15532            panic!("expected EntradaHostInvalid, got {err:?}");
15533        };
15534        assert!(
15535            reason.contains("ASCII whitespace byte"),
15536            "expected byte-naming diagnostic, got {reason:?}"
15537        );
15538        assert!(
15539            reason.contains("0x09"),
15540            "expected offending tab byte 0x09, got {reason:?}"
15541        );
15542    }
15543
15544    #[test]
15545    fn rejects_entrada_host_lf_names_offending_byte() {
15546        // Embedded LF byte in the `:entrada :host` axis — the
15547        // canonical paste-from-shell-heredoc / paste-from-multiline-
15548        // doc footgun the caixa-mesh YAML emitter would silently
15549        // reinterpret at the Gateway API v1 HTTPRoute admission
15550        // layer (an embedded LF byte in a YAML plain scalar either
15551        // truncates the value at the emitter or crashes the parser
15552        // on the k8s-apiserver side). Pins the third representative
15553        // of the full ASCII-whitespace set through the shared
15554        // predicate.
15555        let mut s = three_member_spec();
15556        s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
15557        let err = s.validate().unwrap_err();
15558        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15559            panic!("expected EntradaHostInvalid, got {err:?}");
15560        };
15561        assert!(
15562            reason.contains("ASCII whitespace byte"),
15563            "expected byte-naming diagnostic, got {reason:?}"
15564        );
15565        assert!(
15566            reason.contains("0x0a"),
15567            "expected offending LF byte 0x0a, got {reason:?}"
15568        );
15569    }
15570
15571    #[test]
15572    fn rejects_entrada_host_nbsp_names_offending_codepoint() {
15573        // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
15574        // axis — the canonical paste-from-typography /
15575        // paste-from-word-processor footgun. Before the non-ASCII
15576        // Unicode `White_Space` scan lifted through the shared
15577        // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
15578        // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
15579        // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
15580        // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
15581        // with the far-from-source `label "…" must start and end
15582        // with an alphanumeric` diagnostic — burying the
15583        // paste-from-typography origin under a label-shape leak.
15584        // Peer with the sibling non-ASCII-whitespace pins at
15585        // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
15586        // — 1b75b38), `limits::parse_duration`,
15587        // `limits::parse_millicores`, and the shared duration codec
15588        // — same "the diagnostic carries the offending Unicode
15589        // codepoint's `U+XXXX` shape" discipline extended from every
15590        // typed-magnitude codec to the Gateway API v1 Hostname axis.
15591        let mut s = three_member_spec();
15592        s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
15593        let err = s.validate().unwrap_err();
15594        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15595            panic!("expected EntradaHostInvalid, got {err:?}");
15596        };
15597        assert!(
15598            reason.contains("non-ASCII Unicode whitespace character"),
15599            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
15600        );
15601        assert!(
15602            reason.contains("U+00A0"),
15603            "expected offending NBSP codepoint U+00A0, got {reason:?}"
15604        );
15605    }
15606
15607    #[test]
15608    fn rejects_entrada_host_line_separator_names_offending_codepoint() {
15609        // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
15610        // `:entrada :host` axis — the canonical paste-from-web-doc /
15611        // paste-from-published-HTML footgun. `char::is_whitespace`
15612        // returns true for `U+2028` per the Unicode `White_Space`
15613        // property, so `str::trim` at any downstream site would
15614        // silently strip it — same drift class as NBSP but on a
15615        // different codepoint region. Pins the second representative
15616        // (non-Latin-1 `char::is_whitespace` member) through the
15617        // shared predicate. Peer with
15618        // `parse_byte_size_rejects_internal_line_separator` on
15619        // `limits::parse_byte_size` (1b75b38).
15620        let mut s = three_member_spec();
15621        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
15622        let err = s.validate().unwrap_err();
15623        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15624            panic!("expected EntradaHostInvalid, got {err:?}");
15625        };
15626        assert!(
15627            reason.contains("non-ASCII Unicode whitespace character"),
15628            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
15629        );
15630        assert!(
15631            reason.contains("U+2028"),
15632            "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
15633        );
15634    }
15635
15636    #[test]
15637    fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
15638        // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
15639        // labels in the `:entrada :host` axis — the canonical
15640        // paste-from-CJK-typography footgun (CJK IMEs default to
15641        // full-width whitespace when the space bar is pressed in
15642        // Japanese / Chinese input modes). Pins the third
15643        // representative of the non-ASCII Unicode `White_Space` set
15644        // through the shared predicate: the CJK block, distinct from
15645        // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
15646        // SEPARATOR `U+2028` — covering the same axis breadth the
15647        // sibling `parse_byte_size_rejects_trailing_ideographic_space`
15648        // (1b75b38) pins on `limits::parse_byte_size`.
15649        let mut s = three_member_spec();
15650        s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
15651        let err = s.validate().unwrap_err();
15652        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15653            panic!("expected EntradaHostInvalid, got {err:?}");
15654        };
15655        assert!(
15656            reason.contains("non-ASCII Unicode whitespace character"),
15657            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
15658        );
15659        assert!(
15660            reason.contains("U+3000"),
15661            "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
15662        );
15663    }
15664
15665    #[test]
15666    fn rejects_entrada_host_too_long() {
15667        // Total length cap = 253; build a 254-byte host out of two
15668        // 63-byte labels + one 62-byte label + dots.
15669        let mut s = three_member_spec();
15670        let big = format!(
15671            "{}.{}.{}.{}",
15672            "a".repeat(63),
15673            "b".repeat(63),
15674            "c".repeat(63),
15675            "d".repeat(254 - 63 * 3 - 3)
15676        );
15677        assert_eq!(big.len(), 254);
15678        s.entrada.as_mut().unwrap().host = big;
15679        let err = s.validate().unwrap_err();
15680        assert!(
15681            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15682                if reason.contains("max length of 253")),
15683            "got {err:?}"
15684        );
15685    }
15686
15687    #[test]
15688    fn rejects_entrada_host_label_too_long() {
15689        let mut s = three_member_spec();
15690        // 64-byte label — one over the per-label cap.
15691        s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
15692        let err = s.validate().unwrap_err();
15693        assert!(
15694            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15695                if reason.contains("label max length of 63")),
15696            "got {err:?}"
15697        );
15698    }
15699
15700    #[test]
15701    fn entrada_host_diagnostic_carries_offending_host() {
15702        // Diagnostic-shape pin — the offending host + a non-empty
15703        // reason flow through verbatim so the author can grep their
15704        // caixa.lisp for `:host "<host>"` and fix it in one edit.
15705        let mut s = three_member_spec();
15706        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
15707        let err = s.validate().unwrap_err();
15708        match err {
15709            AplicacaoError::EntradaHostInvalid { host, reason } => {
15710                assert_eq!(host, "checkout.quero.cloud:8080");
15711                assert!(!reason.is_empty(), "reason field must be non-empty");
15712            }
15713            other => panic!("expected EntradaHostInvalid, got {other:?}"),
15714        }
15715    }
15716
15717    #[test]
15718    fn entrada_host_empty_takes_precedence_over_invalid() {
15719        // Ordering pin: `EmptyEntradaHost` is the more self-locating
15720        // diagnostic on `""` and must lead — `validate_entrada_host`
15721        // is only reached after the empty-check fires at the call
15722        // site. (The predicate itself defends against direct
15723        // invocation by returning the same error on `""`.)
15724        let mut s = three_member_spec();
15725        s.entrada.as_mut().unwrap().host = String::new();
15726        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
15727    }
15728
15729    #[test]
15730    fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
15731        // Ordering pin: a missing :para member is the more
15732        // self-locating diagnostic and fires before the host gate.
15733        let mut s = three_member_spec();
15734        let e = s.entrada.as_mut().unwrap();
15735        e.para = "ghost".into();
15736        e.host = "BAD HOST".into();
15737        let err = s.validate().unwrap_err();
15738        assert!(
15739            matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
15740            "got {err:?}"
15741        );
15742    }
15743
15744    #[test]
15745    fn entrada_host_invalid_fires_before_port_zero() {
15746        // Ordering pin: the host gate fires before the port gate so
15747        // a malformed host is named even when the port is also wrong.
15748        let mut s = three_member_spec();
15749        let e = s.entrada.as_mut().unwrap();
15750        e.host = "Checkout.quero.cloud".into();
15751        e.port = 0;
15752        let err = s.validate().unwrap_err();
15753        assert!(
15754            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
15755                if host == "Checkout.quero.cloud"),
15756            "got {err:?}"
15757        );
15758    }
15759
15760    #[test]
15761    fn entrada_accepts_canonical_hosts() {
15762        // Positive-control sweep — every form the Gateway API
15763        // apiserver accepts must round-trip through validate. Covers
15764        // a plain DNS subdomain, a leading wildcard, a single-label
15765        // host (cluster-internal), a max-length-edge label, a
15766        // hyphen-bearing label, and a Punycode IDN label.
15767        for host in [
15768            "checkout.quero.cloud",
15769            "*.quero.cloud",
15770            "checkout",
15771            // 63-byte label — exactly the per-label cap.
15772            "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
15773            "foo-bar.quero.cloud",
15774            // Punycode IDN — valid because the author pre-encoded.
15775            "xn--bcher-kva.example.com",
15776        ] {
15777            let mut s = three_member_spec();
15778            s.entrada.as_mut().unwrap().host = host.into();
15779            s.validate()
15780                .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
15781        }
15782    }
15783
15784    #[test]
15785    fn entrada_host_max_length_validates() {
15786        // 253-byte host is the cap exactly — must validate. Build a
15787        // 253-byte host out of three 63-byte labels + one 61-byte
15788        // label + 3 dots = 252 bytes, then pad one byte to 253.
15789        let mut s = three_member_spec();
15790        let host = format!(
15791            "{}.{}.{}.{}",
15792            "a".repeat(63),
15793            "b".repeat(63),
15794            "c".repeat(63),
15795            "d".repeat(253 - 63 * 3 - 3)
15796        );
15797        assert_eq!(host.len(), 253);
15798        s.entrada.as_mut().unwrap().host = host;
15799        s.validate().unwrap();
15800    }
15801
15802    #[test]
15803    fn entrada_host_total_length_cap_threads_lifted_render_const() {
15804        // Cross-crate-side pin: the aplicacao-side `:entrada :host`
15805        // total-length gate now reads the K8s Gateway API v1 Hostname
15806        // `maxLength: 253` cap from the lifted
15807        // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
15808        // of truth — the same constant every future Gateway-API-Hostname
15809        // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
15810        // materializer's per-host validator, the future per-`Certificate`
15811        // SAN emitter for cert-manager, the multi-`:entrada`
15812        // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
15813        // from. Before the lift, the aplicacao-side reader consumed a
15814        // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
15815        // 253-byte value as the peer render-side canonical bounds
15816        // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
15817        // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
15818        // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
15819        // module boundary — a future 253-byte drift on either side would
15820        // silently split into two axes' worth of admission-schema mismatch
15821        // without a build-time signal. Pin the cap through a fresh 254-
15822        // byte host that hits the total-length arm, then read the reason
15823        // for the exact byte count the shared constant carries: any future
15824        // regression on the lift (a private alias reintroduced, a hard-
15825        // coded literal at the arm, a mismatch between the aplicacao-side
15826        // and render-side canonicals) surfaces as this pin's diagnostic
15827        // failing to match, not as a per-cluster admission rejection far
15828        // from the caixa.lisp source line.
15829        let mut s = three_member_spec();
15830        let over_cap = format!(
15831            "{}.{}.{}.{}",
15832            "a".repeat(63),
15833            "b".repeat(63),
15834            "c".repeat(63),
15835            "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
15836        );
15837        assert_eq!(
15838            over_cap.len(),
15839            crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
15840        );
15841        s.entrada.as_mut().unwrap().host = over_cap;
15842        let err = s.validate().unwrap_err();
15843        match err {
15844            AplicacaoError::EntradaHostInvalid { reason, .. } => {
15845                let needle = format!(
15846                    "max length of {} bytes",
15847                    crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
15848                );
15849                assert!(
15850                    reason.contains(&needle),
15851                    "diagnostic must name the lifted \
15852                     GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
15853                );
15854            }
15855            other => panic!("expected EntradaHostInvalid, got {other:?}"),
15856        }
15857    }
15858
15859    #[test]
15860    fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
15861        // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
15862        // on the per-label-cap axis. Before the lift, the aplicacao-side
15863        // per-label arm consumed a private const alias
15864        // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
15865        // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
15866        // split from it at the module boundary — every `.`-separated
15867        // label in a Gateway API v1 Hostname is a DNS-1123 label under
15868        // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
15869        // so the private alias's 63 and the canonical const's 63 were
15870        // pinning the same underlying rule twice. Pin the cap through a
15871        // 64-byte label that hits the per-label arm, then read the reason
15872        // for the exact byte count the shared constant carries: any
15873        // future drift on either side (a private alias reintroduced, a
15874        // hard-coded literal at the arm, a mismatch between the two
15875        // 63-byte pins) surfaces at this pin's diagnostic rather than at
15876        // a per-cluster admission rejection whose "field is invalid"
15877        // opacity misframes the root cause.
15878        let mut s = three_member_spec();
15879        let over_cap_label = format!(
15880            "{}.quero.cloud",
15881            "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
15882        );
15883        s.entrada.as_mut().unwrap().host = over_cap_label;
15884        let err = s.validate().unwrap_err();
15885        match err {
15886            AplicacaoError::EntradaHostInvalid { reason, .. } => {
15887                let needle = format!(
15888                    "label max length of {} bytes",
15889                    crate::render::DNS_1123_LABEL_MAX_LEN,
15890                );
15891                assert!(
15892                    reason.contains(&needle),
15893                    "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
15894                     cap verbatim on the per-label arm, got: {reason:?}",
15895                );
15896            }
15897            other => panic!("expected EntradaHostInvalid, got {other:?}"),
15898        }
15899    }
15900
15901    #[test]
15902    fn entrada_with_empty_paths_validates() {
15903        // Empty `:paths` is the documented "match every path" form;
15904        // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
15905        let mut s = three_member_spec();
15906        s.entrada.as_mut().unwrap().paths = vec![];
15907        s.validate().unwrap();
15908    }
15909
15910    #[test]
15911    fn entrada_root_path_validates() {
15912        // The author-supplied bare-root `:entrada :paths` entry is the
15913        // same byte-shape the peer emit-side catch-all constant
15914        // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
15915        // the author's `:paths` list is empty — sweeping the test-side
15916        // probe literal onto the lifted const closes the two-axis pin
15917        // (author-side admit + emit-side canonical fallback) around
15918        // one `&'static str`, so a future rebrand of the catch-all
15919        // reaches both consumers by construction. Peer to
15920        // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
15921        // on the canonical-literal pin surface.
15922        let mut s = three_member_spec();
15923        s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
15924        s.validate().unwrap();
15925    }
15926
15927    #[test]
15928    fn placement_strategy_variants_round_trip() {
15929        for s in [
15930            PlacementStrategy::SingleNode,
15931            PlacementStrategy::Replicated,
15932            PlacementStrategy::Sharded,
15933        ] {
15934            let p = Placement {
15935                estrategia: s,
15936                clusters: vec!["rio".into()],
15937                affinity: None,
15938                // Route the paired `:shard-key` fixture-builder through the
15939                // typed cross-slot invariant predicate
15940                // [`PlacementStrategy::requires_shard_key`] rather than the
15941                // [`gen_platform::IsVariant`]-derived [`Self::is_sharded`]
15942                // arm-identity predicate — the two answer the same
15943                // question under today's closed accept-set but a future
15944                // arm addition that consumed `:shard-key` under a
15945                // non-`Sharded` name would silently mis-attach the
15946                // fixture's `:shard-key` if the builder read through the
15947                // arm-identity predicate. The cross-slot-invariant
15948                // predicate migrates through one caixa-core edit on any
15949                // future arm addition; the fixture keeps producing a
15950                // `validate()`-passing round-trip by construction.
15951                shard_key: if s.requires_shard_key() {
15952                    Some("$key".into())
15953                } else {
15954                    None
15955                },
15956            };
15957            let json = serde_json::to_string(&p).unwrap();
15958            let back: Placement = serde_json::from_str(&json).unwrap();
15959            assert_eq!(back, p);
15960        }
15961    }
15962
15963    #[test]
15964    fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
15965        // The fail-before-pass-after pin: pre-lift there was no
15966        // single-source binding between the [`PlacementStrategy`]
15967        // variant name the `Serialize` derive emits and the byte-
15968        // string every downstream cluster-side dispatcher (the
15969        // `lareira-fleet-programs` aggregator's per-entry strategy
15970        // branch, the future `app-operator` reconciler, the M3
15971        // Adaptive compression pass's per-strategy weighting) probes
15972        // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
15973        // future `#[serde(rename_all = "kebab-case")]` attribute on
15974        // the enum — or a variant rename in the source — would
15975        // silently rebrand the emitted scalar under one spelling
15976        // while every downstream dispatcher still probed the other,
15977        // with the failure surfacing at the aggregator's dispatch
15978        // step or the operator's reconcile posture (workloads coming
15979        // up under the `default()` `Replicated` arm rather than the
15980        // typed slot's declared strategy) far from the source
15981        // rebrand commit and with no field naming the drift. Pinning
15982        // the two paths (the `Serialize` derive's serialized string
15983        // AND the [`PlacementStrategy::as_str`] helper) to the same
15984        // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
15985        // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
15986        // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
15987        // makes any future drift on either endpoint fail here at
15988        // caixa-core build time.
15989        for (variant, expected) in [
15990            (
15991                PlacementStrategy::SingleNode,
15992                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15993            ),
15994            (
15995                PlacementStrategy::Replicated,
15996                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15997            ),
15998            (
15999                PlacementStrategy::Sharded,
16000                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
16001            ),
16002        ] {
16003            let json = serde_json::to_string(&variant).unwrap();
16004            assert_eq!(
16005                json,
16006                format!("\"{expected}\""),
16007                "PlacementStrategy::{variant:?} must serialize to {expected:?}"
16008            );
16009            assert_eq!(
16010                variant.as_str(),
16011                expected,
16012                "PlacementStrategy::{variant:?}.as_str() must return the lifted \
16013                 M3_PLACEMENT_ESTRATEGIA_* constant"
16014            );
16015        }
16016    }
16017
16018    #[test]
16019    fn m3_placement_estrategia_consts_are_pairwise_distinct() {
16020        // Cross-arm drift-detection pin on the M3
16021        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
16022        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
16023        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
16024        // scalar-value pentad: a future collapse of two canonical
16025        // variant byte-strings onto the same value (an accidental
16026        // copy-paste flip of
16027        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
16028        // read `"SingleNode"`, a per-arm rebrand that lands one const
16029        // without touching its paired peer) would silently reroute
16030        // every downstream operator's per-strategy dispatch onto the
16031        // sibling arm's reconcile branch and pass every
16032        // propagation-probe test that expected only the stale arm's
16033        // value — a `Replicated`-declared Aplicacao would come up
16034        // under the `SingleNode` primary-and-standby reconcile
16035        // posture, so every-cluster active-active workload would
16036        // silently collapse onto one-cluster-runs-at-a-time takeover
16037        // semantics against its declared strategy, with no field
16038        // naming the strategy-value drift root cause. Peer of the
16039        // sibling
16040        // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
16041        // (09ffb2d) /
16042        // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
16043        // (ccdf955) /
16044        // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
16045        // (d739850) distinctness pins on the sibling OTP-shape /
16046        // caixa-kind closed-set typed-enum discriminator axes — the
16047        // fourth (and structurally the M3 mesh-primitive-defining)
16048        // closed-set typed-enum axis to converge on the same
16049        // "pairwise-distinct-by-construction" discipline.
16050        //
16051        // Fail-before-pass-after locally verified by mutating
16052        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
16053        // also read `"SingleNode"` — this pin fires as expected;
16054        // restoring passes.
16055        let all = [
16056            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16057            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16058            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
16059        ];
16060        for (i, a) in all.iter().enumerate() {
16061            for (j, b) in all.iter().enumerate() {
16062                if i != j {
16063                    assert_ne!(
16064                        a, b,
16065                        "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
16066                         distinct — got duplicate {a:?} at indices {i} and {j}",
16067                    );
16068                }
16069            }
16070        }
16071    }
16072
16073    #[test]
16074    fn placement_strategy_display_routes_through_as_str_helper() {
16075        // The fail-before-pass-after pin: pre-lift the sibling
16076        // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
16077        // / [`crate::supervisor::RestartPolicy`] both carried a stable
16078        // [`std::fmt::Display`] surface via their
16079        // `#[discriminant(also_display)]` gen-platform derive, but
16080        // [`PlacementStrategy`] did not — every consumer reaching for
16081        // a strategy byte-string past the wire format had to pick
16082        // between three paths ([`PlacementStrategy::as_str`], the
16083        // `Serialize` derive's serialized string, or `format!("{v:?}")`
16084        // on the `Debug` derive), any two of which a future variant
16085        // rename or `#[serde(rename_all = "kebab-case")]` attribute
16086        // would silently desynchronize. Wiring [`std::fmt::Display`]
16087        // through [`PlacementStrategy::as_str`] closes the third path:
16088        // every `format!("{v}")` call reaches the same lifted
16089        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
16090        // and the [`PlacementStrategy::as_str`] helper already route
16091        // through, so a future variant rename lands at exactly one
16092        // place. Pin the routing here so a future
16093        // `impl std::fmt::Display for PlacementStrategy` reimplementation
16094        // that hand-rolls the arms instead of delegating to
16095        // [`PlacementStrategy::as_str`] fails at caixa-core build time.
16096        for variant in [
16097            PlacementStrategy::SingleNode,
16098            PlacementStrategy::Replicated,
16099            PlacementStrategy::Sharded,
16100        ] {
16101            assert_eq!(
16102                variant.to_string(),
16103                variant.as_str(),
16104                "PlacementStrategy::{variant:?} Display must route through \
16105                 PlacementStrategy::as_str (single source of truth: the lifted \
16106                 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
16107            );
16108        }
16109    }
16110
16111    #[test]
16112    fn placement_strategy_display_matches_serialized_wire_byte_string() {
16113        // The fail-before-pass-after pin on the second half of the
16114        // three-path convergence: `Display` (user-facing text) agrees
16115        // byte-for-byte with the `Serialize` derive's wire format
16116        // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
16117        // scalar) on every variant. Pre-lift the two paths were
16118        // structurally independent — a future
16119        // `#[serde(rename_all = "kebab-case")]` attribute on the enum
16120        // would silently rebrand the emitted wire scalar
16121        // (`single-node`, `replicated`, `sharded`) while every consumer
16122        // that pretty-prints the strategy (the M3 diagnostic templates,
16123        // the future `feira app graph` per-Aplicacao strategy line,
16124        // the future M4 CR materializer's admission-webhook rejection
16125        // body) would still emit the TitleCase form the `as_str` /
16126        // `Display` route returns, with the mismatch surfacing at
16127        // consumer parse time / operator dispatch time far from the
16128        // source rebrand commit. Pin the two paths byte-for-byte here
16129        // so any future serde-attribute or variant-rename drift is a
16130        // caixa-core-build-time test failure at this call, not a
16131        // silent per-consumer dispatch miss.
16132        for variant in [
16133            PlacementStrategy::SingleNode,
16134            PlacementStrategy::Replicated,
16135            PlacementStrategy::Sharded,
16136        ] {
16137            let wire = serde_json::to_string(&variant).unwrap();
16138            // Strip the outer `"…"` the JSON string form carries — the
16139            // wire scalar the K8s / YAML apiserver consumes is the
16140            // enclosed byte-string, not the quote wrapper.
16141            let unquoted = wire
16142                .strip_prefix('"')
16143                .and_then(|s| s.strip_suffix('"'))
16144                .expect("serialized PlacementStrategy is a JSON string");
16145            assert_eq!(
16146                variant.to_string(),
16147                unquoted,
16148                "PlacementStrategy::{variant:?} Display byte-string must match the \
16149                 Serialize derive's wire byte-string (three-path convergence: \
16150                 Display + as_str + Serialize all resolve to the same \
16151                 M3_PLACEMENT_ESTRATEGIA_* const)"
16152            );
16153        }
16154    }
16155
16156    #[test]
16157    fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
16158        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
16159        // derive on [`PlacementStrategy`]: for each of the three variants
16160        // exactly one of the generated `is_single_node` / `is_replicated`
16161        // / `is_sharded` predicates returns `true` and the other two
16162        // return `false`. Prior to this derive the three per-arm
16163        // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
16164        // (the `placement_strategy_variants_round_trip` fixture, the
16165        // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
16166        // fixture, and the
16167        // `validate_placement_reads_through_lifted_estrategia_accessor`
16168        // fixture) each open-coded a per-arm PartialEq compare against
16169        // the enum variant — three sites that expressed no compile-time
16170        // link back to the closed-set typed dispatch a future fourth
16171        // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
16172        // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
16173        // would have to thread through in lockstep or one fixture would
16174        // silently disagree with the others on which arms consume the
16175        // `:shard-key` axis. Peer of the sibling
16176        // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
16177        // / [`crate::supervisor::RestartPolicy`] /
16178        // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
16179        // the sibling closed-set typed-enum discriminator axes — extends
16180        // the same one-typed-dispatch-per-variant discipline onto the
16181        // fifth (and only remaining) closed-set typed-enum discriminator
16182        // on the caixa surface, closing the axis on the M3 mesh-slot
16183        // family.
16184        let rows: [(PlacementStrategy, [bool; 3]); 3] = [
16185            (PlacementStrategy::SingleNode, [true, false, false]),
16186            (PlacementStrategy::Replicated, [false, true, false]),
16187            (PlacementStrategy::Sharded, [false, false, true]),
16188        ];
16189        for (variant, expected) in rows {
16190            let observed = [
16191                variant.is_single_node(),
16192                variant.is_replicated(),
16193                variant.is_sharded(),
16194            ];
16195            assert_eq!(
16196                observed, expected,
16197                "PlacementStrategy::{variant:?} is_* predicates must partition \
16198                 the arm set (single_node, replicated, sharded); got {observed:?}"
16199            );
16200        }
16201    }
16202
16203    #[test]
16204    fn placement_strategy_is_variant_predicates_are_const_fn() {
16205        // The [`gen_platform::IsVariant`] derive emits `const fn`
16206        // predicates on the peer [`crate::CaixaKind`] +
16207        // [`crate::upgrade::UpgradeInstruction`] +
16208        // [`crate::supervisor::RestartStrategy`] +
16209        // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
16210        // pin the same posture on [`PlacementStrategy`] so a future
16211        // accidental downgrade to non-`const` (an added runtime helper
16212        // reachable only from a non-`const` context, a manual hand-rolled
16213        // `impl` that shadows the derive-generated method) trips at
16214        // caixa-core build time rather than surfacing as a downstream
16215        // `const`-context regression far from the derive declaration.
16216        const IS_SINGLE_NODE: bool = PlacementStrategy::SingleNode.is_single_node();
16217        const IS_REPLICATED: bool = PlacementStrategy::Replicated.is_replicated();
16218        const IS_SHARDED: bool = PlacementStrategy::Sharded.is_sharded();
16219        assert!(IS_SINGLE_NODE);
16220        assert!(IS_REPLICATED);
16221        assert!(IS_SHARDED);
16222    }
16223
16224    #[test]
16225    fn placement_strategy_requires_shard_key_partitions_the_arm_set() {
16226        // Fail-before-pass-after pin on the substrate-lifted
16227        // [`PlacementStrategy::requires_shard_key`] cross-slot-invariant
16228        // per-arm predicate: for each variant in the closed accept-set the
16229        // predicate returns `true` iff the variant consumes the paired
16230        // [`Placement::shard_key`] axis under
16231        // [`AplicacaoSpec::validate_placement`]'s `Sharded` ↔ non-`Sharded`
16232        // partition. Today the accept-set is the singleton `{Sharded}` —
16233        // `Sharded` is the Akka-style hash-keyed distribution arm
16234        // (MESH-COMPOSITION §II.4), `SingleNode` (Erlang/OTP takeover —
16235        // §II.1) and `Replicated` (active-active) refuse the axis through
16236        // [`AplicacaoError::ShardKeyOnNonSharded`].
16237        //
16238        // Pins the per-arm truth-table so a future arm addition (an
16239        // `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint the
16240        // roadmap names, a `WeightedShard` promotion the future M5
16241        // adaptive-placement engine acknowledges) that landed a variant
16242        // without extending this predicate's arm-set would surface as a
16243        // caixa-core build-time exhaustiveness error at the
16244        // `match self { … }` arm-fan below rather than a silent per-consumer
16245        // mis-classification at renderer emit time. The paired
16246        // [`Self::is_sharded`] `gen_platform::IsVariant`-derived arm-identity
16247        // predicate stays a distinct question — arm-identity (which the
16248        // sibling
16249        // [`placement_strategy_is_variant_predicates_partition_the_arm_set`]
16250        // pin already locks) is not cross-slot-invariant consumption; today
16251        // they trip on the same singleton but the pair migrates through
16252        // one caixa-core edit on any future arm addition.
16253        //
16254        // Peer of the sibling per-arm classifier pins
16255        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
16256        // (7b97d26) on the [`WitContract`] pre-projection WIT-shape axis
16257        // and the [`WitTarget::is_capability`] `gen_platform::IsVariant`-
16258        // derived paired predicate on the post-projection typed-view axis
16259        // — same "per-arm semantic-classification predicate paired with
16260        // the arm-identity predicate the derive already emits" discipline
16261        // extended onto the M3 mesh-slot `:placement :estrategia` ↔
16262        // `:placement :shard-key` cross-slot-invariant axis.
16263        let rows: [(PlacementStrategy, bool); 3] = [
16264            (PlacementStrategy::SingleNode, false),
16265            (PlacementStrategy::Replicated, false),
16266            (PlacementStrategy::Sharded, true),
16267        ];
16268        for (variant, expected) in rows {
16269            assert_eq!(
16270                variant.requires_shard_key(),
16271                expected,
16272                "PlacementStrategy::{variant:?}.requires_shard_key() must \
16273                 be {expected} (the substrate-canonical cross-slot invariant \
16274                 on the :placement :shard-key axis; today `Sharded` is the \
16275                 singleton consuming arm — MESH-COMPOSITION §II.4)",
16276            );
16277        }
16278    }
16279
16280    #[test]
16281    fn placement_strategy_requires_shard_key_is_const_fn() {
16282        // The [`PlacementStrategy::requires_shard_key`] cross-slot-
16283        // invariant per-arm predicate is declared `#[must_use] pub const
16284        // fn` — pin the `const`-eval posture here so a future accidental
16285        // downgrade to non-`const` (an added runtime helper reachable
16286        // only from a non-`const` context, a manual hand-rolled `impl`
16287        // that shadows the current three-arm `match self { … }` dispatch)
16288        // trips at caixa-core build time rather than surfacing as a
16289        // downstream `const`-context regression far from the declaration.
16290        // Same shape as the sibling
16291        // [`placement_strategy_is_variant_predicates_are_const_fn`] pin on
16292        // the peer [`gen_platform::IsVariant`]-derived arm-identity
16293        // predicate axis, but here the load-bearing assertions live in
16294        // module-scope `const _: () = assert!(…)` items so a violation
16295        // fails at compile time (const-eval trip) rather than test time —
16296        // strictly stronger than the runtime `assert!(CONST)` pattern the
16297        // sibling pin uses, and side-steps the
16298        // `clippy::assertions_on_constants` lint the runtime pattern
16299        // otherwise accumulates on the module baseline.
16300        //
16301        // The test body simply witnesses that the module-scope items
16302        // compiled and the runtime dispatch agrees with the const-eval
16303        // dispatch on every arm — the runtime read gives the test a
16304        // failure surface (rather than an empty test body clippy would
16305        // flag as a no-op).
16306        const REQUIRES_SINGLE_NODE: bool = PlacementStrategy::SingleNode.requires_shard_key();
16307        const REQUIRES_REPLICATED: bool = PlacementStrategy::Replicated.requires_shard_key();
16308        const REQUIRES_SHARDED: bool = PlacementStrategy::Sharded.requires_shard_key();
16309        assert_eq!(
16310            [REQUIRES_SINGLE_NODE, REQUIRES_REPLICATED, REQUIRES_SHARDED,],
16311            [
16312                PlacementStrategy::SingleNode.requires_shard_key(),
16313                PlacementStrategy::Replicated.requires_shard_key(),
16314                PlacementStrategy::Sharded.requires_shard_key(),
16315            ],
16316            "runtime and const-eval dispatch on \
16317             PlacementStrategy::requires_shard_key must agree on every arm",
16318        );
16319    }
16320
16321    #[test]
16322    fn placement_estrategia_accessor_is_const_fn() {
16323        // The [`Placement::estrategia`] per-`:placement` distribution-
16324        // strategy `Copy`-return scalar accessor is declared
16325        // `#[must_use] pub const fn` — matching the peer M3 mesh-slot
16326        // `Copy`-return accessor family ([`MeshPolicy::timeout`] /
16327        // [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
16328        // [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`]
16329        // on the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`]
16330        // / [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
16331        // [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
16332        // [`RateLimit`], every one a `pub const fn`). Pin the
16333        // `const`-eval posture here so a future accidental downgrade to
16334        // non-`const` (an added runtime helper reachable only from a
16335        // non-`const` context, a slot promotion to a non-`Copy` return
16336        // that would silently drop the `const` qualifier, a manual
16337        // hand-rolled shadow) trips at caixa-core build time rather
16338        // than surfacing as a downstream `const`-context regression far
16339        // from the declaration.
16340        //
16341        // Same shape as the sibling
16342        // [`placement_strategy_requires_shard_key_is_const_fn`] pin on
16343        // the peer [`PlacementStrategy::requires_shard_key`] `const fn`
16344        // predicate axis — the load-bearing witness lives in the
16345        // module-scope `const fn` wrapper `estrategia_via_const_fn`
16346        // below: a body that calls [`Placement::estrategia`] under a
16347        // `const fn` signature is well-formed only when the callee is
16348        // itself `const fn`, so any future accidental downgrade of
16349        // [`Placement::estrategia`] to non-`const` fails at caixa-core
16350        // build time (const-eval E0015 / E0658 depending on the arm),
16351        // strictly stronger than a runtime `assert!(CONST)` and
16352        // side-stepping the destructor-in-const restriction that
16353        // blocks direct `const _: PlacementStrategy = FIXTURE.estrategia()`
16354        // items on `Placement`'s `Vec<String>` / `Option<String>`
16355        // carriers.
16356        //
16357        // The runtime body witnesses that the const-eval-shaped
16358        // wrapper agrees with a direct call on every closed-set arm.
16359        const fn estrategia_via_const_fn(p: &Placement) -> PlacementStrategy {
16360            p.estrategia()
16361        }
16362        for estrategia in [
16363            PlacementStrategy::SingleNode,
16364            PlacementStrategy::Replicated,
16365            PlacementStrategy::Sharded,
16366        ] {
16367            let placement = Placement {
16368                estrategia,
16369                clusters: Vec::new(),
16370                affinity: None,
16371                shard_key: None,
16372            };
16373            assert_eq!(
16374                estrategia_via_const_fn(&placement),
16375                placement.estrategia(),
16376                "const-fn-wrapped and direct dispatch on \
16377                 Placement::estrategia must agree for {estrategia:?}",
16378            );
16379        }
16380    }
16381
16382    #[test]
16383    fn entrada_port_accessor_is_const_fn() {
16384        // The [`Entrada::port`] per-`:entrada` L4-port `Copy`-return
16385        // scalar accessor is declared `#[must_use] pub const fn` —
16386        // matching the peer M3 mesh-slot `Copy`-return accessor family
16387        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`] /
16388        // [`MeshPolicy::mtls_required`] / [`MeshPolicy::rate_limit`] /
16389        // [`MeshPolicy::circuit_breaker`] on the parent [`MeshPolicy`],
16390        // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
16391        // on the sibling [`CircuitBreaker`], [`RateLimit::rate`] /
16392        // [`RateLimit::window`] on the sibling [`RateLimit`], the
16393        // sibling per-`:placement` [`Placement::estrategia`] pinned by
16394        // [`placement_estrategia_accessor_is_const_fn`] above — every
16395        // one a `pub const fn`). Pin the `const`-eval posture here so
16396        // a future accidental downgrade to non-`const` (an added
16397        // runtime helper reachable only from a non-`const` context, an
16398        // `Option<u16>`-shape migration once the substrate grows
16399        // per-`:membros` heterogeneous listener ports that would
16400        // silently drop the `const` qualifier, a manual hand-rolled
16401        // shadow) trips at caixa-core build time rather than surfacing
16402        // as a downstream `const`-context regression far from the
16403        // declaration.
16404        //
16405        // Same shape as the sibling
16406        // [`placement_estrategia_accessor_is_const_fn`] pin above — the
16407        // load-bearing witness lives in the module-scope `const fn`
16408        // wrapper `port_via_const_fn`: a body that calls
16409        // [`Entrada::port`] under a `const fn` signature is well-formed
16410        // only when the callee is itself `const fn`, side-stepping the
16411        // destructor-in-const restriction that would otherwise block a
16412        // direct `const _: u16 = FIXTURE.port()` item on `Entrada`'s
16413        // `String` / `Vec<String>` carriers.
16414        //
16415        // The runtime body sweeps a representative port set spanning
16416        // the [`SERVICO_PORT_MIN`] floor, the substrate-canonical
16417        // [`DEFAULT_SERVICO_PORT`] default, and the top-edge `u16::MAX`
16418        // ceiling — the const-fn-wrapped call must agree with a direct
16419        // call on every fixture (a violation trips the test) and every
16420        // returned scalar must byte-equal the input `port` (a violation
16421        // means the accessor stopped being a raw field-return copy).
16422        const fn port_via_const_fn(e: &Entrada) -> u16 {
16423            e.port()
16424        }
16425        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, u16::MAX] {
16426            let entrada = Entrada {
16427                host: String::new(),
16428                para: String::new(),
16429                port,
16430                paths: Vec::new(),
16431            };
16432            assert_eq!(
16433                port_via_const_fn(&entrada),
16434                entrada.port(),
16435                "const-fn-wrapped and direct dispatch on Entrada::port \
16436                 must agree for port={port}",
16437            );
16438            assert_eq!(
16439                entrada.port(),
16440                port,
16441                "Entrada::port must return the storage-side u16 verbatim \
16442                 for port={port}",
16443            );
16444        }
16445    }
16446
16447    #[test]
16448    fn validate_placement_admits_paired_shape_iff_strategy_requires_shard_key() {
16449        // Load-bearing cross-slot-partition pin closing the loop between
16450        // the substrate-lifted
16451        // [`PlacementStrategy::requires_shard_key`] per-arm predicate on
16452        // the closed-set typed enum and the actual
16453        // [`AplicacaoSpec::validate_placement`] runtime behavior across
16454        // the paired `:placement :shard-key` axis: every validated
16455        // [`Placement`] past [`AplicacaoSpec::validate_placement`]
16456        // satisfies `placement.shard_key().is_some() ==
16457        // placement.estrategia().requires_shard_key()`. The four-cell
16458        // shape witness sweeps every combination of (variant in the
16459        // closed accept-set, `:shard-key` Some/None) and pins:
16460        //
16461        //   * variant.requires_shard_key() && shard_key.is_some() →
16462        //     validate() passes; the paired shape is the sole
16463        //     `requires_shard_key` arm-family accepted shape.
16464        //   * variant.requires_shard_key() && shard_key.is_none() →
16465        //     validate() fails with [`AplicacaoError::ShardedWithoutKey`];
16466        //     the paired shape is the refused missing-key shape on
16467        //     Sharded-family arms.
16468        //   * !variant.requires_shard_key() && shard_key.is_some() →
16469        //     validate() fails with
16470        //     [`AplicacaoError::ShardKeyOnNonSharded`]; the paired shape
16471        //     is the refused declared-but-inert shape on non-Sharded-
16472        //     family arms.
16473        //   * !variant.requires_shard_key() && shard_key.is_none() →
16474        //     validate() passes; the paired shape is the sole
16475        //     non-`requires_shard_key` arm-family accepted shape.
16476        //
16477        // The compile-time-exhaustive `match p.estrategia()` dispatch at
16478        // [`AplicacaoSpec::validate_placement`] preserves its structural
16479        // arm-fan (a future arm addition still surfaces a build-time
16480        // exhaustiveness error there); this pin closes the semantic loop
16481        // between the arm-fan's shape-gate cascades and the substrate-
16482        // canonical predicate every downstream consumer of the paired
16483        // shape reads through. Fail-before-pass-after locally verified by
16484        // mutating the predicate's `Sharded => true` arm to `false` — the
16485        // truthy `expects_ok` cell for `Sharded` + `Some` trips the
16486        // `validate() must pass` assertion; restoring passes. Same "close
16487        // the loop between the typed predicate and the runtime behavior"
16488        // discipline as the sibling
16489        // [`wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant`]
16490        // (7b97d26) cross-projection pin on the peer [`WitTarget`]
16491        // per-arm classifier axis.
16492        for variant in [
16493            PlacementStrategy::SingleNode,
16494            PlacementStrategy::Replicated,
16495            PlacementStrategy::Sharded,
16496        ] {
16497            for present in [false, true] {
16498                let mut spec = three_member_spec();
16499                spec.placement.estrategia = variant;
16500                spec.placement.shard_key = present.then(|| "tenantId".into());
16501                let expects_ok = variant.requires_shard_key() == present;
16502                let result = spec.validate();
16503                match (expects_ok, &result) {
16504                    (true, Ok(())) => {}
16505                    (false, Err(err)) => {
16506                        // Cross-check the refusal diagnostic names the
16507                        // right cell of the four-cell shape witness — the
16508                        // `requires_shard_key && !present` cell must trip
16509                        // [`AplicacaoError::ShardedWithoutKey`]; the
16510                        // `!requires_shard_key && present` cell must trip
16511                        // [`AplicacaoError::ShardKeyOnNonSharded`].
16512                        match (variant.requires_shard_key(), present, err) {
16513                            (true, false, AplicacaoError::ShardedWithoutKey) => {}
16514                            (
16515                                false,
16516                                true,
16517                                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. },
16518                            ) => {
16519                                assert_eq!(
16520                                    *e, variant,
16521                                    "ShardKeyOnNonSharded.estrategia must byte-equal \
16522                                     the paired PlacementStrategy",
16523                                );
16524                            }
16525                            _ => panic!(
16526                                "unexpected refusal for estrategia={variant:?} \
16527                                 present={present}: {err:?}"
16528                            ),
16529                        }
16530                    }
16531                    (true, Err(err)) => panic!(
16532                        "validate() must pass for estrategia={variant:?} \
16533                         present={present} (requires_shard_key={} == present={present}), \
16534                         got {err:?}",
16535                        variant.requires_shard_key(),
16536                    ),
16537                    (false, Ok(())) => panic!(
16538                        "validate() must fail for estrategia={variant:?} \
16539                         present={present} (requires_shard_key={} != present={present})",
16540                        variant.requires_shard_key(),
16541                    ),
16542                }
16543            }
16544        }
16545    }
16546
16547    #[test]
16548    fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
16549        // Pin the M3 diagnostic template routes through the typed
16550        // [`PlacementStrategy`] Display byte-string (rebound from the
16551        // prior `{estrategia:?}` `Debug` route). Pre-lift the two
16552        // routes emitted identical bytes (the `Debug` derive on a
16553        // unit variant emits the variant name verbatim, exactly what
16554        // `as_str` returns), but the two paths were structurally
16555        // independent — a future `#[serde(rename_all = "…")]`
16556        // attribute or variant rename would coordinate the wire /
16557        // `Display` / `as_str` triple through the lifted const but
16558        // leave the `Debug` route on the compiler-derived variant name,
16559        // silently desynchronizing the diagnostic byte-string from the
16560        // wire byte-string. Rebinding the template onto `Display`
16561        // ties the diagnostic to the same lifted
16562        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
16563        // emits — drift becomes structurally impossible. Pin the
16564        // byte-string here so a future edit that reverts the template
16565        // to `{estrategia:?}` is caught at caixa-core test time, not
16566        // at consumer dispatch time.
16567        for (variant, expected_scalar) in [
16568            (
16569                PlacementStrategy::SingleNode,
16570                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16571            ),
16572            (
16573                PlacementStrategy::Replicated,
16574                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16575            ),
16576            (
16577                PlacementStrategy::Sharded,
16578                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
16579            ),
16580        ] {
16581            let err = AplicacaoError::PlacementWithoutClusters {
16582                estrategia: variant,
16583            };
16584            let msg = err.to_string();
16585            assert!(
16586                msg.starts_with(&format!(":placement {expected_scalar} requires")),
16587                "PlacementWithoutClusters diagnostic for {variant:?} must open \
16588                 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
16589            );
16590        }
16591    }
16592
16593    #[test]
16594    fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
16595        // Peer of
16596        // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
16597        // on the second M3 diagnostic that carries the typed
16598        // [`PlacementStrategy`] in its `#[error(…)]` template. Both
16599        // diagnostics now route the strategy scalar through the same
16600        // [`std::fmt::Display`] surface, tying the diagnostic
16601        // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
16602        // const set the wire format also emits. The two non-Sharded
16603        // arms are exercised here (the diagnostic exists to flag a
16604        // `:shard-key` slot the current strategy will never consume);
16605        // the peer `Sharded` arm never reaches this diagnostic (the
16606        // `Sharded` strategy consumes `:shard-key` — the
16607        // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
16608        // slot instead).
16609        for (variant, expected_scalar) in [
16610            (
16611                PlacementStrategy::SingleNode,
16612                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16613            ),
16614            (
16615                PlacementStrategy::Replicated,
16616                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16617            ),
16618        ] {
16619            let err = AplicacaoError::ShardKeyOnNonSharded {
16620                estrategia: variant,
16621                shard_key: "$tenantId".into(),
16622            };
16623            let msg = err.to_string();
16624            assert!(
16625                msg.starts_with(&format!(":placement {expected_scalar} carries")),
16626                "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
16627                 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
16628            );
16629        }
16630    }
16631
16632    #[test]
16633    fn placement_strategy_all_enumerates_every_variant_once() {
16634        // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
16635        // exhaustive-iteration surface: every variant appears exactly
16636        // once, and the slice length matches the arm count of the
16637        // closed set. Every consumer that walks the accepted-strategy
16638        // set (a future `feira app placement --list` CLI-side surfacing,
16639        // a future M4 admission-webhook's rejection body naming the
16640        // accepted-strategy list, the [`PlacementStrategy::from_wire`]
16641        // reverse-projection consumers that iterate the accept-set for
16642        // a "did you mean" hint) reads through this slice, so a future
16643        // variant addition (an `Anycast` mesh-anycast arm the
16644        // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
16645        // grows the enum but forgets to grow [`Self::ALL`] silently
16646        // truncates every downstream consumer's accept-set at the same
16647        // pre-addition boundary — this pin fails at caixa-core build
16648        // time on the pairwise-distinct + arm-count invariants.
16649        //
16650        // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
16651        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
16652        // pins on the peer closed-set typed-enum axes.
16653        let all: &[PlacementStrategy] = PlacementStrategy::ALL;
16654        assert_eq!(
16655            all.len(),
16656            3,
16657            "PlacementStrategy::ALL must enumerate every variant of the \
16658             three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
16659        );
16660        for (i, a) in all.iter().enumerate() {
16661            for (j, b) in all.iter().enumerate() {
16662                if i != j {
16663                    assert_ne!(
16664                        a, b,
16665                        "PlacementStrategy::ALL must carry every variant exactly \
16666                         once — got duplicate {a:?} at indices {i} and {j}"
16667                    );
16668                }
16669            }
16670        }
16671        for variant in [
16672            PlacementStrategy::SingleNode,
16673            PlacementStrategy::Replicated,
16674            PlacementStrategy::Sharded,
16675        ] {
16676            assert!(
16677                all.contains(&variant),
16678                "PlacementStrategy::ALL must contain {variant:?} — a future variant \
16679                 addition that grows the enum but forgets to grow the ALL slice \
16680                 silently truncates every downstream consumer's accept-set at the \
16681                 pre-addition boundary"
16682            );
16683        }
16684    }
16685
16686    #[test]
16687    fn placement_strategy_from_wire_accepts_every_lifted_constant() {
16688        // Fail-before-pass-after pin on the forward accept-set of the
16689        // [`PlacementStrategy::from_wire`] reverse projection: every
16690        // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
16691        // constant the [`PlacementStrategy::as_str`] emitter walks
16692        // parses back to its paired variant. Any future arm addition
16693        // that grows the emitter's `as_str` match but forgets to grow
16694        // the parser's `from_str` match silently splits the two halves
16695        // of the round-trip — the wire byte-string one non-serde
16696        // consumer parses from the one the emitter wrote — with the
16697        // failure surfacing at parse time far from the rebrand commit.
16698        // Pinning the three-arm accept-set here catches the drift at
16699        // caixa-core build time.
16700        //
16701        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
16702        // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
16703        // closed-set typed-enum `str → Self` axes.
16704        for (wire, expected) in [
16705            (
16706                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16707                PlacementStrategy::SingleNode,
16708            ),
16709            (
16710                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16711                PlacementStrategy::Replicated,
16712            ),
16713            (
16714                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
16715                PlacementStrategy::Sharded,
16716            ),
16717        ] {
16718            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
16719                panic!(
16720                    "PlacementStrategy::from_wire({wire:?}) must accept every \
16721                     M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
16722                     lifted canonical byte-string that PlacementStrategy::{expected:?} \
16723                     serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
16724                )
16725            });
16726            assert_eq!(
16727                parsed, expected,
16728                "PlacementStrategy::from_wire({wire:?}) must return \
16729                 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
16730            );
16731        }
16732    }
16733
16734    #[test]
16735    fn placement_strategy_from_wire_round_trips_through_as_str() {
16736        // Fail-before-pass-after pin on the closed round-trip between
16737        // the forward [`PlacementStrategy::as_str`] emitter and the
16738        // reverse [`PlacementStrategy::from_wire`] parser: for every
16739        // variant in [`PlacementStrategy::ALL`], parsing the emitter's
16740        // output must return exactly the same variant. Any per-arm
16741        // divergence — a future arm added to `as_str` but not
16742        // `from_str`, an accidental copy-paste flip in one but not the
16743        // other — silently splits the emit and parse halves and the
16744        // failure surfaces at consumer parse time far from the drift
16745        // site. The `ALL`-iterating shape means a future variant
16746        // addition picks up the coverage by construction.
16747        //
16748        // Peer of the sibling [`crate::kind::tests`] round-trip pin on
16749        // [`crate::CaixaKind::from_wire`] and the
16750        // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
16751        // sibling round-trip pin on [`RateLimitUnit`].
16752        for &variant in PlacementStrategy::ALL {
16753            let wire = variant.as_str();
16754            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
16755                panic!(
16756                    "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
16757                     must be Some({variant:?}) — the two halves of the round-trip \
16758                     dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
16759                     got None on wire byte-string {wire:?}"
16760                )
16761            });
16762            assert_eq!(
16763                parsed, variant,
16764                "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
16765                 must round-trip to the same variant; got {parsed:?}"
16766            );
16767        }
16768    }
16769
16770    #[test]
16771    fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
16772        // Fail-before-pass-after pin on the closed-set refusal
16773        // discipline of [`PlacementStrategy::from_wire`]: every
16774        // byte-string outside the three-arm accept-set returns `None`
16775        // rather than silently collapsing onto the [`Default`]
16776        // (`Replicated`) arm or an arbitrary neighbor. The refusal set
16777        // exercised here sweeps the load-bearing drift shapes: the
16778        // empty string (a stripped serde-attribute drift), an all-
16779        // whitespace string (the canonical text-editor accidental
16780        // padding shape), the lowercased kebab-case forms a future
16781        // `#[serde(rename_all = "kebab-case")]` attribute would emit
16782        // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
16783        // coincidentally match the accepted canonical scalars, so only
16784        // `"single-node"` fires as a refusal, but pinning the case-
16785        // sensitivity of the accepted arms via the peer [`SingleNode`]
16786        // assertion in the round-trip pin makes the discipline
16787        // structurally clear), the lowercased single-word forms
16788        // (`"singlenode"`), the padded canonical scalar
16789        // (`" Sharded "`), the trailing-comma / trailing-newline shapes
16790        // (`"Sharded\n"`), and a pointer-different `&'static str` that
16791        // happens to alias a canonical byte-string by content but not
16792        // by identity (validated implicitly by the emitter's routing
16793        // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
16794        // identity a paired [`crate::assert_str_reexport_identity`] pin
16795        // in caixa-core's per-const declaration surface would catch).
16796        //
16797        // Peer of the sibling
16798        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
16799        // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
16800        for bad in [
16801            "",
16802            " ",
16803            "\n",
16804            "\t",
16805            "single-node",
16806            "singlenode",
16807            "SingleNodes",
16808            "single_node",
16809            "single node",
16810            "SINGLENODE",
16811            "SingleNode ",
16812            " SingleNode",
16813            " Sharded ",
16814            "Sharded\n",
16815            "replicated ",
16816            "sharded",
16817            "REPLICATED",
16818            "Anycast",
16819            "Global",
16820            "?",
16821        ] {
16822            assert!(
16823                PlacementStrategy::from_wire(bad).is_none(),
16824                "PlacementStrategy::from_wire({bad:?}) must return None — the \
16825                 parser's accept-set is exactly the three PlacementStrategy::as_str \
16826                 outputs (SingleNode, Replicated, Sharded), and this byte-string \
16827                 is outside that closed set"
16828            );
16829        }
16830    }
16831
16832    #[test]
16833    fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
16834        // Fail-before-pass-after pin on the third path of the four-path
16835        // convergence: `from_str` (the reverse projection) inverts the
16836        // `Serialize` derive's wire byte-string on every variant.
16837        // Together with the pre-existing three-path convergence
16838        // (`Display` + `as_str` + `Serialize` all resolve to the same
16839        // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
16840        // the peer
16841        // [`placement_strategy_display_matches_serialized_wire_byte_string`])
16842        // this closes the round-trip: the wire byte-string the
16843        // `Serialize` derive emits parses back to the same variant
16844        // through `from_str`, so any future serde-attribute or variant-
16845        // rename drift on the emit half now surfaces as a matched drift
16846        // on the parse half at caixa-core build time — the two halves
16847        // migrate as a unit through the lifted consts on any future
16848        // rename, and the round-trip cannot silently split.
16849        //
16850        // Peer of the sibling
16851        // [`placement_strategy_display_matches_serialized_wire_byte_string`]
16852        // wire-format pin — extends the three-path convergence
16853        // (`Display` + `as_str` + `Serialize`) onto the fourth path
16854        // (`from_str`), closing the `str ↔ Self` round-trip on the
16855        // M3 `:placement :estrategia` closed-set axis.
16856        for &variant in PlacementStrategy::ALL {
16857            let wire = serde_json::to_string(&variant).unwrap();
16858            let unquoted = wire
16859                .strip_prefix('"')
16860                .and_then(|s| s.strip_suffix('"'))
16861                .expect("serialized PlacementStrategy is a JSON string");
16862            let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
16863                panic!(
16864                    "PlacementStrategy::from_wire({unquoted:?}) must accept the \
16865                     Serialize derive's wire byte-string for \
16866                     PlacementStrategy::{variant:?} — the four-path convergence \
16867                     (Display + as_str + Serialize + from_str) resolves through \
16868                     the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
16869                )
16870            });
16871            assert_eq!(
16872                parsed, variant,
16873                "PlacementStrategy::from_wire of the Serialize derive's wire \
16874                 byte-string for PlacementStrategy::{variant:?} must round-trip \
16875                 to the same variant; got {parsed:?}"
16876            );
16877        }
16878    }
16879
16880    #[test]
16881    fn rejects_zero_policy_timeout() {
16882        let mut s = three_member_spec();
16883        s.politicas.timeout = Some(Duration::ZERO);
16884        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
16885    }
16886
16887    #[test]
16888    fn rejects_zero_policy_retries() {
16889        let mut s = three_member_spec();
16890        s.politicas.retries = Some(0);
16891        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
16892    }
16893
16894    #[test]
16895    fn rejects_policy_retries_above_cap() {
16896        // The fail-before-pass-after pin: `Some(11)` is structurally
16897        // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
16898        // passed validate on every pre-gate codebase because the
16899        // typed slot's only check was the zero-floor arm. The
16900        // thundering-herd amplification vector only surfaced at the
16901        // runtime substrate (Envoy / Cilium L7 retry overlay)
16902        // far from the source caixa.lisp with no field naming the
16903        // offending policy.
16904        let mut s = three_member_spec();
16905        s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
16906        assert_eq!(
16907            s.validate().unwrap_err(),
16908            AplicacaoError::PolicyRetriesExceedsCap {
16909                retries: POLICY_RETRIES_MAX + 1
16910            }
16911        );
16912    }
16913
16914    #[test]
16915    fn rejects_policy_retries_far_above_cap() {
16916        // The `u32::MAX` worst case — the four-billion-retry policy
16917        // a typo (`(:retries 4294967295)`) or struct-literal
16918        // copy-paste lands in the slot. Pin the cap arm's coverage
16919        // explicitly across the full `u32` overflow so a future
16920        // relaxation that drops the upper bound surfaces here.
16921        let mut s = three_member_spec();
16922        s.politicas.retries = Some(u32::MAX);
16923        assert_eq!(
16924            s.validate().unwrap_err(),
16925            AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
16926        );
16927    }
16928
16929    #[test]
16930    fn accepts_policy_retries_at_cap() {
16931        // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
16932        // must validate. The cap is inclusive on the top edge,
16933        // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
16934        // discipline on the sibling [`crate::LimitsSpec::memory`]
16935        // axis. Pin the boundary explicitly so a future off-by-one
16936        // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
16937        // surfaces here as a test failure rather than a silent
16938        // contract narrowing.
16939        let mut s = three_member_spec();
16940        s.politicas.retries = Some(POLICY_RETRIES_MAX);
16941        s.validate()
16942            .expect("retries == POLICY_RETRIES_MAX must validate");
16943    }
16944
16945    #[test]
16946    fn accepts_policy_retries_typical_values() {
16947        // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
16948        // every value in the validated set must pass. The
16949        // Envoy / Istio production-playbook recommendation band
16950        // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
16951        // (`maxRetries ≤ 10`) both lie within this set.
16952        for r in 1..=POLICY_RETRIES_MAX {
16953            let mut s = three_member_spec();
16954            s.politicas.retries = Some(r);
16955            s.validate()
16956                .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
16957        }
16958    }
16959
16960    #[test]
16961    fn policy_retries_zero_takes_precedence_over_cap() {
16962        // The cross-arm ordering pin: `Some(0)` is structurally
16963        // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
16964        // (cap), but the zero-floor diagnostic is the more
16965        // self-locating one (it directly names the omit-axis
16966        // remediation), so the validate gate must fire on zero
16967        // first. Pin the order so a future refactor that reorders
16968        // the arms surfaces here as a test failure rather than a
16969        // silent diagnostic regression. Same shape every other
16970        // zero-then-shape ordering on this surface uses
16971        // ([`AplicacaoError::PolicyTimeoutZero`] then
16972        // [`AplicacaoError::PolicyTimeoutNotCanonical`];
16973        // [`AplicacaoError::PolicyBreakerZeroWindow`] then
16974        // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
16975        let mut s = three_member_spec();
16976        s.politicas.retries = Some(0);
16977        assert_eq!(
16978            s.validate().unwrap_err(),
16979            AplicacaoError::PolicyRetriesZero,
16980            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
16981        );
16982    }
16983
16984    #[test]
16985    fn policy_retries_cap_diagnostic_carries_offending_value() {
16986        // The diagnostic-shape pin: the offending `u32` is carried
16987        // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
16988        // variant so the surfaced error message names the value the
16989        // author wrote (`":politicas :retries (47) exceeds the
16990        // mesh-policy ceiling …"`), not just the cap. Same
16991        // self-locating diagnostic shape every other typed-cap arm
16992        // on this surface carries
16993        // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
16994        // offending byte count verbatim).
16995        let mut s = three_member_spec();
16996        s.politicas.retries = Some(47);
16997        let err = s.validate().unwrap_err();
16998        assert!(
16999            matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
17000            "got {err:?}"
17001        );
17002        let msg = err.to_string();
17003        assert!(
17004            msg.contains("47"),
17005            ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
17006        );
17007    }
17008
17009    #[test]
17010    fn policy_retries_cap_is_aws_app_mesh_aligned() {
17011        // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
17012        // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
17013        // schema cap — the only upstream mesh-policy schema that
17014        // documents an explicit hard cap. Pinning the literal value
17015        // here surfaces a future drift (a relaxation to 20, a
17016        // tightening to 5) as a deliberate test edit, not a silent
17017        // contract narrowing.
17018        assert_eq!(POLICY_RETRIES_MAX, 10);
17019    }
17020
17021    #[test]
17022    fn rejects_circuit_breaker_zero_max_failures() {
17023        let mut s = three_member_spec();
17024        s.politicas.circuit_breaker = Some(CircuitBreaker {
17025            max_failures: 0,
17026            window: Duration::from_secs(60),
17027        });
17028        assert_eq!(
17029            s.validate().unwrap_err(),
17030            AplicacaoError::PolicyBreakerZeroFailures
17031        );
17032    }
17033
17034    #[test]
17035    fn rejects_circuit_breaker_max_failures_above_cap() {
17036        // The fail-before-pass-after pin: `1001` is structurally one
17037        // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
17038        // silently passed validate on every pre-gate codebase
17039        // because the typed slot's only check was the zero-floor
17040        // arm. The breaker-no-op vector only surfaced at the runtime
17041        // substrate (Envoy / Cilium L7 outlier-detection overlay)
17042        // far from the source caixa.lisp with no field naming the
17043        // offending policy.
17044        let mut s = three_member_spec();
17045        s.politicas.circuit_breaker = Some(CircuitBreaker {
17046            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
17047            window: Duration::from_secs(60),
17048        });
17049        assert_eq!(
17050            s.validate().unwrap_err(),
17051            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
17052                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
17053            }
17054        );
17055    }
17056
17057    #[test]
17058    fn rejects_circuit_breaker_max_failures_far_above_cap() {
17059        // The `u32::MAX` worst case — the four-billion-failure
17060        // threshold a typo (`(:max-failures 4294967295)`) or a
17061        // struct-literal copy-paste lands in the slot. Pin the cap
17062        // arm's coverage explicitly across the full `u32` overflow
17063        // so a future relaxation that drops the upper bound surfaces
17064        // here.
17065        let mut s = three_member_spec();
17066        s.politicas.circuit_breaker = Some(CircuitBreaker {
17067            max_failures: u32::MAX,
17068            window: Duration::from_secs(60),
17069        });
17070        assert_eq!(
17071            s.validate().unwrap_err(),
17072            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
17073                max_failures: u32::MAX,
17074            }
17075        );
17076    }
17077
17078    #[test]
17079    fn accepts_circuit_breaker_max_failures_at_cap() {
17080        // The boundary value — exactly
17081        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
17082        // cap is inclusive on the top edge, matching the
17083        // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
17084        // discipline on the sibling capped axes. Pin the boundary
17085        // explicitly so a future off-by-one tightening
17086        // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
17087        // surfaces here as a test failure rather than a silent
17088        // contract narrowing.
17089        let mut s = three_member_spec();
17090        s.politicas.circuit_breaker = Some(CircuitBreaker {
17091            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
17092            window: Duration::from_secs(60),
17093        });
17094        s.validate()
17095            .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
17096    }
17097
17098    #[test]
17099    fn accepts_circuit_breaker_max_failures_typical_values() {
17100        // The documented production-playbook band positive-control
17101        // sweep — every value Hystrix / Istio / Envoy / Polly /
17102        // Resilience4j recommend (5..=50) must pass, plus a sweep
17103        // through the hyperscale band (100, 500, 1000) the cap
17104        // accepts. Pin the inclusive validated set explicitly so a
17105        // future tightening of the ceiling surfaces here.
17106        for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
17107            let mut s = three_member_spec();
17108            s.politicas.circuit_breaker = Some(CircuitBreaker {
17109                max_failures: n,
17110                window: Duration::from_secs(60),
17111            });
17112            s.validate()
17113                .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
17114        }
17115    }
17116
17117    #[test]
17118    fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
17119        // The cross-arm ordering pin: `0` is structurally outside
17120        // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
17121        // (cap), but the zero-floor diagnostic is the more
17122        // self-locating one (it directly names the omit-axis
17123        // remediation), so the validate gate must fire on zero
17124        // first. Same shape every other zero-then-shape ordering on
17125        // this surface uses
17126        // ([`AplicacaoError::PolicyRetriesZero`] then
17127        // [`AplicacaoError::PolicyRetriesExceedsCap`];
17128        // [`AplicacaoError::PolicyTimeoutZero`] then
17129        // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
17130        let mut s = three_member_spec();
17131        s.politicas.circuit_breaker = Some(CircuitBreaker {
17132            max_failures: 0,
17133            window: Duration::from_secs(60),
17134        });
17135        assert_eq!(
17136            s.validate().unwrap_err(),
17137            AplicacaoError::PolicyBreakerZeroFailures,
17138            "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
17139        );
17140    }
17141
17142    #[test]
17143    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
17144        // The cross-arm ordering pin between the cap and the
17145        // sibling `:window` gates (zero-window, canonical-window).
17146        // A breaker carrying both an over-cap `max_failures` AND a
17147        // structurally invalid window (zero, sub-ms) must surface
17148        // the cap diagnostic first — the cap arm is wired
17149        // immediately after the zero-failure arm and strictly
17150        // before the window arms, so the offending value the
17151        // diagnostic names matches the order the author would
17152        // discover the gates by reading top-to-bottom through
17153        // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
17154        // future refactor that reorders the arms surfaces here as a
17155        // test failure rather than a silent diagnostic regression.
17156        let mut s = three_member_spec();
17157        s.politicas.circuit_breaker = Some(CircuitBreaker {
17158            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
17159            window: Duration::ZERO,
17160        });
17161        assert_eq!(
17162            s.validate().unwrap_err(),
17163            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
17164                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
17165            },
17166            "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
17167        );
17168    }
17169
17170    #[test]
17171    fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
17172        // The diagnostic-shape pin: the offending `u32` is carried
17173        // verbatim into the
17174        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
17175        // variant so the surfaced error message names the value the
17176        // author wrote (`":politicas :circuit-breaker :max-failures
17177        // (50000) exceeds the mesh-policy ceiling …"`), not just
17178        // the cap. Same self-locating diagnostic shape every other
17179        // typed-cap arm on this surface carries
17180        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
17181        // offending retry count verbatim,
17182        // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
17183        // offending byte count verbatim).
17184        let mut s = three_member_spec();
17185        s.politicas.circuit_breaker = Some(CircuitBreaker {
17186            max_failures: 50_000,
17187            window: Duration::from_secs(60),
17188        });
17189        let err = s.validate().unwrap_err();
17190        assert!(
17191            matches!(
17192                err,
17193                AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
17194                    max_failures: 50_000
17195                }
17196            ),
17197            "got {err:?}"
17198        );
17199        let msg = err.to_string();
17200        assert!(
17201            msg.contains("50000"),
17202            ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
17203        );
17204    }
17205
17206    #[test]
17207    fn policy_breaker_max_failures_cap_pins_canonical_value() {
17208        // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
17209        // value at 1000 — an order of magnitude above every
17210        // documented production-playbook recommendation band
17211        // (Hystrix `requestVolumeThreshold` default 20, Istio
17212        // `outlierDetection.consecutive5xxErrors` default 5, Envoy
17213        // `outlier_detection.consecutive_5xx` default 5, Polly /
17214        // Resilience4j typical 5..=50) and below the
17215        // clearly-pathological "effectively no protection" floor
17216        // (10_000, 100_000, u32::MAX). Pinning the literal value
17217        // here surfaces a future drift (a relaxation to 10_000, a
17218        // tightening to 100) as a deliberate test edit, not a
17219        // silent contract narrowing.
17220        assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
17221    }
17222
17223    #[test]
17224    fn rejects_circuit_breaker_zero_window() {
17225        let mut s = three_member_spec();
17226        s.politicas.circuit_breaker = Some(CircuitBreaker {
17227            max_failures: 5,
17228            window: Duration::ZERO,
17229        });
17230        assert_eq!(
17231            s.validate().unwrap_err(),
17232            AplicacaoError::PolicyBreakerZeroWindow
17233        );
17234    }
17235
17236    #[test]
17237    fn rejects_zero_rate_limit() {
17238        let mut s = three_member_spec();
17239        s.politicas.rate_limit = Some(RateLimit {
17240            rate: 0,
17241            window: Duration::from_secs(1),
17242        });
17243        assert_eq!(
17244            s.validate().unwrap_err(),
17245            AplicacaoError::PolicyRateLimitZero
17246        );
17247    }
17248
17249    #[test]
17250    fn rejects_rate_limit_zero_window() {
17251        // `RateLimit { rate: 100, window: Duration::ZERO }` is
17252        // constructible programmatically (the typed `Duration` field
17253        // imposes no nonzero invariant) but renders through
17254        // `rate_limit_codec::render` as `"100/0s"` — a fragment the
17255        // codec's `parse` rejects as `unknown rate-limit window unit
17256        // "0s"`. Until this validate-time gate landed the typed slot
17257        // accepted the value silently and the round-trip break only
17258        // surfaced at deserialize time (potentially in a downstream
17259        // consumer that never re-validates). Pin the rejection at
17260        // `AplicacaoSpec::validate` so the typed slot's valid set
17261        // matches the codec's round-trippable set structurally.
17262        let mut s = three_member_spec();
17263        s.politicas.rate_limit = Some(RateLimit {
17264            rate: 100,
17265            window: Duration::ZERO,
17266        });
17267        assert_eq!(
17268            s.validate().unwrap_err(),
17269            AplicacaoError::PolicyRateLimitWindowNotCanonical {
17270                window: Duration::ZERO
17271            }
17272        );
17273    }
17274
17275    #[test]
17276    fn rejects_rate_limit_arbitrary_seconds_window() {
17277        // 45 seconds is a valid `Duration` but not one of the three
17278        // canonical rate-limit windows the codec round-trips
17279        // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
17280        // refuses on round-trip — same round-trip-break shape the
17281        // zero-window arm above pins, with a non-zero magnitude to
17282        // guard against a future "reject only zero" half-measure.
17283        let mut s = three_member_spec();
17284        let window = Duration::from_secs(45);
17285        s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
17286        assert_eq!(
17287            s.validate().unwrap_err(),
17288            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
17289        );
17290    }
17291
17292    #[test]
17293    fn rejects_rate_limit_two_minute_window() {
17294        // 120 seconds = 2 minutes is a "looks-canonical" but
17295        // not-canonical window: it's a clean integer multiple of the
17296        // minute unit, but the codec only round-trips the
17297        // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
17298        // A `Duration::from_secs(120)` window renders as `"100/120s"`
17299        // which the parser rejects. Pinning this case rules out a
17300        // future "accept any clean multiple of s/m/h" relaxation
17301        // that would silently break the codec contract.
17302        let mut s = three_member_spec();
17303        let window = Duration::from_secs(120);
17304        s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
17305        assert_eq!(
17306            s.validate().unwrap_err(),
17307            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
17308        );
17309    }
17310
17311    #[test]
17312    fn rejects_rate_limit_subsecond_window() {
17313        // A sub-second window (e.g. 500ms) is a valid `Duration` but
17314        // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
17315        // Pin the rejection so a future relaxation can't silently
17316        // admit fractional-second windows that the codec can't
17317        // round-trip.
17318        let mut s = three_member_spec();
17319        let window = Duration::from_millis(500);
17320        s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
17321        assert_eq!(
17322            s.validate().unwrap_err(),
17323            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
17324        );
17325    }
17326
17327    #[test]
17328    fn rejects_policy_rate_limit_above_cap() {
17329        // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
17330        // is structurally one past the cap and silently passed
17331        // validate on every pre-gate codebase because the typed slot's
17332        // only `rate` check was the zero-floor arm. The no-op-limiter
17333        // shape only surfaced at the runtime substrate (Envoy's
17334        // `local_rate_limit.token_bucket.max_tokens`, the future
17335        // Cilium L7 rate-limit overlay) far from the source caixa.lisp
17336        // with no field naming the offending policy.
17337        let mut s = three_member_spec();
17338        s.politicas.rate_limit = Some(RateLimit {
17339            rate: POLICY_RATE_LIMIT_MAX + 1,
17340            window: Duration::from_secs(1),
17341        });
17342        assert_eq!(
17343            s.validate().unwrap_err(),
17344            AplicacaoError::PolicyRateLimitExceedsCap {
17345                rate: POLICY_RATE_LIMIT_MAX + 1
17346            }
17347        );
17348    }
17349
17350    #[test]
17351    fn rejects_policy_rate_limit_far_above_cap() {
17352        // The `u32::MAX` worst case — the four-billion-token rate-limit
17353        // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
17354        // copy-paste lands in the slot. Pin the cap arm's coverage
17355        // explicitly across the full `u32` overflow so a future
17356        // relaxation that drops the upper bound surfaces here. Peer to
17357        // `rejects_policy_retries_far_above_cap` on the sibling
17358        // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
17359        // on the sibling `:max-failures` axis.
17360        let mut s = three_member_spec();
17361        s.politicas.rate_limit = Some(RateLimit {
17362            rate: u32::MAX,
17363            window: Duration::from_secs(1),
17364        });
17365        assert_eq!(
17366            s.validate().unwrap_err(),
17367            AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
17368        );
17369    }
17370
17371    #[test]
17372    fn accepts_policy_rate_limit_at_cap() {
17373        // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
17374        // must validate. The cap is inclusive on the top edge, matching
17375        // every other typed upper bound in this crate
17376        // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
17377        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
17378        // across all three canonical windows so a future off-by-one
17379        // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
17380        // window-conditional cap surfaces here as a test failure rather
17381        // than a silent contract narrowing.
17382        for secs in [1u64, 60, 3600] {
17383            let mut s = three_member_spec();
17384            s.politicas.rate_limit = Some(RateLimit {
17385                rate: POLICY_RATE_LIMIT_MAX,
17386                window: Duration::from_secs(secs),
17387            });
17388            s.validate().unwrap_or_else(|e| {
17389                panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
17390            });
17391        }
17392    }
17393
17394    #[test]
17395    fn accepts_policy_rate_limit_typical_values() {
17396        // The documented production-playbook recommendation band —
17397        // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
17398        // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
17399        // Enterprise ~1M per-hour. Every value in the validated set
17400        // must pass; pin the band explicitly so a future tightening
17401        // surfaces here.
17402        for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
17403            for secs in [1u64, 60, 3600] {
17404                let mut s = three_member_spec();
17405                s.politicas.rate_limit = Some(RateLimit {
17406                    rate,
17407                    window: Duration::from_secs(secs),
17408                });
17409                s.validate().unwrap_or_else(|e| {
17410                    panic!("rate={rate} window={secs}s must validate; got {e:?}")
17411                });
17412            }
17413        }
17414    }
17415
17416    #[test]
17417    fn policy_rate_limit_zero_takes_precedence_over_cap() {
17418        // The cross-arm ordering pin: `rate == 0` is structurally
17419        // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
17420        // (cap), but the zero-floor diagnostic is the more
17421        // self-locating one (it directly names the omit-axis
17422        // remediation). Pin the order so a future refactor that
17423        // reorders the arms surfaces here as a test failure rather
17424        // than a silent diagnostic regression. Same shape every other
17425        // zero-then-cap ordering on this surface uses
17426        // ([`AplicacaoError::PolicyRetriesZero`] then
17427        // [`AplicacaoError::PolicyRetriesExceedsCap`];
17428        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
17429        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
17430        let mut s = three_member_spec();
17431        s.politicas.rate_limit = Some(RateLimit {
17432            rate: 0,
17433            window: Duration::from_secs(1),
17434        });
17435        assert_eq!(
17436            s.validate().unwrap_err(),
17437            AplicacaoError::PolicyRateLimitZero,
17438            "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
17439        );
17440    }
17441
17442    #[test]
17443    fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
17444        // Two-axis-bad pin: rate above cap *and* window non-canonical.
17445        // The validate gate must fire on the rate cap first — the
17446        // amplification-shape (no-op limiter) diagnostic is the more
17447        // fundamental one; the window-canonical diagnostic is the
17448        // narrower codec-round-trip shape. Pin the ordering so a future
17449        // refactor that reorders the rate-then-window check arms
17450        // surfaces here as a test failure rather than a silent
17451        // diagnostic regression.
17452        let mut s = three_member_spec();
17453        s.politicas.rate_limit = Some(RateLimit {
17454            rate: POLICY_RATE_LIMIT_MAX + 1,
17455            window: Duration::from_secs(45),
17456        });
17457        assert_eq!(
17458            s.validate().unwrap_err(),
17459            AplicacaoError::PolicyRateLimitExceedsCap {
17460                rate: POLICY_RATE_LIMIT_MAX + 1
17461            },
17462            "above-cap rate must surface the cap diagnostic, not the window diagnostic"
17463        );
17464    }
17465
17466    #[test]
17467    fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
17468        // The diagnostic-shape pin: the offending `u32` is carried
17469        // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
17470        // variant so the surfaced error message names the value the
17471        // author wrote (`":politicas :rate-limit rate (5000000) exceeds
17472        // the mesh-policy ceiling …"`), not just the cap. Same
17473        // self-locating diagnostic shape every other typed-cap arm on
17474        // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
17475        // carries the offending retries count verbatim,
17476        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
17477        // the offending failure count verbatim).
17478        let mut s = three_member_spec();
17479        s.politicas.rate_limit = Some(RateLimit {
17480            rate: 5_000_000,
17481            window: Duration::from_secs(1),
17482        });
17483        let err = s.validate().unwrap_err();
17484        assert!(
17485            matches!(
17486                err,
17487                AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
17488            ),
17489            "got {err:?}"
17490        );
17491        let msg = err.to_string();
17492        assert!(
17493            msg.contains("5000000"),
17494            ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
17495        );
17496    }
17497
17498    #[test]
17499    fn policy_rate_limit_cap_pins_canonical_value() {
17500        // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
17501        // 1_000_000 — two-to-three orders of magnitude above every
17502        // documented production-playbook recommendation band (Envoy /
17503        // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
17504        // Gateway 10_000..=100_000 per-minute) and below the
17505        // clearly-pathological "paste-from-binary blob" floor
17506        // (100_000_000, u32::MAX). Pinning the literal value here
17507        // surfaces a future drift (a relaxation to 10_000_000, a
17508        // tightening to 100_000) as a deliberate test edit, not a
17509        // silent contract narrowing.
17510        assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
17511    }
17512
17513    #[test]
17514    fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
17515        // Both axes are invalid here: rate == 0 *and* window is
17516        // non-canonical. The validate gate must fire on rate first
17517        // (matching the existing `rejects_zero_rate_limit` ordering),
17518        // so the existing diagnostic continues to lead with the
17519        // simpler "zero rate" framing. Pinning the order of checks
17520        // so a future refactor that reorders the arms surfaces here
17521        // as a test failure rather than a silent diagnostic
17522        // regression.
17523        let mut s = three_member_spec();
17524        s.politicas.rate_limit = Some(RateLimit {
17525            rate: 0,
17526            window: Duration::from_secs(45),
17527        });
17528        assert_eq!(
17529            s.validate().unwrap_err(),
17530            AplicacaoError::PolicyRateLimitZero
17531        );
17532    }
17533
17534    #[test]
17535    fn rate_limit_canonical_windows_validate() {
17536        // The three canonical windows the codec round-trips
17537        // losslessly — 1s / 60s / 3600s — must all pass `validate()`
17538        // unchanged. Pin the full canonical set as a positive case
17539        // (the existing `rate_limit_round_trip_seconds` /
17540        // `rate_limit_round_trip_minutes` tests pin the
17541        // serialize-then-deserialize property at the codec layer; this
17542        // test pins the validate-side complement so a future tightening
17543        // of the canonical set — e.g. dropping `:hour` — surfaces here
17544        // as a test failure rather than a silent contract narrowing).
17545        for secs in [1u64, 60, 3600] {
17546            let mut s = three_member_spec();
17547            s.politicas.rate_limit = Some(RateLimit {
17548                rate: 100,
17549                window: Duration::from_secs(secs),
17550            });
17551            s.validate().expect("canonical window must validate");
17552        }
17553    }
17554
17555    #[test]
17556    fn rate_limit_validated_value_round_trips_through_codec() {
17557        // The structural property the validate gate enforces:
17558        // every `RateLimit` past `AplicacaoSpec::validate` round-trips
17559        // losslessly through the `rate_limit_codec` (serialize → string
17560        // → deserialize → equal value). Pin this end-to-end so a future
17561        // change to either side (the validate gate's accepted window
17562        // set, the codec's parse/render unit set) that breaks the
17563        // alignment surfaces here. The previous-state shape (typed
17564        // slot accepts arbitrary `Duration`, codec only round-trips
17565        // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
17566        // window — the validate gate now forecloses that.
17567        for secs in [1u64, 60, 3600] {
17568            let mut s = three_member_spec();
17569            s.politicas.rate_limit = Some(RateLimit {
17570                rate: 250,
17571                window: Duration::from_secs(secs),
17572            });
17573            s.validate().unwrap();
17574            let json = serde_json::to_string(&s.politicas).unwrap();
17575            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17576            assert_eq!(
17577                back.rate_limit, s.politicas.rate_limit,
17578                "every validated :rate-limit must round-trip losslessly through the codec"
17579            );
17580        }
17581    }
17582
17583    #[test]
17584    fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
17585        // The hour-window canonical form (`"<n>/h"`) was missing from
17586        // the prior `rate_limit_round_trip_seconds` / `_minutes` test
17587        // pair. Now that the validate gate pins 3600s as part of the
17588        // canonical set, pin its serialize-side render shape too so
17589        // the third leg of the s/m/h tripod is explicitly tested.
17590        let policy = MeshPolicy {
17591            rate_limit: Some(RateLimit {
17592                rate: 10000,
17593                window: Duration::from_secs(3600),
17594            }),
17595            ..Default::default()
17596        };
17597        let json = serde_json::to_string(&policy).unwrap();
17598        assert!(
17599            json.contains("\"10000/h\""),
17600            "hour-window canonical form must render with `h` suffix (got: {json})"
17601        );
17602        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17603        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
17604    }
17605
17606    #[test]
17607    fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
17608        // Pin the substrate-primitive [`RateLimit::canonical_unit`]
17609        // typed accessor's accepted-window set against the codec's
17610        // accepted set explicitly. A future addition to the codec
17611        // (e.g. accepting `:day`/`:week` as authoring units) must be
17612        // accompanied by a parallel addition here, and a regression
17613        // that drops one of the three canonical units from either
17614        // side surfaces as a test failure. The accessor is the
17615        // single source of truth for the canonical-window set —
17616        // [`AplicacaoSpec::validate_politicas`]'s canonical-window
17617        // gate and [`rate_limit_codec::render`]'s canonical arm both
17618        // read through it — this test enshrines that its
17619        // `Duration → Option<RateLimitUnit>` projection matches the
17620        // codec's parse / render arms' accepted-window set exactly.
17621        //
17622        // Predecessor: this pin previously read the module-private
17623        // free helper `is_canonical_rate_limit_window` — a delegate
17624        // that composed [`RateLimitUnit::from_window`] with `.is_some()`
17625        // — but the helper had no production consumers left after the
17626        // validate-gate migration onto [`RateLimit::canonical_unit`]
17627        // and was deleted; the closed-set arm-window bijection now
17628        // lives on exactly one typed dispatch on the substrate
17629        // primitive.
17630        let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
17631            RateLimit { rate: 1, window }.canonical_unit()
17632        };
17633        assert!(canonical_unit(Duration::from_secs(1)).is_some());
17634        assert!(canonical_unit(Duration::from_secs(60)).is_some());
17635        assert!(canonical_unit(Duration::from_secs(3600)).is_some());
17636        // Non-canonical windows the accessor rejects.
17637        assert!(canonical_unit(Duration::ZERO).is_none());
17638        assert!(canonical_unit(Duration::from_secs(2)).is_none());
17639        assert!(canonical_unit(Duration::from_secs(30)).is_none());
17640        assert!(canonical_unit(Duration::from_secs(120)).is_none());
17641        assert!(canonical_unit(Duration::from_secs(86400)).is_none());
17642        // Sub-second windows: even `Duration::from_millis(1000)` is
17643        // exactly 1s and accepted; `Duration::from_millis(500)` is
17644        // sub-second and rejected.
17645        assert!(canonical_unit(Duration::from_millis(1000)).is_some());
17646        assert!(canonical_unit(Duration::from_millis(500)).is_none());
17647        assert!(canonical_unit(Duration::from_millis(1500)).is_none());
17648    }
17649
17650    #[test]
17651    fn rate_limit_unit_table_projections_are_mutual_inverses() {
17652        // Bidirection pin against the closed-set typed enum
17653        // [`RateLimitUnit`] arm-table (the canonical
17654        // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
17655        // of the rate-limit unit surface reads from). The two
17656        // projection directions [`RateLimitUnit::from_suffix`] /
17657        // [`RateLimitUnit::window`] (str → Duration, exposed as one
17658        // typed dispatch through [`RateLimitUnit::window_from_suffix`])
17659        // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
17660        // (Duration → str, exposed as one typed dispatch through
17661        // [`RateLimit::canonical_unit`] composed with
17662        // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
17663        // codec's parse arm ([`rate_limit_codec::parse`] via
17664        // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
17665        // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
17666        // and the validate gate ([`AplicacaoSpec::validate_politicas`]
17667        // via [`RateLimit::canonical_unit`]) all key off. A future
17668        // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
17669        // sub-second window) is one variant + one arm per method on the
17670        // closed-set enum; the compiler-enforced exhaustiveness on
17671        // every consumer's `match self` arms picks it up by
17672        // construction. This pin enshrines that both projection
17673        // directions agree on every canonical arm row and neither
17674        // leaks a spurious entry the other doesn't recognize.
17675        //
17676        // Predecessor: this test previously read the two vestigial
17677        // module-private free helpers `rate_limit_window_unit` and
17678        // `rate_limit_window_from_unit` on the `Duration → &str` and
17679        // `&str → Duration` axes; the former was deleted after its
17680        // sole production consumer ([`rate_limit_codec::render`])
17681        // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
17682        // the latter is folded here into the substrate primitive
17683        // [`RateLimitUnit::window_from_suffix`] so both projection
17684        // directions live on the closed-set enum's arm-table.
17685        for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
17686            let window = super::RateLimitUnit::window_from_suffix(unit)
17687                .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
17688            assert_eq!(
17689                window,
17690                Duration::from_secs(secs),
17691                "unit {unit:?} must resolve to {secs}s"
17692            );
17693            let projected_suffix = RateLimit { rate: 1, window }
17694                .canonical_unit()
17695                .map(super::RateLimitUnit::as_suffix);
17696            assert_eq!(
17697                projected_suffix,
17698                Some(unit),
17699                "Duration({secs}s) must render as {unit:?} \
17700                 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
17701            );
17702        }
17703        // Non-table units yield None on the `unit → Duration`
17704        // projection — a future `"d"` addition to the table would
17705        // flip this arm; today it pins the current three-row table's
17706        // rejection semantics.
17707        assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
17708        assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
17709        assert!(super::RateLimitUnit::window_from_suffix("").is_none());
17710        // Non-table Durations yield None on the `Duration → unit`
17711        // projection — pins that the two projections agree on the
17712        // "not in the table" semantic too, so a drift where the
17713        // parse-side accepts a value the render-side can't emit is
17714        // a build error at the two-arm pair, not a silent codec
17715        // round-trip break.
17716        let projected_suffix = |window: Duration| -> Option<&'static str> {
17717            RateLimit { rate: 1, window }
17718                .canonical_unit()
17719                .map(super::RateLimitUnit::as_suffix)
17720        };
17721        assert!(projected_suffix(Duration::from_secs(2)).is_none());
17722        assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
17723        assert!(projected_suffix(Duration::from_millis(1500)).is_none());
17724    }
17725
17726    #[test]
17727    fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
17728        // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
17729        // substrate-primitive `&str → Duration` associated method the
17730        // codec's parse arm ([`rate_limit_codec::parse`]) now routes
17731        // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
17732        // to the same [`Duration`] the two-step composition
17733        // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
17734        // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
17735        // `"MIN"`) must project to [`None`] on both paths. A future
17736        // implementation of `window_from_suffix` that took a shortcut
17737        // through a per-suffix `match` table (bypassing the arm-table's
17738        // `Self::from_suffix` scan and the arm-table's `Self::window`
17739        // dispatch) would silently split the accept-set — the parse
17740        // arm would accept a suffix the enum's arm-table doesn't know,
17741        // or reject a suffix the enum's arm-table does; this pin
17742        // surfaces that drift at caixa-core build time rather than at a
17743        // downstream serde round-trip audit on a live `MeshPolicy`.
17744        //
17745        // Same byte-parity discipline the sibling
17746        // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
17747        // pin carries on the peer `Duration → RateLimitUnit` axis via
17748        // [`RateLimit::canonical_unit`], and the peer
17749        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
17750        // carries on the bidirectional arm-table axis — extended here
17751        // onto the fifth (and last unlifted) projection axis on the
17752        // closed-set enum's arm-table.
17753        let composition = |suffix: &str| -> Option<Duration> {
17754            super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
17755        };
17756        for suffix in ["s", "m", "h"] {
17757            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
17758            let via_composition = composition(suffix);
17759            assert_eq!(
17760                via_method, via_composition,
17761                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
17762                 from_suffix({suffix:?}).map(window) — the substrate-primitive \
17763                 method must delegate to the arm-table's two typed dispatches, \
17764                 not shortcut through a per-suffix match table"
17765            );
17766            assert!(
17767                via_method.is_some(),
17768                "canonical suffix {suffix:?} must resolve to Some(Duration) via \
17769                 RateLimitUnit::window_from_suffix"
17770            );
17771        }
17772        for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
17773            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
17774            let via_composition = composition(suffix);
17775            assert_eq!(
17776                via_method, via_composition,
17777                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
17778                 from_suffix({suffix:?}).map(window) on the non-arm rejection \
17779                 axis too"
17780            );
17781            assert!(
17782                via_method.is_none(),
17783                "non-arm suffix {suffix:?} must project to None via \
17784                 RateLimitUnit::window_from_suffix — a future extension that \
17785                 accepted this suffix without a corresponding arm on the enum \
17786                 would split the codec's parse-accepted set from the enum's \
17787                 arm-table"
17788            );
17789        }
17790        // And the codec's parse arm now reads through this method: a
17791        // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
17792        // the same `Duration` the method returns for its unit, closing
17793        // the two-consumer drift surface (the codec's parse arm and the
17794        // enum's arm-table) with one typed dispatch on the substrate
17795        // primitive.
17796        for suffix in ["s", "m", "h"] {
17797            let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
17798            let mp: MeshPolicy = serde_json::from_str(&wire)
17799                .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
17800            let parsed = mp.rate_limit().expect("rate_limit payload present");
17801            let via_method = super::RateLimitUnit::window_from_suffix(suffix)
17802                .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
17803            assert_eq!(
17804                parsed.window(),
17805                via_method,
17806                "codec parse arm on {wire:?} must resolve the window through \
17807                 RateLimitUnit::window_from_suffix, not a divergent path"
17808            );
17809        }
17810    }
17811
17812    #[test]
17813    fn rate_limit_unit_all_enumerates_every_arm_once() {
17814        // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
17815        // enumerate every arm of the closed-set enum exactly once, in
17816        // the canonical shortest-to-longest window order (Second before
17817        // Minute before Hour) — the same order the sibling
17818        // [`crate::supervisor::RestartStrategy`] /
17819        // [`crate::supervisor::RestartPolicy`] /
17820        // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
17821        // typed enums carry (the arm declared first is the arm listed
17822        // first). A future variant addition that extends the enum
17823        // without appending to [`RateLimitUnit::ALL`] leaves the
17824        // exhaustive iteration surface silently short one arm — the
17825        // codec's parse arm would then reject the new suffix even
17826        // though the enum knows it. This pin closes the drift.
17827        assert_eq!(
17828            super::RateLimitUnit::ALL,
17829            &[
17830                super::RateLimitUnit::Second,
17831                super::RateLimitUnit::Minute,
17832                super::RateLimitUnit::Hour,
17833            ],
17834            "RateLimitUnit::ALL must enumerate every arm exactly once, \
17835             in canonical shortest-to-longest window order"
17836        );
17837    }
17838
17839    #[test]
17840    fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
17841        // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
17842        // every arm's [`RateLimitUnit::as_suffix`] output must parse
17843        // back through [`RateLimitUnit::from_suffix`] to the same
17844        // variant. A future arm addition that lands `as_suffix` but
17845        // forgets `from_suffix` (`from_suffix` iterates
17846        // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
17847        // is the load-bearing carrier of the round-trip; the sibling
17848        // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
17849        // the `ALL` half) trips here at caixa-core build time rather
17850        // than surfacing as a codec round-trip miss (a `render` emit
17851        // that lands a suffix the paired `parse` cannot decode).
17852        for unit in super::RateLimitUnit::ALL {
17853            let suffix = unit.as_suffix();
17854            let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
17855                panic!(
17856                    "RateLimitUnit::from_suffix({suffix:?}) must accept every \
17857                     RateLimitUnit::as_suffix output — got None for {unit:?}"
17858                )
17859            });
17860            assert_eq!(
17861                parsed, *unit,
17862                "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
17863                 must return RateLimitUnit::{unit:?}"
17864            );
17865        }
17866    }
17867
17868    #[test]
17869    fn rate_limit_unit_from_window_and_window_round_trip() {
17870        // Total round-trip pin on the `(from_window, window)` pair:
17871        // every arm's [`RateLimitUnit::window`] output must parse back
17872        // through [`RateLimitUnit::from_window`] to the same variant.
17873        // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
17874        // on the peer `Duration` axis — the two round-trip pins
17875        // together enshrine that both projections of the typed
17876        // canonical-unit bijection are total on the arm-set.
17877        for unit in super::RateLimitUnit::ALL {
17878            let window = unit.window();
17879            let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
17880                panic!(
17881                    "RateLimitUnit::from_window({window:?}) must accept every \
17882                     RateLimitUnit::window output — got None for {unit:?}"
17883                )
17884            });
17885            assert_eq!(
17886                parsed, *unit,
17887                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
17888                 must return RateLimitUnit::{unit:?}"
17889            );
17890        }
17891    }
17892
17893    #[test]
17894    fn rate_limit_unit_from_window_accessor_is_const_fn() {
17895        // Fail-before-pass-after pin: witnesses the
17896        // [`RateLimitUnit::from_window`] `const`-eval posture via a
17897        // `const fn` wrapper `from_window_via_const_fn(window: Duration)
17898        // -> Option<RateLimitUnit>` whose body calls
17899        // `RateLimitUnit::from_window(window)`, well-formed only when
17900        // the callee is itself `const fn` (any future downgrade to
17901        // non-`const` fails at caixa-core build time with E0015 `cannot
17902        // call non-const function`, strictly stronger than a runtime
17903        // `assert!`, side-stepping the destructor-in-const restriction
17904        // that blocks direct `const _: Option<RateLimitUnit> =
17905        // RateLimitUnit::from_window(...)` items on `Duration`'s
17906        // carrier). The runtime body sweeps every closed-set
17907        // [`RateLimitUnit::ALL`] arm plus a representative non-canonical
17908        // rejection sample (`Duration::from_millis(500)` sub-second
17909        // residue) and asserts the wrapped and direct dispatches agree
17910        // — a violation means the wrapper stopped compiling under a
17911        // future `const`-posture downgrade, or the reverse resolver's
17912        // arm-set silently split from the peer `Self::window` emitter's
17913        // arm-set. Peer of the sibling
17914        // [`crate::supervisor::tests::child_spec_restart_accessor_is_const_fn`]
17915        // (152c868) /
17916        // [`crate::supervisor::tests::supervisor_spec_estrategia_accessor_is_const_fn`]
17917        // (152c868) /
17918        // [`entrada_port_accessor_is_const_fn`] (bafa004) /
17919        // [`placement_estrategia_accessor_is_const_fn`] (bafa004)
17920        // `const`-eval-surface pins on the peer M2 / M3 substrate-
17921        // primitive `Copy`-return accessor axes, extended onto the
17922        // reverse `Duration → RateLimitUnit` projection axis on the
17923        // M3 mesh-slot rate-limit closed-set typed enum.
17924        const fn from_window_via_const_fn(window: Duration) -> Option<super::RateLimitUnit> {
17925            super::RateLimitUnit::from_window(window)
17926        }
17927        for unit in super::RateLimitUnit::ALL {
17928            let window = unit.window();
17929            let via_wrapper = from_window_via_const_fn(window);
17930            let direct = super::RateLimitUnit::from_window(window);
17931            assert_eq!(
17932                via_wrapper, direct,
17933                "RateLimitUnit::from_window({window:?}) via const fn \
17934                 wrapper must agree with direct dispatch for {unit:?}"
17935            );
17936            assert_eq!(
17937                via_wrapper,
17938                Some(*unit),
17939                "RateLimitUnit::from_window({window:?}) via const fn \
17940                 wrapper must return Some({unit:?}) for the peer \
17941                 window() output"
17942            );
17943        }
17944        assert!(from_window_via_const_fn(Duration::from_millis(500)).is_none());
17945        assert!(from_window_via_const_fn(Duration::from_secs(30)).is_none());
17946    }
17947
17948    #[test]
17949    fn rate_limit_unit_from_window_composes_through_window_accessor() {
17950        // Composition-witness pin on the routing-through-peer discipline:
17951        // [`RateLimitUnit::from_window`]'s per-arm probes each dispatch
17952        // through the peer `pub const fn` [`RateLimitUnit::window`]
17953        // canonical-`Duration` projection rather than a hand-authored
17954        // per-arm second-magnitude literal — a future arm-magnitude edit
17955        // on the sibling `window()` accessor (a `Second → 2s` typo, a
17956        // `Hour → 3599s` off-by-one) must therefore reach this reverse
17957        // resolver by construction. A pin that hard-coded the three
17958        // second-magnitudes here would silently split from the peer
17959        // emitter on any such edit; instead, this pin asserts the
17960        // composition invariant `from_window(u.window()) == Some(u)`
17961        // holds byte-for-byte on every closed-set [`RateLimitUnit::ALL`]
17962        // arm — a violation means either the peer `Self::window`
17963        // accessor drifted (breaking every downstream consumer that
17964        // reads through it), or the reverse resolver stopped routing
17965        // through the peer (introducing a hand-authored literal that
17966        // silently disagrees with the emitter). Either failure is a
17967        // caixa-core-build-time surface, not a downstream renderer
17968        // round-trip regression.
17969        //
17970        // Peer of the sibling
17971        // [`crate::render::assert_str_reexport_identity`] discipline on
17972        // the substrate-primitive `&'static str` re-export axis and the
17973        // [`rate_limit_unit_from_window_and_window_round_trip`]
17974        // round-trip pin on the peer projection direction; extends the
17975        // one-canonical-dispatch-per-projection discipline onto the
17976        // reverse-resolver's per-arm probe axis.
17977        for unit in super::RateLimitUnit::ALL {
17978            let window_via_peer = unit.window();
17979            let resolved = super::RateLimitUnit::from_window(window_via_peer);
17980            assert_eq!(
17981                resolved,
17982                Some(*unit),
17983                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
17984                 must return Some({unit:?}) — the reverse resolver's per-arm \
17985                 probes must route through the peer `Self::window` accessor \
17986                 so any future arm-magnitude edit reaches both projection \
17987                 directions by construction"
17988            );
17989        }
17990    }
17991
17992    #[test]
17993    fn rate_limit_canonical_unit_accessor_is_const_fn() {
17994        // Fail-before-pass-after pin: witnesses the
17995        // [`RateLimit::canonical_unit`] `const`-eval posture via a
17996        // `const fn` wrapper
17997        // `canonical_unit_via_const_fn(rl: &RateLimit) -> Option<RateLimitUnit>`
17998        // whose body calls `rl.canonical_unit()`, well-formed only when
17999        // the callee is itself `const fn` (any future downgrade to
18000        // non-`const` fails at caixa-core build time with E0015 `cannot
18001        // call non-const method`). The runtime body sweeps every
18002        // closed-set [`RateLimitUnit::ALL`] arm — for each arm,
18003        // constructs a typed [`RateLimit`] with the peer `Self::window`
18004        // canonical `Duration`, then asserts both the wrapper and the
18005        // direct dispatch agree and both return `Some(unit)`. Composes
18006        // with the sibling
18007        // [`rate_limit_unit_from_window_accessor_is_const_fn`] pin: the
18008        // typed [`RateLimit`] projection layer's `const`-posture is
18009        // load-bearing on the reverse resolver's `const`-posture, and
18010        // both must migrate together (a downgrade of either surface
18011        // splits the paired `const`-eval-surface pass on the M3
18012        // mesh-slot rate-limit `Duration ↔ Self` bijection).
18013        const fn canonical_unit_via_const_fn(
18014            rl: &super::RateLimit,
18015        ) -> Option<super::RateLimitUnit> {
18016            rl.canonical_unit()
18017        }
18018        for unit in super::RateLimitUnit::ALL {
18019            let rl = super::RateLimit {
18020                rate: 1,
18021                window: unit.window(),
18022            };
18023            let via_wrapper = canonical_unit_via_const_fn(&rl);
18024            let direct = rl.canonical_unit();
18025            assert_eq!(
18026                via_wrapper, direct,
18027                "RateLimit::canonical_unit() via const fn wrapper must \
18028                 agree with direct dispatch for {unit:?}"
18029            );
18030            assert_eq!(
18031                via_wrapper,
18032                Some(*unit),
18033                "RateLimit::canonical_unit() via const fn wrapper must \
18034                 return Some({unit:?}) for a RateLimit whose window is \
18035                 the peer RateLimitUnit::{unit:?}.window() output"
18036            );
18037        }
18038    }
18039
18040    #[test]
18041    fn rate_limit_unit_projections_are_pairwise_distinct() {
18042        // Distinctness pin: [`RateLimitUnit::as_suffix`] and
18043        // [`RateLimitUnit::window`] outputs must be pairwise distinct
18044        // across every arm — an accidental copy-paste flip that
18045        // reroutes one arm's suffix or window to also match another
18046        // silently collapses two arms onto one, so
18047        // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
18048        // (both using `find` on `Self::ALL`) would return whichever
18049        // arm the linear scan lands on first — a match-arm-ordering-
18050        // dependent outcome the closed-set typed-enum shape is meant
18051        // to rule out structurally. Peer of the sibling
18052        // `caixa_kind_wire_consts_are_pairwise_distinct` /
18053        // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
18054        // other closed-set typed-enum discriminator axes.
18055        let all = super::RateLimitUnit::ALL;
18056        for (i, a) in all.iter().enumerate() {
18057            for (j, b) in all.iter().enumerate() {
18058                if i != j {
18059                    assert_ne!(
18060                        a.as_suffix(),
18061                        b.as_suffix(),
18062                        "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
18063                         must be distinct — a collision silently collapses two \
18064                         arms onto one under from_suffix's linear scan"
18065                    );
18066                    assert_ne!(
18067                        a.window(),
18068                        b.window(),
18069                        "RateLimitUnit::{a:?}.window() and {b:?}.window() \
18070                         must be distinct — a collision silently collapses two \
18071                         arms onto one under from_window's linear scan"
18072                    );
18073                }
18074            }
18075        }
18076    }
18077
18078    #[test]
18079    fn rate_limit_unit_display_routes_through_as_suffix() {
18080        // Route pin: [`std::fmt::Display`] must byte-equal
18081        // [`RateLimitUnit::as_suffix`] on every arm — the single
18082        // source of truth for the canonical suffix. A future
18083        // reimplementation that hand-rolls the arms instead of
18084        // delegating to [`RateLimitUnit::as_suffix`] would silently
18085        // desynchronize `format!("{u}")` from the codec's parse arm
18086        // (which uses `as_suffix` to compare suffixes). Peer of the
18087        // sibling `caixa_kind_display_routes_through_as_str_helper` /
18088        // `placement_strategy_display_routes_through_as_str_helper`
18089        // pins on the peer closed-set typed-enum Display axes.
18090        for unit in super::RateLimitUnit::ALL {
18091            assert_eq!(
18092                unit.to_string(),
18093                unit.as_suffix(),
18094                "RateLimitUnit::{unit:?} Display must route through \
18095                 as_suffix (single source of truth: the canonical suffix \
18096                 the codec parses and renders)"
18097            );
18098        }
18099    }
18100
18101    #[test]
18102    fn rate_limit_unit_from_window_rejects_non_canonical() {
18103        // Rejection pin on the parser's accept-set: any Duration
18104        // outside the three-arm [`RateLimitUnit::window`] output set
18105        // (sub-second residue, or a second-magnitude outside `{1, 60,
18106        // 3600}`) must return `None`. A future accidental widening of
18107        // the accept-set (rounding down sub-second residue to the
18108        // nearest arm, admitting `Duration::from_secs(30)` as a
18109        // half-minute unit) would silently drift the parser's accept-
18110        // set from the emitter's — a validated slot with a
18111        // non-canonical window would then round-trip through the
18112        // codec to a canonical form the author never wrote.
18113        assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
18114        assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
18115        assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
18116        assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
18117        assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
18118        assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
18119        assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
18120    }
18121
18122    #[test]
18123    fn rate_limit_unit_from_suffix_rejects_unknown() {
18124        // Rejection pin on the suffix parser's accept-set: any string
18125        // outside the three-arm [`RateLimitUnit::as_suffix`] output
18126        // set must return `None`. Peer of the sibling
18127        // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
18128        // the [`crate::CaixaKind`] `from_wire` accept-set.
18129        for bad in [
18130            "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
18131            " s",
18132        ] {
18133            assert!(
18134                super::RateLimitUnit::from_suffix(bad).is_none(),
18135                "RateLimitUnit::from_suffix({bad:?}) must return None — the \
18136                 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
18137                 outputs"
18138            );
18139        }
18140    }
18141
18142    #[test]
18143    fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
18144        // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
18145        // every canonical `:window` magnitude the validate gate
18146        // accepts must map to the paired [`RateLimitUnit`] arm through
18147        // this accessor. A future validate-gate rebrand that widened
18148        // the accepted-window set without extending [`RateLimitUnit`]
18149        // would silently split the accessor's `Some`-return set from
18150        // the validate gate's accept-set — a slot that satisfies
18151        // validate would land at the accessor with `None`, so a
18152        // consumer past validate that pattern-matches on the returned
18153        // `Some` would silently miss the newly-accepted magnitude.
18154        for (window_secs, expected) in [
18155            (1u64, super::RateLimitUnit::Second),
18156            (60, super::RateLimitUnit::Minute),
18157            (3600, super::RateLimitUnit::Hour),
18158        ] {
18159            let rl = RateLimit {
18160                rate: 100,
18161                window: Duration::from_secs(window_secs),
18162            };
18163            assert_eq!(
18164                rl.canonical_unit(),
18165                Some(expected),
18166                "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
18167                 must return Some({expected:?})"
18168            );
18169        }
18170        // Non-canonical windows the validate gate rejects also return
18171        // None here — the accessor is the typed-enum projection of
18172        // the sibling `is_canonical_rate_limit_window` predicate.
18173        let bad = RateLimit {
18174            rate: 100,
18175            window: Duration::from_secs(30),
18176        };
18177        assert!(
18178            bad.canonical_unit().is_none(),
18179            "RateLimit with a non-canonical window must return None from \
18180             canonical_unit — the validate gate rejects the same set"
18181        );
18182    }
18183
18184    #[test]
18185    fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
18186        // Fail-before-pass-after byte-parity pin: for every canonical
18187        // window the [`rate_limit_codec::render`] arm's emitted string
18188        // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
18189        // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
18190        // the vestigial free helper [`rate_limit_window_unit`] (a
18191        // `find_map`-walked `Duration → &'static str` delegate) onto the
18192        // substrate primitive [`RateLimit::canonical_unit`] typed method
18193        // (a closed-set `match self.window` arm on
18194        // [`RateLimitUnit::from_window`], projected through
18195        // [`RateLimitUnit::as_suffix`] via the enum's
18196        // [`std::fmt::Display`] impl). A future re-routing of the render
18197        // arm through a differently-computed unit projection would break
18198        // this pin at build time rather than as a silent per-consumer
18199        // codec round-trip drift far from the substrate primitive edit.
18200        //
18201        // Sibling to the peer
18202        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
18203        // on the free-helper axis: that pin locks the two projections
18204        // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
18205        // on the closed-set arm table; this pin locks the codec's render
18206        // arm reads through the typed accessor rather than the free
18207        // helper. Two production consumers of the canonical-unit axis
18208        // now key off one typed dispatch on the substrate primitive.
18209        for (window_secs, unit) in [
18210            (1u64, super::RateLimitUnit::Second),
18211            (60, super::RateLimitUnit::Minute),
18212            (3600, super::RateLimitUnit::Hour),
18213        ] {
18214            let rl = RateLimit {
18215                rate: 42,
18216                window: Duration::from_secs(window_secs),
18217            };
18218            let policy = MeshPolicy {
18219                rate_limit: Some(rl),
18220                ..Default::default()
18221            };
18222            let json = serde_json::to_string(&policy).unwrap();
18223            let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
18224            assert!(
18225                json.contains(&expected),
18226                "rate_limit_codec::render must emit {expected} (via \
18227                 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
18228                 for a {window_secs}s window; serialized MeshPolicy was: {json}"
18229            );
18230            // And the accessor route resolves to the same typed unit
18231            // the render arm's Display formatting is asked to produce —
18232            // so a future edit that split the two paths (one through
18233            // the accessor, one through a re-introduced free helper)
18234            // trips this pin.
18235            assert_eq!(
18236                rl.canonical_unit(),
18237                Some(unit),
18238                "RateLimit::canonical_unit must return Some({unit:?}) for a \
18239                 {window_secs}s window; the codec render arm reads the same \
18240                 typed unit through this accessor"
18241            );
18242        }
18243    }
18244
18245    #[test]
18246    fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
18247        // Fail-before-pass-after byte-parity pin on the validate gate's
18248        // canonical-window shape probe: every non-canonical `:window`
18249        // the free-helper predicate [`is_canonical_rate_limit_window`]
18250        // rejects is also rejected by the substrate primitive
18251        // [`RateLimit::canonical_unit`] `.is_none()` route the validate
18252        // gate now reads through, and vice versa on the accepted set
18253        // (the three canonical windows). Locks the migration from the
18254        // free helper onto the substrate primitive: a future re-routing
18255        // of one of the two paths through a differently-computed unit
18256        // projection would silently split the codec's accepted set from
18257        // the validate gate's accepted set — a two-consumer drift the
18258        // codec-round-trip pin
18259        // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
18260        // above closes on the render arm and this pin closes on the
18261        // validate arm.
18262        for canonical_window_secs in [1u64, 60, 3600] {
18263            let mut s = three_member_spec();
18264            let rl = RateLimit {
18265                rate: 100,
18266                window: Duration::from_secs(canonical_window_secs),
18267            };
18268            s.politicas.rate_limit = Some(rl);
18269            assert!(
18270                s.validate().is_ok(),
18271                "canonical {canonical_window_secs}s window must pass \
18272                 validate_politicas — the validate gate now reads \
18273                 RateLimit::canonical_unit().is_none() and the accessor \
18274                 returns Some on every canonical arm"
18275            );
18276            assert!(
18277                rl.canonical_unit().is_some(),
18278                "canonical {canonical_window_secs}s window must resolve to \
18279                 Some on RateLimit::canonical_unit — the validate gate reads \
18280                 this accessor directly"
18281            );
18282        }
18283        for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
18284            let mut s = three_member_spec();
18285            let rl = RateLimit {
18286                rate: 100,
18287                window: Duration::from_secs(non_canonical_window_secs),
18288            };
18289            s.politicas.rate_limit = Some(rl);
18290            assert_eq!(
18291                s.validate().unwrap_err(),
18292                AplicacaoError::PolicyRateLimitWindowNotCanonical {
18293                    window: rl.window(),
18294                },
18295                "non-canonical {non_canonical_window_secs}s window must be \
18296                 rejected by validate_politicas — the validate gate now \
18297                 keys off RateLimit::canonical_unit().is_none()"
18298            );
18299            assert!(
18300                rl.canonical_unit().is_none(),
18301                "non-canonical {non_canonical_window_secs}s window must \
18302                 resolve to None on RateLimit::canonical_unit — the two \
18303                 paths (the free helper the validate gate previously read \
18304                 and the substrate primitive the validate gate now reads) \
18305                 must agree on the same rejected set"
18306            );
18307        }
18308        // And the substrate-primitive [`RateLimit::canonical_unit`]
18309        // accessor's accepted-window set matches the codec's parse arm's
18310        // accepted-suffix set on every canonical / non-canonical shape,
18311        // so a future silent drift between the codec's accepted set and
18312        // the validate gate's accepted set is a build error at test time
18313        // (both consumers key off the same closed-set enum's `match self`
18314        // arms). The predecessor free helper `is_canonical_rate_limit_window`
18315        // — a delegate that composed [`RateLimitUnit::from_window`] with
18316        // `.is_some()` — was deleted after this migration; the
18317        // canonical-window set now lives on exactly one typed dispatch
18318        // on the substrate primitive.
18319        for (secs, expected) in [
18320            (1u64, true),
18321            (60, true),
18322            (3600, true),
18323            (2, false),
18324            (30, false),
18325            (86_400, false),
18326        ] {
18327            let window = Duration::from_secs(secs);
18328            let rl = RateLimit { rate: 1, window };
18329            assert_eq!(
18330                rl.canonical_unit().is_some(),
18331                expected,
18332                "RateLimit::canonical_unit().is_some() must agree with the \
18333                 codec-accepted canonical-window set on {secs}s"
18334            );
18335            let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
18336                1 => "s",
18337                60 => "m",
18338                3600 => "h",
18339                _ => return,
18340            })
18341            .is_some_and(|d| d == window);
18342            if expected {
18343                assert!(
18344                    suffix_from_axis,
18345                    "the codec's `&str → Duration` axis \
18346                     ({secs}s) must round-trip to the same Duration the \
18347                     substrate primitive's accessor returns Some on"
18348                );
18349            }
18350        }
18351    }
18352
18353    #[test]
18354    fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
18355        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
18356        // derive: for each of the three variants, exactly one of the
18357        // generated `is_second` / `is_minute` / `is_hour` predicates
18358        // returns `true` and the other two return `false`. Peer of
18359        // the sibling
18360        // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
18361        // sibling `IsVariant`-derived closed-set typed-enum pins.
18362        let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
18363            (super::RateLimitUnit::Second, [true, false, false]),
18364            (super::RateLimitUnit::Minute, [false, true, false]),
18365            (super::RateLimitUnit::Hour, [false, false, true]),
18366        ];
18367        for (variant, expected) in rows {
18368            let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
18369            assert_eq!(
18370                observed, expected,
18371                "RateLimitUnit::{variant:?} is_* predicates must partition \
18372                 the arm set (second, minute, hour); got {observed:?}"
18373            );
18374        }
18375    }
18376
18377    #[test]
18378    fn rejects_policy_timeout_sub_millisecond() {
18379        // A purely sub-millisecond `Duration` (`from_micros(500)` =
18380        // 500_000 ns) is not the zero `Duration` — the `is_zero()`
18381        // arm passes — but `as_millis() == 0`, so the shared codec's
18382        // `render` arm returns the literal `"0s"`, which the
18383        // codec's `parse` arm then deserializes as `Duration::ZERO`
18384        // and the `PolicyTimeoutZero` zero-floor gate would reject
18385        // on re-validate. Pin the rejection at the typed slot's
18386        // canonical-floor gate so the round-trip break surfaces at
18387        // validate time, naming the offending `Duration`, rather
18388        // than at the next serialize → deserialize round-trip far
18389        // from the source `caixa.lisp`.
18390        let mut s = three_member_spec();
18391        let timeout = Duration::from_micros(500);
18392        s.politicas.timeout = Some(timeout);
18393        assert_eq!(
18394            s.validate().unwrap_err(),
18395            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
18396        );
18397    }
18398
18399    #[test]
18400    fn rejects_policy_timeout_non_integer_millisecond() {
18401        // A `Duration` with non-integer-millisecond residue
18402        // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
18403        // through the shared codec's `render` arm as `"1ms"` (the
18404        // `as_millis()` floor truncates), which the codec's `parse`
18405        // arm then deserializes as `Duration::from_millis(1)` =
18406        // 1_000_000 ns — silently *different* from the original.
18407        // Pin the rejection so this round-trip break surfaces at
18408        // validate time, where the offending `Duration` is named,
18409        // rather than as a silent value-laundered round-trip on the
18410        // next codec round-trip.
18411        let mut s = three_member_spec();
18412        let timeout = Duration::from_micros(1500);
18413        s.politicas.timeout = Some(timeout);
18414        assert_eq!(
18415            s.validate().unwrap_err(),
18416            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
18417        );
18418    }
18419
18420    #[test]
18421    fn accepts_policy_timeout_integer_millisecond_forms() {
18422        // The codec's accepted set — integer multiples of 1ms — is
18423        // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
18424        // `1h` all pass the canonical gate. Pin the canonical-forms
18425        // sweep so a future tightening of the codec's grammar (e.g.
18426        // dropping `:ms`) surfaces here as a test failure rather
18427        // than a silent contract narrowing on the typed slot.
18428        for timeout in [
18429            Duration::from_millis(1),
18430            Duration::from_millis(500),
18431            Duration::from_millis(1500),
18432            Duration::from_secs(30),
18433            Duration::from_secs(120),
18434            Duration::from_secs(3600),
18435        ] {
18436            let mut s = three_member_spec();
18437            s.politicas.timeout = Some(timeout);
18438            s.validate()
18439                .expect("integer-millisecond :timeout must validate");
18440        }
18441    }
18442
18443    #[test]
18444    fn policy_timeout_zero_takes_precedence_over_canonical() {
18445        // `Duration::ZERO` carries `subsec_nanos() == 0` and would
18446        // pass the canonical-millisecond gate; the more self-locating
18447        // `PolicyTimeoutZero` arm (which names the omit-axis
18448        // remediation directly) must fire first. Pin the ordering so
18449        // a future refactor that reorders the arms surfaces here as a
18450        // test failure rather than a silent diagnostic regression.
18451        let mut s = three_member_spec();
18452        s.politicas.timeout = Some(Duration::ZERO);
18453        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
18454    }
18455
18456    #[test]
18457    fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
18458        // The diagnostic envelope carries the offending `Duration`
18459        // verbatim so the author can grep their `caixa.lisp` for
18460        // `:timeout "<value>"` and fix it in one edit. Same
18461        // diagnostic shape every other typed-slot canonical-form
18462        // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
18463        // peer `:rate-limit :window` axis.
18464        let mut s = three_member_spec();
18465        let timeout = Duration::from_nanos(1_000_001);
18466        s.politicas.timeout = Some(timeout);
18467        match s.validate().unwrap_err() {
18468            AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
18469                assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
18470            }
18471            other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
18472        }
18473    }
18474
18475    #[test]
18476    fn rejects_policy_timeout_above_cap() {
18477        // The fail-before-pass-after pin: 3601s = 1h + 1s is
18478        // structurally one canonical-tick past the
18479        // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
18480        // integer-millisecond magnitude the canonical-form arm above
18481        // accepts cleanly, that the codec round-trips losslessly as
18482        // `"3601s"`, and that silently passed validate on every
18483        // pre-gate codebase because the typed slot's only checks were
18484        // the zero-floor and canonical-form arms. The mesh-level
18485        // deadline degenerates only at the runtime substrate (Envoy
18486        // / Cilium L7 timeout overlay) far from the source
18487        // `caixa.lisp` with no field naming the offending policy.
18488        let mut s = three_member_spec();
18489        let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
18490        s.politicas.timeout = Some(timeout);
18491        assert_eq!(
18492            s.validate().unwrap_err(),
18493            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
18494        );
18495    }
18496
18497    #[test]
18498    fn rejects_policy_timeout_one_millisecond_above_cap() {
18499        // Boundary case: exactly 1ms past the cap (the granularity
18500        // the canonical-form gate enforces). Catches a future
18501        // "strictly less than" half-measure and pins the diagnostic
18502        // to name the offending `Duration` verbatim. Peer of
18503        // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
18504        // boundary pin on the sibling `:limits :memory` top edge.
18505        let mut s = three_member_spec();
18506        let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
18507        s.politicas.timeout = Some(timeout);
18508        assert_eq!(
18509            s.validate().unwrap_err(),
18510            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
18511        );
18512    }
18513
18514    #[test]
18515    fn rejects_policy_timeout_far_above_cap() {
18516        // The "obvious authoring footgun" case: a `(:timeout "24h")`
18517        // or `(:timeout "86400s")` — values the canonical-form arm
18518        // accepts as integer-millisecond magnitudes, the codec
18519        // round-trips losslessly through serde, but the mesh-level
18520        // policy cannot honor (a 24-hour synchronous-`:contratos`
18521        // deadline is operationally indistinguishable from
18522        // omit-the-axis). Until this gate landed validate accepted
18523        // it. Pin both common above-cap values (24h, 7d) so a future
18524        // relaxation that drops the upper bound surfaces here.
18525        for timeout in [
18526            Duration::from_secs(86_400),    // 24h
18527            Duration::from_secs(604_800),   // 7d
18528            Duration::from_secs(1_000_000), // ~11.5 days
18529        ] {
18530            let mut s = three_member_spec();
18531            s.politicas.timeout = Some(timeout);
18532            assert_eq!(
18533                s.validate().unwrap_err(),
18534                AplicacaoError::PolicyTimeoutExceedsCap { timeout }
18535            );
18536        }
18537    }
18538
18539    #[test]
18540    fn accepts_policy_timeout_at_cap() {
18541        // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
18542        // must validate. The cap is inclusive on the top edge,
18543        // matching the [`POLICY_RETRIES_MAX`] /
18544        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
18545        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
18546        // sibling capped axes. Pin the boundary explicitly so a
18547        // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
18548        // instead of `>`) surfaces here as a test failure rather
18549        // than a silent contract narrowing.
18550        let mut s = three_member_spec();
18551        s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
18552        s.validate()
18553            .expect("timeout == POLICY_TIMEOUT_MAX must validate");
18554    }
18555
18556    #[test]
18557    fn accepts_policy_timeout_typical_values() {
18558        // The documented production-playbook band positive-control
18559        // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
18560        // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
18561        // plus a sweep through the long-running-workflow band
18562        // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
18563        // validated set explicitly so a future tightening of the
18564        // ceiling surfaces here as a deliberate test edit, not a
18565        // silent contract narrowing.
18566        for timeout in [
18567            Duration::from_millis(1),
18568            Duration::from_millis(500),
18569            Duration::from_secs(1),
18570            Duration::from_secs(10),
18571            Duration::from_secs(15), // Envoy default
18572            Duration::from_secs(30),
18573            Duration::from_secs(60), // AWS App Mesh typical
18574            Duration::from_secs(300),
18575            Duration::from_secs(900),
18576            Duration::from_secs(1800),
18577            Duration::from_secs(3600), // exactly 1h, the cap
18578        ] {
18579            let mut s = three_member_spec();
18580            s.politicas.timeout = Some(timeout);
18581            s.validate()
18582                .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
18583        }
18584    }
18585
18586    #[test]
18587    fn policy_timeout_zero_takes_precedence_over_cap() {
18588        // The cross-arm ordering pin: `Duration::ZERO` is
18589        // structurally outside both `>= 1ms` (zero-floor) and
18590        // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
18591        // diagnostic is the more self-locating one (it directly
18592        // names the omit-axis remediation), so the validate gate
18593        // must fire on zero first. Same shape every other
18594        // zero-then-shape ordering on this surface uses
18595        // ([`AplicacaoError::PolicyRetriesZero`] then
18596        // [`AplicacaoError::PolicyRetriesExceedsCap`];
18597        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
18598        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
18599        let mut s = three_member_spec();
18600        s.politicas.timeout = Some(Duration::ZERO);
18601        assert_eq!(
18602            s.validate().unwrap_err(),
18603            AplicacaoError::PolicyTimeoutZero,
18604            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
18605        );
18606    }
18607
18608    #[test]
18609    fn policy_timeout_canonical_takes_precedence_over_cap() {
18610        // The cross-arm ordering pin: a `Duration` that is *both*
18611        // sub-millisecond (non-canonical-form) and structurally
18612        // above the cap surfaces the canonical-form diagnostic
18613        // first, because the round-trip-shape break is the more
18614        // fundamental issue (the value can't even round-trip
18615        // through the codec, so the cap diagnostic naming
18616        // `1ms..=1h` would be misleading — there's no integer-ms
18617        // form of the offending value). Pin the order so a future
18618        // refactor that reorders the arms surfaces here as a test
18619        // failure rather than a silent diagnostic regression.
18620        let mut s = three_member_spec();
18621        // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
18622        // *and* total magnitude above the 1h cap.
18623        let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
18624        s.politicas.timeout = Some(timeout);
18625        assert_eq!(
18626            s.validate().unwrap_err(),
18627            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
18628            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
18629        );
18630    }
18631
18632    #[test]
18633    fn policy_timeout_cap_diagnostic_carries_offending_value() {
18634        // The diagnostic-shape pin: the offending `Duration` is
18635        // carried verbatim into the
18636        // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
18637        // surfaced error message names the value the author wrote
18638        // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
18639        // exceeds the mesh-policy ceiling …"`), not just the cap.
18640        // Same self-locating diagnostic shape every other typed-cap
18641        // arm on this surface carries
18642        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
18643        // offending retry count verbatim).
18644        let mut s = three_member_spec();
18645        let timeout = Duration::from_secs(7200); // 2h
18646        s.politicas.timeout = Some(timeout);
18647        let err = s.validate().unwrap_err();
18648        assert!(
18649            matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
18650            "got {err:?}"
18651        );
18652        let msg = err.to_string();
18653        assert!(
18654            msg.contains("7200"),
18655            ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
18656        );
18657    }
18658
18659    #[test]
18660    fn policy_timeout_cap_pins_canonical_value() {
18661        // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
18662        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
18663        // the shared duration codec emits as a clean canonical
18664        // string (`"<n>h"`). Pinning the literal value here surfaces
18665        // a future drift (a relaxation to 24h, a tightening to 5m)
18666        // as a deliberate test edit, not a silent contract
18667        // narrowing. Same shape every other typed-cap value pin on
18668        // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
18669        assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
18670        assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
18671    }
18672
18673    #[test]
18674    fn policy_timeout_cap_value_round_trips_through_codec() {
18675        // The codec round-trip property the cap arm preserves: the
18676        // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
18677        // the shared duration codec — every value at the cap renders
18678        // to a clean canonical string (`"1h"`) and parses back to
18679        // the same `Duration`. Pin this so a future drift between
18680        // the cap constant and the codec's largest emitted unit
18681        // surfaces here. Same shape every other typed boundary pin
18682        // on this surface uses
18683        // (`wasm32_memory_cap_matches_parsed_4_gib`).
18684        let policy = MeshPolicy {
18685            timeout: Some(POLICY_TIMEOUT_MAX),
18686            ..Default::default()
18687        };
18688        let json = serde_json::to_string(&policy).unwrap();
18689        // The codec emits `"1h"` for the canonical 1-hour magnitude.
18690        assert!(
18691            json.contains("\"1h\""),
18692            "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
18693        );
18694        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18695        assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
18696    }
18697
18698    #[test]
18699    fn rejects_circuit_breaker_window_sub_millisecond() {
18700        // Peer of the `:timeout` sub-millisecond arm on the second
18701        // typed-`Duration` `:politicas` axis: a purely sub-ms
18702        // `Duration` (`from_micros(500)`) renders through the shared
18703        // codec as `"0s"`, which the codec parses back to
18704        // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
18705        // zero-floor gate then rejects on re-validate.
18706        let mut s = three_member_spec();
18707        let window = Duration::from_micros(500);
18708        s.politicas.circuit_breaker = Some(CircuitBreaker {
18709            max_failures: 5,
18710            window,
18711        });
18712        assert_eq!(
18713            s.validate().unwrap_err(),
18714            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
18715        );
18716    }
18717
18718    #[test]
18719    fn rejects_circuit_breaker_window_non_integer_millisecond() {
18720        // Peer of the `:timeout` non-integer-ms arm: a `Duration`
18721        // with non-integer-millisecond residue renders through the
18722        // shared codec as the truncated `"<n>ms"` form, parsing back
18723        // to a *different* `Duration` on the next round-trip.
18724        let mut s = three_member_spec();
18725        let window = Duration::from_micros(1500);
18726        s.politicas.circuit_breaker = Some(CircuitBreaker {
18727            max_failures: 5,
18728            window,
18729        });
18730        assert_eq!(
18731            s.validate().unwrap_err(),
18732            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
18733        );
18734    }
18735
18736    #[test]
18737    fn accepts_circuit_breaker_window_integer_millisecond_forms() {
18738        // The canonical-forms sweep on the breaker axis: every
18739        // integer-ms multiple the codec round-trips losslessly
18740        // passes the canonical gate.
18741        for window in [
18742            Duration::from_millis(1),
18743            Duration::from_millis(500),
18744            Duration::from_millis(1500),
18745            Duration::from_secs(30),
18746            Duration::from_secs(60),
18747            Duration::from_secs(3600),
18748        ] {
18749            let mut s = three_member_spec();
18750            s.politicas.circuit_breaker = Some(CircuitBreaker {
18751                max_failures: 5,
18752                window,
18753            });
18754            s.validate()
18755                .expect("integer-millisecond :circuit-breaker :window must validate");
18756        }
18757    }
18758
18759    #[test]
18760    fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
18761        // `Duration::ZERO` would pass the canonical-ms gate (the
18762        // sub-ns residue is zero) but must surface the narrower
18763        // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
18764        // remediation.
18765        let mut s = three_member_spec();
18766        s.politicas.circuit_breaker = Some(CircuitBreaker {
18767            max_failures: 5,
18768            window: Duration::ZERO,
18769        });
18770        assert_eq!(
18771            s.validate().unwrap_err(),
18772            AplicacaoError::PolicyBreakerZeroWindow
18773        );
18774    }
18775
18776    #[test]
18777    fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
18778        // Both axes invalid: max_failures == 0 *and* window is
18779        // sub-ms. The validate gate must fire on max_failures first
18780        // (matching the existing ordering pin
18781        // `rejects_circuit_breaker_zero_max_failures` enshrines), so
18782        // the existing diagnostic continues to lead with the simpler
18783        // "zero threshold" framing.
18784        let mut s = three_member_spec();
18785        s.politicas.circuit_breaker = Some(CircuitBreaker {
18786            max_failures: 0,
18787            window: Duration::from_micros(500),
18788        });
18789        assert_eq!(
18790            s.validate().unwrap_err(),
18791            AplicacaoError::PolicyBreakerZeroFailures
18792        );
18793    }
18794
18795    #[test]
18796    fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
18797        let mut s = three_member_spec();
18798        let window = Duration::from_nanos(60_000_000_001);
18799        s.politicas.circuit_breaker = Some(CircuitBreaker {
18800            max_failures: 5,
18801            window,
18802        });
18803        match s.validate().unwrap_err() {
18804            AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
18805                assert_eq!(w, window, "diagnostic must carry the offending Duration");
18806            }
18807            other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
18808        }
18809    }
18810
18811    #[test]
18812    fn rejects_circuit_breaker_window_above_cap() {
18813        // The fail-before-pass-after pin: 3601s = 1h + 1s is
18814        // structurally one canonical-tick past the
18815        // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
18816        // integer-millisecond magnitude the canonical-form arm above
18817        // accepts cleanly, that the codec round-trips losslessly as
18818        // `"3601s"`, and that silently passed validate on every
18819        // pre-gate codebase because the typed slot's only checks were
18820        // the zero-floor and canonical-form arms. The
18821        // rolling-window-to-lifetime-counter degeneration surfaces
18822        // only at the runtime substrate (Envoy's outlier_detection
18823        // interval, the future CiliumClusterwideEnvoyConfig overlay)
18824        // far from the source `caixa.lisp` with no field naming the
18825        // offending policy.
18826        let mut s = three_member_spec();
18827        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
18828        s.politicas.circuit_breaker = Some(CircuitBreaker {
18829            max_failures: 5,
18830            window,
18831        });
18832        assert_eq!(
18833            s.validate().unwrap_err(),
18834            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
18835        );
18836    }
18837
18838    #[test]
18839    fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
18840        // Boundary case: exactly 1ms past the cap (the granularity the
18841        // canonical-form gate enforces). Catches a future "strictly
18842        // less than" half-measure and pins the diagnostic to name the
18843        // offending `Duration` verbatim. Peer of
18844        // `rejects_policy_timeout_one_millisecond_above_cap` on the
18845        // sibling duration-typed `:politicas :timeout` top edge.
18846        let mut s = three_member_spec();
18847        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
18848        s.politicas.circuit_breaker = Some(CircuitBreaker {
18849            max_failures: 5,
18850            window,
18851        });
18852        assert_eq!(
18853            s.validate().unwrap_err(),
18854            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
18855        );
18856    }
18857
18858    #[test]
18859    fn rejects_circuit_breaker_window_far_above_cap() {
18860        // The "obvious authoring footgun" case: a `(:window "24h")` or
18861        // `(:window "86400s")` — values the canonical-form arm
18862        // accepts as integer-millisecond magnitudes, the codec
18863        // round-trips losslessly through serde, but the
18864        // rolling-window breaker contract cannot honor (a 24-hour
18865        // rolling failure window is operationally a lifetime counter).
18866        // Until this gate landed validate accepted it. Pin both common
18867        // above-cap values (24h, 7d) so a future relaxation that
18868        // drops the upper bound surfaces here.
18869        for window in [
18870            Duration::from_secs(86_400),    // 24h
18871            Duration::from_secs(604_800),   // 7d
18872            Duration::from_secs(1_000_000), // ~11.5 days
18873        ] {
18874            let mut s = three_member_spec();
18875            s.politicas.circuit_breaker = Some(CircuitBreaker {
18876                max_failures: 5,
18877                window,
18878            });
18879            assert_eq!(
18880                s.validate().unwrap_err(),
18881                AplicacaoError::PolicyBreakerWindowExceedsCap { window }
18882            );
18883        }
18884    }
18885
18886    #[test]
18887    fn accepts_circuit_breaker_window_at_cap() {
18888        // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
18889        // (1h) — must validate. The cap is inclusive on the top edge,
18890        // matching the [`POLICY_TIMEOUT_MAX`] /
18891        // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
18892        // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
18893        // sibling capped axes. Pin the boundary explicitly so a
18894        // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
18895        // instead of `>`) surfaces here as a test failure rather than
18896        // a silent contract narrowing.
18897        let mut s = three_member_spec();
18898        s.politicas.circuit_breaker = Some(CircuitBreaker {
18899            max_failures: 5,
18900            window: POLICY_BREAKER_WINDOW_MAX,
18901        });
18902        s.validate()
18903            .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
18904    }
18905
18906    #[test]
18907    fn accepts_circuit_breaker_window_typical_values() {
18908        // The documented production-playbook band positive-control
18909        // sweep — every value Hystrix / resilience4j / Istio / Envoy
18910        // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
18911        // through the long-tail failure-detection band (15m, 30m, 1h)
18912        // the cap accepts. Pin the inclusive validated set explicitly
18913        // so a future tightening of the ceiling surfaces here as a
18914        // deliberate test edit, not a silent contract narrowing.
18915        for window in [
18916            Duration::from_millis(1),
18917            Duration::from_millis(500),
18918            Duration::from_secs(1),
18919            Duration::from_secs(10), // Hystrix / Istio / Envoy default
18920            Duration::from_secs(30),
18921            Duration::from_secs(60),  // resilience4j typical
18922            Duration::from_secs(300), // AWS App Mesh typical
18923            Duration::from_secs(900),
18924            Duration::from_secs(1800),
18925            Duration::from_secs(3600), // exactly 1h, the cap
18926        ] {
18927            let mut s = three_member_spec();
18928            s.politicas.circuit_breaker = Some(CircuitBreaker {
18929                max_failures: 5,
18930                window,
18931            });
18932            s.validate()
18933                .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
18934        }
18935    }
18936
18937    #[test]
18938    fn circuit_breaker_zero_window_takes_precedence_over_cap() {
18939        // The cross-arm ordering pin: `Duration::ZERO` is structurally
18940        // outside both `>= 1ms` (zero-floor) and
18941        // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
18942        // diagnostic is the more self-locating one (it directly names
18943        // the omit-axis remediation), so the validate gate must fire
18944        // on zero first. Same shape every other zero-then-cap
18945        // ordering on this surface uses
18946        // ([`AplicacaoError::PolicyTimeoutZero`] then
18947        // [`AplicacaoError::PolicyTimeoutExceedsCap`];
18948        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
18949        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
18950        let mut s = three_member_spec();
18951        s.politicas.circuit_breaker = Some(CircuitBreaker {
18952            max_failures: 5,
18953            window: Duration::ZERO,
18954        });
18955        assert_eq!(
18956            s.validate().unwrap_err(),
18957            AplicacaoError::PolicyBreakerZeroWindow,
18958            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
18959        );
18960    }
18961
18962    #[test]
18963    fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
18964        // The cross-arm ordering pin: a `Duration` that is *both*
18965        // sub-millisecond (non-canonical-form) and structurally above
18966        // the cap surfaces the canonical-form diagnostic first,
18967        // because the round-trip-shape break is the more fundamental
18968        // issue (the value can't even round-trip through the codec, so
18969        // the cap diagnostic naming `1ms..=1h` would be misleading —
18970        // there's no integer-ms form of the offending value). Pin the
18971        // order so a future refactor that reorders the arms surfaces
18972        // here as a test failure rather than a silent diagnostic
18973        // regression. Peer of
18974        // `policy_timeout_canonical_takes_precedence_over_cap` on the
18975        // sibling duration-typed `:politicas :timeout` axis.
18976        let mut s = three_member_spec();
18977        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
18978        s.politicas.circuit_breaker = Some(CircuitBreaker {
18979            max_failures: 5,
18980            window,
18981        });
18982        assert_eq!(
18983            s.validate().unwrap_err(),
18984            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
18985            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
18986        );
18987    }
18988
18989    #[test]
18990    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
18991        // The cross-arm ordering pin between the two breaker axes: a
18992        // `CircuitBreaker` whose *both* `max_failures` is above its
18993        // cap *and* `window` is above its cap surfaces the
18994        // max-failures cap diagnostic first, because the validate
18995        // gate visits the failures arm before the window arm. Pin the
18996        // order so a future refactor that reorders the breaker arms
18997        // surfaces here.
18998        let mut s = three_member_spec();
18999        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
19000        s.politicas.circuit_breaker = Some(CircuitBreaker {
19001            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
19002            window,
19003        });
19004        assert_eq!(
19005            s.validate().unwrap_err(),
19006            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
19007                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
19008            },
19009            "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
19010        );
19011    }
19012
19013    #[test]
19014    fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
19015        // The diagnostic-shape pin: the offending `Duration` is
19016        // carried verbatim into the
19017        // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
19018        // the surfaced error message names the value the author wrote
19019        // (`":politicas :circuit-breaker :window (Duration { secs:
19020        // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
19021        // just the cap. Same self-locating diagnostic shape every
19022        // other typed-cap arm on this surface carries
19023        // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
19024        // offending `Duration` verbatim).
19025        let mut s = three_member_spec();
19026        let window = Duration::from_secs(7200); // 2h
19027        s.politicas.circuit_breaker = Some(CircuitBreaker {
19028            max_failures: 5,
19029            window,
19030        });
19031        let err = s.validate().unwrap_err();
19032        assert!(
19033            matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
19034            "got {err:?}"
19035        );
19036        let msg = err.to_string();
19037        assert!(
19038            msg.contains("7200"),
19039            ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
19040        );
19041    }
19042
19043    #[test]
19044    fn circuit_breaker_window_cap_pins_canonical_value() {
19045        // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
19046        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
19047        // shared duration codec emits as a clean canonical string
19048        // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
19049        // the sibling duration-typed `:politicas :timeout` axis (the
19050        // two duration-typed `:politicas` axes share a uniform top
19051        // edge). Pinning the literal value here surfaces a future
19052        // drift (a relaxation to 24h, a tightening to 5m) as a
19053        // deliberate test edit, not a silent contract narrowing. Same
19054        // shape every other typed-cap value pin on this surface uses
19055        // (`policy_timeout_cap_pins_canonical_value`).
19056        assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
19057        assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
19058        assert_eq!(
19059            POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
19060            "the two duration-typed `:politicas` caps share the same top edge"
19061        );
19062    }
19063
19064    #[test]
19065    fn circuit_breaker_window_cap_value_round_trips_through_codec() {
19066        // The codec round-trip property the cap arm preserves: the
19067        // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
19068        // through the shared duration codec — every value at the cap
19069        // renders to a clean canonical string (`"1h"`) and parses back
19070        // to the same `Duration`. Pin this so a future drift between
19071        // the cap constant and the codec's largest emitted unit
19072        // surfaces here. Same shape every other typed boundary pin on
19073        // this surface uses
19074        // (`policy_timeout_cap_value_round_trips_through_codec`).
19075        let policy = MeshPolicy {
19076            circuit_breaker: Some(CircuitBreaker {
19077                max_failures: 5,
19078                window: POLICY_BREAKER_WINDOW_MAX,
19079            }),
19080            ..Default::default()
19081        };
19082        let json = serde_json::to_string(&policy).unwrap();
19083        // The codec emits `"1h"` for the canonical 1-hour magnitude.
19084        assert!(
19085            json.contains("\"1h\""),
19086            "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
19087        );
19088        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
19089        assert_eq!(
19090            back.circuit_breaker.unwrap().window,
19091            POLICY_BREAKER_WINDOW_MAX
19092        );
19093    }
19094
19095    #[test]
19096    fn is_integer_millisecond_duration_predicate_tracks_codec() {
19097        // Pin the predicate's accepted set against the codec's
19098        // accepted set explicitly. The codec parses
19099        // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
19100        // accepted value is an integer-millisecond multiple — so the
19101        // predicate must accept exactly that set. Same shape every
19102        // other predicate-on-the-typed-slot helper carries
19103        // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
19104        // Read directly from the codec-owned predicate — the crate's
19105        // single source of truth every typed-`Duration` axis now routes
19106        // through via
19107        // [`crate::render::require_positive_canonical_bounded_duration`].
19108        use super::supervisor::duration_codec::is_integer_millisecond_duration;
19109        assert!(is_integer_millisecond_duration(Duration::ZERO));
19110        assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
19111        assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
19112        assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
19113        assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
19114        assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
19115        // Non-integer-millisecond residue: rejected.
19116        assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
19117        assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
19118        assert!(!is_integer_millisecond_duration(Duration::from_micros(
19119            1500
19120        )));
19121        assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
19122        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
19123            999_999
19124        )));
19125        // The 1-ns-past-1ms boundary: rejected (no longer a clean
19126        // integer-millisecond multiple).
19127        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
19128            1_000_001
19129        )));
19130    }
19131
19132    #[test]
19133    fn policy_timeout_validated_value_round_trips_through_codec() {
19134        // The structural property the canonical-ms gate enforces:
19135        // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
19136        // round-trips losslessly through the shared `duration_codec`
19137        // (serialize → string → deserialize → equal value). Pin this
19138        // end-to-end so a future change to either side (the validate
19139        // gate's accepted granularity, the codec's parse/render unit
19140        // set) that breaks the alignment surfaces here. The
19141        // previous-state shape (typed slot accepts arbitrary
19142        // `Duration`, codec only round-trips integer-ms) would fail
19143        // this test for any `Duration::from_micros(1500)` timeout —
19144        // the validate gate now forecloses that.
19145        for timeout in [
19146            Duration::from_millis(1),
19147            Duration::from_millis(1500),
19148            Duration::from_secs(30),
19149            Duration::from_secs(3600),
19150        ] {
19151            let mut s = three_member_spec();
19152            s.politicas.timeout = Some(timeout);
19153            s.validate().unwrap();
19154            let json = serde_json::to_string(&s.politicas).unwrap();
19155            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
19156            assert_eq!(
19157                back.timeout, s.politicas.timeout,
19158                "every validated :timeout must round-trip losslessly through the codec"
19159            );
19160        }
19161    }
19162
19163    #[test]
19164    fn circuit_breaker_window_validated_value_round_trips_through_codec() {
19165        // Peer of the `:timeout` round-trip property on the breaker
19166        // axis.
19167        for window in [
19168            Duration::from_millis(1),
19169            Duration::from_millis(1500),
19170            Duration::from_secs(30),
19171            Duration::from_secs(3600),
19172        ] {
19173            let mut s = three_member_spec();
19174            s.politicas.circuit_breaker = Some(CircuitBreaker {
19175                max_failures: 5,
19176                window,
19177            });
19178            s.validate().unwrap();
19179            let json = serde_json::to_string(&s.politicas).unwrap();
19180            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
19181            assert_eq!(
19182                back.circuit_breaker.unwrap().window,
19183                window,
19184                "every validated :circuit-breaker :window must round-trip losslessly"
19185            );
19186        }
19187    }
19188
19189    #[test]
19190    fn empty_politicas_validates() {
19191        // Omitting every policy axis is fine — defaults express "no
19192        // policy on this axis", not "policy = 0". The fixture's typical
19193        // values continue to validate; this test pins that
19194        // MeshPolicy::default() is a clean pass through validate().
19195        let mut s = three_member_spec();
19196        s.politicas = MeshPolicy::default();
19197        s.validate().unwrap();
19198    }
19199
19200    #[test]
19201    fn typical_politicas_validates_with_every_axis_set() {
19202        // The full §III.1 example block (timeout + retries + breaker +
19203        // mtls + rate-limit) — every axis nonzero — must remain a
19204        // clean pass.
19205        let mut s = three_member_spec();
19206        s.politicas = MeshPolicy {
19207            timeout: Some(Duration::from_secs(30)),
19208            retries: Some(3),
19209            circuit_breaker: Some(CircuitBreaker {
19210                max_failures: 5,
19211                window: Duration::from_secs(60),
19212            }),
19213            mtls_required: Some(true),
19214            rate_limit: Some(RateLimit {
19215                rate: 100,
19216                window: Duration::from_secs(1),
19217            }),
19218        };
19219        s.validate().unwrap();
19220    }
19221
19222    #[test]
19223    fn rejects_empty_cluster_name() {
19224        let mut s = three_member_spec();
19225        s.placement.clusters = vec!["rio".into(), "".into()];
19226        assert_eq!(
19227            s.validate().unwrap_err(),
19228            AplicacaoError::PlacementClusterEmpty
19229        );
19230    }
19231
19232    #[test]
19233    fn rejects_duplicate_cluster_names() {
19234        let mut s = three_member_spec();
19235        s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
19236        let err = s.validate().unwrap_err();
19237        assert!(
19238            matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
19239            "got {err:?}"
19240        );
19241    }
19242
19243    #[test]
19244    fn rejects_placement_cluster_with_uppercase() {
19245        // The canonical "I copied the cluster's display name verbatim"
19246        // typo — K8s context names are lowercase per DNS-1123 label
19247        // rule, but org docs often round-trip a TitleCase identifier
19248        // (`Rio`, `Mar-East`) from an ADR. Mirrors the
19249        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
19250        // on the peer name axis.
19251        let mut s = three_member_spec();
19252        s.placement.clusters = vec!["Rio".into(), "mar".into()];
19253        let err = s.validate().unwrap_err();
19254        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
19255            panic!("expected PlacementClusterInvalid, got other variant");
19256        };
19257        assert_eq!(cluster, "Rio");
19258        assert!(
19259            reason.contains("uppercase"),
19260            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
19261        );
19262        assert!(
19263            reason.contains("\"rio\""),
19264            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
19265        );
19266    }
19267
19268    #[test]
19269    fn rejects_placement_cluster_with_underscore() {
19270        // The canonical "I'm thinking of an env var / hostname slug"
19271        // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
19272        // schema. K8s context filtering on `my_cluster` silently misses
19273        // the cluster the author intended; the gate moves it to caixa-
19274        // build time. Same shape as `rejects_membro_caixa_with_underscore`
19275        // (3f9d7a0).
19276        let mut s = three_member_spec();
19277        s.placement.clusters = vec!["my_cluster".into()];
19278        let err = s.validate().unwrap_err();
19279        assert!(
19280            matches!(
19281                err,
19282                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
19283                    if cluster == "my_cluster" && reason.contains('_')
19284            ),
19285            "got {err:?}"
19286        );
19287    }
19288
19289    #[test]
19290    fn rejects_placement_cluster_with_dot() {
19291        // A `:placement :clusters` entry is a single DNS-1123 *label*,
19292        // not a subdomain — even though K8s context names sometimes
19293        // carry a dotted form via kubeconfig conventions, the strictest
19294        // floor among the use sites (DNS-1035 cluster.x-k8s.io
19295        // `metadata.name`, Cilium identity label values) wins. The "I
19296        // want to namespace my cluster names with `.`" intent is
19297        // expressed via `-` (`mar-east`).
19298        let mut s = three_member_spec();
19299        s.placement.clusters = vec!["team.rio".into()];
19300        let err = s.validate().unwrap_err();
19301        assert!(
19302            matches!(
19303                err,
19304                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
19305                    if cluster == "team.rio" && reason.contains('.')
19306            ),
19307            "got {err:?}"
19308        );
19309    }
19310
19311    #[test]
19312    fn rejects_placement_cluster_with_leading_hyphen() {
19313        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
19314        // with an alphanumeric. The K8s apiserver rejects `-rio`
19315        // outright; the rendered fan-out would emit a `metadata.name:
19316        // "-rio"` that fails admission far from the source caixa.lisp.
19317        let mut s = three_member_spec();
19318        s.placement.clusters = vec!["-rio".into()];
19319        let err = s.validate().unwrap_err();
19320        assert!(
19321            matches!(
19322                err,
19323                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
19324                    if cluster == "-rio" && reason.contains("start and end")
19325            ),
19326            "got {err:?}"
19327        );
19328    }
19329
19330    #[test]
19331    fn rejects_placement_cluster_with_trailing_hyphen() {
19332        // The symmetric arm of the boundary rule. Pin separately so
19333        // both ends are covered against a future relaxation that only
19334        // checks one boundary (parallel to
19335        // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
19336        let mut s = three_member_spec();
19337        s.placement.clusters = vec!["rio-".into()];
19338        let err = s.validate().unwrap_err();
19339        assert!(
19340            matches!(
19341                err,
19342                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
19343                    if cluster == "rio-"
19344            ),
19345            "got {err:?}"
19346        );
19347    }
19348
19349    #[test]
19350    fn rejects_placement_cluster_with_unicode() {
19351        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
19352        // before it reaches K8s. The byte-by-byte ASCII validity check
19353        // rejects multi-byte UTF-8 sequences by the first byte that
19354        // fails `[a-z0-9-]`.
19355        let mut s = three_member_spec();
19356        s.placement.clusters = vec!["rió".into()];
19357        let err = s.validate().unwrap_err();
19358        assert!(
19359            matches!(
19360                err,
19361                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
19362                    if cluster == "rió"
19363            ),
19364            "got {err:?}"
19365        );
19366    }
19367
19368    #[test]
19369    fn rejects_placement_cluster_with_whitespace() {
19370        // Whitespace is the canonical "I pasted from a sketch / doc"
19371        // footgun. The apiserver rejects every cluster `metadata.name`
19372        // value carrying whitespace.
19373        let mut s = three_member_spec();
19374        s.placement.clusters = vec!["rio cluster".into()];
19375        let err = s.validate().unwrap_err();
19376        assert!(
19377            matches!(
19378                err,
19379                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
19380                    if cluster == "rio cluster"
19381            ),
19382            "got {err:?}"
19383        );
19384    }
19385
19386    #[test]
19387    fn rejects_placement_cluster_too_long() {
19388        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
19389        // pin. The diagnostic names both the cap (63) and the actual
19390        // length so the author can shorten in one edit. Mirrors
19391        // `rejects_membro_caixa_too_long` (3f9d7a0).
19392        let mut s = three_member_spec();
19393        let too_long = "a".repeat(64);
19394        s.placement.clusters = vec![too_long.clone()];
19395        let err = s.validate().unwrap_err();
19396        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
19397            panic!("expected PlacementClusterInvalid");
19398        };
19399        assert_eq!(cluster, too_long);
19400        assert!(
19401            reason.contains("63") && reason.contains("64"),
19402            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
19403        );
19404    }
19405
19406    #[test]
19407    fn placement_cluster_max_length_validates() {
19408        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
19409        // future tightening (e.g. dropping to 62) surfaces here as a
19410        // regression, mirroring `membro_caixa_max_length_validates`
19411        // (3f9d7a0).
19412        let mut s = three_member_spec();
19413        s.placement.clusters = vec!["a".repeat(63)];
19414        s.validate().unwrap();
19415    }
19416
19417    #[test]
19418    fn accepts_canonical_placement_cluster_forms() {
19419        // The DNS-1123 label shapes a caixa author is realistically
19420        // going to write for cluster names: single-word lowercase
19421        // (`rio`), regional hyphen-joined (`mar-east`), single
19422        // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
19423        // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
19424        // Pin every leg so a future tightening that bans (e.g.) digit-
19425        // start identifiers surfaces here.
19426        for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
19427            let mut s = three_member_spec();
19428            s.placement.clusters = vec![form.into()];
19429            s.validate().unwrap_or_else(|e| {
19430                panic!("canonical cluster form {form:?} must validate, got {e:?}")
19431            });
19432        }
19433    }
19434
19435    #[test]
19436    fn placement_cluster_empty_takes_precedence_over_invalid() {
19437        // Order pin: the existing `PlacementClusterEmpty` diagnostic
19438        // (which doesn't try to parse) fires before the new
19439        // `PlacementClusterInvalid` parse-side diagnostic, so an empty
19440        // `:clusters` entry keeps its narrower error message — the new
19441        // gate would also reject `""`, but the empty-string arm is the
19442        // more self-locating diagnostic. Mirrors the
19443        // `membro_caixa_empty_takes_precedence_over_invalid` pin
19444        // (3f9d7a0).
19445        let mut s = three_member_spec();
19446        s.placement.clusters = vec!["rio".into(), "".into()];
19447        let err = s.validate().unwrap_err();
19448        assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
19449    }
19450
19451    #[test]
19452    fn placement_cluster_invalid_fires_before_duplicate_check() {
19453        // Order pin: a malformed-shape `:clusters` entry surfaces *its
19454        // own* diagnostic, even when a later entry would otherwise
19455        // collapse onto a duplicate name. The per-entry shape gate runs
19456        // inline before the duplicate-key insert, parallel to
19457        // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
19458        let mut s = three_member_spec();
19459        s.placement.clusters = vec!["Rio".into(), "rio".into()];
19460        let err = s.validate().unwrap_err();
19461        assert!(
19462            matches!(
19463                err,
19464                AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
19465            ),
19466            "got {err:?}"
19467        );
19468    }
19469
19470    #[test]
19471    fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
19472        // The diagnostic-shape pin: the error names the offending
19473        // `:clusters` value verbatim so the author can grep their
19474        // caixa.lisp without re-running the build, and carries a
19475        // non-empty `reason` naming the specific violation. Same shape
19476        // every typed-shape gate enshrines
19477        // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
19478        // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
19479        let mut s = three_member_spec();
19480        s.placement.clusters = vec!["BAD_CLUSTER".into()];
19481        let err = s.validate().unwrap_err();
19482        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
19483            panic!("expected PlacementClusterInvalid");
19484        };
19485        assert_eq!(cluster, "BAD_CLUSTER");
19486        assert!(
19487            !reason.is_empty(),
19488            "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
19489        );
19490    }
19491
19492    #[test]
19493    fn rejects_sharded_with_empty_clusters() {
19494        // §III.1: Sharded uses :clusters as the shard pool. An empty
19495        // pool means "shard across no clusters" — meaningless, same as
19496        // Replicated with no hosts.
19497        let mut s = three_member_spec();
19498        s.placement.estrategia = PlacementStrategy::Sharded;
19499        s.placement.shard_key = Some("$tenantId".into());
19500        s.placement.clusters = vec![];
19501        assert!(matches!(
19502            s.validate().unwrap_err(),
19503            AplicacaoError::PlacementWithoutClusters {
19504                estrategia: PlacementStrategy::Sharded
19505            }
19506        ));
19507    }
19508
19509    #[test]
19510    fn rejects_sharded_with_empty_shard_key() {
19511        let mut s = three_member_spec();
19512        s.placement.estrategia = PlacementStrategy::Sharded;
19513        s.placement.shard_key = Some("".into());
19514        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
19515    }
19516
19517    #[test]
19518    fn rejects_shard_key_under_replicated_strategy() {
19519        // The fail-before-pass-after pin: a `:placement (:estrategia
19520        // Replicated :shard-key "tenantId")` manifest carries the
19521        // hash-keyed-distribution slot on a strategy that never consumes
19522        // it. Before the gate the typed slot's value silently vanished
19523        // at the renderer layer (caixa-mesh emits `placement.shardKey`
19524        // verbatim regardless of strategy; the Akka-style cluster-
19525        // sharding reconciler keys off `estrategia == Sharded` and
19526        // ignores the slot otherwise), with no diagnostic. Lifting the
19527        // rejection to a build-time gate makes the
19528        // `shard_key.is_some() == matches!(estrategia, Sharded)`
19529        // partition a structural property of every validated
19530        // [`Placement`].
19531        let mut s = three_member_spec();
19532        // The fixture already uses Replicated; just add a shard-key.
19533        s.placement.shard_key = Some("$tenantId".into());
19534        let err = s.validate().unwrap_err();
19535        let AplicacaoError::ShardKeyOnNonSharded {
19536            estrategia,
19537            shard_key,
19538        } = err
19539        else {
19540            panic!("expected ShardKeyOnNonSharded, got {err:?}");
19541        };
19542        assert_eq!(estrategia, PlacementStrategy::Replicated);
19543        assert_eq!(shard_key, "$tenantId");
19544    }
19545
19546    #[test]
19547    fn rejects_shard_key_under_singlenode_strategy() {
19548        // Peer of the Replicated case above on the SingleNode arm: OTP
19549        // distributed-app takeover (one cluster runs at a time) has no
19550        // hash-keyed routing axis to consume `:shard-key` either, so
19551        // the rejection fires on both non-Sharded arms uniformly.
19552        let mut s = three_member_spec();
19553        s.placement.estrategia = PlacementStrategy::SingleNode;
19554        s.placement.shard_key = Some("$tenantId".into());
19555        let err = s.validate().unwrap_err();
19556        let AplicacaoError::ShardKeyOnNonSharded {
19557            estrategia,
19558            shard_key,
19559        } = err
19560        else {
19561            panic!("expected ShardKeyOnNonSharded, got {err:?}");
19562        };
19563        assert_eq!(estrategia, PlacementStrategy::SingleNode);
19564        assert_eq!(shard_key, "$tenantId");
19565    }
19566
19567    #[test]
19568    fn rejects_empty_shard_key_under_replicated_strategy() {
19569        // The `Some("")` case under non-Sharded is rejected by
19570        // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
19571        // fires before the empty-value gate), not
19572        // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
19573        // the `Sharded` arm). Pin the partition so a future reorder of
19574        // the validate_placement match arms doesn't silently swap which
19575        // diagnostic the author sees — both are author errors, but
19576        // ShardKeyOnNonSharded names which strategy is the actual fix
19577        // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
19578        // only says "pick a non-empty key".
19579        let mut s = three_member_spec();
19580        s.placement.shard_key = Some(String::new());
19581        let err = s.validate().unwrap_err();
19582        assert!(
19583            matches!(
19584                err,
19585                AplicacaoError::ShardKeyOnNonSharded {
19586                    estrategia: PlacementStrategy::Replicated,
19587                    ref shard_key,
19588                } if shard_key.is_empty()
19589            ),
19590            "got {err:?}"
19591        );
19592    }
19593
19594    #[test]
19595    fn replicated_without_shard_key_validates() {
19596        // The complement of the rejection: `:placement :estrategia
19597        // Replicated` with `:shard-key None` is the canonical happy
19598        // path on every existing fixture. Pin the no-shard-key case so
19599        // the new gate doesn't accidentally fire on `None`.
19600        let mut s = three_member_spec();
19601        assert!(matches!(
19602            s.placement.estrategia,
19603            PlacementStrategy::Replicated
19604        ));
19605        s.placement.shard_key = None;
19606        s.validate().unwrap();
19607    }
19608
19609    #[test]
19610    fn singlenode_without_shard_key_validates() {
19611        // Peer of the Replicated no-shard-key case on the SingleNode
19612        // arm — both non-Sharded strategies must validate cleanly when
19613        // the slot is omitted.
19614        let mut s = three_member_spec();
19615        s.placement.estrategia = PlacementStrategy::SingleNode;
19616        s.placement.shard_key = None;
19617        s.validate().unwrap();
19618    }
19619
19620    fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
19621        // Fixture builder for the `:placement :shard-key` shape gate
19622        // tests: a three-member Aplicacao on the `Sharded` strategy
19623        // with the supplied `:shard-key` slot. Co-locates the
19624        // arm-construction so every test below carries one line of
19625        // setup (the offending `:shard-key` value) and the assertion.
19626        let mut s = three_member_spec();
19627        s.placement.estrategia = PlacementStrategy::Sharded;
19628        s.placement.shard_key = Some(key.into());
19629        s
19630    }
19631
19632    #[test]
19633    fn rejects_shard_key_with_embedded_space() {
19634        // The canonical paste-from-aligned-doc footgun:
19635        // `:shard-key "$tenant Id"` — the Akka-style entity-id
19636        // extractor reads the slot as a single-token reference, and an
19637        // embedded space breaks the token boundary at the runtime
19638        // hash-extractor pass with no diagnostic naming the offending
19639        // entry.
19640        let s = sharded_spec_with_key("$tenant Id");
19641        let err = s.validate().unwrap_err();
19642        assert!(
19643            matches!(
19644                err,
19645                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19646                    if shard_key == "$tenant Id" && reason.contains("space")
19647            ),
19648            "got {err:?}"
19649        );
19650    }
19651
19652    #[test]
19653    fn rejects_shard_key_with_leading_space() {
19654        // Leading-space arm of the embedded-whitespace footgun — the
19655        // paste-from-aligned-doc / paste-from-CSV-cell variant where
19656        // the leading column-padding leaked into the slot.
19657        let s = sharded_spec_with_key(" $tenantId");
19658        let err = s.validate().unwrap_err();
19659        assert!(
19660            matches!(
19661                err,
19662                AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
19663                    if shard_key == " $tenantId"
19664            ),
19665            "got {err:?}"
19666        );
19667    }
19668
19669    #[test]
19670    fn rejects_shard_key_with_trailing_newline() {
19671        // The canonical paste-from-shell-heredoc footgun — every
19672        // `<<EOF` heredoc terminator paste leaves a trailing newline
19673        // the YAML emitter then folds away inconsistently across
19674        // emitter implementations.
19675        let s = sharded_spec_with_key("$tenantId\n");
19676        let err = s.validate().unwrap_err();
19677        assert!(
19678            matches!(
19679                err,
19680                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19681                    if shard_key == "$tenantId\n" && reason.contains("0x0a")
19682            ),
19683            "got {err:?}"
19684        );
19685    }
19686
19687    #[test]
19688    fn rejects_shard_key_with_embedded_tab() {
19689        // The paste-from-aligned-doc tab-stop variant — tabs land
19690        // alongside spaces in copy-paste from formatted columns.
19691        let s = sharded_spec_with_key("$tenant\tId");
19692        let err = s.validate().unwrap_err();
19693        assert!(
19694            matches!(
19695                err,
19696                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19697                    if shard_key == "$tenant\tId" && reason.contains("tab")
19698            ),
19699            "got {err:?}"
19700        );
19701    }
19702
19703    #[test]
19704    fn rejects_shard_key_with_control_character() {
19705        // The paste-from-binary / paste-from-screen-cleared-terminal
19706        // footgun — an embedded `\x01` (SOH) byte that some YAML
19707        // emitters silently strip and others escape as ``,
19708        // breaking round-trip across emitter implementations.
19709        let s = sharded_spec_with_key("$tenant\u{0001}Id");
19710        let err = s.validate().unwrap_err();
19711        assert!(
19712            matches!(
19713                err,
19714                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19715                    if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
19716            ),
19717            "got {err:?}"
19718        );
19719    }
19720
19721    #[test]
19722    fn rejects_shard_key_with_non_ascii() {
19723        // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
19724        // footgun — non-ASCII bytes normalize differently between the
19725        // caixa-mesh-side YAML emitter and the in-cluster reconciler's
19726        // YAML parser, the same entity ID can silently map to two
19727        // distinct shards on a re-render.
19728        let s = sharded_spec_with_key("$tenàntId");
19729        let err = s.validate().unwrap_err();
19730        assert!(
19731            matches!(
19732                err,
19733                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19734                    if shard_key == "$tenàntId" && reason.contains("non-ASCII")
19735            ),
19736            "got {err:?}"
19737        );
19738    }
19739
19740    #[test]
19741    fn rejects_shard_key_too_long() {
19742        // Length cap pin: 64 bytes — one byte over the
19743        // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
19744        // here is a paste-from-doc multi-line blob landing in
19745        // `:shard-key` instead of a single-token extractor expression.
19746        let too_long = "a".repeat(64);
19747        let s = sharded_spec_with_key(&too_long);
19748        let err = s.validate().unwrap_err();
19749        let AplicacaoError::ShardKeyInvalid {
19750            ref shard_key,
19751            ref reason,
19752        } = err
19753        else {
19754            panic!("expected ShardKeyInvalid, got {err:?}");
19755        };
19756        assert_eq!(shard_key, &too_long);
19757        assert!(
19758            reason.contains("63") && reason.contains("64"),
19759            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
19760        );
19761    }
19762
19763    #[test]
19764    fn shard_key_max_length_validates() {
19765        // Boundary pin: 63 bytes exactly — the
19766        // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
19767        // dropping to 62) surfaces here as a regression, mirroring
19768        // `placement_cluster_max_length_validates` /
19769        // `placement_affinity_max_length_validates` on the peer
19770        // identifier-shaped slots.
19771        let s = sharded_spec_with_key(&"a".repeat(63));
19772        s.validate().unwrap();
19773    }
19774
19775    #[test]
19776    fn accepts_canonical_shard_key_forms() {
19777        // The Akka-style entity-id extractor shapes a caixa author is
19778        // realistically going to write — pin every leg so a future
19779        // tightening that bans (e.g.) the `${...}` interpolation
19780        // variant or the `metadata.<field>` JSONPath form surfaces
19781        // here as a regression. The canonical forms span:
19782        //
19783        //   - bare property name (`tenantId`, `customerId`)
19784        //   - Akka `ExtractEntityId` placeholder (`$tenantId`)
19785        //   - JSONPath-style nested reference (`metadata.tenantId`,
19786        //     `$.user.id`)
19787        //   - interpolation-style template (`${tenant}`)
19788        //   - snake_case property name (`customer_id`)
19789        //   - kebab-case property name (`customer-id` — accepted
19790        //     because the slot is a printable-ASCII single-token
19791        //     reference, not a DNS-1123 label like
19792        //     `:placement :affinity` / `:clusters`)
19793        //   - single character (`a`, `$` — boundary)
19794        for form in [
19795            "tenantId",
19796            "customerId",
19797            "$tenantId",
19798            "metadata.tenantId",
19799            "$.user.id",
19800            "${tenant}",
19801            "customer_id",
19802            "customer-id",
19803            "a",
19804            "$",
19805        ] {
19806            let s = sharded_spec_with_key(form);
19807            s.validate().unwrap_or_else(|e| {
19808                panic!("canonical shard-key form {form:?} must validate, got {e:?}")
19809            });
19810        }
19811    }
19812
19813    #[test]
19814    fn shard_key_empty_takes_precedence_over_invalid() {
19815        // Order pin: the existing `ShardedKeyEmpty` diagnostic
19816        // (reserved for the `Sharded` `Some("")` arm) fires before the
19817        // new `ShardKeyInvalid` parse-side diagnostic, so an empty
19818        // `:shard-key` keeps its narrower error message — the new gate
19819        // would also reject `""` defensively, but the empty-string arm
19820        // is the more self-locating diagnostic. Mirrors the
19821        // `placement_cluster_empty_takes_precedence_over_invalid` pin
19822        // on the peer identifier-shaped slot.
19823        let s = sharded_spec_with_key("");
19824        let err = s.validate().unwrap_err();
19825        assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
19826    }
19827
19828    #[test]
19829    fn shard_key_invalid_diagnostic_carries_offending_value() {
19830        // The diagnostic-shape pin: the error names the offending
19831        // `:shard-key` value verbatim so the author can grep their
19832        // caixa.lisp without re-running the build, and carries a
19833        // parser-shaped `reason:` naming the specific violation —
19834        // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
19835        // on the peer identifier-shaped slot.
19836        let s = sharded_spec_with_key("$tenant Id");
19837        let err = s.validate().unwrap_err();
19838        let AplicacaoError::ShardKeyInvalid {
19839            ref shard_key,
19840            ref reason,
19841        } = err
19842        else {
19843            panic!("expected ShardKeyInvalid, got {err:?}");
19844        };
19845        assert_eq!(shard_key, "$tenant Id");
19846        assert!(
19847            !reason.is_empty(),
19848            "reason must name the specific violation, got empty string"
19849        );
19850    }
19851
19852    #[test]
19853    fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
19854        // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
19855        // `:shard-key` carried on non-Sharded strategies) fires before
19856        // the shape gate, so a malformed `:shard-key` carried on (e.g.)
19857        // a `Replicated` strategy surfaces the more self-locating
19858        // strategy-mismatch diagnostic (naming the actual fix — drop
19859        // the slot, or switch to Sharded) rather than the shape
19860        // diagnostic. The strategy-mismatch arm is the more actionable
19861        // diagnostic: a malformed shard-key on Replicated is "you
19862        // shouldn't have a :shard-key here at all", not "your
19863        // :shard-key value is malformed".
19864        let mut s = three_member_spec();
19865        // Replicated is the default fixture strategy.
19866        s.placement.shard_key = Some("$tenant Id".into());
19867        let err = s.validate().unwrap_err();
19868        assert!(
19869            matches!(
19870                err,
19871                AplicacaoError::ShardKeyOnNonSharded {
19872                    estrategia: PlacementStrategy::Replicated,
19873                    ..
19874                }
19875            ),
19876            "got {err:?}"
19877        );
19878    }
19879
19880    #[test]
19881    fn rejects_empty_affinity_hint() {
19882        let mut s = three_member_spec();
19883        s.placement.affinity = Some("".into());
19884        assert_eq!(
19885            s.validate().unwrap_err(),
19886            AplicacaoError::PlacementAffinityEmpty
19887        );
19888    }
19889
19890    #[test]
19891    fn placement_without_affinity_validates() {
19892        // Omitting :affinity is fine — the placement engine falls back
19893        // to the default heuristic. Pin the no-hint case so the
19894        // affinity-empty rejection doesn't accidentally fire on `None`.
19895        let mut s = three_member_spec();
19896        s.placement.affinity = None;
19897        s.validate().unwrap();
19898    }
19899
19900    #[test]
19901    fn rejects_placement_affinity_with_uppercase() {
19902        // The canonical "I copied the ADR's display name verbatim" typo
19903        // — placement hints land verbatim in K8s label-selector
19904        // territory, where the apiserver enforces the DNS-1123 label
19905        // rule (lowercase-only) on every identity-keyed admission axis.
19906        // Mirrors `rejects_placement_cluster_with_uppercase` on the
19907        // sibling slot.
19908        let mut s = three_member_spec();
19909        s.placement.affinity = Some("DataLocality".into());
19910        let err = s.validate().unwrap_err();
19911        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
19912            panic!("expected PlacementAffinityInvalid, got other variant");
19913        };
19914        assert_eq!(affinity, "DataLocality");
19915        assert!(
19916            reason.contains("uppercase"),
19917            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
19918        );
19919        assert!(
19920            reason.contains("\"datalocality\""),
19921            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
19922        );
19923    }
19924
19925    #[test]
19926    fn rejects_placement_affinity_with_underscore() {
19927        // The canonical "I'm thinking of an env var / Python identifier"
19928        // leak — `_` is forbidden by every DNS-1123 label schema. Same
19929        // shape as `rejects_placement_cluster_with_underscore` on the
19930        // sibling slot.
19931        let mut s = three_member_spec();
19932        s.placement.affinity = Some("data_locality".into());
19933        let err = s.validate().unwrap_err();
19934        assert!(
19935            matches!(
19936                err,
19937                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
19938                    if affinity == "data_locality" && reason.contains('_')
19939            ),
19940            "got {err:?}"
19941        );
19942    }
19943
19944    #[test]
19945    fn rejects_placement_affinity_with_dot() {
19946        // A `:placement :affinity` value is a single DNS-1123 *label*
19947        // (it lands as a K8s label value selector key), not a subdomain.
19948        // The "I want to namespace my hint with `.`" intent is expressed
19949        // via `-` (`data-locality-east`).
19950        let mut s = three_member_spec();
19951        s.placement.affinity = Some("data.locality".into());
19952        let err = s.validate().unwrap_err();
19953        assert!(
19954            matches!(
19955                err,
19956                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
19957                    if affinity == "data.locality" && reason.contains('.')
19958            ),
19959            "got {err:?}"
19960        );
19961    }
19962
19963    #[test]
19964    fn rejects_placement_affinity_with_unicode() {
19965        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
19966        // before it reaches K8s. The byte-by-byte ASCII validity check
19967        // rejects multi-byte UTF-8 sequences by the first byte that
19968        // fails `[a-z0-9-]`.
19969        let mut s = three_member_spec();
19970        s.placement.affinity = Some("data-localité".into());
19971        let err = s.validate().unwrap_err();
19972        assert!(
19973            matches!(
19974                err,
19975                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
19976                    if affinity == "data-localité"
19977            ),
19978            "got {err:?}"
19979        );
19980    }
19981
19982    #[test]
19983    fn rejects_placement_affinity_with_leading_hyphen() {
19984        // DNS-1123 boundary rule: labels must start with an
19985        // alphanumeric. Pin separately from the trailing-hyphen arm so
19986        // a future relaxation that only checks one boundary surfaces
19987        // here as a regression (parallel to
19988        // `rejects_placement_cluster_with_leading_hyphen`).
19989        let mut s = three_member_spec();
19990        s.placement.affinity = Some("-data-locality".into());
19991        let err = s.validate().unwrap_err();
19992        assert!(
19993            matches!(
19994                err,
19995                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
19996                    if affinity == "-data-locality" && reason.contains("start and end")
19997            ),
19998            "got {err:?}"
19999        );
20000    }
20001
20002    #[test]
20003    fn rejects_placement_affinity_with_trailing_hyphen() {
20004        // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
20005        // ends are covered against a future relaxation.
20006        let mut s = three_member_spec();
20007        s.placement.affinity = Some("data-locality-".into());
20008        let err = s.validate().unwrap_err();
20009        assert!(
20010            matches!(
20011                err,
20012                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
20013                    if affinity == "data-locality-"
20014            ),
20015            "got {err:?}"
20016        );
20017    }
20018
20019    #[test]
20020    fn rejects_placement_affinity_with_whitespace() {
20021        // Whitespace is the canonical "I pasted from a sketch / doc"
20022        // footgun. The apiserver rejects every label-selector value
20023        // carrying whitespace.
20024        let mut s = three_member_spec();
20025        s.placement.affinity = Some("data locality".into());
20026        let err = s.validate().unwrap_err();
20027        assert!(
20028            matches!(
20029                err,
20030                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
20031                    if affinity == "data locality"
20032            ),
20033            "got {err:?}"
20034        );
20035    }
20036
20037    #[test]
20038    fn rejects_placement_affinity_too_long() {
20039        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
20040        // pin. The diagnostic names both the cap (63) and the actual
20041        // length so the author can shorten in one edit. Mirrors
20042        // `rejects_placement_cluster_too_long`.
20043        let mut s = three_member_spec();
20044        let too_long = "a".repeat(64);
20045        s.placement.affinity = Some(too_long.clone());
20046        let err = s.validate().unwrap_err();
20047        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
20048            panic!("expected PlacementAffinityInvalid");
20049        };
20050        assert_eq!(affinity, too_long);
20051        assert!(
20052            reason.contains("63") && reason.contains("64"),
20053            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
20054        );
20055    }
20056
20057    #[test]
20058    fn placement_affinity_max_length_validates() {
20059        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
20060        // future tightening (e.g. dropping to 62) surfaces here as a
20061        // regression, mirroring `placement_cluster_max_length_validates`.
20062        let mut s = three_member_spec();
20063        s.placement.affinity = Some("a".repeat(63));
20064        s.validate().unwrap();
20065    }
20066
20067    #[test]
20068    fn accepts_canonical_placement_affinity_forms() {
20069        // The DNS-1123 label shapes a caixa author is realistically
20070        // going to write for placement hints: the M3 canonical examples
20071        // (`data-locality`, `low-latency`, `anti-affinity`), the
20072        // single-token form (`affinity`), the single-character boundary
20073        // (`a`), the digit-start (DNS-1123 allows this, unlike
20074        // DNS-1035), and a regional-suffixed form. Pin every leg so a
20075        // future tightening that bans (e.g.) digit-start identifiers
20076        // surfaces here.
20077        for form in [
20078            "data-locality",
20079            "low-latency",
20080            "anti-affinity",
20081            "affinity",
20082            "a",
20083            "3-tier",
20084            "locality-east",
20085        ] {
20086            let mut s = three_member_spec();
20087            s.placement.affinity = Some(form.into());
20088            s.validate().unwrap_or_else(|e| {
20089                panic!("canonical affinity form {form:?} must validate, got {e:?}")
20090            });
20091        }
20092    }
20093
20094    #[test]
20095    fn placement_affinity_empty_takes_precedence_over_invalid() {
20096        // Order pin: the existing `PlacementAffinityEmpty` diagnostic
20097        // (which doesn't try to parse) fires before the new
20098        // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
20099        // `:affinity` keeps its narrower error message — the new gate
20100        // would also reject `""`, but the empty-string arm is the more
20101        // self-locating diagnostic. Mirrors the
20102        // `placement_cluster_empty_takes_precedence_over_invalid` pin.
20103        let mut s = three_member_spec();
20104        s.placement.affinity = Some(String::new());
20105        let err = s.validate().unwrap_err();
20106        assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
20107    }
20108
20109    #[test]
20110    fn placement_affinity_invalid_diagnostic_carries_offending_value() {
20111        // The diagnostic shape pin: every rejection carries the offending
20112        // `affinity:` verbatim plus a parser-shaped `reason:` so the
20113        // author can grep their caixa.lisp for `:affinity "<hint>"` and
20114        // fix it in one edit. Mirrors the
20115        // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
20116        // pin on the sibling slot.
20117        let mut s = three_member_spec();
20118        s.placement.affinity = Some("Data_Locality".into());
20119        let err = s.validate().unwrap_err();
20120        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
20121            panic!("expected PlacementAffinityInvalid");
20122        };
20123        assert_eq!(affinity, "Data_Locality");
20124        assert!(
20125            !reason.is_empty(),
20126            "diagnostic reason must not be empty (got: {reason:?})"
20127        );
20128    }
20129
20130    #[test]
20131    fn singlenode_with_takeover_candidates_validates() {
20132        // OTP distributed-application convention (MESH-COMPOSITION
20133        // §II.1): SingleNode runs on one cluster at a time but the
20134        // :clusters list enumerates the takeover candidates. Multiple
20135        // entries are not a contradiction — they are the failover pool.
20136        let mut s = three_member_spec();
20137        s.placement.estrategia = PlacementStrategy::SingleNode;
20138        s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
20139        s.validate().unwrap();
20140    }
20141
20142    // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
20143
20144    #[test]
20145    fn mesh_policy_default_is_empty() {
20146        // The Default impl carries None on every axis — the typed
20147        // analog of an unset `:politicas (())` slot. Renderers that
20148        // overlay the policy onto a cluster artifact key off this
20149        // predicate to skip the slot entirely; pinning so a future
20150        // axis added to MeshPolicy can't silently break the contract
20151        // (a new field whose Default is non-None would flip is_empty
20152        // to false on every existing caixa, surfacing here).
20153        assert!(MeshPolicy::default().is_empty());
20154    }
20155
20156    #[test]
20157    fn mesh_policy_with_only_timeout_is_not_empty() {
20158        let p = MeshPolicy {
20159            timeout: Some(Duration::from_secs(30)),
20160            ..Default::default()
20161        };
20162        assert!(!p.is_empty());
20163    }
20164
20165    #[test]
20166    fn mesh_policy_with_only_retries_is_not_empty() {
20167        let p = MeshPolicy {
20168            retries: Some(3),
20169            ..Default::default()
20170        };
20171        assert!(!p.is_empty());
20172    }
20173
20174    #[test]
20175    fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
20176        let p = MeshPolicy {
20177            circuit_breaker: Some(CircuitBreaker {
20178                max_failures: 5,
20179                window: Duration::from_secs(60),
20180            }),
20181            ..Default::default()
20182        };
20183        assert!(!p.is_empty());
20184    }
20185
20186    #[test]
20187    fn mesh_policy_with_only_mtls_required_is_not_empty() {
20188        // Even `mtls_required: Some(false)` (an explicit opt-out) is
20189        // not empty — the author *named* the axis, the renderer needs
20190        // to honor that vs. fall back to the cluster default.
20191        let p = MeshPolicy {
20192            mtls_required: Some(false),
20193            ..Default::default()
20194        };
20195        assert!(!p.is_empty());
20196    }
20197
20198    #[test]
20199    fn mesh_policy_with_only_rate_limit_is_not_empty() {
20200        let p = MeshPolicy {
20201            rate_limit: Some(RateLimit {
20202                rate: 100,
20203                window: Duration::from_secs(1),
20204            }),
20205            ..Default::default()
20206        };
20207        assert!(!p.is_empty());
20208    }
20209
20210    #[test]
20211    fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
20212        // The three-member happy-path fixture sets timeout + retries +
20213        // mtls_required — every populated axis must read non-empty.
20214        // Pin the round-trip so the M3.x per-:politicas emitter (the
20215        // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
20216        // on is_empty() to decide whether to emit at all without
20217        // re-deriving the contract from inline field probes.
20218        assert!(!three_member_spec().politicas.is_empty());
20219    }
20220
20221    // ── shared duration codec: cross-slot integer-magnitude gate ──
20222    //
20223    // The integer-magnitude discipline applied to
20224    // `supervisor::duration_codec::parse` lifts onto every typed slot
20225    // that routes through the shared codec — `MeshPolicy::timeout`
20226    // (`:politicas :timeout`) and `CircuitBreaker::window`
20227    // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
20228    // These cross-slot tests pin that the gate fires at the serde
20229    // layer for both typed slots, not just for the supervisor side.
20230
20231    #[test]
20232    fn policy_timeout_serde_rejects_fractional_seconds() {
20233        // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
20234        // so the shared codec's integer-magnitude gate applies on
20235        // deserialize. `"1.5s"` previously parsed to 1500ms and round-
20236        // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
20237        // deserialize with the canonical-form diagnostic naming the
20238        // offending `"1.5"` and the remediation `"1500ms"`.
20239        let payload = r#"{"timeout":"1.5s"}"#;
20240        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20241        let msg = err.to_string();
20242        assert!(
20243            msg.contains("not a non-negative integer"),
20244            "expected integer-magnitude diagnostic in {msg:?}"
20245        );
20246        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
20247        assert!(
20248            msg.contains("\"1500ms\""),
20249            "missing canonical-form remediation in {msg:?}"
20250        );
20251    }
20252
20253    #[test]
20254    fn policy_timeout_serde_rejects_leading_plus_sign() {
20255        // Pin the leading-`+` arm cross-slot — the prior f64 parser
20256        // accepted `"+30s"` silently and round-tripped to `"30s"`.
20257        let payload = r#"{"timeout":"+30s"}"#;
20258        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20259        let msg = err.to_string();
20260        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
20261    }
20262
20263    #[test]
20264    fn circuit_breaker_window_serde_rejects_fractional_minutes() {
20265        // `CircuitBreaker::window` uses `with =
20266        // "supervisor::duration_codec_required"` (the required-Duration
20267        // variant that delegates to the same shared parser). `"0.5m"`
20268        // parsed to 30s and round-tripped to `"30s"` on next emit —
20269        // DRIFT closed.
20270        let payload = format!(
20271            r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
20272            max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
20273            window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
20274        );
20275        let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
20276        let msg = err.to_string();
20277        assert!(
20278            msg.contains("not a non-negative integer"),
20279            "expected integer-magnitude diagnostic in {msg:?}"
20280        );
20281        assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
20282        assert!(
20283            msg.contains("\"30s\""),
20284            "missing canonical-form remediation in {msg:?}"
20285        );
20286    }
20287
20288    #[test]
20289    fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
20290        // Pin the happy-path on the cross-slot side: every canonical
20291        // author shape `render` ever emits parses cleanly through the
20292        // shared codec on the `CircuitBreaker` slot. The
20293        // codec's accepted set (post-gate) is exactly its emitted set
20294        // for the integer-magnitude class.
20295        for window_lit in ["30s", "500ms", "2m", "1h"] {
20296            let payload = format!(
20297                r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
20298                max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
20299                window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
20300            );
20301            let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
20302                panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
20303            });
20304            assert_eq!(cb.max_failures, 5);
20305        }
20306    }
20307
20308    // ── rate_limit_codec: integer-magnitude gate ──
20309    //
20310    // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
20311    // / 737a676 / d53c922 trajectory landed on every typed-duration /
20312    // typed-byte-size codec in caixa-core lifts onto the fifth typed
20313    // codec — `rate_limit_codec` — through the digit-only magnitude
20314    // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
20315    // These tests pin the gate at the serde layer for `:politicas
20316    // :rate-limit` (the only typed slot the codec backs), and at the
20317    // codec-internal `parse` layer for the canonical positive cases.
20318
20319    #[test]
20320    fn rate_limit_serde_rejects_fractional_rate() {
20321        // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
20322        // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
20323        // wording, which didn't name the canonical-form remediation or
20324        // the round-trip drift the next emit would produce. Now refused
20325        // at deserialize with the canonical-form diagnostic naming the
20326        // offending `"1.5"` magnitude and the round-trip drift wording.
20327        let payload = r#"{"rateLimit":"1.5/s"}"#;
20328        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20329        let msg = err.to_string();
20330        assert!(
20331            msg.contains("not a non-negative integer"),
20332            "expected integer-magnitude diagnostic in {msg:?}"
20333        );
20334        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
20335        assert!(
20336            msg.contains("THEORY.md"),
20337            "missing render-determinism contract citation in {msg:?}"
20338        );
20339    }
20340
20341    #[test]
20342    fn rate_limit_serde_rejects_leading_plus_sign() {
20343        // `u32::from_str("+100")` returns `Ok(100)` (Rust's
20344        // permissive-`+` parse), so `"+100/s"` silently parsed to
20345        // `RateLimit { 100, 1s }` and round-tripped through `render` to
20346        // `"100/s"` — a *different* canonical string on the next emit,
20347        // breaking the THEORY.md Part V render-determinism contract
20348        // exactly the way the peer duration codecs' `"+30s"` case did.
20349        // This is the load-bearing class the digit-only gate closes
20350        // beyond what `u32::from_str`'s strictness covers on its own.
20351        let payload = r#"{"rateLimit":"+100/s"}"#;
20352        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20353        let msg = err.to_string();
20354        assert!(
20355            msg.contains("not a non-negative integer"),
20356            "expected integer-magnitude diagnostic in {msg:?}"
20357        );
20358        assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
20359    }
20360
20361    #[test]
20362    fn rate_limit_serde_rejects_leading_minus_sign() {
20363        // The signed-negative arm: `"-1/s"` lands on the
20364        // non-canonical-but-numeric branch via the `i64` fallback (the
20365        // `f64` parse also succeeds), surfacing the canonical-form
20366        // diagnostic. Replaces the prior value-laundered "not a u32"
20367        // wording with the unified diagnostic across signs.
20368        let payload = r#"{"rateLimit":"-1/s"}"#;
20369        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20370        let msg = err.to_string();
20371        assert!(
20372            msg.contains("not a non-negative integer"),
20373            "expected integer-magnitude diagnostic in {msg:?}"
20374        );
20375        assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
20376    }
20377
20378    #[test]
20379    fn rate_limit_serde_rejects_decimal_shaped_integer() {
20380        // `"100.0/s"` is integer-valued numerically but not in the
20381        // codec's accepted set — `render` emits `"100/s"`, so the
20382        // round-trip would drift. Lifted to the canonical-form
20383        // diagnostic peer with the duration codec's `"1.0s"` case
20384        // (1c55a2a).
20385        let payload = r#"{"rateLimit":"100.0/s"}"#;
20386        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20387        let msg = err.to_string();
20388        assert!(
20389            msg.contains("not a non-negative integer"),
20390            "expected integer-magnitude diagnostic in {msg:?}"
20391        );
20392        assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
20393    }
20394
20395    #[test]
20396    fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
20397        // Non-numeric, non-digit-only input lands on the existing
20398        // narrower `"not a u32"` arm (preserved for diagnostic-shape
20399        // stability on the parser-shape footgun case). Pin this so a
20400        // future relaxation of the numeric-fallback predicate doesn't
20401        // silently collapse garbage onto the canonical-form arm — same
20402        // partition the peer duration codecs draw between
20403        // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
20404        let payload = r#"{"rateLimit":"abc/s"}"#;
20405        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20406        let msg = err.to_string();
20407        assert!(
20408            msg.contains("not a u32"),
20409            "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
20410        );
20411        assert!(
20412            !msg.contains("not a non-negative integer"),
20413            "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
20414        );
20415    }
20416
20417    #[test]
20418    fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
20419        // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
20420        // u32's range. The digit-only gate passes; `u32::from_str`
20421        // fails on overflow. Surface that with the overflow-shaped
20422        // diagnostic naming the offending magnitude verbatim, peer
20423        // with `supervisor::duration_codec`'s overflow arm. Pinning
20424        // the wording so a future refactor doesn't silently collapse
20425        // overflow onto the canonical-form arm.
20426        let payload = r#"{"rateLimit":"4294967296/s"}"#;
20427        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20428        let msg = err.to_string();
20429        assert!(
20430            msg.contains("overflows u32"),
20431            "expected overflow diagnostic in {msg:?}"
20432        );
20433        assert!(
20434            msg.contains("\"4294967296\""),
20435            "missing offending magnitude in {msg:?}"
20436        );
20437    }
20438
20439    #[test]
20440    fn rate_limit_serde_rejects_leading_zero_magnitude() {
20441        // `"0100/s"` is digit-only, so the existing
20442        // non-digit-only / sign / fractional arm doesn't catch it —
20443        // `u32::from_str("0100")` returns `Ok(100)`, so before this
20444        // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
20445        // round-tripped through `render` to `"100/s"` — a *different*
20446        // canonical string on the next emit, breaking the THEORY.md
20447        // Part V render-determinism contract exactly the way the
20448        // peer `"+100/s"` case did before the leading-`+` arm landed.
20449        // This is the load-bearing class the leading-zero gate closes
20450        // beyond what the existing digit-only / sign / fractional
20451        // gates cover, and the peer arm to the leading-`+` test
20452        // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
20453        // canonical-form-drift axis.
20454        let payload = r#"{"rateLimit":"0100/s"}"#;
20455        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20456        let msg = err.to_string();
20457        assert!(
20458            msg.contains("non-canonical leading zero"),
20459            "expected leading-zero diagnostic in {msg:?}"
20460        );
20461        assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
20462        assert!(
20463            msg.contains("THEORY.md"),
20464            "missing render-determinism contract citation in {msg:?}"
20465        );
20466    }
20467
20468    #[test]
20469    fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
20470        // `"00/s"` is the degenerate leading-zero case — every byte
20471        // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
20472        // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
20473        // a *different* canonical string, same render-determinism
20474        // violation. The single-byte `"0/s"` itself is in the
20475        // accepted set (round-trips losslessly through `render`,
20476        // refused downstream by `PolicyRateLimitZero`); the
20477        // multi-byte `"00/s"` is not. Pins the boundary between the
20478        // accepted single-`0` and the rejected leading-zero class.
20479        let payload = r#"{"rateLimit":"00/s"}"#;
20480        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20481        let msg = err.to_string();
20482        assert!(
20483            msg.contains("non-canonical leading zero"),
20484            "expected leading-zero diagnostic in {msg:?}"
20485        );
20486        assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
20487    }
20488
20489    #[test]
20490    fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
20491        // Cross-window pin — the gate is window-agnostic; the
20492        // leading-zero class is a property of the magnitude, not the
20493        // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
20494        // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
20495        // single-window coverage extended across the three canonical
20496        // windows the codec accepts.
20497        let payload = r#"{"rateLimit":"007/h"}"#;
20498        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20499        let msg = err.to_string();
20500        assert!(
20501            msg.contains("non-canonical leading zero"),
20502            "expected leading-zero diagnostic in {msg:?}"
20503        );
20504        assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
20505    }
20506
20507    #[test]
20508    fn rate_limit_serde_rejects_leading_whitespace() {
20509        // `" 100/s"` — the canonical paste-from-aligned-doc /
20510        // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
20511        // the top-level `s.trim()` silently ate the leading space and
20512        // parsed the value to `RateLimit { 100, 1s }`, which then
20513        // round-tripped through `render` to `"100/s"` (a *different*
20514        // canonical string on the next emit) — the exact
20515        // canonical-form-drift class the leading-`+` / leading-zero
20516        // arms already close, extended to the whitespace byte class.
20517        let payload = r#"{"rateLimit":" 100/s"}"#;
20518        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20519        let msg = err.to_string();
20520        assert!(
20521            msg.contains("contains whitespace byte"),
20522            "expected whitespace diagnostic in {msg:?}"
20523        );
20524        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
20525        assert!(
20526            msg.contains("THEORY.md"),
20527            "missing render-determinism contract citation in {msg:?}"
20528        );
20529    }
20530
20531    #[test]
20532    fn rate_limit_serde_rejects_trailing_whitespace() {
20533        // `"100/s "` — the canonical shell-history / trailing-space
20534        // paste footgun. Before this gate the top-level `s.trim()`
20535        // silently ate the trailing space and parsed to
20536        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
20537        // next emit — same canonical-form drift as the leading-space
20538        // sibling, closed on the same whitespace-byte arm.
20539        let payload = r#"{"rateLimit":"100/s "}"#;
20540        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20541        let msg = err.to_string();
20542        assert!(
20543            msg.contains("contains whitespace byte"),
20544            "expected whitespace diagnostic in {msg:?}"
20545        );
20546        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
20547    }
20548
20549    #[test]
20550    fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
20551        // `"100 / s"` — the canonical typographically-spaced author
20552        // shape (the same idiom every prose reference to a rate limit
20553        // renders as, mistakenly retained when the value is pasted
20554        // into a codec-shaped slot). Before this gate the per-part
20555        // `rate_str.trim()` / `unit.trim()` calls silently ate both
20556        // spaces on either side of `/` and parsed to
20557        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
20558        // codec's *internal* whitespace-tolerance vector, orthogonal
20559        // to the leading / trailing surface but the same canonical-
20560        // form-drift class. Pins the arm as strictly stronger than the
20561        // pre-existing top-level `s.trim()` behavior: it fires on
20562        // whitespace anywhere in the value, not just at the string
20563        // boundary.
20564        let payload = r#"{"rateLimit":"100 / s"}"#;
20565        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20566        let msg = err.to_string();
20567        assert!(
20568            msg.contains("contains whitespace byte"),
20569            "expected whitespace diagnostic in {msg:?}"
20570        );
20571        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
20572    }
20573
20574    #[test]
20575    fn rate_limit_serde_rejects_tab_byte() {
20576        // `"\t100/s"` — the canonical paste-from-indented-doc /
20577        // paste-from-YAML-block-scalar footgun where a tab byte leads
20578        // the magnitude. Pins that the gate covers tab (`0x09`) as
20579        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
20580        // members and both would be silently swallowed by `s.trim()`
20581        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
20582        // space alone to the full ASCII-whitespace set (space `0x20`,
20583        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
20584        // the tab arm as a representative of the non-space members.
20585        let payload = r#"{"rateLimit":"\t100/s"}"#;
20586        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20587        let msg = err.to_string();
20588        assert!(
20589            msg.contains("contains whitespace byte"),
20590            "expected whitespace diagnostic in {msg:?}"
20591        );
20592        assert!(
20593            msg.contains("0x09"),
20594            "missing offending tab byte in {msg:?}"
20595        );
20596    }
20597
20598    // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
20599    //
20600    // Successor to the ASCII-whitespace arm (1ad7755) on
20601    // `rate_limit_codec` — closes the strictly-complementary class the
20602    // byte-scan cannot see, through the lifted
20603    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
20604
20605    #[test]
20606    fn rate_limit_serde_rejects_leading_nbsp() {
20607        // NBSP prefix — paste-from-typography footgun. Byte-scan
20608        // misses, `str::trim` silently strips it, value drifts to
20609        // `"100/s"` on next serialize.
20610        let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
20611        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20612        let msg = err.to_string();
20613        assert!(
20614            msg.contains("non-ASCII Unicode whitespace character"),
20615            "expected non-ASCII whitespace diagnostic in {msg:?}"
20616        );
20617        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
20618    }
20619
20620    #[test]
20621    fn rate_limit_serde_rejects_internal_em_space() {
20622        // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
20623        // paste-from-typography footgun on the `<integer>/<unit>`
20624        // shape.
20625        let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
20626        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20627        let msg = err.to_string();
20628        assert!(
20629            msg.contains("non-ASCII Unicode whitespace character"),
20630            "expected non-ASCII whitespace diagnostic in {msg:?}"
20631        );
20632        assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
20633    }
20634
20635    #[test]
20636    fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
20637        // Positive-control pin: every ASCII-only canonical form the
20638        // renderer emits stays accepted through the new arm.
20639        for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
20640            let payload = format!(r#"{{"rateLimit":{lit}}}"#);
20641            let p: MeshPolicy = serde_json::from_str(&payload)
20642                .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
20643            assert!(p.rate_limit.is_some());
20644        }
20645    }
20646
20647    #[test]
20648    fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
20649        // The boundary case — `"0/s"` is the canonical form
20650        // `render(RateLimit { 0, 1s })` emits, so the codec accepts
20651        // it at the parse layer; the downstream
20652        // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
20653        // `rate == 0` at the typed-validate layer above. Pins the
20654        // partition: the leading-zero gate at the codec layer does
20655        // not poach the rate-zero semantic-validation arm at the
20656        // typed-validate layer above (a future stricter codec must
20657        // not reject `"0/s"` here, or it'd collapse the diagnostic
20658        // partitioning that lets `PolicyRateLimitZero` name the
20659        // offending typed slot).
20660        let payload = r#"{"rateLimit":"0/s"}"#;
20661        let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
20662            panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
20663        });
20664        let rl = policy.rate_limit.expect("rate_limit must be Some");
20665        assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
20666        assert_eq!(
20667            rl.window,
20668            Duration::from_secs(1),
20669            "single-`0` magnitude with `s` unit must parse to window=1s"
20670        );
20671    }
20672
20673    #[test]
20674    fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
20675        // The complementary boundary pin — every magnitude
20676        // `render` emits starts with `[1-9]` (or is the single byte
20677        // `"0"`), so the canonical-form predicate is `(len == 1) ||
20678        // (first byte != '0')`. Pinning the `len > 1 && first byte ==
20679        // '1'` case explicitly so a future tightening of the gate
20680        // (e.g. an over-eager "no leading digit < 5" rule, or a
20681        // mistakenly anchored start-of-magnitude byte check) lands
20682        // here before the canonical-forms-iterating test would catch
20683        // it.
20684        let payload = r#"{"rateLimit":"100/s"}"#;
20685        let policy: MeshPolicy = serde_json::from_str(payload)
20686            .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
20687        let rl = policy.rate_limit.expect("rate_limit must be Some");
20688        assert_eq!(
20689            rl.rate, 100,
20690            "canonical-100 magnitude must parse to rate=100"
20691        );
20692    }
20693
20694    #[test]
20695    fn rate_limit_serde_accepts_integer_canonical_forms() {
20696        // Pin the happy-path: every canonical author shape `render`
20697        // ever emits parses cleanly through the codec post-gate. The
20698        // codec's accepted set (post-gate) is exactly its emitted set
20699        // for the integer-magnitude class — same property
20700        // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
20701        // gates guarantee on the peer codecs. Iterating across rate
20702        // magnitudes (including `"0"`, which the codec accepts even
20703        // though `validate_politicas` rejects `rate == 0` at the typed
20704        // layer above) closes the codec contract at the parse layer
20705        // independently of the validate layer.
20706        for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
20707            for unit_lit in ["s", "m", "h"] {
20708                let lit = format!("{rate_lit}/{unit_lit}");
20709                let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
20710                let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
20711                    panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
20712                });
20713                let rl = policy.rate_limit.expect("rate_limit must be Some");
20714                assert_eq!(
20715                    rl.rate,
20716                    rate_lit.parse::<u32>().unwrap(),
20717                    "rate mismatch for {lit:?}"
20718                );
20719            }
20720        }
20721    }
20722
20723    #[test]
20724    fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
20725        // The structural property the gate enforces: serialize ∘
20726        // deserialize is the identity on every canonical author shape.
20727        // Peer of `parse_byte_size`'s and `parse_duration`'s
20728        // `_round_trips_through_render_for_every_canonical_form` tests
20729        // on the rate-limit axis. Before the gate, `"+100/s"` violated
20730        // this (`parse` → `RateLimit { 100, 1s }` → `render` →
20731        // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
20732        for rate in [1u32, 100, 5000, 1_000_000] {
20733            for (window, unit) in [
20734                (Duration::from_secs(1), "s"),
20735                (Duration::from_secs(60), "m"),
20736                (Duration::from_secs(3600), "h"),
20737            ] {
20738                let policy = MeshPolicy {
20739                    rate_limit: Some(RateLimit { rate, window }),
20740                    ..Default::default()
20741                };
20742                let json = serde_json::to_string(&policy).unwrap();
20743                let expected = format!("\"{rate}/{unit}\"");
20744                assert!(
20745                    json.contains(&expected),
20746                    "expected {expected:?} in {json:?}"
20747                );
20748                let back: MeshPolicy = serde_json::from_str(&json).unwrap();
20749                assert_eq!(
20750                    back.rate_limit, policy.rate_limit,
20751                    "round-trip for {json:?}"
20752                );
20753            }
20754        }
20755    }
20756
20757    // ── self-membership cross-slot gate ──────────────────────────────
20758
20759    #[test]
20760    fn validate_no_self_membership_rejects_self_named_membro() {
20761        // An Aplicacao whose `:membros` lists its own `:nome` is a
20762        // one-node lacre-closure recursion — rejected, naming the parent.
20763        let membros = vec![
20764            membro("catalog", "^0.1"),
20765            membro("checkout", "^0.1"),
20766            membro("cart", "^0.1"),
20767        ];
20768        let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
20769        assert!(
20770            matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
20771            "got {err:?}"
20772        );
20773    }
20774
20775    #[test]
20776    fn validate_no_self_membership_accepts_distinct_membros() {
20777        // Positive control: distinct member names (including a member
20778        // that is itself an Aplicacao — recursive composition is valid,
20779        // MESH-COMPOSITION §V) pass the gate.
20780        let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
20781        validate_no_self_membership(&membros, "checkout").unwrap();
20782    }
20783
20784    #[test]
20785    fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
20786        // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
20787        // `NoMembros` arm (the more-fundamental "graph must have nodes"
20788        // gate), not by this cross-slot self-edge gate. Keeping the
20789        // self-membership predicate vacuously-ok on the empty input
20790        // matches its supervisor-axis peer
20791        // (`validate_no_self_supervision_empty_children_is_ok`) and
20792        // makes the gate composable from any future call site (an M4
20793        // CR materializer's per-membros validator) without re-checking
20794        // emptiness.
20795        validate_no_self_membership(&[], "checkout").unwrap();
20796    }
20797
20798    #[test]
20799    fn validate_no_self_membership_diagnostic_names_offending_caixa() {
20800        // Pinning the Display: the self-membership diagnostic must name
20801        // the offending caixa verbatim + the "lists itself" framing the
20802        // author can grep for, so the cluster-far failure surfaces at
20803        // build time with one-line remediation. Same diagnostic shape
20804        // as the supervisor-axis `ChildSupervisesSelf` peer.
20805        let membros = vec![membro("orquestra", "^0.1")];
20806        let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
20807        let msg = err.to_string();
20808        assert!(
20809            msg.contains("orquestra"),
20810            "diagnostic must name the offending caixa nome (got: {msg:?})"
20811        );
20812        assert!(
20813            msg.contains("lists itself"),
20814            "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
20815        );
20816    }
20817
20818    #[test]
20819    fn default_servico_port_constant_pins_canonical_8080_literal() {
20820        // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
20821        // at the verbatim `8080` literal both consumers (the
20822        // `Entrada::port` serde default via [`default_port`] and the
20823        // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
20824        // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
20825        // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
20826        // discipline (a085b26) on the per-renderer canonical-K8s-axis
20827        // string-constant axis: a future refactor that drifts the
20828        // constant out from under either consumer surfaces here ahead
20829        // of every per-renderer's first emission. The literal value
20830        // matches the well-known HTTP-alt port the `pleme-computeunit`
20831        // library chart already emits as its `trigger.service.port`
20832        // default — by construction the same value the substrate
20833        // assumes about every Servico's in-cluster L4 listener.
20834        assert_eq!(
20835            DEFAULT_SERVICO_PORT, 8080,
20836            "canonical Servico port literal must remain `8080` verbatim — \
20837             this is the value both the `Entrada::port` serde default and the \
20838             caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
20839        );
20840    }
20841
20842    #[test]
20843    fn default_port_helper_returns_canonical_servico_port_constant() {
20844        // The bridge-arm — pins that the [`default_port`] helper
20845        // [`Entrada::port`]'s `#[serde(default = "default_port")]`
20846        // attribute hooks routes through the lifted
20847        // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
20848        // literal. A future refactor that re-introduces the `8080`
20849        // literal at the helper's return site (silently re-opening
20850        // the drift footgun this lift closed) surfaces here ahead of
20851        // every author-side `(:entrada (:host … :para …))` slot
20852        // without an explicit `:port`. Peer with the
20853        // `default_namespace_re_export_points_at_caixa_core_canonical`
20854        // pin on the caixa-mesh-side re-export axis.
20855        assert_eq!(
20856            default_port(),
20857            DEFAULT_SERVICO_PORT,
20858            "the serde-default helper must route through the lifted constant"
20859        );
20860    }
20861
20862    #[test]
20863    fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
20864        // The end-to-end pin — an author-surface `(:entrada (:host …
20865        // :para …))` without an explicit `:port` slot deserializes to
20866        // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
20867        // verbatim. Routes the canonical lifted constant through both
20868        // the serde-default machinery (the `#[serde(default =
20869        // "default_port")]` attribute) and the typed-value-shape
20870        // contract (the resulting [`Entrada::port`] value). A future
20871        // refactor that drifts either axis — replacing the serde
20872        // hook's helper, changing the typed slot's wire shape — would
20873        // surface here before any per-renderer's CNP / Gateway /
20874        // HTTPRoute emission consumed the drifted default.
20875        let entrada: Entrada =
20876            serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
20877        assert_eq!(
20878            entrada.port, DEFAULT_SERVICO_PORT,
20879            "the serde default must materialize as the lifted canonical Servico port"
20880        );
20881    }
20882
20883    #[test]
20884    fn servico_port_min_pins_canonical_accept_set_floor() {
20885        // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
20886        // verbatim `1` literal every typed `:entrada :port` acceptance
20887        // gate keys off. Peer with the
20888        // [`default_servico_port_constant_pins_canonical_8080_literal`]
20889        // discipline on the canonical-Servico-port-constant axis: a
20890        // future refactor that drifts the accept-set floor out from
20891        // under the sole consumer at [`AplicacaoSpec::validate`]'s
20892        // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
20893        // every per-`:entrada` `EntradaPortZero` diagnostic. The
20894        // literal value matches the IANA-registered TCP/UDP port
20895        // space floor (`1..=65535` — port `0` is the "any ephemeral"
20896        // sentinel, not a well-defined destination the substrate's
20897        // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
20898        // axis can honor).
20899        assert_eq!(
20900            SERVICO_PORT_MIN, 1,
20901            "canonical Servico port accept-set floor must remain `1` verbatim — \
20902             this is the value the `AplicacaoSpec::validate` gate at \
20903             `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
20904        );
20905    }
20906
20907    #[test]
20908    fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
20909        // The cross-const invariant pin — the substrate's canonical
20910        // default port must satisfy its own accept-set floor by
20911        // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
20912        // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
20913        // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
20914        // override the operator pins through a future
20915        // `:placement :default-port` slot that lands out-of-range, a
20916        // per-edition Servico-port migration that lifted the floor
20917        // above the previous default without coordinating the pair —
20918        // would silently invalidate the serde-default emission at
20919        // every author-side `(:entrada (:host … :para …))` slot
20920        // without an explicit `:port`: the default port would fall
20921        // below the accept-set floor, the `AplicacaoSpec::validate`
20922        // gate would reject every default-carrying Aplicacao as
20923        // `EntradaPortZero`, and the substrate's typed
20924        // `(defcaixa … :kind Aplicacao)` surface would fail validate
20925        // on every Aplicacao whose author omitted `:entrada :port`
20926        // for the substrate's chosen default — a class of authoring-
20927        // surface footguns the compile-time pin structurally closes.
20928        // Peer with the
20929        // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
20930        // (27f9b34) cross-const invariant pin discipline on the peer
20931        // canonical-Helm-per-values-block child-chart-enablement-toggle
20932        // axis pair.
20933        assert!(
20934            SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
20935            "the substrate's canonical default port ({DEFAULT_SERVICO_PORT}) must \
20936             satisfy its own accept-set floor (SERVICO_PORT_MIN = {SERVICO_PORT_MIN}) — \
20937             every default-carrying `(:entrada (:host … :para …))` slot without an \
20938             explicit `:port` inherits `DEFAULT_SERVICO_PORT` through the serde default \
20939             hook and must pass the `AplicacaoSpec::validate` floor gate by construction"
20940        );
20941    }
20942
20943    #[test]
20944    fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
20945        // The gate-site pin — asserts the `AplicacaoSpec::validate`
20946        // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
20947        // `EntradaPortZero` diagnostic on the below-floor input
20948        // `port: 0` (the only below-floor value the `u16` field can
20949        // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
20950        // is the singleton `{0}`). A future refactor that drifts the
20951        // gate off the lifted const (silently re-introducing an
20952        // inline `if e.port == 0` byte-check) surfaces here — the
20953        // pin cannot distinguish `< 1` from `== 0` on the current
20954        // floor, but it *does* pin that the diagnostic fires on `0`
20955        // through whichever gate is wired, so any future accept-set
20956        // floor migration (a hypothetical unprivileged-only
20957        // migration lifting `SERVICO_PORT_MIN` to `1024`) must
20958        // update this test alongside the const declaration —
20959        // structurally guaranteeing the gate + accept-set + pin
20960        // trio move together. Peer with the
20961        // [`rejects_zero_entrada_port`] behavioral pin on the same
20962        // per-`:entrada :port` axis — that pin asserts the pre-lift
20963        // behavioral contract (`port: 0` → `EntradaPortZero`); this
20964        // pin adds the structural link to the lifted floor const.
20965        assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
20966        let mut s = three_member_spec();
20967        s.entrada.as_mut().unwrap().port = 0;
20968        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
20969    }
20970
20971    // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
20972
20973    #[test]
20974    fn membro_serde_keys_match_lifted_membro_key_consts() {
20975        // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
20976        // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
20977        // name the exact camelCase JSON keys the
20978        // `#[serde(rename_all = "camelCase")]` attribute on
20979        // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
20980        // that each canonical byte-sequence appears verbatim in the
20981        // JSON — a future accidental `rename_all = "snake_case"` /
20982        // `"kebab-case"` / verbatim-field-name flip at the derive
20983        // attribute (any of which would silently break every downstream
20984        // JSON consumer that reaches for one of the two consts via
20985        // `Value::get(...)`) surfaces here as a build-time test failure
20986        // at `aplicacao.rs`, not as an apply-time
20987        // `.get(<stale-canonical-const>)` returning `None` far from the
20988        // derive-attr drift's commit. Peer with the sibling
20989        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
20990        // (40cc4e5) pin on the M2 supervision-tree top-level axis —
20991        // same discipline the SupervisorSpec top-level lift established,
20992        // extended here to the M3 [`Membro`] per-`:membros` axis.
20993        let m = Membro {
20994            caixa: "catalog".into(),
20995            versao: "^0.1".into(),
20996        };
20997        let json = serde_json::to_string(&m).unwrap();
20998        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
20999            let quoted = format!("\"{key}\"");
21000            assert!(
21001                json.contains(&quoted),
21002                "serialized Membro must carry the lifted MEMBRO_KEY_* \
21003                 byte-sequence {quoted} verbatim in the JSON emission \
21004                 (got: {json})",
21005            );
21006        }
21007    }
21008
21009    #[test]
21010    fn membro_key_consts_are_pairwise_distinct() {
21011        // Cross-axis drift-detection pin: a future collapse of the two
21012        // canonical [`Membro`] per-entry byte-strings onto the same
21013        // value (e.g. an accidental copy-paste flip of
21014        // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
21015        // silently reroute every downstream probe on one axis onto the
21016        // sibling axis's overlay entry and pass every propagation-probe
21017        // test that expected only the stale axis's value. Peer of the
21018        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
21019        // (40cc4e5).
21020        let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
21021        for (i, a) in all.iter().enumerate() {
21022            for b in all.iter().skip(i + 1) {
21023                assert_ne!(
21024                    a, b,
21025                    "MEMBRO_KEY_* consts must be pairwise-distinct \
21026                     canonical byte-sequences — got `{a}` == `{b}`",
21027                );
21028            }
21029        }
21030    }
21031
21032    // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
21033    //    URL-path fallback resolver every HTTPRoute-aware renderer
21034    //    reaching for a per-rule path-list resolution routes through.
21035    //    The four pin tests below fix the four-way accept-set the
21036    //    resolver must always honor: (:paths-non-empty-verbatim,
21037    //    :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
21038    //    :paths-preserves-order-across-multiple-entries) — drift on any
21039    //    arm surfaces at caixa-core build time rather than at cluster-
21040    //    apply time. Peer discipline with `MeshPolicy::is_empty` on the
21041    //    sibling `:politicas` typed-primitive dispatch axis.
21042
21043    fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
21044        Entrada {
21045            host: "example.com".into(),
21046            para: "cart".into(),
21047            paths: paths.into_iter().map(String::from).collect(),
21048            port: DEFAULT_SERVICO_PORT,
21049        }
21050    }
21051
21052    #[test]
21053    fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
21054        // The typed `:entrada :paths` slot carries an author-declared
21055        // list — the resolver returns each entry verbatim, no
21056        // catch-all substitution. The canonical "author declared
21057        // paths, honor them verbatim" arm of the path-list dispatch.
21058        let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
21059        assert_eq!(
21060            e.resolved_paths(),
21061            vec!["/api/cart", "/api/products"],
21062            "resolved_paths must return each `:entrada :paths` entry \
21063             verbatim when the typed slot is non-empty (got {:?})",
21064            e.resolved_paths(),
21065        );
21066    }
21067
21068    #[test]
21069    fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
21070        // Empty `:entrada :paths` slot — the resolver substitutes the
21071        // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
21072        // catch-all fallback verbatim. Pins the empty-arm of the
21073        // resolver's four-way accept-set against a future silent
21074        // detour that returned an empty Vec (which would emit an
21075        // HTTPRoute with zero rules — silently dropping every
21076        // external `:entrada` flow at admission time), routed to a
21077        // different fallback shape, or dropped the catch-all
21078        // altogether.
21079        let e = entrada_with_paths(vec![]);
21080        assert_eq!(
21081            e.resolved_paths(),
21082            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
21083            "resolved_paths on empty `:entrada :paths` must fall back \
21084             to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
21085             all — got {:?}",
21086            e.resolved_paths(),
21087        );
21088    }
21089
21090    #[test]
21091    fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
21092        // Single-entry `:entrada :paths` — the resolver returns the
21093        // single declared path verbatim, NOT the catch-all fallback
21094        // (author declared a path, honor it — the empty-arm and the
21095        // len-1 arm are semantically distinct axes of the resolver's
21096        // accept-set). Pins that the resolver treats "author declared
21097        // one path" as authored input, not as the empty case.
21098        let e = entrada_with_paths(vec!["/api/only"]);
21099        assert_eq!(
21100            e.resolved_paths(),
21101            vec!["/api/only"],
21102            "resolved_paths on single-entry `:entrada :paths` must \
21103             return the declared path verbatim, NOT the catch-all \
21104             fallback (got {:?})",
21105            e.resolved_paths(),
21106        );
21107    }
21108
21109    #[test]
21110    fn resolved_paths_preserves_author_declared_order() {
21111        // The `:entrada :paths` list is author-ordered — the resolver
21112        // preserves the author's declaration order verbatim, since
21113        // per-rule dispatch order at the K8s Gateway API HTTPRoute
21114        // consumer is significant (first-match-wins under the
21115        // path-prefix matcher). Pins against a future silent
21116        // re-sort / dedup / normalize detour that reordered author
21117        // input.
21118        let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
21119        assert_eq!(
21120            e.resolved_paths(),
21121            vec!["/z/last", "/a/first", "/m/mid"],
21122            "resolved_paths must preserve author-declared `:entrada \
21123             :paths` order verbatim — got {:?}",
21124            e.resolved_paths(),
21125        );
21126    }
21127
21128    // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
21129    //    slot `&[String]` slice accessor every per-`:entrada` consumer
21130    //    that must see the author's declaration verbatim (not the
21131    //    fallback-applied projection the sibling `resolved_paths`
21132    //    returns) routes through. The three pin tests below fix the
21133    //    accept-set the accessor must honor: (:non-empty-byte-equal,
21134    //    :empty-projects-empty-slice, :preserves-author-declared-order)
21135    //    — drift on any arm surfaces at caixa-core build time rather
21136    //    than at cluster-apply time. Peer discipline with the sibling
21137    //    [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
21138    //    peer M3 mesh-slot `Vec<String>`-carry axis.
21139
21140    #[test]
21141    fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
21142        // Byte-equal pin: [`Entrada::paths`] must project the raw
21143        // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
21144        // slice borrowed from the typed slot's own [`Vec<String>`]
21145        // storage — no re-ordering, no dedup, no per-entry normalization,
21146        // no fallback substitution (the fallback-applying projection is
21147        // the sibling [`Entrada::resolved_paths`] resolver). Pins against
21148        // a future silent detour that re-normalized the list, dropped
21149        // duplicates the [`AplicacaoSpec::validate`]
21150        // `EntradaPathDuplicate` refusal already rejects at build time,
21151        // or (most severe) accidentally routed through the fallback-
21152        // applying sibling and returned the substrate catch-all when
21153        // the author declared an empty list — collapsing the raw-slot
21154        // and fallback-applied axes into one and breaking the
21155        // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
21156        //
21157        // Peer of the sibling
21158        // [`Placement::clusters`]-shape byte-equal pin
21159        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
21160        // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
21161        let fixtures: Vec<Vec<String>> = vec![
21162            Vec::new(),
21163            vec!["/api/cart".into()],
21164            vec!["/api/cart".into(), "/api/products".into()],
21165            vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
21166        ];
21167        for paths in fixtures {
21168            let e = Entrada {
21169                host: "example.com".into(),
21170                para: "cart".into(),
21171                paths: paths.clone(),
21172                port: DEFAULT_SERVICO_PORT,
21173            };
21174            assert_eq!(
21175                e.paths(),
21176                paths.as_slice(),
21177                "Entrada::paths must return :entrada :paths verbatim \
21178                 (got {:?}, expected {:?})",
21179                e.paths(),
21180                paths.as_slice(),
21181            );
21182            assert_eq!(
21183                e.paths(),
21184                e.paths.as_slice(),
21185                "Entrada::paths accessor and .paths.as_slice() field \
21186                 access must byte-equal — the accessor is the substrate-\
21187                 primitive typed dispatch every downstream per-`:entrada` \
21188                 raw-slot path-list consumer must route through",
21189            );
21190            assert_eq!(
21191                e.paths().len(),
21192                e.paths.len(),
21193                "Entrada::paths().len() must byte-equal self.paths.len() \
21194                 — a length drift would silently split the paired \
21195                 pre-flight cascade-head `.is_empty()` probe input in \
21196                 the sibling [`Entrada::resolved_paths`] resolver from \
21197                 the per-entry validate loop's traversal input in \
21198                 [`AplicacaoSpec::validate`]",
21199            );
21200        }
21201    }
21202
21203    #[test]
21204    fn resolved_paths_reads_through_lifted_paths_accessor() {
21205        // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
21206        // pre-flight `.paths().is_empty()` cascade-head probe (which
21207        // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
21208        // catch-all fallback arm when the accessor projects the empty
21209        // slice) and the per-entry `.paths().iter().map(String::as_str)`
21210        // projection (which must reach every entry in the same order
21211        // the accessor projects, so the sibling
21212        // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
21213        // per-entry projection stay in lockstep by construction) must
21214        // both key off the lifted accessor. Pins the two-site coherence
21215        // by exercising each production consumer end-to-end: (1) the
21216        // catch-all-fallback arm under the empty slice, (2) the
21217        // author-declared-verbatim arm under a two-entry cohort whose
21218        // per-entry projection must byte-equal the input's per-entry
21219        // author-declared paths in the author's declared order.
21220        //
21221        // Peer of the sibling M3
21222        // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
21223        // `validate_placement_reads_through_lifted_clusters_accessor`
21224        // on the sibling `Placement::clusters` reader-site convergence.
21225        let empty = entrada_with_paths(vec![]);
21226        assert_eq!(
21227            empty.resolved_paths(),
21228            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
21229            "resolved_paths on empty :entrada :paths must trip the \
21230             lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
21231             catch-all fallback — routing through the lifted paths() \
21232             accessor must not silently drop the fallback arm",
21233        );
21234
21235        let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
21236        assert_eq!(
21237            declared.resolved_paths(),
21238            vec!["/api/cart", "/api/products"],
21239            "resolved_paths on non-empty :entrada :paths must return each \
21240             entry verbatim in the author's declared order — routing \
21241             through the lifted paths() accessor must not silently \
21242             reorder or drop entries",
21243        );
21244        // Byte-equal pin against the raw-slot accessor to keep the
21245        // fallback-applying resolver's per-entry projection input in
21246        // lockstep with the raw-slot accessor's projection.
21247        let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
21248        assert_eq!(
21249            declared.resolved_paths(),
21250            raw_projected,
21251            "resolved_paths non-empty projection must byte-equal the \
21252             lifted paths() accessor's per-entry String::as_str projection \
21253             — the two projections share the same input slice by \
21254             construction, so any drift here would surface a silent \
21255             re-ordering / dedup / normalization detour in the resolver",
21256        );
21257    }
21258
21259    #[test]
21260    fn validate_reads_through_lifted_entrada_paths_accessor() {
21261        // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
21262        // per-entry value-shape gate's `for p in e.paths()` traversal
21263        // (which must reach every entry in the same order the accessor
21264        // projects, so both the per-entry `EntradaPathEmpty` /
21265        // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
21266        // the duplicate-detection HashSet insert that trips
21267        // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
21268        // projection) must route through the lifted accessor. Pins the
21269        // coherence by exercising each production consumer end-to-end:
21270        // (1) the `EntradaPathEmpty` refusal fires on the second entry
21271        // of a two-entry cohort whose head is valid but tail is empty
21272        // (which requires the loop to reach the second entry through
21273        // the accessor), and (2) the `EntradaPathDuplicate` refusal
21274        // fires on the second entry of a two-entry cohort that shares
21275        // a path (which requires the loop to reach both entries — a
21276        // first-entry-only projection would silently pass since the
21277        // dedup HashSet has room for the first insert).
21278        //
21279        // Peer of the sibling
21280        // `validate_placement_reads_through_lifted_clusters_accessor`
21281        // on the sibling `Placement::clusters` reader-site convergence.
21282        let base = crate::AplicacaoSpec {
21283            membros: vec![crate::Membro {
21284                caixa: "cart".into(),
21285                versao: "^0.1".into(),
21286            }],
21287            contratos: Vec::new(),
21288            politicas: crate::MeshPolicy::default(),
21289            placement: crate::Placement {
21290                estrategia: crate::PlacementStrategy::SingleNode,
21291                clusters: vec!["rio".into()],
21292                shard_key: None,
21293                affinity: None,
21294            },
21295            entrada: Some(Entrada {
21296                host: "example.com".into(),
21297                para: "cart".into(),
21298                paths: vec!["/api/cart".into(), String::new()],
21299                port: DEFAULT_SERVICO_PORT,
21300            }),
21301        };
21302        assert_eq!(
21303            base.validate(),
21304            Err(crate::AplicacaoError::EntradaPathEmpty),
21305            "validate must trip EntradaPathEmpty on the second entry of \
21306             a two-entry cohort — routing through the lifted paths() \
21307             accessor must not silently short-circuit the loop at the \
21308             valid head entry",
21309        );
21310
21311        let mut dup = base;
21312        dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
21313        assert_eq!(
21314            dup.validate(),
21315            Err(crate::AplicacaoError::EntradaPathDuplicate {
21316                path: "/api/cart".into(),
21317            }),
21318            "validate must trip EntradaPathDuplicate on the second entry \
21319             of a two-entry cohort that shares a path — routing through \
21320             the lifted paths() accessor must not silently short-circuit \
21321             the dedup HashSet insert at the first entry",
21322        );
21323    }
21324
21325    // ── Entrada::hostname / Entrada::hostnames — the substrate-
21326    //    canonical per-`:entrada` DNS-hostname resolver pair every
21327    //    Gateway-API-aware renderer reaching for a per-listener
21328    //    singular `hostname:` filter (Gateway) or a per-route plural
21329    //    `spec.hostnames[]` filter list (HTTPRoute) routes through.
21330    //    The three pin tests below fix the two-way accept-set the pair
21331    //    must always honor: (:singular-byte-equal-to-host,
21332    //    :plural-is-singleton-of-singular, :plural-len-is-one) — drift
21333    //    on any arm surfaces at caixa-core build time rather than at
21334    //    cluster-apply time when the API server refuses the HTTPRoute
21335    //    for non-intersecting hostname filters. Peer discipline with
21336    //    the sibling `resolved_paths` accept-set pin block above on the
21337    //    per-`:entrada` path-list resolver axis.
21338
21339    fn entrada_with_host(host: &str) -> Entrada {
21340        Entrada {
21341            host: host.into(),
21342            para: "cart".into(),
21343            paths: Vec::new(),
21344            port: DEFAULT_SERVICO_PORT,
21345        }
21346    }
21347
21348    #[test]
21349    fn hostname_returns_entrada_host_byte_equal() {
21350        // The canonical singular-axis pin: [`Entrada::hostname`] must
21351        // return the `:entrada :host` field byte-for-byte, borrowed
21352        // from the typed slot's own [`String`] storage. Pins against a
21353        // future silent detour that re-normalized the host (an
21354        // accidental `.to_lowercase()` — validate_entrada_host already
21355        // enforces lowercase, so any re-normalization is redundant + a
21356        // drift surface between the validator and the accessor), a
21357        // trailing-`.` fully-qualified DNS shape substitution, or a
21358        // Punycode round-trip that lowered a Unicode host through IDNA.
21359        let e = entrada_with_host("checkout.quero.cloud");
21360        assert_eq!(
21361            e.hostname(),
21362            "checkout.quero.cloud",
21363            "Entrada::hostname must return :entrada :host verbatim \
21364             (got {:?})",
21365            e.hostname(),
21366        );
21367        assert_eq!(
21368            e.hostname(),
21369            e.host.as_str(),
21370            "Entrada::hostname must byte-equal the .host field access",
21371        );
21372    }
21373
21374    #[test]
21375    fn hostnames_returns_singleton_of_hostname_accessor() {
21376        // The pair-invariant pin: [`Entrada::hostnames`] must always
21377        // return exactly `vec![hostname()]` — the singleton list whose
21378        // sole entry is the substrate's canonical per-`:entrada`
21379        // singular hostname. Pins the two-consumer coherence axis: the
21380        // Gateway listener's singular `hostname:` filter and the
21381        // HTTPRoute's plural `spec.hostnames[]` filter list must
21382        // agree, else the Gateway API v1.x conformance layer rejects
21383        // the HTTPRoute at attach time with
21384        // `Accepted:False/NoMatchingParent` (the parent Gateway's
21385        // listener hostname doesn't intersect the route's hostname
21386        // filter list) — a divergence whose apply-time symptom is far
21387        // from any single-site commit and never surfaces in the
21388        // emitted YAML. Pinning the pair-invariant here makes any
21389        // future accidental split (an accidental `.to_string() + "."`
21390        // trailing-`.` on the plural side that didn't land on the
21391        // singular side, an accidental prefix stripping on one axis,
21392        // an accidental wildcard prepend the SNI fan-out overlay
21393        // authors on the plural side without a paired singular
21394        // migration) trip at caixa-core build time.
21395        let e = entrada_with_host("checkout.quero.cloud");
21396        assert_eq!(
21397            e.hostnames(),
21398            vec![e.hostname()],
21399            "Entrada::hostnames must return `vec![hostname()]` under \
21400             the pair-invariant — got {:?} vs. singleton {:?}",
21401            e.hostnames(),
21402            vec![e.hostname()],
21403        );
21404    }
21405
21406    #[test]
21407    fn hostnames_is_singleton_under_single_host_author_surface() {
21408        // The singleton-shape pin: under today's single-hostname-per-
21409        // `:entrada` author surface (the `:host` slot is a single
21410        // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
21411        // must always return a list of length exactly one. Pins
21412        // against a future silent detour that returned an empty list
21413        // (which would emit an HTTPRoute with `spec.hostnames: []` —
21414        // matching every incoming Host header regardless of the
21415        // Aplicacao's declared ingress apex, silently over-matching
21416        // every foreign VirtualHost the parent Gateway also fronts) or
21417        // a duplicated entry (which the Gateway API v1.x parser
21418        // accepts as a `[]-length-2 list of equal hostnames]` but
21419        // whose semantics differ from the intended singleton). The
21420        // author-surface extension point ("a future `:entrada
21421        // :alt-hosts` list overlay" the docstring names) is the sole
21422        // future axis that flips this pin — that migration will re-
21423        // author this test to pin the new plural cardinality.
21424        let e = entrada_with_host("checkout.quero.cloud");
21425        assert_eq!(
21426            e.hostnames().len(),
21427            1,
21428            "Entrada::hostnames must be a singleton under today's \
21429             single-hostname-per-`:entrada` author surface — got \
21430             length {}: {:?}",
21431            e.hostnames().len(),
21432            e.hostnames(),
21433        );
21434    }
21435
21436    // ── Entrada::destination — the substrate-canonical per-`:entrada`
21437    //    destination-Servico scalar accessor every Gateway-API
21438    //    HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
21439    //    discriminator arg (HTTPRoute name composer) or a per-rule
21440    //    `backendRefs[0].name` axis routes through. The two pin tests
21441    //    below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
21442    //    either arm surfaces at caixa-core build time rather than at
21443    //    cluster-apply time when an HTTPRoute's `metadata.name` and
21444    //    `backendRefs[]` silently disagree on which destination Servico
21445    //    the ingress fronts. Peer discipline with the sibling
21446    //    `resolved_paths` + `hostname` + `hostnames` accept-set pin
21447    //    blocks above on the per-`:entrada` path-list / DNS-hostname
21448    //    resolver axes.
21449
21450    #[test]
21451    fn destination_returns_entrada_para_byte_equal() {
21452        // The canonical destination-scalar pin: [`Entrada::destination`]
21453        // must return the `:entrada :para` field byte-for-byte, borrowed
21454        // from the typed slot's own [`String`] storage. Pins against a
21455        // future silent detour that re-normalized the destination (an
21456        // accidental `.to_lowercase()` — the destination Servico is
21457        // already validated as a DNS-1123 label upstream, so any
21458        // re-normalization is redundant + a drift surface between the
21459        // validator and the accessor), a namespace-prefix rewrite (an
21460        // accidental `format!("{namespace}/{para}")` per-CR fully-
21461        // qualified rewrite that didn't land on the peer axis), or a
21462        // per-cluster suffix stamp the operator authors on one
21463        // consumer without the other.
21464        for para in ["cart", "checkout", "catalog", "orders-v2"] {
21465            let e = Entrada {
21466                host: "checkout.quero.cloud".into(),
21467                para: para.into(),
21468                paths: Vec::new(),
21469                port: DEFAULT_SERVICO_PORT,
21470            };
21471            assert_eq!(
21472                e.destination(),
21473                para,
21474                "Entrada::destination must return :entrada :para verbatim \
21475                 (got {:?}, expected {para:?})",
21476                e.destination(),
21477            );
21478            assert_eq!(
21479                e.destination(),
21480                e.para.as_str(),
21481                "Entrada::destination must byte-equal the .para field access",
21482            );
21483        }
21484    }
21485
21486    #[test]
21487    fn destination_borrows_from_entrada_para_storage() {
21488        // The borrow-not-copy pin: [`Entrada::destination`] must
21489        // return a `&str` slice that borrows from the typed slot's
21490        // own [`String`] storage — same-address invariant with
21491        // `entrada.para.as_str()`. Pins against a future silent detour
21492        // that allocated a fresh `String` (`self.para.clone()` in the
21493        // body would type-check but silently drop the borrow, and
21494        // every downstream consumer that assumed the returned slice
21495        // outlives `&self` would break on a stale-reference use-after-
21496        // free). Peer with the sibling `hostname_returns_entrada_
21497        // host_byte_equal` on the singular-DNS-hostname axis.
21498        let e = entrada_with_host("checkout.quero.cloud");
21499        let dest = e.destination();
21500        let para_slice = e.para.as_str();
21501        assert_eq!(
21502            dest.as_ptr(),
21503            para_slice.as_ptr(),
21504            "Entrada::destination must borrow from the .para String's \
21505             backing storage — a fresh allocation here means the \
21506             accessor no longer names the substrate-primitive typed \
21507             dispatch and every downstream consumer would silently \
21508             carry a detached copy",
21509        );
21510        assert_eq!(
21511            dest.len(),
21512            para_slice.len(),
21513            "Entrada::destination and .para.as_str() must byte-equal in \
21514             length as well as in address",
21515        );
21516    }
21517
21518    #[test]
21519    fn port_returns_entrada_port_verbatim_across_permutations() {
21520        // The canonical L4-port-scalar pin: [`Entrada::port`] must
21521        // return the `:entrada :port` field verbatim as a `u16` across
21522        // every author-declared value in the validated accept-set
21523        // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
21524        // silent detour that clamped the port (an accidental
21525        // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
21526        // land on the peer [`AplicacaoSpec::port_for_destination`]
21527        // resolver), rewrote it through a per-cluster port-remap table
21528        // the operator authors on one consumer without the other, or
21529        // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
21530        // serde-default value (which would silently collapse the
21531        // distinction between "author explicitly declared `:port 8080`"
21532        // and "author omitted the slot and inherited the default" the
21533        // future per-cluster override slot depends on). Peer with the
21534        // sibling `destination_returns_entrada_para_byte_equal` +
21535        // `hostname_returns_entrada_host_byte_equal` pins on the
21536        // per-`:entrada` `&str` scalar axes.
21537        for port in [
21538            SERVICO_PORT_MIN,
21539            DEFAULT_SERVICO_PORT,
21540            8443u16,
21541            9090u16,
21542            u16::MAX,
21543        ] {
21544            let e = Entrada {
21545                host: "checkout.quero.cloud".into(),
21546                para: "cart".into(),
21547                paths: Vec::new(),
21548                port,
21549            };
21550            assert_eq!(
21551                e.port(),
21552                port,
21553                "Entrada::port must return :entrada :port verbatim \
21554                 (got {}, expected {port})",
21555                e.port(),
21556            );
21557            assert_eq!(
21558                e.port(),
21559                e.port,
21560                "Entrada::port accessor and .port field access must \
21561                 byte-equal — the accessor is the substrate-primitive \
21562                 typed dispatch every downstream L4-port consumer must \
21563                 route through",
21564            );
21565        }
21566    }
21567
21568    #[test]
21569    fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
21570        // Two-consumer coherence pin: the
21571        // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
21572        // (which reads through [`Entrada::port`] to compare against
21573        // [`SERVICO_PORT_MIN`]) and the
21574        // [`AplicacaoSpec::port_for_destination`] resolver (which reads
21575        // through [`Entrada::port`] to emit the per-destination
21576        // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
21577        // lifted accessor, so any future rebrand on the typed slot's
21578        // reader shape lands at exactly one place. Pins the two-site
21579        // coherence by exercising a below-floor port through validate
21580        // (which must reject) and a validated in-accept-set port through
21581        // port_for_destination (which must emit the same value the
21582        // accessor returns).
21583        let mut spec = three_member_spec();
21584        if let Some(e) = spec.entrada.as_mut() {
21585            e.port = 0;
21586        }
21587        assert_eq!(
21588            spec.validate().unwrap_err(),
21589            AplicacaoError::EntradaPortZero,
21590            "validate must reject `:entrada :port 0` through the lifted \
21591             Entrada::port accessor — port zero lies below \
21592             SERVICO_PORT_MIN and the validator routes through port() \
21593             to name the floor",
21594        );
21595
21596        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
21597            let mut spec = three_member_spec();
21598            if let Some(e) = spec.entrada.as_mut() {
21599                e.port = port;
21600            }
21601            spec.validate().expect(
21602                "entrada with in-accept-set :port must validate — the \
21603                 structural-floor gate reads through Entrada::port",
21604            );
21605            let entrada_ref = spec.entrada().expect(":entrada present");
21606            assert_eq!(
21607                spec.port_for_destination(entrada_ref.destination()),
21608                entrada_ref.port(),
21609                "port_for_destination(entrada.destination()) must equal \
21610                 entrada.port() — the two consumers of the per-:entrada \
21611                 L4-port axis (validator, per-destination resolver) both \
21612                 route through Entrada::port",
21613            );
21614        }
21615    }
21616
21617    #[test]
21618    fn wit_contract_source_returns_de_byte_equal_across_permutations() {
21619        // The canonical caller-Servico-scalar pin: [`WitContract::source`]
21620        // must return the `:contratos :de` field byte-for-byte, borrowed
21621        // from the typed slot's own [`String`] storage. Peer of the
21622        // sibling `destination_returns_entrada_para_byte_equal` pin on
21623        // the per-`:entrada` axis — same "the substrate-primitive
21624        // accessor must byte-equal the raw field access verbatim across
21625        // every author-declared value" discipline extended to the
21626        // per-`:contratos` caller arm. Pins against a future silent
21627        // detour that re-normalized the caller (an accidental
21628        // `.to_lowercase()` — every `:contratos :de` is validated as a
21629        // DNS-1123 label upstream via `validate_contrato_caixa`, so any
21630        // re-normalization is redundant + a drift surface between the
21631        // validator and the accessor), a namespace-prefix rewrite (an
21632        // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
21633        // rewrite that didn't land on the peer axis), or a per-cluster
21634        // suffix stamp the operator authors on one consumer without the
21635        // other.
21636        for de in ["cart", "checkout", "catalog", "orders-v2"] {
21637            let c = WitContract {
21638                de: de.into(),
21639                para: "downstream".into(),
21640                wit: "wasi:http/proxy".into(),
21641                endpoint: Some("/lookup".into()),
21642                subject: None,
21643                slot: None,
21644            };
21645            assert_eq!(
21646                c.source(),
21647                de,
21648                "WitContract::source must return :contratos :de verbatim \
21649                 (got {:?}, expected {de:?})",
21650                c.source(),
21651            );
21652            assert_eq!(
21653                c.source(),
21654                c.de.as_str(),
21655                "WitContract::source must byte-equal the .de field access",
21656            );
21657        }
21658    }
21659
21660    #[test]
21661    fn wit_contract_source_borrows_from_de_storage() {
21662        // The borrow-not-copy pin: [`WitContract::source`] must return a
21663        // `&str` slice that borrows from the typed slot's own [`String`]
21664        // storage — same-address invariant with `c.de.as_str()`. Pins
21665        // against a future silent detour that allocated a fresh `String`
21666        // (`self.de.clone()` in the body would type-check but silently
21667        // drop the borrow, and every downstream consumer that assumed
21668        // the returned slice outlives `&self` would break on a stale-
21669        // reference use-after-free). Peer of the sibling
21670        // `destination_borrows_from_entrada_para_storage` on the
21671        // per-`:entrada` axis.
21672        let c = WitContract {
21673            de: "cart".into(),
21674            para: "catalog".into(),
21675            wit: "wasi:http/proxy".into(),
21676            endpoint: Some("/lookup".into()),
21677            subject: None,
21678            slot: None,
21679        };
21680        let src = c.source();
21681        let de_slice = c.de.as_str();
21682        assert_eq!(
21683            src.as_ptr(),
21684            de_slice.as_ptr(),
21685            "WitContract::source must borrow from the .de String's \
21686             backing storage — a fresh allocation here means the \
21687             accessor no longer names the substrate-primitive typed \
21688             dispatch and every downstream consumer would silently \
21689             carry a detached copy",
21690        );
21691        assert_eq!(
21692            src.len(),
21693            de_slice.len(),
21694            "WitContract::source and .de.as_str() must byte-equal in \
21695             length as well as in address",
21696        );
21697    }
21698
21699    #[test]
21700    fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
21701        // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
21702        // must return the `:contratos :para` field byte-for-byte,
21703        // borrowed from the typed slot's own [`String`] storage. Peer of
21704        // the sibling `destination_returns_entrada_para_byte_equal` on
21705        // the per-`:entrada` axis — both accessors name "the destination-
21706        // Servico byte-string" concept on their respective mesh-slot
21707        // atoms (per-ingress apex vs. per-typed-edge callee) and both
21708        // must project the underlying `.para` field verbatim so every
21709        // downstream renderer that composes them with peer accessors
21710        // (e.g. `spec.port_for_destination(c.destination())` at the CNP
21711        // per-edge L4 port emit site) reads the same byte-string the
21712        // author declared.
21713        for para in ["catalog", "payment", "orders", "inventory-v3"] {
21714            let c = WitContract {
21715                de: "cart".into(),
21716                para: para.into(),
21717                wit: "wasi:http/proxy".into(),
21718                endpoint: Some("/lookup".into()),
21719                subject: None,
21720                slot: None,
21721            };
21722            assert_eq!(
21723                c.destination(),
21724                para,
21725                "WitContract::destination must return :contratos :para \
21726                 verbatim (got {:?}, expected {para:?})",
21727                c.destination(),
21728            );
21729            assert_eq!(
21730                c.destination(),
21731                c.para.as_str(),
21732                "WitContract::destination must byte-equal the .para \
21733                 field access",
21734            );
21735        }
21736    }
21737
21738    #[test]
21739    fn wit_contract_destination_borrows_from_para_storage() {
21740        // The borrow-not-copy pin: [`WitContract::destination`] must
21741        // return a `&str` slice that borrows from the typed slot's own
21742        // [`String`] storage — same-address invariant with
21743        // `c.para.as_str()`. Peer of the sibling
21744        // `destination_borrows_from_entrada_para_storage` on the
21745        // per-`:entrada` axis.
21746        let c = WitContract {
21747            de: "cart".into(),
21748            para: "catalog".into(),
21749            wit: "wasi:http/proxy".into(),
21750            endpoint: Some("/lookup".into()),
21751            subject: None,
21752            slot: None,
21753        };
21754        let dest = c.destination();
21755        let para_slice = c.para.as_str();
21756        assert_eq!(
21757            dest.as_ptr(),
21758            para_slice.as_ptr(),
21759            "WitContract::destination must borrow from the .para \
21760             String's backing storage — a fresh allocation here means \
21761             the accessor no longer names the substrate-primitive typed \
21762             dispatch and every downstream consumer would silently \
21763             carry a detached copy",
21764        );
21765        assert_eq!(
21766            dest.len(),
21767            para_slice.len(),
21768            "WitContract::destination and .para.as_str() must byte-equal \
21769             in length as well as in address",
21770        );
21771    }
21772
21773    #[test]
21774    fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
21775        // The canonical per-`:contratos` WIT-world-reference scalar pin:
21776        // [`WitContract::world_ref`] must return the `:contratos :wit`
21777        // field byte-for-byte, borrowed from the typed slot's own
21778        // [`String`] storage. Sibling of the peer per-`:contratos`
21779        // [`WitContract::source`] / [`WitContract::destination`]
21780        // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
21781        // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
21782        // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
21783        // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
21784        // "the substrate-primitive accessor must byte-equal the raw
21785        // field access verbatim across every author-declared value"
21786        // discipline extended to the per-`:contratos` WIT-world arm.
21787        // Pins against a future silent detour that re-canonicalized the
21788        // WIT world reference (an accidental `.to_lowercase()` pass that
21789        // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
21790        // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
21791        // gate is already lowercase-prefixed so any re-normalization is
21792        // redundant + a drift surface between the validator and the
21793        // accessor), an M4-promotion-shape rewrite that formatted a
21794        // typed WIT-world enum through [`Display`] and silently drifted
21795        // the printer output from the source `caixa.lisp`, or a per-
21796        // cluster WIT-alias rewrite that didn't land on the peer field-
21797        // access sites. Five values sweep the shape-dispatch accept-set
21798        // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
21799        // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
21800        // `wasi:keyvalue/`).
21801        for (wit, endpoint, subject, slot) in [
21802            ("wasi:http/proxy", Some("/lookup"), None, None),
21803            ("http:proxy", Some("/health"), None, None),
21804            ("nats:pub-sub", None, Some("orders.paid"), None),
21805            ("kafka:events", None, Some("checkout-events"), None),
21806            ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
21807        ] {
21808            let c = WitContract {
21809                de: "cart".into(),
21810                para: "downstream".into(),
21811                wit: wit.into(),
21812                endpoint: endpoint.map(str::to_string),
21813                subject: subject.map(str::to_string),
21814                slot: slot.map(str::to_string),
21815            };
21816            assert_eq!(
21817                c.world_ref(),
21818                wit,
21819                "WitContract::world_ref must return :contratos :wit \
21820                 verbatim (got {:?}, expected {wit:?})",
21821                c.world_ref(),
21822            );
21823            assert_eq!(
21824                c.world_ref(),
21825                c.wit.as_str(),
21826                "WitContract::world_ref must byte-equal the .wit field \
21827                 access",
21828            );
21829        }
21830    }
21831
21832    #[test]
21833    fn wit_contract_world_ref_borrows_from_wit_storage() {
21834        // The borrow-not-copy pin: [`WitContract::world_ref`] must
21835        // return a `&str` slice that borrows from the typed slot's own
21836        // [`String`] storage — same-address invariant with
21837        // `c.wit.as_str()`. Pins against a future silent detour that
21838        // allocated a fresh `String` (`self.wit.clone()` in the body
21839        // would type-check but silently drop the borrow, and every
21840        // downstream consumer that assumed the returned slice outlives
21841        // `&self` would break on a stale-reference use-after-free — the
21842        // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
21843        // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
21844        // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
21845        // / [`is_pubsub`][WitContract::is_pubsub] /
21846        // [`is_store`][WitContract::is_store] methods route through —
21847        // each borrow from the WitContract's own storage and each would
21848        // silently misbehave if this accessor produced a detached copy).
21849        // Peer of the sibling per-`:contratos` [`WitContract::source`] /
21850        // [`WitContract::destination`] and per-`:entrada`
21851        // [`Entrada::destination`] / [`Entrada::hostname`] and
21852        // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
21853        // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
21854        let c = WitContract {
21855            de: "cart".into(),
21856            para: "catalog".into(),
21857            wit: "wasi:http/proxy".into(),
21858            endpoint: Some("/lookup".into()),
21859            subject: None,
21860            slot: None,
21861        };
21862        let world = c.world_ref();
21863        let wit_slice = c.wit.as_str();
21864        assert_eq!(
21865            world.as_ptr(),
21866            wit_slice.as_ptr(),
21867            "WitContract::world_ref must borrow from the .wit String's \
21868             backing storage — a fresh allocation here means the \
21869             accessor no longer names the substrate-primitive typed \
21870             dispatch and every downstream consumer would silently carry \
21871             a detached copy",
21872        );
21873        assert_eq!(
21874            world.len(),
21875            wit_slice.len(),
21876            "WitContract::world_ref and .wit.as_str() must byte-equal in \
21877             length as well as in address",
21878        );
21879    }
21880
21881    #[test]
21882    fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
21883        // Sibling-triple invariant pin composing all three per-`:contratos`
21884        // substrate-primitive typed dispatches — [`WitContract::source`]
21885        // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
21886        // [`WitContract::world_ref`] — at the joint
21887        // `(source(), destination(), world_ref())` call shape every
21888        // renderer that fans on per-edge caller-callee-shape identity
21889        // keys off. The invariant, evaluated per-contract:
21890        //
21891        //   (c.source(), c.destination(), c.world_ref())
21892        //   == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
21893        //
21894        // Closes the last unlifted per-`:contratos` scalar axis — every
21895        // downstream consumer that reads the triple now routes through
21896        // exactly three typed dispatches on the substrate primitive,
21897        // not two typed + one open-coded field access. A future refactor
21898        // that silently split any one accessor's projection (an
21899        // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
21900        // canonicalization that didn't reach the peer `source`/
21901        // `destination` arms, an accidental `source()` per-cluster
21902        // caller-alias rewrite that didn't land on the `world_ref` peer)
21903        // surfaces at caixa-core build time. Peer of the sibling per-
21904        // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
21905        // per-`:entrada` `(hostname(), destination())` (6db982c /
21906        // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
21907        // axes, extended to the per-`:contratos` triple.
21908        for (de, para, wit, endpoint, subject, slot) in [
21909            (
21910                "cart",
21911                "catalog",
21912                "wasi:http/proxy",
21913                Some("/lookup"),
21914                None,
21915                None,
21916            ),
21917            (
21918                "checkout",
21919                "orders",
21920                "nats:pub-sub",
21921                None,
21922                Some("orders.paid"),
21923                None,
21924            ),
21925            (
21926                "cart",
21927                "kv",
21928                "wasi:keyvalue/store",
21929                None,
21930                None,
21931                Some("carts/{cart_id}"),
21932            ),
21933            (
21934                "orders-v2",
21935                "inventory-v3",
21936                "http:proxy",
21937                Some("/reserve"),
21938                None,
21939                None,
21940            ),
21941        ] {
21942            let c = WitContract {
21943                de: de.into(),
21944                para: para.into(),
21945                wit: wit.into(),
21946                endpoint: endpoint.map(str::to_string),
21947                subject: subject.map(str::to_string),
21948                slot: slot.map(str::to_string),
21949            };
21950            assert_eq!(
21951                (c.source(), c.destination(), c.world_ref()),
21952                (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
21953                "(WitContract::source, ::destination, ::world_ref) must \
21954                 project (.de, .para, .wit) verbatim across every author-\
21955                 declared triple (got ({:?}, {:?}, {:?}), expected \
21956                 ({de:?}, {para:?}, {wit:?}))",
21957                c.source(),
21958                c.destination(),
21959                c.world_ref(),
21960            );
21961        }
21962    }
21963
21964    #[test]
21965    fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
21966        // The canonical per-`:contratos` owned-form caller-callee-pair
21967        // pin: [`WitContract::edge_pair`] must return the
21968        // `(source(), destination())` tuple in owned form byte-for-byte,
21969        // projected through the lifted [`WitContract::source`] /
21970        // [`WitContract::destination`] scalar accessors. Pins the
21971        // composite-projection invariant on the per-`:contratos`
21972        // mesh-slot atom — every author-declared `(de, para)` pair must
21973        // round-trip verbatim through the substrate primitive's typed
21974        // dispatch, so the nine [`AplicacaoError`] diagnostic-
21975        // construction sites the accessor now feeds
21976        // ([`AplicacaoError::EmptyWit`],
21977        // [`AplicacaoError::ContratoEndpointEmpty`],
21978        // [`AplicacaoError::ContratoEndpointNotAbsolute`],
21979        // [`AplicacaoError::ContratoEndpointInvalid`],
21980        // [`AplicacaoError::ContratoSubjectEmpty`],
21981        // [`AplicacaoError::ContratoSubjectInvalid`],
21982        // [`AplicacaoError::ContratoSlotEmpty`],
21983        // [`AplicacaoError::ContratoSlotInvalid`],
21984        // [`AplicacaoError::ContratoDuplicate`]) all read the same
21985        // `(de, para)` label pair every author sees at the source
21986        // `caixa.lisp`. Pins against a future silent detour that swapped
21987        // the `.0` / `.1` arms (an accidental `(destination(),
21988        // source())` re-order in the body would silently invert every
21989        // downstream diagnostic's `de:` / `para:` label pair, silently
21990        // reversing the direction of every operator-facing typed error
21991        // arrow), a fresh-allocation shape drift (an accidental
21992        // `.to_string()` on one arm but not the other would leave the
21993        // owned/borrowed pair mismatched vs. the sibling `source()` /
21994        // `destination()` returns), or an M4 per-cluster caller/callee-
21995        // alias rewrite that landed on `source()` without reaching
21996        // `destination()` (or vice versa). Peer of the sibling per-
21997        // `:contratos` `(source, destination, world_ref)` triple
21998        // pin above on the mesh-slot-atom scalar-value axes, extended
21999        // to the owned-form pair-projection axis.
22000        for (de, para, wit, endpoint, subject, slot) in [
22001            (
22002                "cart",
22003                "catalog",
22004                "wasi:http/proxy",
22005                Some("/lookup"),
22006                None,
22007                None,
22008            ),
22009            (
22010                "checkout",
22011                "orders",
22012                "nats:pub-sub",
22013                None,
22014                Some("orders.paid"),
22015                None,
22016            ),
22017            (
22018                "cart",
22019                "kv",
22020                "wasi:keyvalue/store",
22021                None,
22022                None,
22023                Some("carts/{cart_id}"),
22024            ),
22025            (
22026                "orders-v2",
22027                "inventory-v3",
22028                "http:proxy",
22029                Some("/reserve"),
22030                None,
22031                None,
22032            ),
22033        ] {
22034            let c = WitContract {
22035                de: de.into(),
22036                para: para.into(),
22037                wit: wit.into(),
22038                endpoint: endpoint.map(str::to_string),
22039                subject: subject.map(str::to_string),
22040                slot: slot.map(str::to_string),
22041            };
22042            assert_eq!(
22043                c.edge_pair(),
22044                (de.to_string(), para.to_string()),
22045                "WitContract::edge_pair must return (:contratos :de, \
22046                 :contratos :para) as an owned tuple verbatim (got {:?}, \
22047                 expected ({de:?}, {para:?}))",
22048                c.edge_pair(),
22049            );
22050        }
22051    }
22052
22053    #[test]
22054    fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
22055        // The composition pin: [`WitContract::edge_pair`] must return
22056        // exactly `(source().to_string(), destination().to_string())` —
22057        // the owned form of the sibling accessor pair — so any future
22058        // refactor that silently re-authored the caller-arm / callee-arm
22059        // projection to bypass the lifted scalar accessors (an accidental
22060        // `(self.de.clone(), self.para.clone())` regression back to the
22061        // raw field-access shape, an M4-typed-caller-enum `Display`
22062        // re-canonicalization on `source()` that didn't reach
22063        // `edge_pair()`, a per-cluster alias rewrite the operator lands
22064        // on `destination()` without reaching this composite projection)
22065        // trips at caixa-core build time. Pins the "typed dispatch
22066        // composes with typed dispatch, not with raw field access"
22067        // discipline every downstream diagnostic-construction site now
22068        // routes through — a `de:` / `para:` label pair whose
22069        // projection silently drifted off the substrate primitive's
22070        // scalar accessors would silently split the diagnostic's self-
22071        // locating signal from the source `caixa.lisp` author's view.
22072        // Peer of the sibling per-`:politicas` `is_empty` /
22073        // `validate_politicas` accessor-routing-pin family on the M3
22074        // mesh-slot family (18575, 18739, 18918, 19140, 19371).
22075        let c = WitContract {
22076            de: "cart".into(),
22077            para: "catalog".into(),
22078            wit: "wasi:http/proxy".into(),
22079            endpoint: Some("/lookup".into()),
22080            subject: None,
22081            slot: None,
22082        };
22083        assert_eq!(
22084            c.edge_pair(),
22085            (c.source().to_string(), c.destination().to_string()),
22086            "WitContract::edge_pair must compose exactly \
22087             (source().to_string(), destination().to_string()) — a \
22088             bypass of either sibling accessor here would silently \
22089             decouple the composite-projection axis from the \
22090             substrate-primitive scalar accessors every downstream \
22091             consumer routes through",
22092        );
22093    }
22094
22095    #[test]
22096    fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
22097     {
22098        // The canonical per-`:contratos` owned-form
22099        // caller-callee-world-ref-triple pin:
22100        // [`WitContract::edge_triple`] must return the
22101        // `(source(), destination(), world_ref())` tuple in owned form
22102        // byte-for-byte, projected through the lifted
22103        // [`WitContract::source`] / [`WitContract::destination`] /
22104        // [`WitContract::world_ref`] scalar accessors. Pins the
22105        // composite-projection invariant on the per-`:contratos`
22106        // mesh-slot atom — every author-declared `(de, para, wit)`
22107        // triple must round-trip verbatim through the substrate
22108        // primitive's typed dispatch, so the nine
22109        // [`AplicacaoError`] diagnostic-construction sites the
22110        // accessor now feeds (the [`WitTarget`]-dispatch's eight
22111        // wrong-target / missing-target / invalid-wit / capability-
22112        // with-payload arms in [`WitContract::target`], plus the
22113        // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
22114        // diagnostic constructor in [`AplicacaoSpec::validate`]) all
22115        // read the same `(de, para, wit)` triple every author sees at
22116        // the source `caixa.lisp`. Pins against a future silent
22117        // detour that swapped any two arms (an accidental `(destination(),
22118        // source(), world_ref())` re-order in the body would silently
22119        // invert every downstream diagnostic's `de:` / `para:` label
22120        // pair, silently reversing the direction of every operator-
22121        // facing typed error arrow), a fresh-allocation shape drift
22122        // (an accidental `.to_string()` skipped on one arm would leave
22123        // the owned/borrowed triple mismatched vs. the sibling
22124        // `source()` / `destination()` / `world_ref()` returns), or an
22125        // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
22126        // canonicalization pass that landed on one accessor without
22127        // reaching the peers. Peer of the sibling per-`:contratos`
22128        // caller-callee-pair
22129        // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
22130        // pin on the mesh-slot-atom composite-projection axis,
22131        // extended to the triple-projection axis.
22132        for (de, para, wit, endpoint, subject, slot) in [
22133            (
22134                "cart",
22135                "catalog",
22136                "wasi:http/proxy",
22137                Some("/lookup"),
22138                None,
22139                None,
22140            ),
22141            (
22142                "checkout",
22143                "orders",
22144                "nats:pub-sub",
22145                None,
22146                Some("orders.paid"),
22147                None,
22148            ),
22149            (
22150                "cart",
22151                "kv",
22152                "wasi:keyvalue/store",
22153                None,
22154                None,
22155                Some("carts/{cart_id}"),
22156            ),
22157            (
22158                "orders-v2",
22159                "inventory-v3",
22160                "http:proxy",
22161                Some("/reserve"),
22162                None,
22163                None,
22164            ),
22165        ] {
22166            let c = WitContract {
22167                de: de.into(),
22168                para: para.into(),
22169                wit: wit.into(),
22170                endpoint: endpoint.map(str::to_string),
22171                subject: subject.map(str::to_string),
22172                slot: slot.map(str::to_string),
22173            };
22174            assert_eq!(
22175                c.edge_triple(),
22176                (de.to_string(), para.to_string(), wit.to_string()),
22177                "WitContract::edge_triple must return (:contratos :de, \
22178                 :contratos :para, :contratos :wit) as an owned triple \
22179                 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
22180                c.edge_triple(),
22181            );
22182        }
22183    }
22184
22185    #[test]
22186    fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
22187        // The composition pin: [`WitContract::edge_triple`] must return
22188        // exactly `(source().to_string(), destination().to_string(),
22189        // world_ref().to_string())` — the owned form of the sibling
22190        // scalar-accessor triple — so any future refactor that silently
22191        // re-authored one arm's projection to bypass the lifted scalar
22192        // accessors (an accidental `(self.de.clone(), self.para.clone(),
22193        // self.wit.clone())` regression back to the raw field-access
22194        // shape the internal `edge` closure and the ContratoDuplicate
22195        // diagnostic both carried before this lift landed, an
22196        // M4-typed-caller-enum `Display` re-canonicalization on
22197        // `source()` that didn't reach `edge_triple()`, a per-cluster
22198        // alias rewrite the operator lands on `destination()` /
22199        // `world_ref()` without reaching this composite projection)
22200        // trips at caixa-core build time. Pins the "typed dispatch
22201        // composes with typed dispatch, not with raw field access"
22202        // discipline every downstream diagnostic-construction site now
22203        // routes through — a `de:` / `para:` / `wit:` triple whose
22204        // projection silently drifted off the substrate primitive's
22205        // scalar accessors would silently split the diagnostic's self-
22206        // locating signal from the source `caixa.lisp` author's view.
22207        // Peer of the sibling per-`:contratos` edge_pair composition-
22208        // pin above on the mesh-slot-atom composite-projection axis.
22209        let c = WitContract {
22210            de: "cart".into(),
22211            para: "catalog".into(),
22212            wit: "wasi:http/proxy".into(),
22213            endpoint: Some("/lookup".into()),
22214            subject: None,
22215            slot: None,
22216        };
22217        assert_eq!(
22218            c.edge_triple(),
22219            (
22220                c.source().to_string(),
22221                c.destination().to_string(),
22222                c.world_ref().to_string(),
22223            ),
22224            "WitContract::edge_triple must compose exactly \
22225             (source().to_string(), destination().to_string(), \
22226             world_ref().to_string()) — a bypass of any sibling accessor \
22227             here would silently decouple the composite-projection axis \
22228             from the substrate-primitive scalar accessors every \
22229             downstream consumer routes through",
22230        );
22231    }
22232
22233    #[test]
22234    fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
22235        // The canonical semantics-pin: [`WitContract::edge_triple`] must
22236        // project the full `(de, para, wit)` identity of a `:contratos`
22237        // edge — the sub-triple every triple-carrying
22238        // [`AplicacaoError::Contrato*`] diagnostic weaves into its
22239        // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
22240        // missing-target, capability-with-payload, invalid-wit, and the
22241        // duplicate-gate). Rejects a drift in shape (an accidental
22242        // silent detour that returned a `(de, para)` pair or added an
22243        // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
22244        // would trip here because the return type would no longer
22245        // pattern-match the eight `let (de, para, wit) = edge();`
22246        // destructures the [`WitContract::target`] dispatch feeds off
22247        // + the paired duplicate-gate `let (de, para, wit) =
22248        // c.edge_triple();` destructure in
22249        // [`AplicacaoSpec::validate`]). Peer of the sibling per-
22250        // `:contratos` caller-callee-pair pin above extended to the
22251        // triple projection surface: closes the "one composite
22252        // accessor per typed diagnostic-construction sub-tuple"
22253        // discipline on the per-`:contratos` mesh-slot-atom axis.
22254        let c = WitContract {
22255            de: "checkout".into(),
22256            para: "orders".into(),
22257            wit: "nats:pub-sub".into(),
22258            endpoint: None,
22259            subject: Some("orders.paid".into()),
22260            slot: None,
22261        };
22262        let (de, para, wit) = c.edge_triple();
22263        assert_eq!(de, "checkout");
22264        assert_eq!(para, "orders");
22265        assert_eq!(wit, "nats:pub-sub");
22266    }
22267
22268    #[test]
22269    fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
22270     {
22271        // The composition pin: [`WitContract::identity`] must return
22272        // exactly `(source(), destination(), world_ref(), endpoint(),
22273        // subject(), slot())` — the borrowed form of the six-scalar-
22274        // accessor identity axis. Any future refactor that silently
22275        // re-authored one arm's projection to bypass a scalar accessor
22276        // (a `self.de.as_str()` regression back to raw field access on
22277        // any of the three required arms, a `self.endpoint.as_deref()`
22278        // regression on any of the three optional arms, an M4 per-
22279        // cluster caller/callee-alias rewrite the operator lands on
22280        // `source()` / `destination()` without reaching this composite
22281        // projection) trips at caixa-core build time. Sweeps four
22282        // permutations of the WIT-shape × payload lattice — HTTP with
22283        // endpoint, pub-sub with subject, store with slot, payload-less
22284        // capability — so every payload arm is exercised. Peer of the
22285        // sibling per-`:contratos`
22286        // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
22287        // composition pin on the mesh-slot-atom composite-projection
22288        // axis; extends the discipline from the (de, para, wit) prefix
22289        // onto the full-identity axis carrying the three payload arms.
22290        for (de, para, wit, endpoint, subject, slot) in [
22291            (
22292                "cart",
22293                "catalog",
22294                "wasi:http/proxy",
22295                Some("/lookup"),
22296                None,
22297                None,
22298            ),
22299            (
22300                "checkout",
22301                "orders",
22302                "nats:pub-sub",
22303                None,
22304                Some("orders.paid"),
22305                None,
22306            ),
22307            (
22308                "cart",
22309                "kv",
22310                "wasi:keyvalue/store",
22311                None,
22312                None,
22313                Some("carts/{cart_id}"),
22314            ),
22315            ("audit", "sink", "wasi:logging", None, None, None),
22316        ] {
22317            let c = WitContract {
22318                de: de.into(),
22319                para: para.into(),
22320                wit: wit.into(),
22321                endpoint: endpoint.map(str::to_owned),
22322                subject: subject.map(str::to_owned),
22323                slot: slot.map(str::to_owned),
22324            };
22325            assert_eq!(
22326                c.identity(),
22327                (
22328                    c.source(),
22329                    c.destination(),
22330                    c.world_ref(),
22331                    c.endpoint(),
22332                    c.subject(),
22333                    c.slot(),
22334                ),
22335                "WitContract::identity must compose exactly \
22336                 (source(), destination(), world_ref(), endpoint(), \
22337                 subject(), slot()) — a bypass of any sibling accessor \
22338                 here would silently decouple the identity-projection \
22339                 axis from the substrate-primitive scalar accessors \
22340                 every dedup-key consumer routes through",
22341            );
22342        }
22343    }
22344
22345    #[test]
22346    fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
22347        // The canonical semantics-pin: [`WitContract::identity`] must
22348        // project the six-axis (de, para, wit, endpoint, subject, slot)
22349        // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
22350        // gate keys off — two `WitContract`s that agree on all six axes
22351        // are the same typed edge declared twice, the graph-edge
22352        // analogue of duplicate `:membros` / `:placement :clusters` /
22353        // `:entrada :paths` entries. Rejects a shape drift (an
22354        // accidental silent detour that returned a prefix tuple or
22355        // added an extra field) by pattern-matching the six-arm shape.
22356        // Peer of the sibling per-`:contratos`
22357        // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
22358        // pin extended from the (de, para, wit) prefix onto the full
22359        // six-axis identity that the dedup key rides.
22360        let c = WitContract {
22361            de: "cart".into(),
22362            para: "catalog".into(),
22363            wit: "wasi:http/proxy".into(),
22364            endpoint: Some("/products/:id".into()),
22365            subject: None,
22366            slot: None,
22367        };
22368        let (de, para, wit, endpoint, subject, slot) = c.identity();
22369        assert_eq!(de, "cart");
22370        assert_eq!(para, "catalog");
22371        assert_eq!(wit, "wasi:http/proxy");
22372        assert_eq!(endpoint, Some("/products/:id"));
22373        assert_eq!(subject, None);
22374        assert_eq!(slot, None);
22375
22376        // Two byte-identical contracts must produce equal identities —
22377        // the dedup key's foundational invariant.
22378        let c2 = c.clone();
22379        assert_eq!(c.identity(), c2.identity());
22380
22381        // Any change on any of the six axes must break the identity —
22382        // sweeps by mutating one axis at a time.
22383        let mut mutated = c.clone();
22384        mutated.de = "search".into();
22385        assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
22386        let mut mutated = c.clone();
22387        mutated.para = "warehouse".into();
22388        assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
22389        let mut mutated = c.clone();
22390        mutated.wit = "http:legacy".into();
22391        assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
22392        let mut mutated = c.clone();
22393        mutated.endpoint = Some("/search".into());
22394        assert_ne!(
22395            c.identity(),
22396            mutated.identity(),
22397            "endpoint axis must partition"
22398        );
22399        let mut mutated = c.clone();
22400        mutated.subject = Some("orders.paid".into());
22401        assert_ne!(
22402            c.identity(),
22403            mutated.identity(),
22404            "subject axis must partition"
22405        );
22406        let mut mutated = c;
22407        mutated.slot = Some("carts/{id}".into());
22408        assert_ne!(mutated.identity().5, None, "slot axis must partition");
22409    }
22410
22411    #[test]
22412    fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
22413        // The canonical per-`:contratos` structural-self-edge pin:
22414        // [`WitContract::is_self_loop`] must return `true` when the
22415        // `:de` and `:para` fields agree byte-for-byte, across every
22416        // WIT-shape variant the per-edge shape family carries. Pins
22417        // the shape-agnostic identity-space partition the
22418        // [`AplicacaoSpec::validate`] self-edge gate at
22419        // caixa-core/src/aplicacao.rs:5559 fires against — all four
22420        // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
22421        // under the same one predicate. Four permutations sweep the
22422        // accept-set: HTTP with endpoint, pub-sub with subject, KV
22423        // store with slot, and payload-less capability.
22424        for (nome, wit, endpoint, subject, slot) in [
22425            ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
22426            ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
22427            (
22428                "kv",
22429                "wasi:keyvalue/store",
22430                None,
22431                None,
22432                Some("carts/{cart_id}"),
22433            ),
22434            ("audit", "wasi:logging", None, None, None),
22435        ] {
22436            let c = WitContract {
22437                de: nome.into(),
22438                para: nome.into(),
22439                wit: wit.into(),
22440                endpoint: endpoint.map(str::to_string),
22441                subject: subject.map(str::to_string),
22442                slot: slot.map(str::to_string),
22443            };
22444            assert!(
22445                c.is_self_loop(),
22446                "WitContract::is_self_loop must return true when \
22447                 :contratos :de == :contratos :para (got false on \
22448                 {nome:?} under {wit:?})",
22449            );
22450        }
22451    }
22452
22453    #[test]
22454    fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
22455        // The complement pin: [`WitContract::is_self_loop`] must return
22456        // `false` on every well-shaped inter-Servico contract (the
22457        // author-intended `:contratos` shape MESH-COMPOSITION §III.1
22458        // names — "Servico A calls Servico B" between two distinct
22459        // graph nodes). Pins against a future silent detour that
22460        // inverted the predicate (an accidental `!= ` swap for `==`
22461        // would silently reject every legitimate inter-Servico edge
22462        // and admit every self-edge — the exact inversion of the
22463        // author-intended shape). Four permutations sweep the same
22464        // WIT-shape accept-set the sibling positive-arm test carries.
22465        for (de, para, wit, endpoint, subject, slot) in [
22466            (
22467                "cart",
22468                "catalog",
22469                "wasi:http/proxy",
22470                Some("/lookup"),
22471                None,
22472                None,
22473            ),
22474            (
22475                "checkout",
22476                "orders",
22477                "nats:pub-sub",
22478                None,
22479                Some("orders.paid"),
22480                None,
22481            ),
22482            (
22483                "cart",
22484                "kv",
22485                "wasi:keyvalue/store",
22486                None,
22487                None,
22488                Some("carts/{cart_id}"),
22489            ),
22490            ("audit", "sink", "wasi:logging", None, None, None),
22491        ] {
22492            let c = WitContract {
22493                de: de.into(),
22494                para: para.into(),
22495                wit: wit.into(),
22496                endpoint: endpoint.map(str::to_string),
22497                subject: subject.map(str::to_string),
22498                slot: slot.map(str::to_string),
22499            };
22500            assert!(
22501                !c.is_self_loop(),
22502                "WitContract::is_self_loop must return false when \
22503                 :contratos :de differs from :contratos :para (got true \
22504                 on {de:?} → {para:?} under {wit:?})",
22505            );
22506        }
22507    }
22508
22509    #[test]
22510    fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
22511        // The composition pin: [`WitContract::is_self_loop`] must
22512        // resolve to exactly `self.source() == self.destination()` —
22513        // the equality probe of the sibling scalar-accessor pair — so
22514        // any future refactor that silently re-authored the predicate
22515        // to bypass the lifted scalar accessors (an accidental
22516        // `self.de == self.para` regression back to the raw field-
22517        // access shape, an M4-typed-caller-enum identity-comparison
22518        // rule that landed on `source()` without reaching
22519        // `destination()`, a per-cluster alias rewrite the operator
22520        // pins on `destination()` without reaching this predicate)
22521        // trips at caixa-core build time. Pins the "typed dispatch
22522        // composes with typed dispatch, not with raw field access"
22523        // discipline the sibling [`WitContract::edge_pair`] /
22524        // [`WitContract::edge_triple`] composite-projection accessors
22525        // already carry, extended onto the per-edge endpoint-equality
22526        // predicate axis. Positive and complement arms both fire.
22527        let self_edge = WitContract {
22528            de: "cart".into(),
22529            para: "cart".into(),
22530            wit: "wasi:http/proxy".into(),
22531            endpoint: Some("/lookup".into()),
22532            subject: None,
22533            slot: None,
22534        };
22535        assert_eq!(
22536            self_edge.is_self_loop(),
22537            self_edge.source() == self_edge.destination(),
22538            "WitContract::is_self_loop must compose exactly \
22539             `source() == destination()` — a bypass of either sibling \
22540             accessor here would silently decouple the endpoint-\
22541             equality predicate from the substrate-primitive scalar \
22542             accessors every downstream consumer routes through",
22543        );
22544        let inter_edge = WitContract {
22545            de: "cart".into(),
22546            para: "catalog".into(),
22547            wit: "wasi:http/proxy".into(),
22548            endpoint: Some("/lookup".into()),
22549            subject: None,
22550            slot: None,
22551        };
22552        assert_eq!(
22553            inter_edge.is_self_loop(),
22554            inter_edge.source() == inter_edge.destination(),
22555            "WitContract::is_self_loop must compose exactly \
22556             `source() == destination()` on the complement arm too",
22557        );
22558    }
22559
22560    #[test]
22561    fn wit_contract_is_self_loop_predicate_is_const_fn() {
22562        // Fail-before-pass-after pin on the [`WitContract::is_self_loop`]
22563        // caller-callee identity-space predicate's `const`-eval-surface
22564        // posture. The wrapper below dispatches through
22565        // [`WitContract::is_self_loop`] and is well-formed only when the
22566        // callee is itself `pub const fn` — any future accidental
22567        // downgrade to non-`const` fails the wrapper at caixa-core build
22568        // time with E0015 (`cannot call non-const method`), strictly
22569        // stronger than a runtime `assert!` and strictly stronger than a
22570        // module-scope `const _: () = assert!(…)` pin (the type's
22571        // `String` / `Option<String>` carriers rule out `const`-context
22572        // value construction; the `const fn` wrapper is the load-bearing
22573        // shape that side-steps the destructor-in-const restriction on
22574        // the value axis while still pinning the `const`-fn posture on
22575        // the callee — mirror of the sibling
22576        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
22577        // (279823b) and
22578        // [`wit_contract_identity_projection_accessor_is_const_fn`]
22579        // (1ab648c) pins' discipline verbatim on the peer scalar-
22580        // accessor and composite-projection surfaces). Closes the last
22581        // unlifted per-`:contratos` shape/identity predicate on the
22582        // const-eval surface — the peer WIT-shape-partition family
22583        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
22584        // [`WitContract::is_store`] / [`WitContract::is_capability`]
22585        // already carried the `pub const fn` posture on the peer
22586        // WIT-world-ref classifier axis (d46420c / 84c2325 / 279823b);
22587        // this pin extends the same posture onto the caller-callee
22588        // identity-space partition. Sweeps every WIT-shape arm on both
22589        // the equal-endpoints (self-edge) and distinct-endpoints
22590        // (inter-edge) arms of the identity-space partition, plus one
22591        // same-length distinct-byte pair to pin the mid-loop `!=` arm
22592        // past the leading length-mismatch shortcut.
22593        const fn is_self_loop_via_const_fn(c: &WitContract) -> bool {
22594            c.is_self_loop()
22595        }
22596        let mk = |de: &str, para: &str, wit: &str| WitContract {
22597            de: de.into(),
22598            para: para.into(),
22599            wit: wit.into(),
22600            endpoint: None,
22601            subject: None,
22602            slot: None,
22603        };
22604        for (nome, wit) in [
22605            ("cart", "wasi:http/proxy"),
22606            ("checkout", "nats:pub-sub"),
22607            ("kv", "wasi:keyvalue/store"),
22608            ("audit", "wasi:logging"),
22609        ] {
22610            let self_edge = mk(nome, nome, wit);
22611            assert!(
22612                is_self_loop_via_const_fn(&self_edge),
22613                "self-edge {nome:?} under {wit:?}"
22614            );
22615            assert_eq!(
22616                is_self_loop_via_const_fn(&self_edge),
22617                self_edge.is_self_loop()
22618            );
22619        }
22620        for (de, para, wit) in [
22621            ("cart", "catalog", "wasi:http/proxy"),
22622            ("checkout", "orders", "nats:pub-sub"),
22623            ("cart", "kv", "wasi:keyvalue/store"),
22624            ("audit", "sink", "wasi:logging"),
22625        ] {
22626            let inter_edge = mk(de, para, wit);
22627            assert!(
22628                !is_self_loop_via_const_fn(&inter_edge),
22629                "inter-edge {de:?}→{para:?} under {wit:?}",
22630            );
22631            assert_eq!(
22632                is_self_loop_via_const_fn(&inter_edge),
22633                inter_edge.is_self_loop()
22634            );
22635        }
22636        // Same-length distinct-byte pair — pins the mid-loop `!=` arm
22637        // past the leading `a.len() != b.len()` shortcut so the const-fn
22638        // wrapper exercises every arm of the byte-slice equality loop.
22639        let same_len_pair = mk("cart", "kart", "wasi:http/proxy");
22640        assert!(
22641            !is_self_loop_via_const_fn(&same_len_pair),
22642            "same-length distinct-byte"
22643        );
22644        assert_eq!(
22645            is_self_loop_via_const_fn(&same_len_pair),
22646            same_len_pair.is_self_loop()
22647        );
22648    }
22649
22650    #[test]
22651    fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
22652        // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
22653        // pin: [`WitContract::endpoint`] must return the `:contratos
22654        // :endpoint` field byte-for-byte, borrowed from the typed slot's
22655        // own `Option<String>` storage. Peer of the sibling
22656        // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
22657        // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
22658        // mesh-slot `Option<String>` optional-scalar axes — same "the
22659        // substrate-primitive accessor must byte-equal the raw field
22660        // access verbatim across every author-declared value" discipline
22661        // extended to the per-`:contratos` HTTP-payload-carrier arm.
22662        // Pins against a future silent detour that re-canonicalized the
22663        // endpoint (an accidental percent-encoding pass that didn't
22664        // reach the peer field-access site at the dedup key, a per-CR
22665        // fully-qualified prefix rewrite the operator authors on one
22666        // consumer without the other, or an M4 typed-path-template
22667        // `Display` re-canonicalization that silently drifted the
22668        // printer output from the source `caixa.lisp`). Four values
22669        // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
22670        // gate upstream admits (short root-path, dashed, param-shaped,
22671        // deep-hierarchy).
22672        for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
22673            let c = WitContract {
22674                de: "cart".into(),
22675                para: "catalog".into(),
22676                wit: "wasi:http/proxy".into(),
22677                endpoint: Some(endpoint.into()),
22678                subject: None,
22679                slot: None,
22680            };
22681            assert_eq!(
22682                c.endpoint(),
22683                Some(endpoint),
22684                "WitContract::endpoint must return :contratos :endpoint \
22685                 verbatim (got {:?}, expected Some({endpoint:?}))",
22686                c.endpoint(),
22687            );
22688            assert_eq!(
22689                c.endpoint(),
22690                c.endpoint.as_deref(),
22691                "WitContract::endpoint must byte-equal the .endpoint \
22692                 field's `.as_deref()` projection",
22693            );
22694        }
22695    }
22696
22697    #[test]
22698    fn wit_contract_endpoint_none_when_field_is_none() {
22699        // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
22700        // payload-carrier accessor pin: when the typed slot is absent —
22701        // the canonical shape under a non-HTTP `:wit` world per the
22702        // [`WitContract::target`]-enforced shape ↔ target partition
22703        // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
22704        // carries `:slot`, [`WitTarget::Capability`] carries none) —
22705        // [`WitContract::endpoint`] must return `None`. Pins against a
22706        // future silent detour that projected the absent slot to a
22707        // `Some("")` empty-string default (the canonical `Option<String>`
22708        // → `String` collapse footgun the sibling M2
22709        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
22710        // emptiness predicates already guard on the peer M2 typed-slot
22711        // surfaces), a `Some("None")` stringified-None round-trip, or a
22712        // `Some` arm whose contents were derived from a sibling slot (an
22713        // accidental fallback to the `:subject` / `:slot` payload that
22714        // read the pub-sub / store payload into the endpoint axis).
22715        // Three contracts sweep the accept-set every non-HTTP `:wit`
22716        // world lands on — pub-sub NATS, key/value, and payload-less
22717        // capability.
22718        for (wit, subject, slot) in [
22719            ("nats:pub-sub", Some("orders.paid"), None),
22720            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
22721            ("wasi:cli/environment", None, None),
22722        ] {
22723            let c = WitContract {
22724                de: "cart".into(),
22725                para: "downstream".into(),
22726                wit: wit.into(),
22727                endpoint: None,
22728                subject: subject.map(str::to_string),
22729                slot: slot.map(str::to_string),
22730            };
22731            assert!(
22732                c.endpoint().is_none(),
22733                "WitContract::endpoint must return None when the typed \
22734                 slot is absent under :wit {wit:?} (got {:?})",
22735                c.endpoint(),
22736            );
22737            assert_eq!(
22738                c.endpoint(),
22739                c.endpoint.as_deref(),
22740                "WitContract::endpoint must byte-equal the .endpoint \
22741                 field's `.as_deref()` projection in the absent arm",
22742            );
22743        }
22744    }
22745
22746    #[test]
22747    fn wit_contract_endpoint_borrows_from_endpoint_storage() {
22748        // The borrow-not-copy pin: [`WitContract::endpoint`] must return
22749        // an `Option<&str>` whose `Some` arm borrows from the typed
22750        // slot's own [`String`] storage — same-address invariant with
22751        // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
22752        // detour that allocated a fresh `String`
22753        // (`self.endpoint.clone().map(...)` in the body would type-check
22754        // but silently drop the borrow, and every downstream consumer
22755        // that assumed the returned slice outlives `&self` would break
22756        // on a stale-reference use-after-free — the [`WitContract::target`]
22757        // Http-arm payload extraction rebinds the returned `Option<&str>`
22758        // through `.ok_or_else(...)` and threads the `&str` payload into
22759        // [`WitTarget::Http { endpoint: &'a str }`], the
22760        // [`AplicacaoSpec::validate`] duplicate-`:contratos`
22761        // [`ContratoIdentity`] dedup key threads the returned
22762        // `Option<&str>` into the six-tuple's HTTP arm — each borrow
22763        // from the WitContract's own storage and each would silently
22764        // misbehave if this accessor produced a detached copy). Peer of
22765        // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
22766        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
22767        // shaped optional-scalar axes — first extension of the
22768        // `Option<&str>` borrow-not-copy discipline onto the
22769        // per-`:contratos` HTTP-shaped payload-carrier axis.
22770        let c = WitContract {
22771            de: "cart".into(),
22772            para: "catalog".into(),
22773            wit: "wasi:http/proxy".into(),
22774            endpoint: Some("/lookup".into()),
22775            subject: None,
22776            slot: None,
22777        };
22778        let ep = c.endpoint().expect("Some arm");
22779        let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
22780        assert_eq!(
22781            ep.as_ptr(),
22782            storage_slice.as_ptr(),
22783            "WitContract::endpoint must borrow from the .endpoint \
22784             String's backing storage — a fresh allocation here means \
22785             the accessor no longer names the substrate-primitive typed \
22786             dispatch and every downstream consumer would silently \
22787             carry a detached copy",
22788        );
22789        assert_eq!(
22790            ep.len(),
22791            storage_slice.len(),
22792            "WitContract::endpoint and .endpoint.as_deref() must byte-\
22793             equal in length as well as in address",
22794        );
22795    }
22796
22797    #[test]
22798    fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
22799        // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
22800        // pin: [`WitContract::subject`] must return the `:contratos
22801        // :subject` field byte-for-byte, borrowed from the typed slot's
22802        // own `Option<String>` storage. Peer of the sibling per-`:contratos`
22803        // [`WitContract::endpoint`] (7020470) accessor pin on the M3
22804        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
22805        // optional-scalar axis — same "the substrate-primitive accessor
22806        // must byte-equal the raw field access verbatim across every
22807        // author-declared value" discipline extended to the pub-sub arm.
22808        // Pins against a future silent detour that re-canonicalized the
22809        // subject (an accidental `.to_lowercase()` normalization that
22810        // didn't reach the peer field-access site at the dedup key, a
22811        // per-CR fully-qualified prefix rewrite the operator authors on
22812        // one consumer without the other, or an M4 typed-subject-template
22813        // `Display` re-canonicalization that silently drifted the printer
22814        // output from the source `caixa.lisp`). Four values sweep the
22815        // NATS accept-set every pub-sub author-declared subject lands on
22816        // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
22817        for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
22818            let c = WitContract {
22819                de: "cart".into(),
22820                para: "notifier".into(),
22821                wit: "nats:pub-sub".into(),
22822                endpoint: None,
22823                subject: Some(subject.into()),
22824                slot: None,
22825            };
22826            assert_eq!(
22827                c.subject(),
22828                Some(subject),
22829                "WitContract::subject must return :contratos :subject \
22830                 verbatim (got {:?}, expected Some({subject:?}))",
22831                c.subject(),
22832            );
22833            assert_eq!(
22834                c.subject(),
22835                c.subject.as_deref(),
22836                "WitContract::subject must byte-equal the .subject \
22837                 field's `.as_deref()` projection",
22838            );
22839        }
22840    }
22841
22842    #[test]
22843    fn wit_contract_subject_none_when_field_is_none() {
22844        // The absent-`:subject` arm of the per-`:contratos` pub-sub-
22845        // shaped payload-carrier accessor pin: when the typed slot is
22846        // absent — the canonical shape under a non-pub-sub `:wit` world
22847        // per the [`WitContract::target`]-enforced shape ↔ target
22848        // partition ([`WitTarget::Http`] carries `:endpoint`,
22849        // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
22850        // carries none) — [`WitContract::subject`] must return `None`.
22851        // Pins against a future silent detour that projected the absent
22852        // slot to a `Some("")` empty-string default (the canonical
22853        // `Option<String>` → `String` collapse footgun the sibling M2
22854        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
22855        // emptiness predicates already guard on the peer M2 typed-slot
22856        // surfaces), a `Some("None")` stringified-None round-trip, or a
22857        // `Some` arm whose contents were derived from a sibling slot (an
22858        // accidental fallback to the `:endpoint` / `:slot` payload that
22859        // read the HTTP / store payload into the subject axis). Three
22860        // contracts sweep the accept-set every non-pub-sub `:wit` world
22861        // lands on — HTTP proxy, key/value store, and payload-less
22862        // capability.
22863        for (wit, endpoint, slot) in [
22864            ("wasi:http/proxy", Some("/lookup"), None),
22865            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
22866            ("wasi:cli/environment", None, None),
22867        ] {
22868            let c = WitContract {
22869                de: "cart".into(),
22870                para: "downstream".into(),
22871                wit: wit.into(),
22872                endpoint: endpoint.map(str::to_string),
22873                subject: None,
22874                slot: slot.map(str::to_string),
22875            };
22876            assert!(
22877                c.subject().is_none(),
22878                "WitContract::subject must return None when the typed \
22879                 slot is absent under :wit {wit:?} (got {:?})",
22880                c.subject(),
22881            );
22882            assert_eq!(
22883                c.subject(),
22884                c.subject.as_deref(),
22885                "WitContract::subject must byte-equal the .subject \
22886                 field's `.as_deref()` projection in the absent arm",
22887            );
22888        }
22889    }
22890
22891    #[test]
22892    fn wit_contract_subject_borrows_from_subject_storage() {
22893        // The borrow-not-copy pin: [`WitContract::subject`] must return
22894        // an `Option<&str>` whose `Some` arm borrows from the typed
22895        // slot's own [`String`] storage — same-address invariant with
22896        // `c.subject.as_deref().unwrap()`. Pins against a future silent
22897        // detour that allocated a fresh `String`
22898        // (`self.subject.clone().map(...)` in the body would type-check
22899        // but silently drop the borrow, and every downstream consumer
22900        // that assumed the returned slice outlives `&self` would break
22901        // on a stale-reference use-after-free — the [`WitContract::target`]
22902        // PubSub-arm payload extraction rebinds the returned
22903        // `Option<&str>` through `.ok_or_else(...)` and threads the
22904        // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
22905        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
22906        // [`ContratoIdentity`] dedup key threads the returned
22907        // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
22908        // from the WitContract's own storage and each would silently
22909        // misbehave if this accessor produced a detached copy). Peer of
22910        // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
22911        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
22912        // shaped optional-scalar axis — second extension of the
22913        // `Option<&str>` borrow-not-copy discipline onto the
22914        // per-`:contratos` payload-carrier family, this time on the
22915        // pub-sub arm.
22916        let c = WitContract {
22917            de: "cart".into(),
22918            para: "notifier".into(),
22919            wit: "nats:pub-sub".into(),
22920            endpoint: None,
22921            subject: Some("orders.paid".into()),
22922            slot: None,
22923        };
22924        let sub = c.subject().expect("Some arm");
22925        let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
22926        assert_eq!(
22927            sub.as_ptr(),
22928            storage_slice.as_ptr(),
22929            "WitContract::subject must borrow from the .subject \
22930             String's backing storage — a fresh allocation here means \
22931             the accessor no longer names the substrate-primitive typed \
22932             dispatch and every downstream consumer would silently \
22933             carry a detached copy",
22934        );
22935        assert_eq!(
22936            sub.len(),
22937            storage_slice.len(),
22938            "WitContract::subject and .subject.as_deref() must byte-\
22939             equal in length as well as in address",
22940        );
22941    }
22942
22943    #[test]
22944    fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
22945        // The canonical per-`:contratos` key/value-store-shaped
22946        // `:slot`-scalar pin: [`WitContract::slot`] must return the
22947        // `:contratos :slot` field byte-for-byte, borrowed from the
22948        // typed slot's own `Option<String>` storage. Peer of the
22949        // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
22950        // [`WitContract::subject`] (90de675) accessor pins on the M3
22951        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
22952        // optional-scalar axis — same "the substrate-primitive
22953        // accessor must byte-equal the raw field access verbatim
22954        // across every author-declared value" discipline extended to
22955        // the store arm. Pins against a future silent detour that
22956        // re-canonicalized the slot template (an accidental
22957        // `.to_lowercase()` bucket-prefix normalization that didn't
22958        // reach the peer field-access site at the dedup key, a per-CR
22959        // fully-qualified prefix rewrite the operator authors on one
22960        // consumer without the other, or an M4 typed-key-template
22961        // `Display` re-canonicalization that silently drifted the
22962        // printer output from the source `caixa.lisp`). Four values
22963        // sweep the wasi:keyvalue accept-set every store-shaped
22964        // author-declared slot lands on (flat bucket, single-param
22965        // template, multi-param template, nested-hierarchy template).
22966        for slot in [
22967            "sessions",
22968            "carts/{cart_id}",
22969            "orders/{tenant}/{order_id}",
22970            "cache/tenant-a/orders/{id}",
22971        ] {
22972            let c = WitContract {
22973                de: "cart".into(),
22974                para: "kv".into(),
22975                wit: "wasi:keyvalue/store".into(),
22976                endpoint: None,
22977                subject: None,
22978                slot: Some(slot.into()),
22979            };
22980            assert_eq!(
22981                c.slot(),
22982                Some(slot),
22983                "WitContract::slot must return :contratos :slot \
22984                 verbatim (got {:?}, expected Some({slot:?}))",
22985                c.slot(),
22986            );
22987            assert_eq!(
22988                c.slot(),
22989                c.slot.as_deref(),
22990                "WitContract::slot must byte-equal the .slot field's \
22991                 `.as_deref()` projection",
22992            );
22993        }
22994    }
22995
22996    #[test]
22997    fn wit_contract_slot_none_when_field_is_none() {
22998        // The absent-`:slot` arm of the per-`:contratos` store-shaped
22999        // payload-carrier accessor pin: when the typed slot is absent —
23000        // the canonical shape under a non-store `:wit` world per the
23001        // [`WitContract::target`]-enforced shape ↔ target partition
23002        // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
23003        // carries `:subject`, [`WitTarget::Capability`] carries none) —
23004        // [`WitContract::slot`] must return `None`. Pins against a
23005        // future silent detour that projected the absent slot to a
23006        // `Some("")` empty-string default (the canonical
23007        // `Option<String>` → `String` collapse footgun the sibling M2
23008        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
23009        // emptiness predicates already guard on the peer M2 typed-slot
23010        // surfaces), a `Some("None")` stringified-None round-trip, or
23011        // a `Some` arm whose contents were derived from a sibling
23012        // slot (an accidental fallback to the `:endpoint` / `:subject`
23013        // payload that read the HTTP / pub-sub payload into the store
23014        // axis). Three contracts sweep the accept-set every non-store
23015        // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
23016        // payload-less capability.
23017        for (wit, endpoint, subject) in [
23018            ("wasi:http/proxy", Some("/lookup"), None),
23019            ("nats:pub-sub", None, Some("orders.paid")),
23020            ("wasi:cli/environment", None, None),
23021        ] {
23022            let c = WitContract {
23023                de: "cart".into(),
23024                para: "downstream".into(),
23025                wit: wit.into(),
23026                endpoint: endpoint.map(str::to_string),
23027                subject: subject.map(str::to_string),
23028                slot: None,
23029            };
23030            assert!(
23031                c.slot().is_none(),
23032                "WitContract::slot must return None when the typed \
23033                 slot is absent under :wit {wit:?} (got {:?})",
23034                c.slot(),
23035            );
23036            assert_eq!(
23037                c.slot(),
23038                c.slot.as_deref(),
23039                "WitContract::slot must byte-equal the .slot field's \
23040                 `.as_deref()` projection in the absent arm",
23041            );
23042        }
23043    }
23044
23045    #[test]
23046    fn wit_contract_slot_borrows_from_slot_storage() {
23047        // The borrow-not-copy pin: [`WitContract::slot`] must return
23048        // an `Option<&str>` whose `Some` arm borrows from the typed
23049        // slot's own [`String`] storage — same-address invariant with
23050        // `c.slot.as_deref().unwrap()`. Pins against a future silent
23051        // detour that allocated a fresh `String`
23052        // (`self.slot.clone().map(...)` in the body would type-check
23053        // but silently drop the borrow, and every downstream consumer
23054        // that assumed the returned slice outlives `&self` would
23055        // break on a stale-reference use-after-free — the
23056        // [`WitContract::target`] Store-arm payload extraction rebinds
23057        // the returned `Option<&str>` through `.ok_or_else(...)` and
23058        // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
23059        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
23060        // [`ContratoIdentity`] dedup key threads the returned
23061        // `Option<&str>` into the six-tuple's store arm — each borrow
23062        // from the WitContract's own storage and each would silently
23063        // misbehave if this accessor produced a detached copy). Peer
23064        // of the sibling per-`:contratos` [`WitContract::endpoint`]
23065        // (7020470) / [`WitContract::subject`] (90de675)
23066        // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
23067        // shaped optional-scalar axis — third and final extension of
23068        // the `Option<&str>` borrow-not-copy discipline onto the
23069        // per-`:contratos` payload-carrier family, this time on the
23070        // store arm.
23071        let c = WitContract {
23072            de: "cart".into(),
23073            para: "kv".into(),
23074            wit: "wasi:keyvalue/store".into(),
23075            endpoint: None,
23076            subject: None,
23077            slot: Some("carts/{cart_id}".into()),
23078        };
23079        let slot = c.slot().expect("Some arm");
23080        let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
23081        assert_eq!(
23082            slot.as_ptr(),
23083            storage_slice.as_ptr(),
23084            "WitContract::slot must borrow from the .slot String's \
23085             backing storage — a fresh allocation here means the \
23086             accessor no longer names the substrate-primitive typed \
23087             dispatch and every downstream consumer would silently \
23088             carry a detached copy",
23089        );
23090        assert_eq!(
23091            slot.len(),
23092            storage_slice.len(),
23093            "WitContract::slot and .slot.as_deref() must byte-equal \
23094             in length as well as in address",
23095        );
23096    }
23097
23098    #[test]
23099    fn membro_nome_returns_caixa_byte_equal_across_permutations() {
23100        // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
23101        // [`Membro::nome`] must return the `:membros :caixa` field
23102        // byte-for-byte, borrowed from the typed slot's own [`String`]
23103        // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
23104        // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
23105        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
23106        // slot-atom scalar-value axes — same "the substrate-primitive
23107        // accessor must byte-equal the raw field access verbatim across
23108        // every author-declared value" discipline extended to the
23109        // per-`:membros` member-identity arm. Pins against a future
23110        // silent detour that re-normalized the member identity (an
23111        // accidental `.to_lowercase()` — every `:membros :caixa` is
23112        // validated as a DNS-1123 label upstream via
23113        // [`validate_membro_caixa`], so any re-normalization is
23114        // redundant + a drift surface between the validator and the
23115        // accessor), a namespace-prefix rewrite (an accidental
23116        // `format!("{namespace}/{caixa}")` per-CR fully-qualified
23117        // rewrite that didn't land on the peer axes), or a per-cluster
23118        // alias stamp the operator authors on one consumer without the
23119        // other. Four values sweep the accept-set the DNS-1123 gate
23120        // upstream admits (short single-word / dashed / v-suffixed
23121        // member names).
23122        for name in ["cart", "checkout", "catalog", "orders-v2"] {
23123            let m = Membro {
23124                caixa: name.into(),
23125                versao: "^0.1".into(),
23126            };
23127            assert_eq!(
23128                m.nome(),
23129                name,
23130                "Membro::nome must return :membros :caixa verbatim \
23131                 (got {:?}, expected {name:?})",
23132                m.nome(),
23133            );
23134            assert_eq!(
23135                m.nome(),
23136                m.caixa.as_str(),
23137                "Membro::nome must byte-equal the .caixa field access",
23138            );
23139        }
23140    }
23141
23142    #[test]
23143    fn membro_nome_borrows_from_caixa_storage() {
23144        // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
23145        // slice that borrows from the typed slot's own [`String`]
23146        // storage — same-address invariant with `m.caixa.as_str()`. Pins
23147        // against a future silent detour that allocated a fresh `String`
23148        // (`self.caixa.clone()` in the body would type-check but
23149        // silently drop the borrow, and every downstream consumer that
23150        // assumed the returned slice outlives `&self` would break on a
23151        // stale-reference use-after-free — the `HashSet<&str>` collector
23152        // at [`AplicacaoSpec::validate`]'s `names` seed, the
23153        // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
23154        // [`AplicacaoSpec::detect_sync_cycles`], the
23155        // [`crate::render::insert_first_seen`] dedup key at
23156        // [`AplicacaoSpec::validate_membros`] — each borrow from the
23157        // Membro's own storage and each would silently misbehave if
23158        // this accessor produced a detached copy). Peer of the sibling
23159        // per-`:contratos` [`WitContract::source`] /
23160        // [`WitContract::destination`] and per-`:entrada`
23161        // [`Entrada::destination`] borrow-invariant pins on the mesh-
23162        // slot-atom scalar-value axes.
23163        let m = Membro {
23164            caixa: "checkout".into(),
23165            versao: "^0.1".into(),
23166        };
23167        let name = m.nome();
23168        let caixa_slice = m.caixa.as_str();
23169        assert_eq!(
23170            name.as_ptr(),
23171            caixa_slice.as_ptr(),
23172            "Membro::nome must borrow from the .caixa String's backing \
23173             storage — a fresh allocation here means the accessor no \
23174             longer names the substrate-primitive typed dispatch and \
23175             every downstream consumer would silently carry a detached \
23176             copy",
23177        );
23178        assert_eq!(
23179            name.len(),
23180            caixa_slice.len(),
23181            "Membro::nome and .caixa.as_str() must byte-equal in length \
23182             as well as in address",
23183        );
23184    }
23185
23186    #[test]
23187    fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
23188        // The canonical per-`:membros` member-`:versao`-scalar pin:
23189        // [`Membro::versao_requirement`] must return the
23190        // `:membros :versao` field byte-for-byte, borrowed from the typed
23191        // slot's own [`String`] storage. Sibling of the peer
23192        // `membro_nome_returns_caixa_byte_equal_across_permutations`
23193        // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
23194        // — same "the substrate-primitive accessor must byte-equal the
23195        // raw field access verbatim across every author-declared value"
23196        // discipline extended to the per-`:membros` member-`:versao`
23197        // requirement-string arm. Pins against a future silent detour
23198        // that re-canonicalized the requirement (an accidental
23199        // `.to_string()` via [`parse_requirement`] → [`Display`] round-
23200        // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
23201        // drifted the printer output away from the source `caixa.lisp`,
23202        // an accidental whitespace trim on `"^ 0.1"` that no consumer
23203        // ever produced from the field-access side, an accidental
23204        // per-cluster lacre-projected concrete-version rewrite that
23205        // didn't land on the peer field-access sites). Five values sweep
23206        // the accept-set the shared
23207        // [`crate::render::require_valid_versao_requirement`] gate
23208        // admits (caret / tilde / exact / wildcard / bare-major).
23209        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
23210            let m = Membro {
23211                caixa: "cart".into(),
23212                versao: req.into(),
23213            };
23214            assert_eq!(
23215                m.versao_requirement(),
23216                req,
23217                "Membro::versao_requirement must return :membros :versao \
23218                 verbatim (got {:?}, expected {req:?})",
23219                m.versao_requirement(),
23220            );
23221            assert_eq!(
23222                m.versao_requirement(),
23223                m.versao.as_str(),
23224                "Membro::versao_requirement must byte-equal the .versao \
23225                 field access",
23226            );
23227        }
23228    }
23229
23230    #[test]
23231    fn membro_versao_requirement_borrows_from_versao_storage() {
23232        // The borrow-not-copy pin: [`Membro::versao_requirement`] must
23233        // return a `&str` slice that borrows from the typed slot's own
23234        // [`String`] storage — same-address invariant with
23235        // `m.versao.as_str()`. Pins against a future silent detour that
23236        // allocated a fresh `String` (`self.versao.clone()` in the body
23237        // would type-check but silently drop the borrow, and every
23238        // downstream consumer that assumed the returned slice outlives
23239        // `&self` would break on a stale-reference use-after-free). Peer
23240        // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
23241        // per-`:contratos` [`WitContract::source`] /
23242        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
23243        // [`Entrada::destination`] (6db982c) borrow-invariant pins on
23244        // the mesh-slot-atom scalar-value axes.
23245        let m = Membro {
23246            caixa: "checkout".into(),
23247            versao: "^0.1".into(),
23248        };
23249        let req = m.versao_requirement();
23250        let versao_slice = m.versao.as_str();
23251        assert_eq!(
23252            req.as_ptr(),
23253            versao_slice.as_ptr(),
23254            "Membro::versao_requirement must borrow from the .versao \
23255             String's backing storage — a fresh allocation here means \
23256             the accessor no longer names the substrate-primitive typed \
23257             dispatch and every downstream consumer would silently carry \
23258             a detached copy",
23259        );
23260        assert_eq!(
23261            req.len(),
23262            versao_slice.len(),
23263            "Membro::versao_requirement and .versao.as_str() must byte-\
23264             equal in length as well as in address",
23265        );
23266    }
23267
23268    #[test]
23269    fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
23270        // Sibling-pair invariant pin composing both per-`:membros`
23271        // substrate-primitive typed dispatches — [`Membro::nome`]
23272        // (4a32abf) and [`Membro::versao_requirement`] — at the joint
23273        // `(nome(), versao_requirement())` call shape every renderer
23274        // that fans on per-member identity + version pin keys off. The
23275        // invariant, evaluated per-member:
23276        //
23277        //   (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
23278        //
23279        // Closes the last unlifted per-`:membros` scalar axis — every
23280        // downstream consumer that reads the pair now routes through
23281        // exactly two typed dispatches on the substrate primitive, not
23282        // one typed + one open-coded field access. A future refactor
23283        // that silently split either accessor's projection (an
23284        // accidental `nome()` namespace-prefix rewrite that didn't
23285        // reach the peer, an accidental `versao_requirement()` lacre-
23286        // projected concrete-version rewrite that didn't land on the
23287        // `nome()` peer) surfaces at caixa-core build time. Peer of the
23288        // sibling per-`:entrada` `(hostname(), destination())` and
23289        // per-`:contratos` `(source(), destination())` pair invariants
23290        // on the mesh-slot-atom scalar-value axes.
23291        for (caixa, versao) in [
23292            ("cart", "^0.1"),
23293            ("checkout", "~0.1.2"),
23294            ("catalog", "0.1.0"),
23295            ("orders-v2", "*"),
23296        ] {
23297            let m = Membro {
23298                caixa: caixa.into(),
23299                versao: versao.into(),
23300            };
23301            assert_eq!(
23302                (m.nome(), m.versao_requirement()),
23303                (m.caixa.as_str(), m.versao.as_str()),
23304                "(Membro::nome, Membro::versao_requirement) must project \
23305                 (.caixa, .versao) verbatim across every author-declared \
23306                 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
23307                m.nome(),
23308                m.versao_requirement(),
23309            );
23310        }
23311    }
23312
23313    #[test]
23314    fn validate_membros_empty_gate_routes_through_nome_accessor() {
23315        // Composition pin: [`AplicacaoSpec::validate_membros`]'s
23316        // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
23317        // not the raw `.caixa` field access. Structurally: setting
23318        // ONLY the `.caixa` field to `""` on an otherwise-well-formed
23319        // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
23320        // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
23321        // (i.e. the empty string) — so the emptiness predicate the
23322        // refusal arm reaches under is the accessor-projected value,
23323        // not a peer field that would silently drift under a future
23324        // accessor-side rewrite.
23325        //
23326        // Pins against a future silent detour that (a) re-derived the
23327        // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
23328        // instead of `self.nome().is_empty()`, silently disagreeing with
23329        // every peer consumer (the `validate_membro_caixa(m.nome())`
23330        // call one line below, the dedup-key `insert_first_seen(&mut
23331        // seen, m.nome(), …)` two lines below, the emit-side per-
23332        // `programs[]` entry-`name:` at caixa-mesh/src/lib.rs:133),
23333        // (b) accessor-side introduced a per-tenant alias arm the
23334        // caller was unaware of, silently rewriting an author-declared
23335        // `:caixa "checkout"` to `""` — the raw-field-access gate
23336        // would fail-open while the accessor-routed peer consumers
23337        // would fail-closed, splitting the diagnostic from the actual
23338        // failure surface.
23339        //
23340        // Peer of the sibling
23341        // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
23342        // (c0110f1) composition pin — same "the shape-gate predicate
23343        // must route through the substrate-primitive typed dispatch"
23344        // discipline extended onto the per-`:membros` empty-`:caixa`
23345        // refusal-arm axis. Closes the last unlifted `.caixa` production-
23346        // code read site on `Membro` — after this converge every
23347        // caixa-core `.caixa` field access outside the accessor's own
23348        // body is either a test-side field-setter (in-module tests
23349        // constructing invalid-shape inputs) or a doc-comment reference.
23350        let mut s = three_member_spec();
23351        s.membros[1].caixa = String::new();
23352        assert!(
23353            s.membros[1].nome().is_empty(),
23354            "Membro::nome must byte-equal the .caixa field access — an \
23355             accessor-side detour that no longer projects the raw field \
23356             would silently split this drift-detection test from the \
23357             validate() refusal arm",
23358        );
23359        assert_eq!(
23360            s.membros[1].nome(),
23361            s.membros[1].caixa.as_str(),
23362            "Membro::nome and .caixa.as_str() must byte-equal on an \
23363             empty-`:caixa` entry — the emptiness gate keys off the \
23364             accessor by construction",
23365        );
23366        assert_eq!(
23367            s.validate().unwrap_err(),
23368            AplicacaoError::MembroCaixaEmpty,
23369            "validate_membros' emptiness gate must fire MembroCaixaEmpty \
23370             on an entry whose accessor-projected `nome()` is empty",
23371        );
23372    }
23373
23374    #[test]
23375    fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
23376        // The canonical per-`:placement` Akka-cluster-sharding
23377        // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
23378        // the `:placement :shard-key` field byte-for-byte, borrowed
23379        // from the typed slot's own `Option<String>` storage. Peer of
23380        // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
23381        // per-`:contratos` [`WitContract::source`] /
23382        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
23383        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
23384        // slot-atom scalar-value axes — same "the substrate-primitive
23385        // accessor must byte-equal the raw field access verbatim across
23386        // every author-declared value" discipline extended to the
23387        // per-`:placement` Akka-cluster-sharding key extractor arm.
23388        // Pins against a future silent detour that re-normalized the
23389        // key (an accidental `.to_lowercase()` — every non-empty
23390        // `:shard-key` is validated as a printable-ASCII single-token
23391        // reference upstream via [`validate_placement_shard_key`], so
23392        // any re-normalization is redundant + a drift surface between
23393        // the validator and the accessor), a per-cluster alias rewrite
23394        // the operator authors on one consumer without the other, or an
23395        // accidental variable-prefix strip (`$tenantId` → `tenantId`)
23396        // that didn't land on the peer field-access sites. Four values
23397        // sweep the accept-set the shape gate admits — bare identifier,
23398        // `$`-prefixed variable, dotted path, `${}`-quoted variable —
23399        // the four canonical Akka-style entity-id extractor shapes the
23400        // future M4 cluster-sharding reconciler hashes.
23401        for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
23402            let p = Placement {
23403                estrategia: PlacementStrategy::Sharded,
23404                clusters: vec!["rio".into()],
23405                affinity: None,
23406                shard_key: Some(key.into()),
23407            };
23408            assert_eq!(
23409                p.shard_key(),
23410                Some(key),
23411                "Placement::shard_key must return :placement :shard-key \
23412                 verbatim (got {:?}, expected Some({key:?}))",
23413                p.shard_key(),
23414            );
23415            assert_eq!(
23416                p.shard_key(),
23417                p.shard_key.as_deref(),
23418                "Placement::shard_key must byte-equal the .shard_key \
23419                 field's `.as_deref()` projection",
23420            );
23421        }
23422    }
23423
23424    #[test]
23425    fn placement_shard_key_none_when_field_is_none() {
23426        // The absent-`:shard-key` arm of the per-`:placement`
23427        // Akka-cluster-sharding accessor pin: when the typed slot is
23428        // absent — the canonical shape under `:estrategia Replicated` /
23429        // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
23430        // enforced `shard_key.is_some() == matches!(estrategia,
23431        // Sharded)` partition — [`Placement::shard_key`] must return
23432        // `None`. Pins against a future silent detour that projected
23433        // the absent slot to a `Some("")` empty-string default (the
23434        // canonical `Option<String>` → `String` collapse footgun the
23435        // sibling M2 [`crate::LimitsSpec::is_empty`] /
23436        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
23437        // already guard on the peer M2 typed-slot surfaces), a
23438        // `Some("None")` stringified-None round-trip, or a `Some` arm
23439        // whose contents were derived from a sibling slot (an
23440        // accidental fallback to `estrategia.as_str()` that read the
23441        // strategy discriminator into the key axis). Two placements
23442        // sweep the accept-set every `validate`-passing non-`Sharded`
23443        // shape lands on — `Replicated` (Erlang/OTP distributed-app
23444        // takeover) and `SingleNode` (single-node hosting).
23445        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
23446            let p = Placement {
23447                estrategia,
23448                clusters: vec!["rio".into()],
23449                affinity: None,
23450                shard_key: None,
23451            };
23452            assert!(
23453                p.shard_key().is_none(),
23454                "Placement::shard_key must return None when the typed \
23455                 slot is absent under :estrategia {estrategia:?} (got {:?})",
23456                p.shard_key(),
23457            );
23458            assert_eq!(
23459                p.shard_key(),
23460                p.shard_key.as_deref(),
23461                "Placement::shard_key must byte-equal the .shard_key \
23462                 field's `.as_deref()` projection in the absent arm",
23463            );
23464        }
23465    }
23466
23467    #[test]
23468    fn placement_shard_key_borrows_from_shard_key_storage() {
23469        // The borrow-not-copy pin: [`Placement::shard_key`] must return
23470        // an `Option<&str>` whose `Some` arm borrows from the typed
23471        // slot's own [`String`] storage — same-address invariant with
23472        // `p.shard_key.as_deref().unwrap()`. Pins against a future
23473        // silent detour that allocated a fresh `String`
23474        // (`self.shard_key.clone().map(...)` in the body would type-
23475        // check but silently drop the borrow, and every downstream
23476        // consumer that assumed the returned slice outlives `&self`
23477        // would break on a stale-reference use-after-free — the
23478        // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
23479        // gate's `Some(k)`-bound match arm reads `k: &str` under the
23480        // accessor's return type and would silently misbehave if this
23481        // accessor produced a detached copy). Peer of the sibling
23482        // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
23483        // [`WitContract::source`] / [`WitContract::destination`]
23484        // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
23485        // (6db982c) borrow-invariant pins on the mesh-slot-atom
23486        // scalar-value axes — first extension of the discipline onto
23487        // an `Option<String>`-shaped optional-scalar axis.
23488        let p = Placement {
23489            estrategia: PlacementStrategy::Sharded,
23490            clusters: vec!["rio".into()],
23491            affinity: None,
23492            shard_key: Some("tenantId".into()),
23493        };
23494        let key = p.shard_key().expect("Some arm");
23495        let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
23496        assert_eq!(
23497            key.as_ptr(),
23498            storage_slice.as_ptr(),
23499            "Placement::shard_key must borrow from the .shard_key \
23500             String's backing storage — a fresh allocation here means \
23501             the accessor no longer names the substrate-primitive typed \
23502             dispatch and every downstream consumer would silently \
23503             carry a detached copy",
23504        );
23505        assert_eq!(
23506            key.len(),
23507            storage_slice.len(),
23508            "Placement::shard_key and .shard_key.as_deref() must byte-\
23509             equal in length as well as in address",
23510        );
23511    }
23512
23513    #[test]
23514    fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
23515        // The canonical per-`:placement` M3-Adaptive-compression-hint
23516        // scalar pin: [`Placement::affinity`] must return the
23517        // `:placement :affinity` field byte-for-byte, borrowed from the
23518        // typed slot's own `Option<String>` storage. Peer of the sibling
23519        // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
23520        // pin on the sibling `Option<&str>` optional-scalar axis — same
23521        // "the substrate-primitive accessor must byte-equal the raw
23522        // field access verbatim across every author-declared value"
23523        // discipline extended to the peer per-`:placement` M3-Adaptive-
23524        // compression-hint arm. Pins against a future silent detour
23525        // that re-normalized the hint (an accidental `.to_lowercase()`
23526        // — every `:affinity` is already validated as a DNS-1123 label
23527        // upstream via [`validate_placement_affinity`], so any re-
23528        // normalization is redundant + a drift surface between the
23529        // validator and the accessor), a per-cluster alias rewrite the
23530        // operator authors on one consumer without the other, or an
23531        // accidental hint-family collapse (`low-latency` → `latency`
23532        // that dropped the qualifier prefix). Four values sweep the
23533        // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
23534        // canonical adaptive-compression-weight biases the future M4
23535        // placement engine reads.
23536        for hint in [
23537            "data-locality",
23538            "low-latency",
23539            "high-throughput",
23540            "cost-optimized",
23541        ] {
23542            let p = Placement {
23543                estrategia: PlacementStrategy::Replicated,
23544                clusters: vec!["rio".into()],
23545                affinity: Some(hint.into()),
23546                shard_key: None,
23547            };
23548            assert_eq!(
23549                p.affinity(),
23550                Some(hint),
23551                "Placement::affinity must return :placement :affinity \
23552                 verbatim (got {:?}, expected Some({hint:?}))",
23553                p.affinity(),
23554            );
23555            assert_eq!(
23556                p.affinity(),
23557                p.affinity.as_deref(),
23558                "Placement::affinity must byte-equal the .affinity \
23559                 field's `.as_deref()` projection",
23560            );
23561        }
23562    }
23563
23564    #[test]
23565    fn placement_affinity_none_when_field_is_none() {
23566        // The absent-`:affinity` arm of the per-`:placement`
23567        // M3-Adaptive-compression-hint accessor pin: when the typed
23568        // slot is absent — the canonical shape of an Aplicacao that
23569        // leaves the compression weighting up to the placement engine's
23570        // cluster-default arm — [`Placement::affinity`] must return
23571        // `None`. Pins against a future silent detour that projected
23572        // the absent slot to a `Some("")` empty-string default (the
23573        // canonical `Option<String>` → `String` collapse footgun the
23574        // sibling M2 [`crate::LimitsSpec::is_empty`] /
23575        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
23576        // already guard on the peer M2 typed-slot surfaces), a
23577        // `Some("None")` stringified-None round-trip, a `Some` arm
23578        // whose contents were derived from a sibling slot (an
23579        // accidental fallback to `estrategia.as_str()` that read the
23580        // strategy discriminator into the hint axis), or a
23581        // `Some("default")` implicit-default that would silently biases
23582        // the routing without the author having written one. Three
23583        // placements sweep the accept-set every `validate`-passing
23584        // `:affinity None` shape lands on — one per PlacementStrategy
23585        // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
23586        // with a shard-key), since `:affinity` is orthogonal to
23587        // `:estrategia` in the typed grammar.
23588        for (estrategia, shard_key) in [
23589            (PlacementStrategy::SingleNode, None),
23590            (PlacementStrategy::Replicated, None),
23591            (PlacementStrategy::Sharded, Some("tenantId".to_string())),
23592        ] {
23593            let p = Placement {
23594                estrategia,
23595                clusters: vec!["rio".into()],
23596                affinity: None,
23597                shard_key,
23598            };
23599            assert!(
23600                p.affinity().is_none(),
23601                "Placement::affinity must return None when the typed \
23602                 slot is absent under :estrategia {estrategia:?} (got {:?})",
23603                p.affinity(),
23604            );
23605            assert_eq!(
23606                p.affinity(),
23607                p.affinity.as_deref(),
23608                "Placement::affinity must byte-equal the .affinity \
23609                 field's `.as_deref()` projection in the absent arm",
23610            );
23611        }
23612    }
23613
23614    #[test]
23615    fn placement_affinity_borrows_from_affinity_storage() {
23616        // The borrow-not-copy pin: [`Placement::affinity`] must return
23617        // an `Option<&str>` whose `Some` arm borrows from the typed
23618        // slot's own [`String`] storage — same-address invariant with
23619        // `p.affinity.as_deref().unwrap()`. Pins against a future
23620        // silent detour that allocated a fresh `String`
23621        // (`self.affinity.clone().map(...)` in the body would type-
23622        // check but silently drop the borrow, and every downstream
23623        // consumer that assumed the returned slice outlives `&self`
23624        // would break on a stale-reference use-after-free — the
23625        // [`AplicacaoSpec::validate_placement`] per-hint value-shape
23626        // gate reads the accessor's `&str` return through the
23627        // [`validate_placement_affinity`] `&str` parameter and would
23628        // silently misbehave if this accessor produced a detached
23629        // copy). Peer of the sibling per-`:placement`
23630        // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
23631        // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
23632        // extends the discipline onto the sibling per-`:placement`
23633        // M3-Adaptive-compression-hint arm.
23634        let p = Placement {
23635            estrategia: PlacementStrategy::Replicated,
23636            clusters: vec!["rio".into()],
23637            affinity: Some("data-locality".into()),
23638            shard_key: None,
23639        };
23640        let hint = p.affinity().expect("Some arm");
23641        let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
23642        assert_eq!(
23643            hint.as_ptr(),
23644            storage_slice.as_ptr(),
23645            "Placement::affinity must borrow from the .affinity \
23646             String's backing storage — a fresh allocation here means \
23647             the accessor no longer names the substrate-primitive typed \
23648             dispatch and every downstream consumer would silently \
23649             carry a detached copy",
23650        );
23651        assert_eq!(
23652            hint.len(),
23653            storage_slice.len(),
23654            "Placement::affinity and .affinity.as_deref() must byte-\
23655             equal in length as well as in address",
23656        );
23657    }
23658
23659    #[test]
23660    fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
23661        // The canonical per-`:placement` distribution-strategy-scalar
23662        // pin: [`Placement::estrategia`] must return the `:placement
23663        // :estrategia` field verbatim as a [`PlacementStrategy`],
23664        // `Copy`-projected from the typed slot's own `PlacementStrategy`
23665        // storage across every variant in the closed accept-set
23666        // (`SingleNode` — Erlang/OTP distributed-app takeover;
23667        // `Replicated` — active-active across every named cluster;
23668        // `Sharded` — Akka-style hash-keyed entity distribution). Pins
23669        // against a future silent detour that re-derived the strategy
23670        // from a peer axis (an accidental fallback to
23671        // `if shard_key.is_some() { Sharded } else { Replicated }`
23672        // collapse that read the shard-key axis into the strategy
23673        // discriminator), a variant remap the operator authors on one
23674        // consumer without the other, or a stale-derive detour that
23675        // substituted [`PlacementStrategy::default`] when the field
23676        // held any explicit variant (which would silently collapse the
23677        // distinction between "author explicitly declared `:estrategia
23678        // Replicated`" and "author omitted the slot and inherited the
23679        // default" the future per-cluster override slot depends on).
23680        // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
23681        // pin on the `Copy`-return `u16` scalar axis — same "the
23682        // substrate-primitive accessor must byte-equal the raw field
23683        // access verbatim across every author-declared value" discipline
23684        // extended onto the per-`:placement` distribution-strategy
23685        // `Copy`-composite-enum scalar axis.
23686        for estrategia in [
23687            PlacementStrategy::SingleNode,
23688            PlacementStrategy::Replicated,
23689            PlacementStrategy::Sharded,
23690        ] {
23691            // Route the paired `:shard-key` fixture-builder through the
23692            // typed cross-slot invariant predicate
23693            // [`PlacementStrategy::requires_shard_key`] rather than the
23694            // [`gen_platform::IsVariant`]-derived [`PlacementStrategy::is_sharded`]
23695            // arm-identity predicate — same discipline the sibling
23696            // `placement_strategy_variants_round_trip` fixture builder now
23697            // reads through.
23698            let shard_key = estrategia
23699                .requires_shard_key()
23700                .then(|| "tenantId".to_string());
23701            let p = Placement {
23702                estrategia,
23703                clusters: vec!["rio".into()],
23704                affinity: None,
23705                shard_key,
23706            };
23707            assert_eq!(
23708                p.estrategia(),
23709                estrategia,
23710                "Placement::estrategia must return :placement :estrategia \
23711                 verbatim (got {:?}, expected {estrategia:?})",
23712                p.estrategia(),
23713            );
23714            assert_eq!(
23715                p.estrategia(),
23716                p.estrategia,
23717                "Placement::estrategia accessor and .estrategia field \
23718                 access must byte-equal — the accessor is the substrate-\
23719                 primitive typed dispatch every downstream distribution-\
23720                 strategy consumer must route through",
23721            );
23722        }
23723    }
23724
23725    #[test]
23726    fn validate_placement_reads_through_lifted_estrategia_accessor() {
23727        // Three-consumer coherence pin: the
23728        // [`AplicacaoSpec::validate_placement`]
23729        // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
23730        // `estrategia:` field (which reads through
23731        // [`Placement::estrategia`] to name the strategy the empty
23732        // `:clusters` list was declared against), the same method's
23733        // `Sharded ↔ non-Sharded` `match` partition dispatch (which
23734        // reads through [`Placement::estrategia`] to fan across the
23735        // shape-gate cascades), and the non-`Sharded`-arm
23736        // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
23737        // `estrategia:` field (which reads through
23738        // [`Placement::estrategia`] to name the strategy the declared-
23739        // but-inert `:shard-key` was authored under) must all key off
23740        // the lifted accessor, so any future rebrand on the typed
23741        // slot's reader shape lands at exactly one place. Pins the
23742        // three-site coherence by exercising each error surface end-
23743        // to-end and asserting the surfaced `estrategia:` field byte-
23744        // equals the accessor's return. Peer of the sibling per-
23745        // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
23746        // pin on the M3 mesh-slot `Copy`-return scalar axis.
23747
23748        // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
23749        // whose `estrategia:` field must byte-equal the accessor's return
23750        // for every variant in the closed accept-set.
23751        for estrategia in [
23752            PlacementStrategy::SingleNode,
23753            PlacementStrategy::Replicated,
23754            PlacementStrategy::Sharded,
23755        ] {
23756            let mut spec = three_member_spec();
23757            spec.placement.estrategia = estrategia;
23758            spec.placement.clusters = Vec::new();
23759            // Route the paired `:shard-key` spec-mutator through the typed
23760            // cross-slot invariant predicate
23761            // [`PlacementStrategy::requires_shard_key`] rather than the
23762            // [`gen_platform::IsVariant`]-derived
23763            // [`PlacementStrategy::is_sharded`] arm-identity predicate —
23764            // same discipline the sibling
23765            // `placement_strategy_variants_round_trip` and
23766            // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
23767            // fixture builders now read through.
23768            spec.placement.shard_key = estrategia
23769                .requires_shard_key()
23770                .then(|| "tenantId".to_string());
23771            let err = spec.validate().unwrap_err();
23772            match err {
23773                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
23774                    assert_eq!(
23775                        e,
23776                        spec.placement.estrategia(),
23777                        "PlacementWithoutClusters.estrategia must byte-equal \
23778                         Placement::estrategia() — the error carrier reads \
23779                         through the lifted accessor",
23780                    );
23781                }
23782                other => panic!(
23783                    "expected PlacementWithoutClusters, got {other:?} for \
23784                     estrategia={estrategia:?}"
23785                ),
23786            }
23787        }
23788
23789        // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
23790        // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
23791        // must byte-equal the accessor's return for both non-`Sharded`
23792        // strategies.
23793        for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
23794            let mut spec = three_member_spec();
23795            spec.placement.estrategia = estrategia;
23796            spec.placement.shard_key = Some("tenantId".into());
23797            let err = spec.validate().unwrap_err();
23798            match err {
23799                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
23800                    assert_eq!(
23801                        e,
23802                        spec.placement.estrategia(),
23803                        "ShardKeyOnNonSharded.estrategia must byte-equal \
23804                         Placement::estrategia() — the non-Sharded-arm \
23805                         refusal reads through the lifted accessor",
23806                    );
23807                }
23808                other => panic!(
23809                    "expected ShardKeyOnNonSharded, got {other:?} for \
23810                     estrategia={estrategia:?}"
23811                ),
23812            }
23813        }
23814    }
23815
23816    // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
23817    //
23818    // The [`Placement::clusters`] accessor lift is the second slice-return
23819    // (`&[T]`) accessor on any typed slot — sibling to the seed M2
23820    // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
23821    // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
23822    // below cover (1) the accessor's byte-equal projection against the raw
23823    // field access across the empty / singleton / cohort fixtures the
23824    // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
23825    // and the per-cluster validate loop fan between, and (2) the two-
23826    // consumer coherence of the paired pre-flight refusal probe and the
23827    // per-cluster validate loop routing through the accessor on both arms.
23828
23829    #[test]
23830    fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
23831        // The canonical per-`:placement` cluster-pool-scalar-shape pin:
23832        // [`Placement::clusters`] must return the `:placement :clusters`
23833        // typed `Vec<String>` verbatim as a `&[String]` slice-view over
23834        // the same backing buffer the raw `self.clusters.as_slice()`
23835        // field access borrows from, byte-equal across every
23836        // representative fixture in the accept-set — the empty slice
23837        // (the pre-validation sentinel every
23838        // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
23839        // the singleton slice (the minimal `SingleNode`-shape cohort),
23840        // and multi-entry cohorts (the peer `Replicated` / `Sharded`
23841        // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
23842        //
23843        // Pins against a future silent detour that returned
23844        // `&Vec<String>` (which would type-check but leak the storage-
23845        // side `Vec`'s grow/push/reserve surface no consumer of the
23846        // typed view reaches for), a fresh-allocated `Vec<String>` copy
23847        // (which would type-check via a coercion but silently break
23848        // every downstream caller that relied on the slice sharing the
23849        // backing buffer's identity), or an out-of-order or length-
23850        // drifted projection (which would silently split the paired
23851        // pre-flight `.is_empty()` refusal probe's input from the per-
23852        // cluster validate loop's traversal input).
23853        //
23854        // Peer of the sibling M2
23855        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
23856        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
23857        // `:supervisor` static-child-list axis, extended onto the M3
23858        // per-`:placement` distribution-target-list `Vec`-carry axis.
23859        let fixtures: Vec<Vec<String>> = vec![
23860            Vec::new(),
23861            vec!["rio".into()],
23862            vec!["rio".into(), "mar".into()],
23863            vec!["rio".into(), "mar".into(), "plo".into()],
23864        ];
23865        for clusters in fixtures {
23866            let p = Placement {
23867                clusters: clusters.clone(),
23868                ..Placement::default()
23869            };
23870            assert_eq!(
23871                p.clusters(),
23872                clusters.as_slice(),
23873                "Placement::clusters must return :placement :clusters \
23874                 verbatim (got {:?}, expected {:?})",
23875                p.clusters(),
23876                clusters.as_slice(),
23877            );
23878            assert_eq!(
23879                p.clusters(),
23880                p.clusters.as_slice(),
23881                "Placement::clusters accessor and .clusters.as_slice() \
23882                 field access must byte-equal — the accessor is the \
23883                 substrate-primitive typed dispatch every downstream \
23884                 cluster-pool consumer must route through",
23885            );
23886            assert_eq!(
23887                p.clusters().len(),
23888                p.clusters.len(),
23889                "Placement::clusters().len() must byte-equal \
23890                 self.clusters.len() — a length-drift would silently \
23891                 split the paired pre-flight `.is_empty()` refusal \
23892                 probe input from the per-cluster validate loop's \
23893                 traversal input",
23894            );
23895        }
23896    }
23897
23898    #[test]
23899    fn validate_placement_reads_through_lifted_clusters_accessor() {
23900        // Two-consumer coherence pin: the
23901        // [`AplicacaoSpec::validate_placement`] pre-flight
23902        // `self.placement.clusters().is_empty()` refusal probe (which
23903        // must trip [`AplicacaoError::PlacementWithoutClusters`] when
23904        // the accessor projects the empty slice) and the per-cluster
23905        // validate loop's `for c in self.placement.clusters()`
23906        // traversal (which must reach every entry in the same order
23907        // the accessor projects, so both the per-entry value-shape
23908        // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
23909        // and the duplicate-detection HashSet insert that trips
23910        // [`AplicacaoError::PlacementClusterDuplicate`] key off the
23911        // accessor's projection) must both key off the lifted
23912        // accessor, so any future rebrand on the typed slot's reader
23913        // shape lands at exactly one place. Pins the two-site
23914        // coherence by exercising each production consumer end-to-end:
23915        // (1) the `PlacementWithoutClusters` refusal under the empty
23916        // slice, (2) the `PlacementClusterInvalid` refusal fires on
23917        // the second entry of a two-cluster cohort whose head is
23918        // valid but tail is not (which requires the loop to reach the
23919        // second entry through the accessor), and (3) the
23920        // `PlacementClusterDuplicate` refusal fires on the second
23921        // entry of a two-cluster cohort that shares a name (which
23922        // requires the loop to reach both entries — a first-entry-only
23923        // projection would silently pass since the dedup HashSet has
23924        // room for the first insert).
23925        //
23926        // Peer of the sibling M2
23927        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
23928        // (bc92bce) coherence pin on the per-`:supervisor` static-
23929        // child-list axis, extended onto the M3 per-`:placement`
23930        // distribution-target-list `Vec`-carry axis.
23931
23932        // (1) Pre-flight `.is_empty()` probe: the empty slice must
23933        // trip `PlacementWithoutClusters`.
23934        let mut spec = three_member_spec();
23935        spec.placement.clusters = Vec::new();
23936        match spec.validate().unwrap_err() {
23937            AplicacaoError::PlacementWithoutClusters { .. } => {}
23938            other => panic!("expected PlacementWithoutClusters, got {other:?}"),
23939        }
23940        assert!(
23941            spec.placement.clusters().is_empty(),
23942            "the pre-flight refusal input must be the empty slice per \
23943             the accessor's projection",
23944        );
23945
23946        // (2) Per-cluster validate loop: a two-cluster cohort with an
23947        // invalid tail entry must trip `PlacementClusterInvalid` on
23948        // the tail — the loop must reach the second entry through
23949        // the accessor.
23950        let mut spec = three_member_spec();
23951        spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
23952        match spec.validate().unwrap_err() {
23953            AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
23954                assert_eq!(
23955                    cluster, "BAD_CLUSTER",
23956                    "PlacementClusterInvalid.cluster must carry the \
23957                     tail entry the loop reached through the accessor",
23958                );
23959            }
23960            other => panic!("expected PlacementClusterInvalid, got {other:?}"),
23961        }
23962        assert_eq!(
23963            spec.placement.clusters().len(),
23964            2,
23965            "the per-cluster validate loop's traversal input must be \
23966             a two-element slice per the accessor's projection",
23967        );
23968
23969        // (3) Per-cluster validate loop: a two-cluster cohort that
23970        // shares a name must trip `PlacementClusterDuplicate` on the
23971        // second entry — the loop must reach both entries through the
23972        // accessor for the dedup HashSet's second insert to collide.
23973        let mut spec = three_member_spec();
23974        spec.placement.clusters = vec!["rio".into(), "rio".into()];
23975        match spec.validate().unwrap_err() {
23976            AplicacaoError::PlacementClusterDuplicate { cluster } => {
23977                assert_eq!(
23978                    cluster, "rio",
23979                    "PlacementClusterDuplicate.cluster must carry the \
23980                     shared cluster name verbatim",
23981                );
23982            }
23983            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
23984        }
23985        assert_eq!(
23986            spec.placement.clusters().len(),
23987            2,
23988            "the per-cluster validate loop's traversal input must be \
23989             a two-element slice per the accessor's projection",
23990        );
23991    }
23992
23993    #[test]
23994    fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
23995        // The canonical per-`:membros` member-list-slice-shape pin:
23996        // [`AplicacaoSpec::membros`] must return the `:membros` typed
23997        // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
23998        // same backing buffer the raw `self.membros.as_slice()` field
23999        // access borrows from, byte-equal across every representative
24000        // fixture in the accept-set — the empty slice (the pre-
24001        // validation sentinel every [`AplicacaoError::NoMembros`]
24002        // refusal keys off), the singleton slice (the minimal one-
24003        // Servico Aplicacao shape), and multi-entry cohorts (the peer
24004        // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
24005        // load-bearing identity of the application graph).
24006        //
24007        // Pins against a future silent detour that returned
24008        // `&Vec<Membro>` (which would type-check but leak the storage-
24009        // side `Vec`'s grow/push/reserve surface no consumer of the
24010        // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
24011        // (which would type-check via a coercion but silently break
24012        // every downstream caller that relied on the slice sharing the
24013        // backing buffer's identity), or an out-of-order or length-
24014        // drifted projection (which would silently split the paired
24015        // `HashSet<&str>` name-set seed's collect input from the
24016        // pre-flight `.is_empty()` refusal probe's input from the per-
24017        // member validate loop's traversal input from the
24018        // programs.yaml emitter's per-entry fan-out loop's input from
24019        // the `feira app graph` per-member print traversal's input).
24020        //
24021        // Peer of the sibling M2
24022        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
24023        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
24024        // `:supervisor` static-child-list axis and the sibling M3
24025        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
24026        // (a6e18d7) `&[String]` byte-equal pin on the per-
24027        // `:placement` distribution-target-list axis — extends the
24028        // slice-return-accessor byte-equal-projection discipline onto
24029        // the outermost M3 mesh-slot type's per-Aplicacao member-list
24030        // `Vec`-carry axis.
24031        let fixtures: Vec<Vec<Membro>> = vec![
24032            Vec::new(),
24033            vec![membro("catalog", "^0.1")],
24034            vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
24035            vec![
24036                membro("catalog", "^0.1"),
24037                membro("cart", "^0.1"),
24038                membro("payment", "^0.2"),
24039            ],
24040        ];
24041        for membros in fixtures {
24042            let s = AplicacaoSpec {
24043                membros: membros.clone(),
24044                contratos: Vec::new(),
24045                politicas: MeshPolicy::default(),
24046                placement: Placement::default(),
24047                entrada: None,
24048            };
24049            assert_eq!(
24050                s.membros(),
24051                membros.as_slice(),
24052                "AplicacaoSpec::membros must return :membros verbatim \
24053                 (got {:?}, expected {:?})",
24054                s.membros(),
24055                membros.as_slice(),
24056            );
24057            assert_eq!(
24058                s.membros(),
24059                s.membros.as_slice(),
24060                "AplicacaoSpec::membros accessor and .membros.as_slice() \
24061                 field access must byte-equal — the accessor is the \
24062                 substrate-primitive typed dispatch every downstream \
24063                 member-list consumer must route through",
24064            );
24065            assert_eq!(
24066                s.membros().len(),
24067                s.membros.len(),
24068                "AplicacaoSpec::membros().len() must byte-equal \
24069                 self.membros.len() — a length-drift would silently \
24070                 split the paired `HashSet<&str>` name-set seed's \
24071                 collect input from the pre-flight `.is_empty()` \
24072                 refusal probe input from the per-member validate \
24073                 loop's traversal input",
24074            );
24075        }
24076    }
24077
24078    #[test]
24079    fn validate_reads_through_lifted_membros_accessor() {
24080        // Three-consumer coherence pin: the
24081        // [`AplicacaoSpec::validate_membros`] pre-flight
24082        // `self.membros().is_empty()` refusal probe (which must trip
24083        // [`AplicacaoError::NoMembros`] when the accessor projects the
24084        // empty slice), the same method's per-member validate loop's
24085        // `for m in self.membros()` traversal (which must reach every
24086        // entry in the same order the accessor projects, so both the
24087        // per-entry empty-`:caixa` gate that trips
24088        // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
24089        // detection `insert_first_seen` that trips
24090        // [`AplicacaoError::MembroDuplicate`] key off the accessor's
24091        // projection), and the peer [`AplicacaoSpec::validate`]'s
24092        // `HashSet<&str>` name-set seed's
24093        // `self.membros().iter().map(Membro::nome).collect()` collect
24094        // input (which every `:contratos` `:de` / `:para` membership
24095        // lookup rejects an unknown name against) must all three key
24096        // off the lifted accessor, so any future rebrand on the typed
24097        // slot's reader shape lands at exactly one place. Pins the
24098        // three-site coherence by exercising each production consumer
24099        // end-to-end: (1) the `NoMembros` refusal under the empty
24100        // slice, (2) the `MembroCaixaEmpty` refusal fires on the
24101        // second entry of a two-member cohort whose head is valid but
24102        // tail has an empty `:caixa` (which requires the loop to
24103        // reach the second entry through the accessor), and (3) the
24104        // `MembroDuplicate` refusal fires on the second entry of a
24105        // two-member cohort that shares a `:caixa` name (which
24106        // requires the loop to reach both entries through the
24107        // accessor for the dedup HashSet's second insert to collide).
24108        //
24109        // Peer of the sibling M2
24110        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
24111        // (bc92bce) coherence pin on the per-`:supervisor` static-
24112        // child-list axis and the sibling M3
24113        // `validate_placement_reads_through_lifted_clusters_accessor`
24114        // (a6e18d7) coherence pin on the per-`:placement` distribution-
24115        // target-list axis — extends the slice-return-accessor
24116        // multi-consumer coherence discipline onto the outermost M3
24117        // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
24118
24119        // (1) Pre-flight `.is_empty()` probe: the empty slice must
24120        // trip `NoMembros`.
24121        let mut spec = three_member_spec();
24122        spec.membros = Vec::new();
24123        assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
24124        assert!(
24125            spec.membros().is_empty(),
24126            "the pre-flight refusal input must be the empty slice per \
24127             the accessor's projection",
24128        );
24129
24130        // (2) Per-member validate loop: a two-member cohort with an
24131        // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
24132        // the tail — the loop must reach the second entry through
24133        // the accessor.
24134        let mut spec = three_member_spec();
24135        spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
24136        assert_eq!(
24137            spec.validate().unwrap_err(),
24138            AplicacaoError::MembroCaixaEmpty,
24139        );
24140        assert_eq!(
24141            spec.membros().len(),
24142            2,
24143            "the per-member validate loop's traversal input must be \
24144             a two-element slice per the accessor's projection",
24145        );
24146
24147        // (3) Per-member validate loop: a two-member cohort that
24148        // shares a `:caixa` name must trip `MembroDuplicate` on the
24149        // second entry — the loop must reach both entries through the
24150        // accessor for the dedup HashSet's second insert to collide.
24151        let mut spec = three_member_spec();
24152        spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
24153        match spec.validate().unwrap_err() {
24154            AplicacaoError::MembroDuplicate { caixa } => {
24155                assert_eq!(
24156                    caixa, "catalog",
24157                    "MembroDuplicate.caixa must carry the shared \
24158                     member name verbatim",
24159                );
24160            }
24161            other => panic!("expected MembroDuplicate, got {other:?}"),
24162        }
24163        assert_eq!(
24164            spec.membros().len(),
24165            2,
24166            "the per-member validate loop's traversal input must be \
24167             a two-element slice per the accessor's projection",
24168        );
24169    }
24170
24171    #[test]
24172    fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
24173        // The canonical per-`:contratos` contract-list-slice-shape pin:
24174        // [`AplicacaoSpec::contratos`] must return the `:contratos`
24175        // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
24176        // slice-view over the same backing buffer the raw
24177        // `self.contratos.as_slice()` field access borrows from, byte-
24178        // equal across every representative fixture in the accept-set —
24179        // the empty slice (the pre-validation "internal-only mesh" shape
24180        // an Aplicacao whose members exchange no typed edges renders
24181        // through), the singleton slice (the minimal one-edge Aplicacao
24182        // shape), and multi-entry cohorts (the peer multi-edge shapes
24183        // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
24184        // of the application graph).
24185        //
24186        // Pins against a future silent detour that returned
24187        // `&Vec<WitContract>` (which would type-check but leak the
24188        // storage-side `Vec`'s grow/push/reserve surface no consumer of
24189        // the typed view reaches for), a fresh-allocated
24190        // `Vec<WitContract>` copy (which would type-check via a coercion
24191        // but silently break every downstream caller that relied on the
24192        // slice sharing the backing buffer's identity), or an out-of-
24193        // order or length-drifted projection (which would silently split
24194        // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
24195        // seed's traversal input from the `detect_sync_cycles` per-edge
24196        // adjacency-list seed's traversal input from the
24197        // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
24198        // BTreeMap grouping loop's traversal input from the
24199        // `feira app graph` per-contract print traversal's input).
24200        //
24201        // Peer of the immediately-adjacent sibling M3
24202        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
24203        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
24204        // node-list axis, the sibling M3
24205        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
24206        // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
24207        // distribution-target-list axis, and the sibling M2
24208        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
24209        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
24210        // `:supervisor` static-child-list axis — extends the slice-
24211        // return-accessor byte-equal-projection discipline onto the
24212        // outermost M3 mesh-slot type's per-Aplicacao contract-list
24213        // `Vec`-carry axis, closing the last unlifted per-
24214        // `AplicacaoSpec` `Vec`-carry axis.
24215        let fixtures: Vec<Vec<WitContract>> = vec![
24216            Vec::new(),
24217            vec![contract_http("cart", "catalog", "/products/:id")],
24218            vec![
24219                contract_http("cart", "catalog", "/products/:id"),
24220                contract_http("cart", "payment", "/charge"),
24221            ],
24222            vec![
24223                contract_http("cart", "catalog", "/products/:id"),
24224                contract_http("cart", "payment", "/charge"),
24225                contract_http("payment", "catalog", "/audit"),
24226            ],
24227        ];
24228        for contratos in fixtures {
24229            let s = AplicacaoSpec {
24230                membros: vec![
24231                    membro("catalog", "^0.1"),
24232                    membro("cart", "^0.1"),
24233                    membro("payment", "^0.2"),
24234                ],
24235                contratos: contratos.clone(),
24236                politicas: MeshPolicy::default(),
24237                placement: Placement::default(),
24238                entrada: None,
24239            };
24240            assert_eq!(
24241                s.contratos(),
24242                contratos.as_slice(),
24243                "AplicacaoSpec::contratos must return :contratos verbatim \
24244                 (got {:?}, expected {:?})",
24245                s.contratos(),
24246                contratos.as_slice(),
24247            );
24248            assert_eq!(
24249                s.contratos(),
24250                s.contratos.as_slice(),
24251                "AplicacaoSpec::contratos accessor and \
24252                 .contratos.as_slice() field access must byte-equal — \
24253                 the accessor is the substrate-primitive typed dispatch \
24254                 every downstream contract-list consumer must route \
24255                 through",
24256            );
24257            assert_eq!(
24258                s.contratos().len(),
24259                s.contratos.len(),
24260                "AplicacaoSpec::contratos().len() must byte-equal \
24261                 self.contratos.len() — a length-drift would silently \
24262                 split the paired per-edge validate-loop's traversal \
24263                 input from the sync-cycle adjacency-list seed's \
24264                 traversal input from the cilium_network_policies \
24265                 per-`(:de, :para)` BTreeMap grouping loop's traversal \
24266                 input from the `feira app graph` per-contract print \
24267                 traversal's input",
24268            );
24269        }
24270    }
24271
24272    #[test]
24273    fn validate_reads_through_lifted_contratos_accessor() {
24274        // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
24275        // per-`:contratos` validate-loop's `for c in self.contratos()`
24276        // traversal (which must reach every entry in the same order the
24277        // accessor projects, so both the per-entry
24278        // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
24279        // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
24280        // dedup `HashSet` insert key off the accessor's projection),
24281        // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
24282        // `for c in self.contratos()` adjacency-list seed (which drives
24283        // the sync-subgraph deadlock-detection gate via
24284        // [`AplicacaoError::SyncCycle`]), and the peer
24285        // [`caixa_mesh::cilium_network_policies`]'s
24286        // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
24287        // grouping loop (which drives the per-CNP fan-out) must all
24288        // three key off the lifted accessor, so any future rebrand on
24289        // the typed slot's reader shape lands at exactly one place. Pins
24290        // the three-site coherence by exercising the two caixa-core
24291        // production consumers end-to-end: (1) the empty-`:contratos`
24292        // slice must validate without a per-edge diagnostic (the
24293        // per-edge loop is a no-op under the empty projection), (2) the
24294        // `ContratoMemberMissing` refusal fires on the second entry of a
24295        // two-edge cohort whose head references a valid member but tail
24296        // references a phantom name (which requires the loop to reach
24297        // the second entry through the accessor), and (3) the
24298        // `SyncCycle` refusal fires on a self-referential two-edge
24299        // cohort through the sync-cycle detector's peer projection
24300        // (which requires the detector to iterate the accessor's
24301        // projection to add the back-edge to its adjacency list).
24302        //
24303        // Peer of the sibling M3
24304        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
24305        // three-consumer coherence pin on the per-`:membros` node-list
24306        // axis and the sibling M3
24307        // `validate_placement_reads_through_lifted_clusters_accessor`
24308        // (a6e18d7) coherence pin on the per-`:placement` distribution-
24309        // target-list axis — extends the slice-return-accessor multi-
24310        // consumer coherence discipline onto the outermost M3 mesh-slot
24311        // type's per-Aplicacao contract-list `Vec`-carry axis.
24312
24313        // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
24314        // and no per-edge diagnostic surfaces. Validate succeeds on
24315        // the well-formed `:membros` head.
24316        let mut spec = three_member_spec();
24317        spec.contratos = Vec::new();
24318        assert!(
24319            spec.validate().is_ok(),
24320            "empty :contratos must validate — the per-edge loop is a \
24321             no-op under the accessor's empty projection",
24322        );
24323        assert!(
24324            spec.contratos().is_empty(),
24325            "the per-edge validate loop's traversal input must be the \
24326             empty slice per the accessor's projection",
24327        );
24328
24329        // (2) Per-edge validate loop: a two-edge cohort whose tail
24330        // references a phantom `:para` member must trip
24331        // `ContratoMemberMissing` on the tail — the loop must reach
24332        // the second entry through the accessor for the membership
24333        // lookup to fail on the phantom name.
24334        let mut spec = three_member_spec();
24335        spec.contratos = vec![
24336            contract_http("cart", "catalog", "/products/:id"),
24337            contract_http("cart", "phantom", "/x"),
24338        ];
24339        let err = spec.validate().unwrap_err();
24340        assert!(
24341            matches!(
24342                err,
24343                AplicacaoError::ContratoMemberMissing { ref caixa }
24344                    if caixa == "phantom"
24345            ),
24346            "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
24347        );
24348        assert_eq!(
24349            spec.contratos().len(),
24350            2,
24351            "the per-edge validate loop's traversal input must be \
24352             a two-element slice per the accessor's projection",
24353        );
24354
24355        // (3) Sync-cycle detector: a two-edge synchronous cohort
24356        // whose second edge closes the sync-subgraph back onto the
24357        // first must trip [`AplicacaoError::ContratoCycle`] — the
24358        // detector must iterate the accessor's projection to add
24359        // both edges to its adjacency list, so a length-drift on
24360        // the accessor's projection would silently disagree with
24361        // the sync-cycle detector on which edge closes the loop.
24362        // Peer projection to the `validate` per-edge loop above:
24363        // the sync-cycle detector routes through the same lifted
24364        // accessor, so a rebrand of the reader shape lands at one
24365        // place. Uses a two-edge cohort (cart → catalog → cart)
24366        // because the per-edge `ContratoSelfLoop` gate fires before
24367        // the sync-cycle detector on a single self-referential edge
24368        // (`cart → cart`) — the cycle-detector's input must be a
24369        // multi-edge cohort for its per-edge traversal input to be
24370        // observably wider than the per-edge validate loop's input.
24371        let mut spec = three_member_spec();
24372        spec.contratos = vec![
24373            contract_http("cart", "catalog", "/products/:id"),
24374            contract_http("catalog", "cart", "/callback"),
24375        ];
24376        let err = spec.validate().unwrap_err();
24377        assert!(
24378            matches!(err, AplicacaoError::ContratoCycle { .. }),
24379            "expected ContratoCycle from the sync-cycle detector on a \
24380             two-edge back-edge cohort, got {err:?}",
24381        );
24382        assert_eq!(
24383            spec.contratos().len(),
24384            2,
24385            "the sync-cycle detector's traversal input must be a \
24386             two-element slice per the accessor's projection",
24387        );
24388    }
24389
24390    #[test]
24391    fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
24392        // The canonical per-`:politicas` outer-composite-reference-shape
24393        // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
24394        // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
24395        // the same backing storage the raw `&self.politicas` field
24396        // access borrows from, byte-equal across every representative
24397        // fixture in the accept-set — the default `MeshPolicy` (the
24398        // author-empty "no policy on any axis" shape whose
24399        // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
24400        // shapes carrying one axis at a time
24401        // (`{mtls_required, timeout, retries, circuit_breaker,
24402        // rate_limit}` — the minimal five-axis fan-out over the
24403        // per-axis lifted accessor family every downstream mesh-artifact
24404        // emitter dispatches on), and the multi-axis composite (the
24405        // canonical `three_member_spec` fixture's `{timeout, retries,
24406        // mtls_required}` triple — the load-bearing shape every
24407        // Aplicacao-scoped fixture in this suite constructs).
24408        //
24409        // Pins against a future silent detour that returned a fresh-
24410        // cloned `MeshPolicy` copy (which would type-check via a `Clone`
24411        // impl but silently break every downstream caller that relied
24412        // on the reference sharing the composite's backing identity), a
24413        // reference to an operator-resolved overlay (the future
24414        // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
24415        // acknowledges — its resolution must land at exactly this
24416        // accessor body, not silently divert the raw slot away from a
24417        // second consumer), or an axis-shuffled projection (a future
24418        // detour that swapped `timeout` and `retries` through the
24419        // accessor would silently split the paired `validate_politicas`
24420        // per-axis bracket-dispatch's traversal input from the peer
24421        // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
24422        // emitter's fan-out input from the peer
24423        // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
24424        // overlay emitter's fan-out input).
24425        //
24426        // Peer of the sibling M3
24427        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
24428        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
24429        // node-list `Vec`-carry axis and the sibling M3
24430        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
24431        // (0dcc926) `&[WitContract]` byte-equal pin on the per-
24432        // `:contratos` edge-list `Vec`-carry axis — extends the outer-
24433        // accessor byte-equal-projection discipline onto the outermost
24434        // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
24435        // reference axis, the first `&Composite`-return accessor on the
24436        // outer [`AplicacaoSpec`] type.
24437        let fixtures: Vec<MeshPolicy> = vec![
24438            MeshPolicy::default(),
24439            MeshPolicy {
24440                mtls_required: Some(true),
24441                ..MeshPolicy::default()
24442            },
24443            MeshPolicy {
24444                mtls_required: Some(false),
24445                ..MeshPolicy::default()
24446            },
24447            MeshPolicy {
24448                timeout: Some(Duration::from_secs(30)),
24449                ..MeshPolicy::default()
24450            },
24451            MeshPolicy {
24452                retries: Some(3),
24453                ..MeshPolicy::default()
24454            },
24455            MeshPolicy {
24456                circuit_breaker: Some(CircuitBreaker {
24457                    max_failures: 5,
24458                    window: Duration::from_secs(30),
24459                }),
24460                ..MeshPolicy::default()
24461            },
24462            MeshPolicy {
24463                rate_limit: Some(RateLimit {
24464                    rate: 100,
24465                    window: Duration::from_secs(1),
24466                }),
24467                ..MeshPolicy::default()
24468            },
24469            MeshPolicy {
24470                timeout: Some(Duration::from_secs(30)),
24471                retries: Some(3),
24472                mtls_required: Some(true),
24473                ..MeshPolicy::default()
24474            },
24475        ];
24476        for politicas in fixtures {
24477            let s = AplicacaoSpec {
24478                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
24479                contratos: Vec::new(),
24480                politicas: politicas.clone(),
24481                placement: Placement::default(),
24482                entrada: None,
24483            };
24484            assert_eq!(
24485                *s.politicas(),
24486                politicas,
24487                "AplicacaoSpec::politicas must return :politicas verbatim \
24488                 (got {:?}, expected {:?})",
24489                s.politicas(),
24490                politicas,
24491            );
24492            assert!(
24493                std::ptr::eq(s.politicas(), &s.politicas),
24494                "AplicacaoSpec::politicas accessor and &self.politicas \
24495                 field access must borrow the same backing storage — \
24496                 the accessor is the substrate-primitive typed dispatch \
24497                 every downstream mesh-policy composite consumer must \
24498                 route through, and a reference-identity split would \
24499                 silently break every consumer that relied on the \
24500                 borrow sharing the composite's storage",
24501            );
24502            assert_eq!(
24503                s.politicas().is_empty(),
24504                s.politicas.is_empty(),
24505                "AplicacaoSpec::politicas().is_empty() must byte-equal \
24506                 self.politicas.is_empty() — an emptiness-drift would \
24507                 silently split the paired `validate_politicas` \
24508                 per-axis bracket-dispatch's seed from the peer \
24509                 caixa-mesh CNP mTLS-overlay emitter's key from the \
24510                 peer caixa-mesh HTTPRoute timeout+retry overlay \
24511                 emitter's key",
24512            );
24513        }
24514    }
24515
24516    #[test]
24517    fn validate_politicas_reads_through_lifted_politicas_accessor() {
24518        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
24519        // per-axis bracket-dispatch seed (`let p = self.politicas();`,
24520        // followed by the per-axis fan-out `p.timeout()` /
24521        // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
24522        // the lifted axis-level accessor family) must key off the
24523        // lifted outer accessor, so any future rebrand on the typed
24524        // slot's outer-composite reader shape lands at exactly one
24525        // place. Pins the multi-axis coherence by exercising each
24526        // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
24527        // a `Some(Duration::ZERO)` timeout under the outer accessor's
24528        // reference projection, (2) `PolicyRetriesZero` fires on a
24529        // `Some(0)` retries under the same projection, and (3) an
24530        // empty [`MeshPolicy::default`] passes `validate_politicas` —
24531        // the outer accessor's reference-projection reaches every
24532        // per-axis branch without silently short-circuiting any.
24533        //
24534        // Peer of the sibling M3
24535        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
24536        // three-consumer coherence pin on the per-`:membros` node-list
24537        // axis and the sibling M3
24538        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
24539        // three-consumer coherence pin on the per-`:contratos`
24540        // edge-list axis — extends the multi-consumer coherence
24541        // discipline onto the outermost M3 mesh-slot type's per-
24542        // Aplicacao mesh-policy composite-reference axis, the first
24543        // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
24544        // type.
24545
24546        // (1) `PolicyTimeoutZero` refusal under the outer accessor's
24547        // reference projection: a `Some(Duration::ZERO)` timeout must
24548        // trip the zero-floor gate. The bracket-dispatch's first arm
24549        // reads `p.timeout()` on the reference returned by the outer
24550        // accessor.
24551        let mut spec = three_member_spec();
24552        spec.politicas.timeout = Some(Duration::ZERO);
24553        spec.politicas.retries = None;
24554        spec.politicas.circuit_breaker = None;
24555        spec.politicas.rate_limit = None;
24556        assert_eq!(
24557            spec.validate().unwrap_err(),
24558            AplicacaoError::PolicyTimeoutZero,
24559        );
24560        assert!(
24561            std::ptr::eq(spec.politicas(), &spec.politicas),
24562            "the `validate_politicas` per-axis bracket-dispatch's \
24563             traversal input must be the same backing composite the \
24564             accessor's reference projection borrows from",
24565        );
24566
24567        // (2) `PolicyRetriesZero` refusal under the outer accessor's
24568        // reference projection: a `Some(0)` retries must trip the
24569        // zero-floor gate. The bracket-dispatch's second arm reads
24570        // `p.retries()` on the reference returned by the outer accessor.
24571        let mut spec = three_member_spec();
24572        spec.politicas.timeout = None;
24573        spec.politicas.retries = Some(0);
24574        spec.politicas.circuit_breaker = None;
24575        spec.politicas.rate_limit = None;
24576        assert_eq!(
24577            spec.validate().unwrap_err(),
24578            AplicacaoError::PolicyRetriesZero,
24579        );
24580
24581        // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
24582        // — every per-axis arm short-circuits on `None`, so the outer
24583        // accessor's reference projection reaches the fall-through
24584        // `Ok(())` without any per-axis refusal firing.
24585        let mut spec = three_member_spec();
24586        spec.politicas = MeshPolicy::default();
24587        assert!(
24588            spec.validate().is_ok(),
24589            "an empty `MeshPolicy` must pass `validate_politicas` — \
24590             every per-axis arm short-circuits on `None` under the \
24591             outer accessor's reference projection",
24592        );
24593        assert!(
24594            spec.politicas().is_empty(),
24595            "the outer accessor's reference projection must be the \
24596             empty composite per the `MeshPolicy::default()` fixture",
24597        );
24598    }
24599
24600    #[test]
24601    #[allow(clippy::too_many_lines)]
24602    fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
24603        // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
24604        // per-axis bracket-dispatch's `:timeout` and `:retries` arms
24605        // must both key off the lifted axis-level accessors
24606        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
24607        // the peer `:circuit-breaker` / `:rate-limit` arms already
24608        // routing through [`MeshPolicy::circuit_breaker`] /
24609        // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
24610        // per axis on the substrate primitive" shape at the fan-out
24611        // (four axes, four accessors, no raw-field-access site
24612        // anywhere on the bracket-dispatch). Pins the per-axis
24613        // coherence at the accept-set boundaries the bracket carves:
24614        //   1. accessor byte-equal to raw field on every representative
24615        //      accept-set value (`None`, sub-cap, at-cap, past-cap
24616        //      sentinel) — a future accessor drift that no longer
24617        //      shipped the raw slot verbatim would surface here,
24618        //   2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
24619        //      routed through the accessor's projection, proving the
24620        //      first arm reads through the accessor rather than a
24621        //      silent-detour peer-axis field access,
24622        //   3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
24623        //      through the accessor's projection, proving the second
24624        //      arm reads through the accessor,
24625        //   4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
24626        //      passes validate under the accessor projection (paired
24627        //      with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
24628        //      sibling axis), pinning the upper-boundary accept-arm
24629        //      also routes through the accessor.
24630        //
24631        // Peer of the sibling M3
24632        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
24633        // outer-composite-reference coherence pin (which asserts the
24634        // `let p = self.politicas()` seed); extends the discipline onto
24635        // the per-axis fan-out layer that consumes the seed's
24636        // reference. Same shape as
24637        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
24638        // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
24639        // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
24640        // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
24641
24642        // (1) Accessor byte-equal to raw field on the `:timeout` axis
24643        // across the accept-set boundaries the bracket dispatch's
24644        // three-arm gate carves out
24645        // ([`crate::render::require_positive_canonical_bounded_duration`]
24646        // — zero-floor + canonical-form + upper-cap).
24647        for timeout in [
24648            None,
24649            Some(Duration::ZERO),
24650            Some(Duration::from_millis(1)),
24651            Some(POLICY_TIMEOUT_MAX),
24652        ] {
24653            let p = MeshPolicy {
24654                timeout,
24655                ..MeshPolicy::default()
24656            };
24657            assert_eq!(
24658                p.timeout(),
24659                p.timeout,
24660                "MeshPolicy::timeout accessor must byte-equal the raw \
24661                 .timeout field across every accept-set boundary the \
24662                 validate_politicas :timeout arm carves out — a drift \
24663                 here would silently split the validate bracket's arm \
24664                 from the peer caixa-mesh HTTPRoute timeout-overlay \
24665                 emitter's read",
24666            );
24667        }
24668
24669        // (2) Accessor byte-equal to raw field on the `:retries` axis
24670        // across the accept-set boundaries the bracket dispatch's
24671        // two-arm gate carves out
24672        // ([`crate::render::require_positive_bounded_u32`] — zero-floor
24673        // + upper-cap).
24674        for retries in [
24675            None,
24676            Some(0u32),
24677            Some(1u32),
24678            Some(POLICY_RETRIES_MAX),
24679            Some(POLICY_RETRIES_MAX + 1),
24680            Some(u32::MAX),
24681        ] {
24682            let p = MeshPolicy {
24683                retries,
24684                ..MeshPolicy::default()
24685            };
24686            assert_eq!(
24687                p.retries(),
24688                p.retries,
24689                "MeshPolicy::retries accessor must byte-equal the raw \
24690                 .retries field across every accept-set boundary the \
24691                 validate_politicas :retries arm carves out — a drift \
24692                 here would silently split the validate bracket's arm \
24693                 from the peer caixa-mesh HTTPRoute retry-overlay \
24694                 emitter's read",
24695            );
24696        }
24697
24698        // (3) `PolicyTimeoutZero` fires on the accessor-projected
24699        // zero-floor boundary. A silent detour that no longer read
24700        // through `p.timeout()` (a peer-axis field read, an accidental
24701        // Option::and-then chain that collapsed the None arm to Some,
24702        // an accessor rebrand that clamped the return through the
24703        // upper cap) would fail to refuse here.
24704        let mut spec = three_member_spec();
24705        spec.politicas.timeout = Some(Duration::ZERO);
24706        spec.politicas.retries = None;
24707        spec.politicas.circuit_breaker = None;
24708        spec.politicas.rate_limit = None;
24709        assert_eq!(
24710            spec.politicas().timeout(),
24711            Some(Duration::ZERO),
24712            "the accessor projection must reflect the fixture's \
24713             `Some(Duration::ZERO)` :timeout verbatim",
24714        );
24715        assert_eq!(
24716            spec.validate().unwrap_err(),
24717            AplicacaoError::PolicyTimeoutZero,
24718            "the validate_politicas :timeout zero-floor arm must fire \
24719             through the lifted accessor's projection — a silent \
24720             detour to a peer-axis field would fail to refuse",
24721        );
24722
24723        // (4) `PolicyRetriesZero` fires on the accessor-projected
24724        // zero-floor boundary on the sibling `:retries` axis.
24725        let mut spec = three_member_spec();
24726        spec.politicas.timeout = None;
24727        spec.politicas.retries = Some(0);
24728        spec.politicas.circuit_breaker = None;
24729        spec.politicas.rate_limit = None;
24730        assert_eq!(
24731            spec.politicas().retries(),
24732            Some(0),
24733            "the accessor projection must reflect the fixture's \
24734             `Some(0)` :retries verbatim",
24735        );
24736        assert_eq!(
24737            spec.validate().unwrap_err(),
24738            AplicacaoError::PolicyRetriesZero,
24739            "the validate_politicas :retries zero-floor arm must fire \
24740             through the lifted accessor's projection — a silent \
24741             detour to a peer-axis field would fail to refuse",
24742        );
24743
24744        // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
24745        // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
24746        // must pass validate under the accessor projection — pins the
24747        // upper-boundary accept-arm also routes through the lifted
24748        // accessor (a drift that clamped or short-circuited at the
24749        // upper boundary would fail the whole-spec validate here).
24750        let mut spec = three_member_spec();
24751        spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
24752        spec.politicas.retries = Some(POLICY_RETRIES_MAX);
24753        spec.politicas.circuit_breaker = None;
24754        spec.politicas.rate_limit = None;
24755        assert_eq!(
24756            spec.politicas().timeout(),
24757            Some(POLICY_TIMEOUT_MAX),
24758            "the accessor projection must reflect the fixture's \
24759             at-cap :timeout verbatim",
24760        );
24761        assert_eq!(
24762            spec.politicas().retries(),
24763            Some(POLICY_RETRIES_MAX),
24764            "the accessor projection must reflect the fixture's \
24765             at-cap :retries verbatim",
24766        );
24767        assert!(
24768            spec.validate().is_ok(),
24769            "at-cap :timeout + :retries must pass validate under the \
24770             accessor projection — the upper-boundary accept-arm on \
24771             both axes routes through the lifted accessor",
24772        );
24773    }
24774
24775    #[test]
24776    fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
24777        // The canonical per-`:placement` outer-composite-reference-shape
24778        // pin: [`AplicacaoSpec::placement`] must return the `:placement`
24779        // typed `Placement` verbatim as a `&Placement` reference over the
24780        // same backing storage the raw `&self.placement` field access
24781        // borrows from, byte-equal across every representative fixture in
24782        // the accept-set — the default `Placement` (the substrate seed
24783        // shape whose [`PlacementStrategy::default`] evaluates to
24784        // `SingleNode` with an empty `:clusters` pool and both
24785        // optional-scalar axes `None`), and every canonical strategy /
24786        // cluster-pool / optional-scalar combination the
24787        // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
24788        // three [`PlacementStrategy`] variants — `SingleNode`,
24789        // `Replicated`, `Sharded` — cross-projected with a non-empty
24790        // `:clusters` pool and, on the `Sharded` arm, a non-empty
24791        // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
24792        // canonical `three_member_spec` `Replicated` fixture's
24793        // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
24794        //
24795        // Pins against a future silent detour that returned a fresh-
24796        // cloned `Placement` copy (which would type-check via a `Clone`
24797        // impl but silently break every downstream caller that relied on
24798        // the reference sharing the composite's backing identity), a
24799        // reference to an operator-resolved overlay (the future per-
24800        // cluster `:placement-overrides` slot MESH-COMPOSITION §V
24801        // acknowledges — its resolution must land at exactly this
24802        // accessor body, not silently divert the raw slot away from a
24803        // second consumer), or an axis-shuffled projection (a future
24804        // detour that swapped `clusters` and `affinity` through the
24805        // accessor would silently split the paired `validate_placement`
24806        // per-axis bracket-dispatch's traversal input from the peer
24807        // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
24808        // programs.yaml distribution-annotation emitter's fan-out input
24809        // from the peer `feira app graph` per-Aplicacao print line's
24810        // input).
24811        //
24812        // Peer of the sibling M3
24813        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
24814        // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
24815        // outer mesh-policy composite-reference axis, and of the sibling
24816        // slice-return `aplicacao_spec_membros_returns_membros_slice_
24817        // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
24818        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
24819        // across_permutations` (0dcc926) `&[WitContract]` pins — extends
24820        // the outer-accessor byte-equal-projection discipline onto the
24821        // outermost M3 mesh-slot type's per-Aplicacao distribution
24822        // composite-reference axis, the second `&Composite`-return
24823        // accessor on the outer [`AplicacaoSpec`] type.
24824        let fixtures: Vec<Placement> = vec![
24825            Placement::default(),
24826            Placement {
24827                estrategia: PlacementStrategy::SingleNode,
24828                clusters: vec!["rio".into()],
24829                affinity: None,
24830                shard_key: None,
24831            },
24832            Placement {
24833                estrategia: PlacementStrategy::Replicated,
24834                clusters: vec!["rio".into(), "mar".into()],
24835                affinity: None,
24836                shard_key: None,
24837            },
24838            Placement {
24839                estrategia: PlacementStrategy::Replicated,
24840                clusters: vec!["rio".into(), "mar".into()],
24841                affinity: Some("data-locality".into()),
24842                shard_key: None,
24843            },
24844            Placement {
24845                estrategia: PlacementStrategy::Sharded,
24846                clusters: vec!["rio".into(), "mar".into()],
24847                affinity: None,
24848                shard_key: Some("tenantId".into()),
24849            },
24850            Placement {
24851                estrategia: PlacementStrategy::Sharded,
24852                clusters: vec!["rio".into(), "mar".into(), "sol".into()],
24853                affinity: Some("low-latency".into()),
24854                shard_key: Some("metadata.tenantId".into()),
24855            },
24856        ];
24857        for placement in fixtures {
24858            let s = AplicacaoSpec {
24859                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
24860                contratos: Vec::new(),
24861                politicas: MeshPolicy::default(),
24862                placement: placement.clone(),
24863                entrada: None,
24864            };
24865            assert_eq!(
24866                *s.placement(),
24867                placement,
24868                "AplicacaoSpec::placement must return :placement verbatim \
24869                 (got {:?}, expected {:?})",
24870                s.placement(),
24871                placement,
24872            );
24873            assert!(
24874                std::ptr::eq(s.placement(), &s.placement),
24875                "AplicacaoSpec::placement accessor and &self.placement \
24876                 field access must borrow the same backing storage — the \
24877                 accessor is the substrate-primitive typed dispatch every \
24878                 downstream distribution-composite consumer must route \
24879                 through, and a reference-identity split would silently \
24880                 break every consumer that relied on the borrow sharing \
24881                 the composite's storage",
24882            );
24883            assert_eq!(
24884                s.placement().estrategia(),
24885                s.placement.estrategia,
24886                "AplicacaoSpec::placement().estrategia() must byte-equal \
24887                 self.placement.estrategia — a strategy-drift would \
24888                 silently split the paired `validate_placement` \
24889                 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
24890                 peer caixa-mesh programs.yaml `placement.estrategia` \
24891                 emitter's key from the peer `feira app graph` printer's \
24892                 strategy label",
24893            );
24894            assert_eq!(
24895                s.placement().clusters(),
24896                s.placement.clusters.as_slice(),
24897                "AplicacaoSpec::placement().clusters() must byte-equal \
24898                 self.placement.clusters — a cluster-pool drift would \
24899                 silently split the paired `validate_placement` \
24900                 pre-flight `.is_empty()` refusal probe's traversal from \
24901                 the peer caixa-mesh programs.yaml `placement.clusters` \
24902                 emitter's fan-out from the peer `feira app graph` \
24903                 printer's cluster list",
24904            );
24905        }
24906    }
24907
24908    #[test]
24909    fn validate_placement_reads_through_lifted_placement_accessor() {
24910        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
24911        // per-axis bracket-dispatch seed (`let p = self.placement();`,
24912        // followed by the per-axis fan-out `p.clusters()` /
24913        // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
24914        // lifted axis-level accessor family) must key off the lifted
24915        // outer accessor, so any future rebrand on the typed slot's
24916        // outer-composite reader shape lands at exactly one place. Pins
24917        // the multi-axis coherence by exercising each per-axis refusal
24918        // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
24919        // `:clusters` pool under the outer accessor's reference
24920        // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
24921        // strategy with a `None` `:shard-key` under the same projection,
24922        // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
24923        // with a `Some` `:shard-key` under the same projection, and
24924        // (4) the canonical `three_member_spec` `Replicated` fixture
24925        // passes `validate_placement` under the outer accessor's
24926        // reference projection — the accessor's reference-projection
24927        // reaches every per-axis branch (cluster-pool refusal, `Sharded`
24928        // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
24929        // without silently short-circuiting any.
24930        //
24931        // Peer of the sibling M3
24932        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
24933        // (534dc21) multi-axis coherence pin on the per-`:politicas`
24934        // outer mesh-policy composite-reference axis — extends the
24935        // multi-consumer coherence discipline onto the outermost M3
24936        // mesh-slot type's per-Aplicacao distribution composite-
24937        // reference axis, the second `&Composite`-return accessor on
24938        // the outer [`AplicacaoSpec`] type.
24939
24940        // (1) `PlacementWithoutClusters` refusal under the outer
24941        // accessor's reference projection: an empty `:clusters` pool
24942        // must trip the pre-flight refusal probe. The bracket-dispatch's
24943        // first arm reads `p.clusters()` on the reference returned by
24944        // the outer accessor.
24945        let mut spec = three_member_spec();
24946        spec.placement.clusters = Vec::new();
24947        assert_eq!(
24948            spec.validate().unwrap_err(),
24949            AplicacaoError::PlacementWithoutClusters {
24950                estrategia: PlacementStrategy::Replicated,
24951            },
24952        );
24953        assert!(
24954            std::ptr::eq(spec.placement(), &spec.placement),
24955            "the `validate_placement` per-axis bracket-dispatch's \
24956             traversal input must be the same backing composite the \
24957             accessor's reference projection borrows from",
24958        );
24959
24960        // (2) `ShardedWithoutKey` refusal under the outer accessor's
24961        // reference projection: a `Sharded` strategy with a `None`
24962        // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
24963        // The bracket-dispatch's third arm reads `p.estrategia()` for
24964        // the match scrutinee then `p.shard_key()` for the cascade
24965        // scrutinee, both on the reference returned by the outer
24966        // accessor.
24967        let mut spec = three_member_spec();
24968        spec.placement.estrategia = PlacementStrategy::Sharded;
24969        spec.placement.shard_key = None;
24970        assert_eq!(
24971            spec.validate().unwrap_err(),
24972            AplicacaoError::ShardedWithoutKey,
24973        );
24974
24975        // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
24976        // reference projection: a non-`Sharded` strategy with a `Some`
24977        // `:shard-key` must trip the declared-but-inert refusal. The
24978        // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
24979        // + `p.estrategia()` for the diagnostic on the reference
24980        // returned by the outer accessor.
24981        let mut spec = three_member_spec();
24982        spec.placement.estrategia = PlacementStrategy::Replicated;
24983        spec.placement.shard_key = Some("tenantId".into());
24984        assert_eq!(
24985            spec.validate().unwrap_err(),
24986            AplicacaoError::ShardKeyOnNonSharded {
24987                estrategia: PlacementStrategy::Replicated,
24988                shard_key: "tenantId".into(),
24989            },
24990        );
24991
24992        // (4) Canonical `three_member_spec` `Replicated` fixture passes
24993        // `validate_placement` — every per-axis arm reaches the fall-
24994        // through `Ok(())` without any per-axis refusal firing under the
24995        // outer accessor's reference projection.
24996        let spec = three_member_spec();
24997        assert!(
24998            spec.validate().is_ok(),
24999            "the canonical Replicated placement fixture must pass \
25000             `validate_placement` — every per-axis arm short-circuits on \
25001             valid input under the outer accessor's reference projection",
25002        );
25003        assert_eq!(
25004            spec.placement().estrategia(),
25005            PlacementStrategy::Replicated,
25006            "the outer accessor's reference projection must be the \
25007             canonical Replicated fixture's strategy",
25008        );
25009        assert_eq!(
25010            spec.placement().clusters(),
25011            &["rio", "mar"],
25012            "the outer accessor's reference projection must be the \
25013             canonical Replicated fixture's cluster pool",
25014        );
25015    }
25016
25017    #[test]
25018    fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
25019        // The canonical per-`:entrada` outer-composite-optional-
25020        // reference-shape pin: [`AplicacaoSpec::entrada`] must return
25021        // the `:entrada` typed `Option<Entrada>` verbatim as an
25022        // `Option<&Entrada>` reference over the same backing storage
25023        // the raw `self.entrada.as_ref()` field access borrows from,
25024        // byte-equal across every representative fixture in the
25025        // accept-set — the author-omitted `None` shape (the
25026        // "internal-only mesh" partition every downstream external-
25027        // gateway emitter treats as "emit nothing"), the minimal
25028        // singleton `:entrada` composite (host + destination + empty
25029        // paths + default port), the paths-carrying composite (the
25030        // canonical `three_member_spec` fixture's ["/api" "/health"]
25031        // path-list shape every HTTPRoute per-rule fan-out emitter
25032        // reads), and the non-default port composite (the canonical
25033        // custom-port shape the port-fallback resolver reads).
25034        //
25035        // Pins against a future silent detour that returned a fresh-
25036        // cloned `Entrada` copy (which would type-check via a `Clone`
25037        // impl but silently break every downstream caller that
25038        // relied on the reference sharing the composite's backing
25039        // identity), a reference to an operator-resolved overlay
25040        // (the future per-cluster `:entrada-overrides` slot the
25041        // MESH-COMPOSITION §V federation roadmap acknowledges — its
25042        // resolution must land at exactly this accessor body, not
25043        // silently divert the raw slot away from a second consumer),
25044        // a `None` → `Some(Entrada::default)` cluster-default
25045        // projection (which would collapse the load-bearing
25046        // "author-omitted `:entrada` ⇒ internal-only mesh" partition
25047        // the peer `gateway_routes` early-return + `feira app graph`
25048        // internal-only-mesh partition both read), or an axis-
25049        // shuffled projection (a future detour that swapped
25050        // `host` and `para` through the accessor would silently
25051        // split the paired `validate` per-`:entrada` shape-and-
25052        // membership gate's traversal input from the peer
25053        // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
25054        // fan-out input from the peer `feira app graph` external-
25055        // gateway summary line).
25056        //
25057        // Peer of the sibling M3
25058        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
25059        // (534dc21) `&MeshPolicy` byte-equal pin on the per-
25060        // `:politicas` outer mesh-policy composite-reference axis
25061        // and of the sibling M3
25062        // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
25063        // (9abb8f0) `&Placement` byte-equal pin on the per-
25064        // `:placement` outer distribution-composite composite-
25065        // reference axis — extends the outer-accessor byte-equal-
25066        // projection discipline onto the last unlifted outermost M3
25067        // mesh-slot type's per-Aplicacao external-gateway composite-
25068        // reference axis, the third and final `&Composite`-return
25069        // accessor on the outer [`AplicacaoSpec`] type.
25070        let fixtures: Vec<Option<Entrada>> = vec![
25071            None,
25072            Some(Entrada {
25073                host: "checkout.quero.cloud".into(),
25074                para: "cart".into(),
25075                paths: Vec::new(),
25076                port: DEFAULT_SERVICO_PORT,
25077            }),
25078            Some(Entrada {
25079                host: "checkout.quero.cloud".into(),
25080                para: "cart".into(),
25081                paths: vec!["/api".into(), "/health".into()],
25082                port: DEFAULT_SERVICO_PORT,
25083            }),
25084            Some(Entrada {
25085                host: "checkout.quero.cloud".into(),
25086                para: "cart".into(),
25087                paths: vec!["/api".into()],
25088                port: 9443,
25089            }),
25090        ];
25091        for entrada in fixtures {
25092            let s = AplicacaoSpec {
25093                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
25094                contratos: Vec::new(),
25095                politicas: MeshPolicy::default(),
25096                placement: Placement::default(),
25097                entrada: entrada.clone(),
25098            };
25099            assert_eq!(
25100                s.entrada(),
25101                entrada.as_ref(),
25102                "AplicacaoSpec::entrada must return :entrada verbatim \
25103                 (got {:?}, expected {:?})",
25104                s.entrada(),
25105                entrada.as_ref(),
25106            );
25107            match (s.entrada(), s.entrada.as_ref()) {
25108                (Some(a), Some(b)) => assert!(
25109                    std::ptr::eq(a, b),
25110                    "AplicacaoSpec::entrada accessor and \
25111                     self.entrada.as_ref() field access must borrow \
25112                     the same backing storage — the accessor is the \
25113                     substrate-primitive typed dispatch every \
25114                     downstream external-gateway composite consumer \
25115                     must route through, and a reference-identity \
25116                     split would silently break every consumer that \
25117                     relied on the borrow sharing the composite's \
25118                     storage",
25119                ),
25120                (None, None) => {}
25121                _ => panic!(
25122                    "AplicacaoSpec::entrada presence bit must byte-\
25123                     equal self.entrada.is_some() — a presence-bit \
25124                     drift would silently split the paired `validate` \
25125                     per-`:entrada` shape-and-membership gate's \
25126                     traversal head from the peer \
25127                     caixa-mesh gateway_routes early-return partition \
25128                     from the peer `feira app graph` internal-only-\
25129                     mesh partition",
25130                ),
25131            }
25132            assert_eq!(
25133                s.entrada().is_some(),
25134                s.entrada.is_some(),
25135                "AplicacaoSpec::entrada().is_some() must byte-equal \
25136                 self.entrada.is_some() — a presence-bit drift would \
25137                 silently split every downstream `Option<&Entrada>` \
25138                 consumer's partition on the internal-only-mesh arm",
25139            );
25140        }
25141    }
25142
25143    #[test]
25144    fn validate_reads_through_lifted_entrada_accessor() {
25145        // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
25146        // per-`:entrada` shape-and-membership gate (`if let Some(e) =
25147        // self.entrada() { … }`, followed by the per-axis fan-out
25148        // `validate_entrada_para(&e.para)` /
25149        // `EntradaMemberMissing` membership lookup /
25150        // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
25151        // per-`e.paths` `validate_entrada_path` traversal) must key
25152        // off the lifted outer accessor, so any future rebrand on
25153        // the typed slot's outer-composite reader shape lands at
25154        // exactly one place. Pins the multi-axis coherence by
25155        // exercising each per-axis refusal end-to-end: (1) the
25156        // author-omitted `None` shape short-circuits past every
25157        // per-`:entrada` refusal (the internal-only mesh partition
25158        // the accessor's `None` arm names), (2) `EntradaMemberMissing`
25159        // fires on a well-shaped but phantom `:para` under the outer
25160        // accessor's reference projection, and (3) the canonical
25161        // `three_member_spec` `:entrada` fixture passes `validate`
25162        // under the outer accessor's reference projection.
25163        //
25164        // Peer of the sibling M3
25165        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
25166        // (534dc21) multi-axis coherence pin on the per-`:politicas`
25167        // outer mesh-policy composite-reference axis and the sibling
25168        // M3
25169        // [`validate_placement_reads_through_lifted_placement_accessor`]
25170        // (9abb8f0) multi-axis coherence pin on the per-`:placement`
25171        // outer distribution-composite composite-reference axis —
25172        // extends the multi-consumer coherence discipline onto the
25173        // last unlifted outermost M3 mesh-slot type's per-Aplicacao
25174        // external-gateway composite-reference axis, the third and
25175        // final `&Composite`-return accessor on the outer
25176        // [`AplicacaoSpec`] type.
25177
25178        // (1) `None` :entrada — the internal-only-mesh partition
25179        // short-circuits past every per-`:entrada` refusal. The outer
25180        // accessor's reference projection reaches the fall-through
25181        // `Ok(())` on the `None` arm without any per-axis refusal
25182        // firing.
25183        let mut spec = three_member_spec();
25184        spec.entrada = None;
25185        assert!(
25186            spec.validate().is_ok(),
25187            "an author-omitted `:entrada` must pass `validate` — the \
25188             internal-only-mesh partition short-circuits past every \
25189             per-`:entrada` refusal under the outer accessor's \
25190             reference projection",
25191        );
25192        assert!(
25193            spec.entrada().is_none(),
25194            "the outer accessor's reference projection must name the \
25195             internal-only-mesh partition per the `None` fixture",
25196        );
25197
25198        // (2) `EntradaMemberMissing` refusal under the outer accessor's
25199        // reference projection: a well-shaped but phantom `:para` must
25200        // trip the membership-lookup refusal. The gate's second arm
25201        // reads `e.para` on the reference returned by the outer
25202        // accessor.
25203        let mut spec = three_member_spec();
25204        if let Some(e) = spec.entrada.as_mut() {
25205            e.para = "phantom".into();
25206        }
25207        assert_eq!(
25208            spec.validate().unwrap_err(),
25209            AplicacaoError::EntradaMemberMissing {
25210                para: "phantom".into(),
25211            },
25212        );
25213        match (spec.entrada(), spec.entrada.as_ref()) {
25214            (Some(a), Some(b)) => assert!(
25215                std::ptr::eq(a, b),
25216                "the `validate` per-`:entrada` gate's traversal head \
25217                 must be the same backing composite the accessor's \
25218                 reference projection borrows from",
25219            ),
25220            _ => panic!("fixture must carry Some(:entrada)"),
25221        }
25222
25223        // (3) Canonical `three_member_spec` `:entrada` fixture passes
25224        // `validate` — every per-axis arm reaches the fall-through
25225        // `Ok(())` without any per-axis refusal firing under the
25226        // outer accessor's reference projection.
25227        let spec = three_member_spec();
25228        assert!(
25229            spec.validate().is_ok(),
25230            "the canonical `:entrada` fixture must pass `validate` — \
25231             every per-axis arm short-circuits on valid input under \
25232             the outer accessor's reference projection",
25233        );
25234        assert!(
25235            spec.entrada().is_some(),
25236            "the outer accessor's reference projection must be the \
25237             canonical `:entrada` fixture's composite",
25238        );
25239    }
25240
25241    #[test]
25242    fn port_for_destination_reads_through_lifted_entrada_accessor() {
25243        // Peer coherence pin: the
25244        // [`AplicacaoSpec::port_for_destination`] per-destination
25245        // L4-port fallback resolver's composite-projection seed
25246        // (`self.entrada().filter(…).map_or(…)`) must key off the
25247        // lifted outer accessor. Pins the coherence by exercising
25248        // the resolver end-to-end: (1) the `None` `:entrada` shape
25249        // falls through to `DEFAULT_SERVICO_PORT` under the outer
25250        // accessor's reference projection, (2) a non-matching
25251        // destination falls through to `DEFAULT_SERVICO_PORT` under
25252        // the outer accessor's reference projection, and (3) the
25253        // matching destination resolves to the `:entrada :port`
25254        // value under the outer accessor's reference projection.
25255        //
25256        // Peer of the sibling
25257        // [`validate_reads_through_lifted_entrada_accessor`] multi-
25258        // consumer coherence pin on the same per-`:entrada` outer-
25259        // composite axis — extends the multi-consumer coherence
25260        // discipline onto the second per-`:entrada` production
25261        // consumer, the L4-port fallback resolver.
25262
25263        // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
25264        // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
25265        // arm under the outer accessor's reference projection.
25266        let mut spec = three_member_spec();
25267        spec.entrada = None;
25268        assert_eq!(
25269            spec.port_for_destination("cart"),
25270            DEFAULT_SERVICO_PORT,
25271            "the port-fallback resolver must fall through to \
25272             DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
25273             under the outer accessor's reference projection",
25274        );
25275
25276        // (2) Non-matching destination — the resolver's `filter(…)`
25277        // arm rejects a mismatched destination and falls through
25278        // to `DEFAULT_SERVICO_PORT` under the outer accessor's
25279        // reference projection.
25280        let mut spec = three_member_spec();
25281        if let Some(e) = spec.entrada.as_mut() {
25282            e.para = "cart".into();
25283            e.port = 9443;
25284        }
25285        assert_eq!(
25286            spec.port_for_destination("catalog"),
25287            DEFAULT_SERVICO_PORT,
25288            "the port-fallback resolver must fall through to \
25289             DEFAULT_SERVICO_PORT on a non-matching destination \
25290             under the outer accessor's reference projection",
25291        );
25292
25293        // (3) Matching destination — the resolver's `map_or(…)` arm
25294        // returns the `:entrada :port` value under the outer
25295        // accessor's reference projection.
25296        let mut spec = three_member_spec();
25297        if let Some(e) = spec.entrada.as_mut() {
25298            e.para = "cart".into();
25299            e.port = 9443;
25300        }
25301        assert_eq!(
25302            spec.port_for_destination("cart"),
25303            9443,
25304            "the port-fallback resolver must return the \
25305             `:entrada :port` value on a matching destination \
25306             under the outer accessor's reference projection",
25307        );
25308    }
25309
25310    #[test]
25311    fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
25312        // The canonical per-`:politicas` `:mtls-required` mTLS-
25313        // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
25314        // must return the `:politicas :mtls-required` typed bool
25315        // verbatim as an `Option<bool>`, byte-equal to the raw field
25316        // access across every value in the three-way accept-set —
25317        // `None` (cluster default applies), `Some(true)` (mTLS
25318        // handshake enforced — the sandboxing-by-default arm the
25319        // MeshPolicy's docstring names), `Some(false)` (handshake
25320        // skipped — the explicit debug-edge opt-out).
25321        //
25322        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
25323        // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
25324        // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
25325        // shape — first `Option<Copy-T>`-return accessor on the M3
25326        // mesh-slot family. Pins against a future silent detour that
25327        // re-derived the toggle from a peer axis (an accidental
25328        // `.circuit_breaker.is_some()` collapse that assumed mTLS on
25329        // whenever a breaker is set), a `None` → `Some(false)` cluster-
25330        // default projection (the canonical `Option<bool>` → `bool`
25331        // collapse footgun the surrounding `is_empty()` predicate
25332        // guards on the peer emptiness axis), or a `Some(true)` /
25333        // `Some(false)` variant swap that landed on one consumer
25334        // without the other.
25335        for required in [None, Some(true), Some(false)] {
25336            let p = MeshPolicy {
25337                mtls_required: required,
25338                ..MeshPolicy::default()
25339            };
25340            assert_eq!(
25341                p.mtls_required(),
25342                required,
25343                "MeshPolicy::mtls_required must return :politicas \
25344                 :mtls-required verbatim (got {:?}, expected {required:?})",
25345                p.mtls_required(),
25346            );
25347            assert_eq!(
25348                p.mtls_required(),
25349                p.mtls_required,
25350                "MeshPolicy::mtls_required must byte-equal the raw \
25351                 .mtls_required field access across every value in the \
25352                 three-way accept-set",
25353            );
25354        }
25355    }
25356
25357    #[test]
25358    fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
25359        // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
25360        // arm must key off [`MeshPolicy::mtls_required`], not the raw
25361        // `.mtls_required` field access. Structurally: toggling ONLY
25362        // the `mtls_required` slot on an otherwise-default MeshPolicy
25363        // must flip `is_empty()` from `true` (all-`None`) to `false`
25364        // (one axis carries a value); the flip must be observed for
25365        // both `Some(true)` and `Some(false)` since the emptiness
25366        // semantic reads "any axis carries a value" — not "any axis
25367        // carries a truthy value" — the same non-collapsing shape the
25368        // sibling M2 [`crate::LimitsSpec::is_empty`] /
25369        // [`crate::BehaviorSpec::is_empty`] predicates carry on their
25370        // peer `Option<T>`-typed slot surfaces.
25371        //
25372        // Pins against a future silent detour that re-derived the
25373        // emptiness predicate off a peer axis (an accidental
25374        // `.rate_limit.is_none()`-only chain that dropped the
25375        // `mtls_required` arm entirely), a `mtls_required == Some(_)`
25376        // collapse to a truthy-only check (which would silently
25377        // classify `Some(false)` as empty), or an accessor-side
25378        // detour that no longer names the substrate-primitive typed
25379        // dispatch (an accidental `self.mtls_required.unwrap_or(false)
25380        // == false` fallback in the accessor that would silently
25381        // classify both `None` and `Some(false)` as the same value).
25382        //
25383        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
25384        // (7cd2a28) accessor-composition pin on the sibling optional-
25385        // scalar axis — same "the emptiness / shape-gate predicate
25386        // must route through the substrate-primitive typed dispatch"
25387        // discipline extended onto the peer per-`:politicas` emptiness
25388        // predicate.
25389        let empty = MeshPolicy::default();
25390        assert!(
25391            empty.is_empty(),
25392            "MeshPolicy::default() must be is_empty() — every axis \
25393             defaults to None",
25394        );
25395        for required in [Some(true), Some(false)] {
25396            let p = MeshPolicy {
25397                mtls_required: required,
25398                ..MeshPolicy::default()
25399            };
25400            assert!(
25401                !p.is_empty(),
25402                "MeshPolicy::is_empty must return false when \
25403                 :mtls-required is {required:?} — the emptiness \
25404                 predicate reads \"any axis carries a value\", not \
25405                 \"any axis carries a truthy value\"",
25406            );
25407            assert_eq!(
25408                p.mtls_required().is_none(),
25409                p.is_empty(),
25410                "when :mtls-required is the only set axis, \
25411                 is_empty() must equal mtls_required().is_none() — \
25412                 the accessor and the emptiness predicate must \
25413                 route through the same substrate-primitive typed \
25414                 dispatch on the :mtls-required arm",
25415            );
25416        }
25417    }
25418
25419    #[test]
25420    fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
25421        // The by-copy pin: [`MeshPolicy::mtls_required`] returns
25422        // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
25423        // accessor must return by value, not by reference. Peer of the
25424        // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
25425        // borrow-invariant pin on the sibling `Option<String>` slot,
25426        // but extended onto the peer `Option<bool>` copy-invariant
25427        // shape — the accessor's returned `Option<bool>` must outlive
25428        // `&self` (multiple calls must return equal values from a
25429        // dropped-`&self` copy, since the returned Option carries no
25430        // borrow), and calling the accessor twice on the same
25431        // MeshPolicy must yield the same `Option<bool>` verbatim
25432        // (idempotent, no side effects on `&self`).
25433        //
25434        // Pins against a future silent detour that returned
25435        // `Option<&bool>` (which would type-check but silently break
25436        // every downstream caller — [`single_field_overlay`]'s first
25437        // parameter is `Option<T: Clone>`, and `&bool` would fold to a
25438        // detached copy at the call site), an accidental
25439        // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
25440        // would also type-check but return `Option<&bool>`), or a
25441        // one-arm-only accessor that reads `Some(*b)` in the Some arm
25442        // but reads a fresh Default::default() in the None arm.
25443        for required in [None, Some(true), Some(false)] {
25444            let p = MeshPolicy {
25445                mtls_required: required,
25446                ..MeshPolicy::default()
25447            };
25448            let first = p.mtls_required();
25449            let second = p.mtls_required();
25450            assert_eq!(
25451                first, second,
25452                "MeshPolicy::mtls_required must be idempotent — two \
25453                 successive calls on the same &self must return the \
25454                 same Option<bool>",
25455            );
25456            assert_eq!(
25457                first, required,
25458                "MeshPolicy::mtls_required must return :politicas \
25459                 :mtls-required verbatim by copy — got {first:?}, \
25460                 expected {required:?}",
25461            );
25462        }
25463    }
25464
25465    #[test]
25466    fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
25467        // The canonical per-`:politicas` `:retries` transient-failure-
25468        // retry-budget scalar pin: [`MeshPolicy::retries`] must return
25469        // the `:politicas :retries` typed `u32` verbatim as an
25470        // `Option<u32>`, byte-equal to the raw field access across every
25471        // representative value in the accept-set — `None` (cluster
25472        // default applies — typically "no retries beyond a single
25473        // dispatch attempt" the caixa-mesh `retry_overlay` builder
25474        // documents), `Some(1)` (the lower boundary of the
25475        // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
25476        // `AplicacaoSpec::validate_politicas` gate carves out on the
25477        // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
25478        // (the upper boundary the same gate carves out on the sibling
25479        // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
25480        // past-the-guard sentinel that pins the accessor doesn't perform
25481        // a silent bounds-collapse at the return path).
25482        //
25483        // Sibling of the peer per-`:politicas`
25484        // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
25485        // sibling `Option<Copy-T>` optional-scalar axis, extended to the
25486        // peer per-`:politicas` `Option<u32>` shape — second
25487        // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
25488        // Pins against a future silent detour that re-derived the retry
25489        // cap from a peer axis (an accidental `.circuit_breaker
25490        // .as_ref().map(|b| b.max_failures)` collapse that read the
25491        // breaker's max-failure count as a retry budget), a
25492        // `None → Some(0)` cluster-default projection (which would
25493        // silently re-introduce the `PolicyRetriesZero` refusal case at
25494        // the emit boundary), or a bounds-collapsing accessor that
25495        // clamped the return through `POLICY_RETRIES_MAX` (the
25496        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
25497        // must ship the raw slot verbatim so a validate-time gate
25498        // regression surfaces at the emit boundary rather than being
25499        // silently absorbed).
25500        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
25501            let p = MeshPolicy {
25502                retries,
25503                ..MeshPolicy::default()
25504            };
25505            assert_eq!(
25506                p.retries(),
25507                retries,
25508                "MeshPolicy::retries must return :politicas :retries \
25509                 verbatim (got {:?}, expected {retries:?})",
25510                p.retries(),
25511            );
25512            assert_eq!(
25513                p.retries(),
25514                p.retries,
25515                "MeshPolicy::retries must byte-equal the raw .retries \
25516                 field access across every value in the accept-set",
25517            );
25518        }
25519    }
25520
25521    #[test]
25522    fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
25523        // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
25524        // must key off [`MeshPolicy::retries`], not the raw `.retries`
25525        // field access. Structurally: toggling ONLY the `retries` slot
25526        // on an otherwise-default MeshPolicy must flip `is_empty()`
25527        // from `true` (all-`None`) to `false` (one axis carries a
25528        // value); the flip must be observed for every value in the
25529        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
25530        // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
25531        // the emptiness semantic reads "any axis carries a value" —
25532        // not "any axis carries a value the validate gate accepts" —
25533        // the same non-collapsing shape the peer M2
25534        // [`crate::LimitsSpec::is_empty`] /
25535        // [`crate::BehaviorSpec::is_empty`] predicates carry.
25536        //
25537        // Pins against a future silent detour that re-derived the
25538        // emptiness predicate off a peer axis (an accidental
25539        // `.rate_limit.is_none()`-only chain that dropped the
25540        // `retries` arm entirely), a `retries == Some(_)` collapse
25541        // that key-off a validate-gate-clamped bounds check (which
25542        // would silently classify a past-the-guard `Some(u32::MAX)`
25543        // as empty because it fails the `1..=POLICY_RETRIES_MAX`
25544        // check), or an accessor-side detour that no longer names the
25545        // substrate-primitive typed dispatch.
25546        //
25547        // Sibling of the peer per-`:politicas`
25548        // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
25549        // pin on the sibling `Option<Copy-T>` optional-scalar axis —
25550        // same "the emptiness predicate must route through the
25551        // substrate-primitive typed dispatch" discipline extended onto
25552        // the peer per-`:politicas` `Option<u32>` axis.
25553        let empty = MeshPolicy::default();
25554        assert!(
25555            empty.is_empty(),
25556            "MeshPolicy::default() must be is_empty() — every axis \
25557             defaults to None",
25558        );
25559        for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
25560            let p = MeshPolicy {
25561                retries,
25562                ..MeshPolicy::default()
25563            };
25564            assert!(
25565                !p.is_empty(),
25566                "MeshPolicy::is_empty must return false when \
25567                 :retries is {retries:?} — the emptiness \
25568                 predicate reads \"any axis carries a value\", not \
25569                 \"any axis carries a value the validate gate \
25570                 accepts\"",
25571            );
25572            assert_eq!(
25573                p.retries().is_none(),
25574                p.is_empty(),
25575                "when :retries is the only set axis, is_empty() \
25576                 must equal retries().is_none() — the accessor and \
25577                 the emptiness predicate must route through the same \
25578                 substrate-primitive typed dispatch on the :retries \
25579                 arm",
25580            );
25581        }
25582    }
25583
25584    #[test]
25585    fn mesh_policy_retries_projects_option_u32_by_copy() {
25586        // The by-copy pin: [`MeshPolicy::retries`] returns
25587        // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
25588        // accessor must return by value, not by reference. Sibling of
25589        // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
25590        // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
25591        // extended onto the sibling `Option<u32>` copy-invariant
25592        // shape — the accessor's returned `Option<u32>` must outlive
25593        // `&self` (multiple calls must return equal values from a
25594        // dropped-`&self` copy, since the returned Option carries no
25595        // borrow), and calling the accessor twice on the same
25596        // MeshPolicy must yield the same `Option<u32>` verbatim
25597        // (idempotent, no side effects on `&self`).
25598        //
25599        // Pins against a future silent detour that returned
25600        // `Option<&u32>` (which would type-check but silently break
25601        // every downstream caller — [`crate::render::single_field_overlay`]'s
25602        // first parameter is `Option<T: Clone>`, and `&u32` would
25603        // fold to a detached copy at the call site), an accidental
25604        // `Option::as_ref()` projection (`self.retries.as_ref()` would
25605        // also type-check but return `Option<&u32>`), or a one-arm-
25606        // only accessor that reads `Some(*n)` in the Some arm but
25607        // reads a fresh `Default::default()` (`0_u32`) in the None
25608        // arm.
25609        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
25610            let p = MeshPolicy {
25611                retries,
25612                ..MeshPolicy::default()
25613            };
25614            let first = p.retries();
25615            let second = p.retries();
25616            assert_eq!(
25617                first, second,
25618                "MeshPolicy::retries must be idempotent — two \
25619                 successive calls on the same &self must return the \
25620                 same Option<u32>",
25621            );
25622            assert_eq!(
25623                first, retries,
25624                "MeshPolicy::retries must return :politicas :retries \
25625                 verbatim by copy — got {first:?}, expected {retries:?}",
25626            );
25627        }
25628    }
25629
25630    #[test]
25631    fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
25632        // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
25633        // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
25634        // return the `:politicas :timeout` typed [`Duration`] verbatim
25635        // as an `Option<Duration>`, byte-equal to the raw field access
25636        // across every representative value in the accept-set — `None`
25637        // (cluster default applies — typically the gateway class's
25638        // implementation-side per-request wall-clock cap the caixa-mesh
25639        // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
25640        // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
25641        // set the surrounding `AplicacaoSpec::validate_politicas` gate
25642        // carves out on the sibling `PolicyTimeoutZero` /
25643        // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
25644        // (the upper boundary the same gate carves out on the sibling
25645        // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
25646        // (a past-the-guard sentinel that pins the accessor doesn't
25647        // perform a silent bounds-collapse into `None` on the zero-
25648        // Duration arm — validate rejects zero but the accessor must
25649        // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
25650        // past-the-guard sentinel that pins the accessor doesn't
25651        // perform a silent bounds-collapse at the return path).
25652        //
25653        // Sibling of the peer per-`:politicas`
25654        // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
25655        // `Option<u32>` optional-scalar axis and the peer per-
25656        // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
25657        // pin on the sibling `Option<bool>` optional-scalar axis,
25658        // extended onto the peer per-`:politicas` `Option<Duration>`
25659        // shape — third `Option<Copy-T>`-return accessor on the M3
25660        // mesh-slot family. Pins against a future silent detour that
25661        // re-derived the per-call cap from a peer axis (an accidental
25662        // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
25663        // read the breaker's rolling-window duration as a per-call
25664        // deadline), a `None → Some(Duration::MAX)` cluster-default
25665        // projection (which would silently re-introduce the
25666        // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
25667        // blocking" arm at the emit boundary), or a bounds-collapsing
25668        // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
25669        // (the `AplicacaoSpec::validate` gate owns the bounds; the
25670        // accessor must ship the raw slot verbatim so a validate-time
25671        // gate regression surfaces at the emit boundary rather than
25672        // being silently absorbed).
25673        for timeout in [
25674            None,
25675            Some(Duration::from_millis(1)),
25676            Some(POLICY_TIMEOUT_MAX),
25677            Some(Duration::ZERO),
25678            Some(Duration::MAX),
25679        ] {
25680            let p = MeshPolicy {
25681                timeout,
25682                ..MeshPolicy::default()
25683            };
25684            assert_eq!(
25685                p.timeout(),
25686                timeout,
25687                "MeshPolicy::timeout must return :politicas :timeout \
25688                 verbatim (got {:?}, expected {timeout:?})",
25689                p.timeout(),
25690            );
25691            assert_eq!(
25692                p.timeout(),
25693                p.timeout,
25694                "MeshPolicy::timeout must byte-equal the raw .timeout \
25695                 field access across every value in the accept-set",
25696            );
25697        }
25698    }
25699
25700    #[test]
25701    fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
25702        // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
25703        // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
25704        // field access. Structurally: toggling ONLY the `timeout` slot
25705        // on an otherwise-default MeshPolicy must flip `is_empty()`
25706        // from `true` (all-`None`) to `false` (one axis carries a
25707        // value); the flip must be observed for every value in the
25708        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
25709        // gate accepts (`Some(Duration::from_millis(1))`,
25710        // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
25711        // reads "any axis carries a value" — not "any axis carries a
25712        // value the validate gate accepts" — the same non-collapsing
25713        // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
25714        // [`crate::BehaviorSpec::is_empty`] predicates carry.
25715        //
25716        // Pins against a future silent detour that re-derived the
25717        // emptiness predicate off a peer axis (an accidental
25718        // `.rate_limit.is_none()`-only chain that dropped the
25719        // `timeout` arm entirely), a `timeout == Some(_)` collapse
25720        // that key-off a validate-gate-clamped bounds check (which
25721        // would silently classify a past-the-guard `Some(Duration::MAX)`
25722        // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
25723        // check), or an accessor-side detour that no longer names the
25724        // substrate-primitive typed dispatch.
25725        //
25726        // Sibling of the peer per-`:politicas`
25727        // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
25728        // the sibling `Option<u32>` optional-scalar axis and the peer
25729        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
25730        // accessor-composition pin on the sibling `Option<bool>`
25731        // optional-scalar axis — same "the emptiness predicate must
25732        // route through the substrate-primitive typed dispatch"
25733        // discipline extended onto the peer per-`:politicas`
25734        // `Option<Duration>` axis.
25735        let empty = MeshPolicy::default();
25736        assert!(
25737            empty.is_empty(),
25738            "MeshPolicy::default() must be is_empty() — every axis \
25739             defaults to None",
25740        );
25741        for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
25742            let p = MeshPolicy {
25743                timeout,
25744                ..MeshPolicy::default()
25745            };
25746            assert!(
25747                !p.is_empty(),
25748                "MeshPolicy::is_empty must return false when \
25749                 :timeout is {timeout:?} — the emptiness \
25750                 predicate reads \"any axis carries a value\", not \
25751                 \"any axis carries a value the validate gate \
25752                 accepts\"",
25753            );
25754            assert_eq!(
25755                p.timeout().is_none(),
25756                p.is_empty(),
25757                "when :timeout is the only set axis, is_empty() \
25758                 must equal timeout().is_none() — the accessor and \
25759                 the emptiness predicate must route through the same \
25760                 substrate-primitive typed dispatch on the :timeout \
25761                 arm",
25762            );
25763        }
25764    }
25765
25766    #[test]
25767    fn mesh_policy_timeout_projects_option_duration_by_copy() {
25768        // The by-copy pin: [`MeshPolicy::timeout`] returns
25769        // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
25770        // and the accessor must return by value, not by reference.
25771        // Sibling of the peer per-`:politicas`
25772        // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
25773        // sibling `Option<u32>` optional-scalar axis and the peer
25774        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
25775        // by-copy pin on the sibling `Option<bool>` optional-scalar
25776        // axis, extended onto the peer per-`:politicas`
25777        // `Option<Duration>` copy-invariant shape — the accessor's
25778        // returned `Option<Duration>` must outlive `&self` (multiple
25779        // calls must return equal values from a dropped-`&self`
25780        // copy, since the returned Option carries no borrow), and
25781        // calling the accessor twice on the same MeshPolicy must
25782        // yield the same `Option<Duration>` verbatim (idempotent, no
25783        // side effects on `&self`).
25784        //
25785        // Pins against a future silent detour that returned
25786        // `Option<&Duration>` (which would type-check but silently
25787        // break every downstream caller — [`crate::render::single_field_overlay`]'s
25788        // first parameter is `Option<T: Clone>`, and `&Duration`
25789        // would fold to a detached copy at the call site), an
25790        // accidental `Option::as_ref()` projection
25791        // (`self.timeout.as_ref()` would also type-check but return
25792        // `Option<&Duration>`), or a one-arm-only accessor that
25793        // reads `Some(*d)` in the Some arm but reads a fresh
25794        // `Default::default()` (`Duration::ZERO`) in the None arm
25795        // (which would silently re-classify every unset `:timeout`
25796        // as the `PolicyTimeoutZero`-refused zero-Duration value at
25797        // the accessor boundary).
25798        for timeout in [
25799            None,
25800            Some(Duration::from_millis(1)),
25801            Some(POLICY_TIMEOUT_MAX),
25802            Some(Duration::ZERO),
25803            Some(Duration::MAX),
25804        ] {
25805            let p = MeshPolicy {
25806                timeout,
25807                ..MeshPolicy::default()
25808            };
25809            let first = p.timeout();
25810            let second = p.timeout();
25811            assert_eq!(
25812                first, second,
25813                "MeshPolicy::timeout must be idempotent — two \
25814                 successive calls on the same &self must return the \
25815                 same Option<Duration>",
25816            );
25817            assert_eq!(
25818                first, timeout,
25819                "MeshPolicy::timeout must return :politicas :timeout \
25820                 verbatim by copy — got {first:?}, expected {timeout:?}",
25821            );
25822        }
25823    }
25824
25825    #[test]
25826    fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
25827        // The canonical per-`:politicas` `:rate-limit` Envoy-
25828        // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
25829        // [`MeshPolicy::rate_limit`] must return the `:politicas
25830        // :rate-limit` typed [`RateLimit`] verbatim as an
25831        // `Option<RateLimit>`, byte-equal to the raw field access
25832        // across every representative value in the accept-set — `None`
25833        // (cluster default applies — no per-Aplicacao rate declaration,
25834        // the gateway-class per-listener default arm the future caixa-
25835        // mesh `local_rate_limit_overlay` emitter documents),
25836        // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
25837        // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
25838        // accept-set the surrounding
25839        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
25840        // sibling `PolicyRateLimitZero` refusal, paired with the
25841        // canonical-window "1 second" arm of the three-unit
25842        // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
25843        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
25844        // (the upper boundary the same gate carves out on the sibling
25845        // `PolicyRateLimitExceedsCap` refusal, paired with the
25846        // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
25847        // (a past-the-guard sentinel that pins the accessor doesn't
25848        // perform a silent bounds-collapse into `None` on the
25849        // zero-rate/zero-window arm — validate rejects zero but the
25850        // accessor must ship the raw slot verbatim so a validate-time
25851        // gate regression surfaces at the emit boundary rather than
25852        // being silently absorbed), and
25853        // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
25854        // (a past-the-guard sentinel that pins the accessor doesn't
25855        // perform a silent bounds-collapse at the return path).
25856        //
25857        // First `Option<Copy-composite-T>`-return accessor pin on the
25858        // M3 mesh-slot family (peer of the sibling per-`:politicas`
25859        // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
25860        // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
25861        // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
25862        // Copy accessor pins, extended onto the peer per-`:politicas`
25863        // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
25864        // and the accessor returns by value). Pins against a future
25865        // silent detour that re-derived the rate declaration from a
25866        // peer axis (an accidental
25867        // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
25868        // collapse that read the breaker's trip threshold + rolling
25869        // window as a rate declaration), a `None → Some(default())`
25870        // cluster-default projection (which would silently re-
25871        // introduce a "cluster default is 0/s" arm the emit boundary
25872        // would take as "declared but inert" — the canonical
25873        // declared-but-inert footgun the sibling
25874        // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
25875        // amplification-shape axis), a bounds-collapsing accessor
25876        // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
25877        // clamped `rl.window` through [`is_canonical_rate_limit_window`]
25878        // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
25879        // accessor must ship the raw slot verbatim), or a
25880        // by-reference detour (`Option<&RateLimit>`) that broke every
25881        // downstream consumer keying off `Option<RateLimit>` by-copy.
25882        for rl in [
25883            None,
25884            Some(RateLimit {
25885                rate: 1,
25886                window: Duration::from_secs(1),
25887            }),
25888            Some(RateLimit {
25889                rate: POLICY_RATE_LIMIT_MAX,
25890                window: Duration::from_secs(3600),
25891            }),
25892            Some(RateLimit {
25893                rate: 0,
25894                window: Duration::ZERO,
25895            }),
25896            Some(RateLimit {
25897                rate: u32::MAX,
25898                window: Duration::MAX,
25899            }),
25900        ] {
25901            let p = MeshPolicy {
25902                rate_limit: rl,
25903                ..MeshPolicy::default()
25904            };
25905            assert_eq!(
25906                p.rate_limit(),
25907                rl,
25908                "MeshPolicy::rate_limit must return :politicas :rate-limit \
25909                 verbatim (got {:?}, expected {rl:?})",
25910                p.rate_limit(),
25911            );
25912            assert_eq!(
25913                p.rate_limit(),
25914                p.rate_limit,
25915                "MeshPolicy::rate_limit must byte-equal the raw \
25916                 .rate_limit field access across every value in the \
25917                 accept-set",
25918            );
25919        }
25920    }
25921
25922    #[test]
25923    fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
25924        // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
25925        // must key off [`MeshPolicy::rate_limit`], not the raw
25926        // `.rate_limit` field access. Structurally: toggling ONLY the
25927        // `rate_limit` slot on an otherwise-default MeshPolicy must
25928        // flip `is_empty()` from `true` (all-`None`) to `false` (one
25929        // axis carries a value); the flip must be observed for every
25930        // representative value in the accept-set the surrounding
25931        // [`AplicacaoSpec::validate_politicas`] gate accepts
25932        // (`Some(RateLimit { rate: 1, window: 1s })`,
25933        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
25934        // since the emptiness semantic reads "any axis carries a
25935        // value" — not "any axis carries a value the validate gate
25936        // accepts" — the same non-collapsing shape the peer M2
25937        // [`crate::LimitsSpec::is_empty`] /
25938        // [`crate::BehaviorSpec::is_empty`] predicates carry.
25939        //
25940        // Pins against a future silent detour that re-derived the
25941        // emptiness predicate off a peer axis (an accidental
25942        // `.timeout.is_none()`-only chain that dropped the
25943        // `rate_limit` arm entirely — the last unlifted inline field
25944        // access on `is_empty` before this lift), a `rate_limit ==
25945        // Some(_)` collapse that key-off a validate-gate-clamped
25946        // bounds check (which would silently classify a past-the-
25947        // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
25948        // because it fails the value-shape gate), or an accessor-
25949        // side detour that no longer names the substrate-primitive
25950        // typed dispatch.
25951        //
25952        // Fourth "the emptiness predicate must route through the
25953        // substrate-primitive typed dispatch" composition pin on the
25954        // M3 mesh-slot family — closes the last unlifted composition
25955        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
25956        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
25957        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
25958        // 7073d0f is_empty-composition pins on the sibling primitive-
25959        // Copy axes, extended onto the peer per-`:politicas`
25960        // composite-Copy `Option<RateLimit>` axis).
25961        let empty = MeshPolicy::default();
25962        assert!(
25963            empty.is_empty(),
25964            "MeshPolicy::default() must be is_empty() — every axis \
25965             defaults to None",
25966        );
25967        for rl in [
25968            RateLimit {
25969                rate: 1,
25970                window: Duration::from_secs(1),
25971            },
25972            RateLimit {
25973                rate: POLICY_RATE_LIMIT_MAX,
25974                window: Duration::from_secs(3600),
25975            },
25976        ] {
25977            let p = MeshPolicy {
25978                rate_limit: Some(rl),
25979                ..MeshPolicy::default()
25980            };
25981            assert!(
25982                !p.is_empty(),
25983                "MeshPolicy::is_empty must return false when \
25984                 :rate-limit is {rl:?} — the emptiness predicate \
25985                 reads \"any axis carries a value\", not \"any axis \
25986                 carries a value the validate gate accepts\"",
25987            );
25988            assert_eq!(
25989                p.rate_limit().is_none(),
25990                p.is_empty(),
25991                "when :rate-limit is the only set axis, is_empty() \
25992                 must equal rate_limit().is_none() — the accessor \
25993                 and the emptiness predicate must route through the \
25994                 same substrate-primitive typed dispatch on the \
25995                 :rate-limit arm",
25996            );
25997        }
25998    }
25999
26000    #[test]
26001    fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
26002        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26003        // `:rate-limit` value-shape gate must key off
26004        // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
26005        // field bind. Structurally: a `MeshPolicy` whose only set
26006        // axis is a `Some(RateLimit { rate: 0, .. })` must surface
26007        // the `PolicyRateLimitZero` refusal exactly, and the same
26008        // MeshPolicy with the rate at the canonical lower boundary
26009        // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
26010        // The pair jointly pins the accessor + validate-gate
26011        // composition: any future silent detour that had the accessor
26012        // omit the `Some(RateLimit { rate: 0, .. })` arm (a
26013        // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
26014        // silently absorb the `PolicyRateLimitZero` refusal at the
26015        // accessor boundary — the composition pin catches that at
26016        // caixa-core build time.
26017        //
26018        // Sibling of the peer [`validate_politicas`]
26019        // `:mtls-required` / `:retries` / `:timeout` composition pins
26020        // on the sibling primitive-Copy optional-scalar axes — same
26021        // "the validate / shape-gate predicate must route through the
26022        // substrate-primitive typed dispatch" discipline extended
26023        // onto the peer per-`:politicas` composite-Copy
26024        // `Option<RateLimit>` axis. Second composition-with-accessor
26025        // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
26026        // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
26027        let mut spec = three_member_spec();
26028        spec.politicas = MeshPolicy {
26029            rate_limit: Some(RateLimit {
26030                rate: 0,
26031                window: Duration::from_secs(1),
26032            }),
26033            ..MeshPolicy::default()
26034        };
26035        assert!(
26036            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
26037            "validate_politicas must reject rate == 0 with \
26038             PolicyRateLimitZero — the accessor and the validate gate \
26039             must route through the same substrate-primitive typed \
26040             dispatch on the :rate-limit zero-floor arm",
26041        );
26042        spec.politicas = MeshPolicy {
26043            rate_limit: Some(RateLimit {
26044                rate: 1,
26045                window: Duration::from_secs(1),
26046            }),
26047            ..MeshPolicy::default()
26048        };
26049        assert!(
26050            spec.validate().is_ok(),
26051            "validate_politicas must accept rate == 1 (the canonical \
26052             lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
26053             set) with a canonical 1s window",
26054        );
26055    }
26056
26057    #[test]
26058    fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
26059        // The canonical per-`:politicas` `:circuit-breaker` Envoy-
26060        // `outlier_detection`-mesh consecutive-failure-ejection scalar
26061        // pin: [`MeshPolicy::circuit_breaker`] must return the
26062        // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
26063        // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
26064        // raw field access across every representative value in the
26065        // accept-set — `None` (cluster default applies — no
26066        // per-Aplicacao breaker declaration, the gateway-class per-
26067        // listener default arm the future caixa-mesh
26068        // `outlier_detection_overlay` emitter documents),
26069        // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
26070        // (the lower boundary of the accept-set the surrounding
26071        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
26072        // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
26073        // refusals),
26074        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
26075        // (the upper boundary the same gate carves out on the sibling
26076        // `PolicyBreakerMaxFailuresExceedsCap` /
26077        // `PolicyBreakerWindowExceedsCap` refusals),
26078        // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
26079        // (a past-the-guard sentinel that pins the accessor doesn't
26080        // perform a silent bounds-collapse into `None` on the
26081        // zero-failures/zero-window arm — validate rejects zero but
26082        // the accessor must ship the raw slot verbatim so a validate-
26083        // time gate regression surfaces at the emit boundary rather
26084        // than being silently absorbed), and
26085        // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
26086        // (a past-the-guard sentinel that pins the accessor doesn't
26087        // perform a silent bounds-collapse at the return path).
26088        //
26089        // Second `Option<Copy-composite-T>`-return accessor pin on the
26090        // M3 mesh-slot family (peer of the sibling per-`:politicas`
26091        // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
26092        // composite-Copy accessor pin, and of the sibling per-
26093        // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
26094        // [`MeshPolicy::retries`] bdfb399 /
26095        // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
26096        // accessor pins). Pins against a future silent detour that
26097        // re-derived the breaker declaration from a peer axis (an
26098        // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
26099        // collapse that read the rate-limit's bucket capacity + refill
26100        // period as a breaker declaration), a `None → Some(default())`
26101        // cluster-default projection (which would silently re-
26102        // introduce the `PolicyBreakerZeroFailures` /
26103        // `PolicyBreakerZeroWindow` refusal cases at the emit
26104        // boundary), a bounds-collapsing accessor that clamped
26105        // `cb.max_failures` through
26106        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
26107        // through [`POLICY_BREAKER_WINDOW_MAX`] (the
26108        // [`AplicacaoSpec::validate`] gate owns the bounds; the
26109        // accessor must ship the raw slot verbatim), or a
26110        // by-reference detour (`Option<&CircuitBreaker>`) that broke
26111        // every downstream consumer keying off `Option<CircuitBreaker>`
26112        // by-copy.
26113        for cb in [
26114            None,
26115            Some(CircuitBreaker {
26116                max_failures: 1,
26117                window: Duration::from_millis(1),
26118            }),
26119            Some(CircuitBreaker {
26120                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
26121                window: POLICY_BREAKER_WINDOW_MAX,
26122            }),
26123            Some(CircuitBreaker {
26124                max_failures: 0,
26125                window: Duration::ZERO,
26126            }),
26127            Some(CircuitBreaker {
26128                max_failures: u32::MAX,
26129                window: Duration::MAX,
26130            }),
26131        ] {
26132            let p = MeshPolicy {
26133                circuit_breaker: cb,
26134                ..MeshPolicy::default()
26135            };
26136            assert_eq!(
26137                p.circuit_breaker(),
26138                cb,
26139                "MeshPolicy::circuit_breaker must return :politicas \
26140                 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
26141                p.circuit_breaker(),
26142            );
26143            assert_eq!(
26144                p.circuit_breaker(),
26145                p.circuit_breaker,
26146                "MeshPolicy::circuit_breaker must byte-equal the raw \
26147                 .circuit_breaker field access across every value in \
26148                 the accept-set",
26149            );
26150        }
26151    }
26152
26153    #[test]
26154    fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
26155        // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
26156        // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
26157        // `.circuit_breaker` field access. Structurally: toggling ONLY
26158        // the `circuit_breaker` slot on an otherwise-default MeshPolicy
26159        // must flip `is_empty()` from `true` (all-`None`) to `false`
26160        // (one axis carries a value); the flip must be observed for
26161        // every representative value in the accept-set the surrounding
26162        // [`AplicacaoSpec::validate_politicas`] gate accepts
26163        // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
26164        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
26165        // since the emptiness semantic reads "any axis carries a
26166        // value" — not "any axis carries a value the validate gate
26167        // accepts" — the same non-collapsing shape the peer M2
26168        // [`crate::LimitsSpec::is_empty`] /
26169        // [`crate::BehaviorSpec::is_empty`] predicates carry.
26170        //
26171        // Pins against a future silent detour that re-derived the
26172        // emptiness predicate off a peer axis (an accidental
26173        // `.rate_limit.is_none()`-only chain that dropped the
26174        // `circuit_breaker` arm entirely — the last unlifted inline
26175        // field access on `is_empty` before this lift), a
26176        // `circuit_breaker == Some(_)` collapse that key-off a
26177        // validate-gate-clamped bounds check (which would silently
26178        // classify a past-the-guard `Some(CircuitBreaker { max_failures:
26179        // 0, window: 0s })` as empty because it fails the value-shape
26180        // gate), or an accessor-side detour that no longer names the
26181        // substrate-primitive typed dispatch.
26182        //
26183        // Fifth "the emptiness predicate must route through the
26184        // substrate-primitive typed dispatch" composition pin on the
26185        // M3 mesh-slot family — closes the last unlifted composition
26186        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
26187        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
26188        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
26189        // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
26190        // composition pins on the sibling primitive-Copy + composite-
26191        // Copy axes, extended onto the peer per-`:politicas`
26192        // composite-Copy `Option<CircuitBreaker>` axis).
26193        let empty = MeshPolicy::default();
26194        assert!(
26195            empty.is_empty(),
26196            "MeshPolicy::default() must be is_empty() — every axis \
26197             defaults to None",
26198        );
26199        for cb in [
26200            CircuitBreaker {
26201                max_failures: 1,
26202                window: Duration::from_millis(1),
26203            },
26204            CircuitBreaker {
26205                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
26206                window: POLICY_BREAKER_WINDOW_MAX,
26207            },
26208        ] {
26209            let p = MeshPolicy {
26210                circuit_breaker: Some(cb),
26211                ..MeshPolicy::default()
26212            };
26213            assert!(
26214                !p.is_empty(),
26215                "MeshPolicy::is_empty must return false when \
26216                 :circuit-breaker is {cb:?} — the emptiness predicate \
26217                 reads \"any axis carries a value\", not \"any axis \
26218                 carries a value the validate gate accepts\"",
26219            );
26220            assert_eq!(
26221                p.circuit_breaker().is_none(),
26222                p.is_empty(),
26223                "when :circuit-breaker is the only set axis, \
26224                 is_empty() must equal circuit_breaker().is_none() — \
26225                 the accessor and the emptiness predicate must route \
26226                 through the same substrate-primitive typed dispatch \
26227                 on the :circuit-breaker arm",
26228            );
26229        }
26230    }
26231
26232    #[test]
26233    fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
26234        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26235        // `:circuit-breaker` value-shape gate must key off
26236        // [`MeshPolicy::circuit_breaker`], not the raw
26237        // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
26238        // whose only set axis is a `Some(CircuitBreaker { max_failures:
26239        // 0, .. })` must surface the `PolicyBreakerZeroFailures`
26240        // refusal exactly, and the same MeshPolicy with the breaker at
26241        // the canonical lower boundary
26242        // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
26243        // pass validate. The pair jointly pins the accessor +
26244        // validate-gate composition: any future silent detour that had
26245        // the accessor omit the `Some(CircuitBreaker { max_failures:
26246        // 0, .. })` arm (a
26247        // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
26248        // collapse) would silently absorb the
26249        // `PolicyBreakerZeroFailures` refusal at the accessor
26250        // boundary — the composition pin catches that at caixa-core
26251        // build time.
26252        //
26253        // Sibling of the peer [`validate_politicas`]
26254        // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
26255        // composition pins on the sibling primitive-Copy + composite-
26256        // Copy optional-scalar axes — same "the validate / shape-gate
26257        // predicate must route through the substrate-primitive typed
26258        // dispatch" discipline extended onto the peer per-`:politicas`
26259        // composite-Copy `Option<CircuitBreaker>` axis. Second
26260        // composition-with-accessor pin on the M3 mesh-slot
26261        // `Option<CircuitBreaker>` arm alongside the
26262        // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
26263        let mut spec = three_member_spec();
26264        spec.politicas = MeshPolicy {
26265            circuit_breaker: Some(CircuitBreaker {
26266                max_failures: 0,
26267                window: Duration::from_millis(1),
26268            }),
26269            ..MeshPolicy::default()
26270        };
26271        assert!(
26272            matches!(
26273                spec.validate(),
26274                Err(AplicacaoError::PolicyBreakerZeroFailures)
26275            ),
26276            "validate_politicas must reject max_failures == 0 with \
26277             PolicyBreakerZeroFailures — the accessor and the validate \
26278             gate must route through the same substrate-primitive \
26279             typed dispatch on the :circuit-breaker zero-floor arm",
26280        );
26281        spec.politicas = MeshPolicy {
26282            circuit_breaker: Some(CircuitBreaker {
26283                max_failures: 1,
26284                window: Duration::from_millis(1),
26285            }),
26286            ..MeshPolicy::default()
26287        };
26288        assert!(
26289            spec.validate().is_ok(),
26290            "validate_politicas must accept a CircuitBreaker at the \
26291             canonical lower boundary (max_failures = 1, window = \
26292             1ms) — the accessor and the validate gate must route \
26293             through the same substrate-primitive typed dispatch on \
26294             the :circuit-breaker arm",
26295        );
26296    }
26297
26298    #[test]
26299    fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
26300        // The canonical per-`:politicas :circuit-breaker` `:max-failures`
26301        // Envoy-outlier-detection trip-threshold scalar pin:
26302        // [`CircuitBreaker::max_failures`] must return the
26303        // `:politicas :circuit-breaker :max-failures` typed `u32`
26304        // verbatim, byte-equal to the raw field access across every
26305        // representative value in the accept-set — `1` (the lower
26306        // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
26307        // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
26308        // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
26309        // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
26310        // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
26311        // refusal), `0` (a past-the-guard sentinel that pins the accessor
26312        // doesn't perform a silent bounds-collapse into `1` on the zero
26313        // arm — validate rejects zero but the accessor must ship the
26314        // raw slot verbatim so a validate-time gate regression surfaces
26315        // at the emit boundary rather than being silently absorbed),
26316        // `u32::MAX` (a past-the-guard sentinel that pins the accessor
26317        // doesn't perform a silent bounds-collapse through
26318        // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
26319        //
26320        // First sub-struct required-scalar accessor pin on the M3
26321        // mesh-slot family — sibling in shape to the peer per-`:membros`
26322        // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
26323        // (a40b0e3) required-`String`-carry accessor pins and the peer
26324        // per-`:contratos` [`WitContract::source`] /
26325        // [`WitContract::destination`] (7f0fd43) required-`String`-carry
26326        // accessor pins, extended onto the peer per-`CircuitBreaker`
26327        // required-`u32` scalar-value axis. Pins against a future silent
26328        // detour that re-derived the trip threshold from a peer axis (an
26329        // accidental `self.window.as_secs() as u32` collapse that read
26330        // the breaker's rolling-window duration as a failure count), a
26331        // `0 → 1` cluster-default projection (which would silently absorb
26332        // the `PolicyBreakerZeroFailures` refusal case at the accessor
26333        // boundary), or a bounds-collapsing accessor that clamped the
26334        // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
26335        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
26336        // must ship the raw slot verbatim).
26337        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
26338            let cb = CircuitBreaker {
26339                max_failures,
26340                window: Duration::from_secs(60),
26341            };
26342            assert_eq!(
26343                cb.max_failures(),
26344                max_failures,
26345                "CircuitBreaker::max_failures must return :politicas \
26346                 :circuit-breaker :max-failures verbatim (got {}, \
26347                 expected {max_failures})",
26348                cb.max_failures(),
26349            );
26350            assert_eq!(
26351                cb.max_failures(),
26352                cb.max_failures,
26353                "CircuitBreaker::max_failures must byte-equal the raw \
26354                 .max_failures field access across every value in the \
26355                 u32 accept-set",
26356            );
26357        }
26358    }
26359
26360    #[test]
26361    fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
26362        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26363        // `:circuit-breaker :max-failures` zero-floor arm must key off
26364        // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
26365        // field access. Structurally: a `CircuitBreaker { max_failures:
26366        // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
26367        // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
26368        // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
26369        // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
26370        // pass validate. The pair jointly pins the accessor +
26371        // validate-gate composition: any future silent detour that had
26372        // the accessor return a fresh `1` on the zero arm (a
26373        // `.max_failures().max(1)` collapse) would silently absorb the
26374        // `PolicyBreakerZeroFailures` refusal at the accessor boundary
26375        // and the validate gate would accept a struct-literal
26376        // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
26377        // catches that at caixa-core build time.
26378        //
26379        // Peer of the sibling per-`:politicas`
26380        // [`MeshPolicy::mtls_required`] (c0110f1) /
26381        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
26382        // (7073d0f) accessor-composition pins on the sibling optional-
26383        // scalar axes — same "the validate / shape-gate predicate must
26384        // route through the substrate-primitive typed dispatch"
26385        // discipline extended onto the peer per-`CircuitBreaker`
26386        // required-scalar composition axis.
26387        let mut spec = three_member_spec();
26388        spec.politicas = MeshPolicy {
26389            circuit_breaker: Some(CircuitBreaker {
26390                max_failures: 0,
26391                window: Duration::from_secs(60),
26392            }),
26393            ..MeshPolicy::default()
26394        };
26395        assert!(
26396            matches!(
26397                spec.validate(),
26398                Err(AplicacaoError::PolicyBreakerZeroFailures)
26399            ),
26400            "validate_politicas must reject max_failures == 0 with \
26401             PolicyBreakerZeroFailures — the accessor and the validate \
26402             gate must route through the same substrate-primitive typed \
26403             dispatch on the :max-failures zero-floor arm",
26404        );
26405        spec.politicas = MeshPolicy {
26406            circuit_breaker: Some(CircuitBreaker {
26407                max_failures: 1,
26408                window: Duration::from_secs(60),
26409            }),
26410            ..MeshPolicy::default()
26411        };
26412        assert!(
26413            spec.validate().is_ok(),
26414            "validate_politicas must accept max_failures == 1 (the \
26415             lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
26416             accept-set)",
26417        );
26418    }
26419
26420    #[test]
26421    fn circuit_breaker_max_failures_projects_u32_by_copy() {
26422        // The by-copy pin: [`CircuitBreaker::max_failures`] returns
26423        // `u32` by copy — `u32` is `Copy` and the accessor must return
26424        // by value, not by reference. Peer of the sibling
26425        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
26426        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
26427        // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
26428        // optional-scalar axes, extended onto the peer
26429        // per-`CircuitBreaker` required-`u32` copy-invariant shape —
26430        // the accessor's returned `u32` must outlive `&self` (multiple
26431        // calls must return equal values from a dropped-`&self` copy,
26432        // since the returned scalar carries no borrow), and calling
26433        // the accessor twice on the same CircuitBreaker must yield the
26434        // same `u32` verbatim (idempotent, no side effects on `&self`).
26435        //
26436        // Pins against a future silent detour that returned `&u32`
26437        // (which would type-check but silently break every downstream
26438        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
26439        // first parameter is `u32`, and `&u32` would fold to a detached
26440        // copy at the call site with a `*` deref the sibling accessors
26441        // don't need), an accidental `.max_failures.wrapping_add(0)`
26442        // detour that returned a fresh copy through an arithmetic
26443        // no-op (breaking a future `const fn` regression), or a
26444        // one-arm-only accessor that returned a saturating value on
26445        // some sentinel input (breaking the pass-through invariant the
26446        // sibling required-scalar accessors carry).
26447        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
26448            let cb = CircuitBreaker {
26449                max_failures,
26450                window: Duration::from_secs(60),
26451            };
26452            let first = cb.max_failures();
26453            let second = cb.max_failures();
26454            assert_eq!(
26455                first, second,
26456                "CircuitBreaker::max_failures must be idempotent — two \
26457                 successive calls on the same &self must return the \
26458                 same u32",
26459            );
26460            assert_eq!(
26461                first, max_failures,
26462                "CircuitBreaker::max_failures must return :politicas \
26463                 :circuit-breaker :max-failures verbatim by copy — \
26464                 got {first}, expected {max_failures}",
26465            );
26466        }
26467    }
26468
26469    #[test]
26470    fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
26471        // The canonical per-`:politicas :circuit-breaker` `:window`
26472        // Envoy-outlier-detection rolling-observation-interval scalar
26473        // pin: [`CircuitBreaker::window`] must return the
26474        // `:politicas :circuit-breaker :window` typed `Duration`
26475        // verbatim, byte-equal to the raw field access across every
26476        // representative value in the accept-set — `Duration::from_millis(1)`
26477        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
26478        // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
26479        // gate carves out on the sibling `PolicyBreakerZeroWindow`
26480        // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
26481        // same gate carves out on the sibling
26482        // `PolicyBreakerWindowExceedsCap` refusal),
26483        // `Duration::ZERO` (a past-the-guard sentinel that pins the
26484        // accessor doesn't perform a silent bounds-collapse into
26485        // `Duration::from_millis(1)` on the zero arm — validate rejects
26486        // zero but the accessor must ship the raw slot verbatim so a
26487        // validate-time gate regression surfaces at the emit boundary
26488        // rather than being silently absorbed),
26489        // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
26490        // far above the 1h cap — that pins the accessor doesn't perform
26491        // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
26492        // at the return path).
26493        //
26494        // Second sub-struct required-scalar accessor pin on the M3
26495        // mesh-slot family — sibling in shape to the just-landed
26496        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
26497        // (3a74062) required-`u32` accessor pin on the peer
26498        // per-`CircuitBreaker` required-axis, extended onto the
26499        // per-sub-struct required-`Duration` axis. Pins against a
26500        // future silent detour that re-derived the observation window
26501        // from a peer axis (an accidental
26502        // `Duration::from_secs(self.max_failures as u64)` collapse that
26503        // read the breaker's trip count as an observation-interval
26504        // duration), a `Duration::ZERO → Duration::from_millis(1)`
26505        // cluster-default projection (which would silently absorb the
26506        // `PolicyBreakerZeroWindow` refusal case at the accessor
26507        // boundary), or a bounds-collapsing accessor that clamped the
26508        // return through `POLICY_BREAKER_WINDOW_MAX` (the
26509        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
26510        // must ship the raw slot verbatim).
26511        for window in [
26512            Duration::from_millis(1),
26513            POLICY_BREAKER_WINDOW_MAX,
26514            Duration::ZERO,
26515            Duration::from_secs(86_400),
26516        ] {
26517            let cb = CircuitBreaker {
26518                max_failures: 5,
26519                window,
26520            };
26521            assert_eq!(
26522                cb.window(),
26523                window,
26524                "CircuitBreaker::window must return :politicas \
26525                 :circuit-breaker :window verbatim (got {:?}, \
26526                 expected {window:?})",
26527                cb.window(),
26528            );
26529            assert_eq!(
26530                cb.window(),
26531                cb.window,
26532                "CircuitBreaker::window must byte-equal the raw \
26533                 .window field access across every value in the \
26534                 Duration accept-set",
26535            );
26536        }
26537    }
26538
26539    #[test]
26540    fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
26541        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26542        // `:circuit-breaker :window` zero-floor arm must key off
26543        // [`CircuitBreaker::window`], not the raw `.window` field
26544        // access. Structurally: a `CircuitBreaker { window:
26545        // Duration::ZERO, .. }` embedded in a
26546        // `:politicas :circuit-breaker` slot must surface the
26547        // `PolicyBreakerZeroWindow` refusal exactly, and a
26548        // `CircuitBreaker { window: Duration::from_millis(1), .. }`
26549        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
26550        // accept-set) must pass validate. The pair jointly pins the
26551        // accessor + validate-gate composition: any future silent
26552        // detour that had the accessor return a fresh
26553        // `Duration::from_millis(1)` on the zero arm (a
26554        // `.window().max(Duration::from_millis(1))` collapse) would
26555        // silently absorb the `PolicyBreakerZeroWindow` refusal at the
26556        // accessor boundary and the validate gate would accept a
26557        // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
26558        // — the composition pin catches that at caixa-core build time.
26559        //
26560        // Peer of the sibling per-`CircuitBreaker`
26561        // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
26562        // pin on the peer required-scalar `:max-failures` axis — same
26563        // "the validate / shape-gate predicate must route through the
26564        // substrate-primitive typed dispatch" discipline extended onto
26565        // the peer per-`CircuitBreaker` required-`Duration` composition
26566        // axis.
26567        let mut spec = three_member_spec();
26568        spec.politicas = MeshPolicy {
26569            circuit_breaker: Some(CircuitBreaker {
26570                max_failures: 5,
26571                window: Duration::ZERO,
26572            }),
26573            ..MeshPolicy::default()
26574        };
26575        assert!(
26576            matches!(
26577                spec.validate(),
26578                Err(AplicacaoError::PolicyBreakerZeroWindow)
26579            ),
26580            "validate_politicas must reject window == Duration::ZERO \
26581             with PolicyBreakerZeroWindow — the accessor and the \
26582             validate gate must route through the same substrate-\
26583             primitive typed dispatch on the :window zero-floor arm",
26584        );
26585        spec.politicas = MeshPolicy {
26586            circuit_breaker: Some(CircuitBreaker {
26587                max_failures: 5,
26588                window: Duration::from_millis(1),
26589            }),
26590            ..MeshPolicy::default()
26591        };
26592        assert!(
26593            spec.validate().is_ok(),
26594            "validate_politicas must accept window == \
26595             Duration::from_millis(1) (the lower boundary of the \
26596             1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
26597        );
26598    }
26599
26600    #[test]
26601    fn circuit_breaker_window_projects_duration_by_copy() {
26602        // The by-copy pin: [`CircuitBreaker::window`] returns
26603        // `Duration` by copy — `Duration` is `Copy` and the accessor
26604        // must return by value, not by reference. Peer of the sibling
26605        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
26606        // (3a74062) by-copy pin on the peer required-scalar
26607        // `:max-failures` axis, extended onto the peer
26608        // per-`CircuitBreaker` required-`Duration` copy-invariant shape
26609        // — the accessor's returned `Duration` must outlive `&self`
26610        // (multiple calls must return equal values from a
26611        // dropped-`&self` copy, since the returned scalar carries no
26612        // borrow), and calling the accessor twice on the same
26613        // CircuitBreaker must yield the same `Duration` verbatim
26614        // (idempotent, no side effects on `&self`).
26615        //
26616        // Pins against a future silent detour that returned
26617        // `&Duration` (which would type-check but silently break every
26618        // downstream `Duration`-by-value consumer —
26619        // [`crate::render::require_positive_canonical_bounded_duration`]'s
26620        // first parameter is `Duration`, and `&Duration` would fold to
26621        // a detached copy at the call site with a `*` deref the sibling
26622        // accessors don't need), an accidental `.window + Duration::ZERO`
26623        // detour that returned a fresh copy through an arithmetic
26624        // no-op (breaking a future `const fn` regression), or a
26625        // one-arm-only accessor that returned a saturating value on
26626        // some sentinel input (breaking the pass-through invariant the
26627        // sibling required-scalar accessors carry).
26628        for window in [
26629            Duration::from_millis(1),
26630            POLICY_BREAKER_WINDOW_MAX,
26631            Duration::ZERO,
26632            Duration::from_secs(86_400),
26633        ] {
26634            let cb = CircuitBreaker {
26635                max_failures: 5,
26636                window,
26637            };
26638            let first = cb.window();
26639            let second = cb.window();
26640            assert_eq!(
26641                first, second,
26642                "CircuitBreaker::window must be idempotent — two \
26643                 successive calls on the same &self must return the \
26644                 same Duration",
26645            );
26646            assert_eq!(
26647                first, window,
26648                "CircuitBreaker::window must return :politicas \
26649                 :circuit-breaker :window verbatim by copy — \
26650                 got {first:?}, expected {window:?}",
26651            );
26652        }
26653    }
26654
26655    #[test]
26656    fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
26657        // Apex-identity pair-invariant pin composing both substrate-
26658        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
26659        // and [`WitContract::destination`] — at the emit-side call shape
26660        // every per-`(:de, :para)` CNP L4 port reader now takes. The
26661        // invariant, evaluated per-edge:
26662        //
26663        //   spec.port_for_destination(c.destination()) == expected_port
26664        //
26665        // where `expected_port` is `entrada.port` when
26666        // `c.destination() == entrada.destination()` and
26667        // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
26668        // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
26669        // pin on the per-`:entrada` axis — that pin encodes the apex
26670        // ingress L4 identity via `entrada.destination()`; this pin
26671        // encodes the per-edge L4 identity via `c.destination()`, and
26672        // both compose on the same substrate-primitive resolver so a
26673        // future refactor that silently split either accessor's apex
26674        // behavior surfaces at caixa-core build time.
26675        let mut spec = three_member_spec();
26676        if let Some(e) = spec.entrada.as_mut() {
26677            e.para = "cart".into();
26678            e.port = 8443;
26679        }
26680        let apex_contract = WitContract {
26681            de: "checkout".into(),
26682            para: "cart".into(),
26683            wit: "wasi:http/proxy".into(),
26684            endpoint: Some("/hello".into()),
26685            subject: None,
26686            slot: None,
26687        };
26688        assert_eq!(
26689            spec.port_for_destination(apex_contract.destination()),
26690            8443,
26691            "`spec.port_for_destination(c.destination())` must equal \
26692             `entrada.port` when the contract callee names the ingress \
26693             apex — the CNP per-edge L4 port and the HTTPRoute apex \
26694             backendRef port share this substrate-primitive resolver.",
26695        );
26696        let non_apex_contract = WitContract {
26697            de: "cart".into(),
26698            para: "payment".into(),
26699            wit: "wasi:http/proxy".into(),
26700            endpoint: Some("/charge".into()),
26701            subject: None,
26702            slot: None,
26703        };
26704        assert_eq!(
26705            spec.port_for_destination(non_apex_contract.destination()),
26706            DEFAULT_SERVICO_PORT,
26707            "`spec.port_for_destination(c.destination())` must fall back \
26708             to the substrate-canonical port floor when the contract \
26709             callee is not the ingress apex — the resolver's non-apex \
26710             arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
26711        );
26712    }
26713
26714    #[test]
26715    fn membro_key_consts_are_lower_camel_case_shape() {
26716        // Shape-pin: every `MEMBRO_KEY_*` const must be a
26717        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26718        // `kebab-case` hyphens, no leading colon, no `PascalCase`
26719        // leading capital, no whitespace / dots) — the canonical shape
26720        // the `#[serde(rename_all = "camelCase")]` derive produces on
26721        // [`Membro`]. A future flip to a non-camelCase attribute at
26722        // the derive surfaces both here (this test fails on the
26723        // stale-constant shape) and at
26724        // `membro_serde_keys_match_lifted_membro_key_consts` (that test
26725        // fails on the mismatch between const and derive). Peer with
26726        // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
26727        // on the sibling `SupervisorSpec` top-level axis.
26728        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
26729            assert!(
26730                !key.is_empty(),
26731                "MEMBRO_KEY_* must be non-empty (got {key:?})"
26732            );
26733            let first = key.chars().next().unwrap();
26734            assert!(
26735                first.is_ascii_lowercase(),
26736                "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
26737                 (got {key:?}, leads with {first:?})",
26738            );
26739            assert!(
26740                key.chars().all(|c| c.is_ascii_alphanumeric()),
26741                "MEMBRO_KEY_* must be ASCII-alphanumeric only \
26742                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26743            );
26744        }
26745    }
26746
26747    // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
26748
26749    #[test]
26750    fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
26751        // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
26752        // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
26753        // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
26754        // keys the `#[serde(rename_all = "camelCase")]` attribute on
26755        // [`WitContract`] emits for the required-triad. The three
26756        // sibling payload-arm keys already pin under
26757        // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
26758        // `STORE_FIELD_NAME` — pin all six alongside so a future
26759        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
26760        // verbatim-field-name flip at the derive attribute (any of which
26761        // would silently break every downstream JSON consumer that
26762        // reaches for one of the six via `Value::get(...)`) surfaces
26763        // here as a build-time test failure at `aplicacao.rs`, not as an
26764        // apply-time `.get(<stale-canonical-const>)` returning `None`
26765        // far from the derive-attr drift's commit. Peer with the sibling
26766        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
26767        // pin on the M3 `:membros` per-entry axis — same discipline the
26768        // `Membro` per-entry lift established, extended here to the
26769        // sibling M3 `WitContract` per-`:contratos` entry axis, the last
26770        // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
26771        // axis on the Aplicacao surface without a lifted serde-key peer.
26772        let c = WitContract {
26773            de: "cart".into(),
26774            para: "catalog".into(),
26775            wit: "wasi:http/proxy".into(),
26776            endpoint: Some("/lookup".into()),
26777            subject: None,
26778            slot: None,
26779        };
26780        let json = serde_json::to_string(&c).unwrap();
26781        for key in [
26782            crate::CONTRATO_KEY_DE,
26783            crate::CONTRATO_KEY_PARA,
26784            crate::CONTRATO_KEY_WIT,
26785            WitTarget::HTTP_FIELD_NAME,
26786        ] {
26787            let quoted = format!("\"{key}\"");
26788            assert!(
26789                json.contains(&quoted),
26790                "serialized WitContract must carry the lifted \
26791                 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
26792                 {quoted} verbatim in the JSON emission (got: {json})",
26793            );
26794        }
26795
26796        // Pin the two remaining payload-arm keys by round-tripping a
26797        // `WitContract` under each payload-shape (pub-sub, store) — the
26798        // required-triad appears on every emission but the payload arms
26799        // only surface when their `Option<String>` field is `Some`.
26800        let pubsub = WitContract {
26801            de: "cart".into(),
26802            para: "events".into(),
26803            wit: "nats:pub-sub".into(),
26804            endpoint: None,
26805            subject: Some("orders.placed".into()),
26806            slot: None,
26807        };
26808        let pubsub_json = serde_json::to_string(&pubsub).unwrap();
26809        let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
26810        assert!(
26811            pubsub_json.contains(&pubsub_quoted),
26812            "serialized pub-sub WitContract must carry the lifted \
26813             WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
26814             verbatim in the JSON emission (got: {pubsub_json})",
26815        );
26816        let store = WitContract {
26817            de: "cart".into(),
26818            para: "sessions".into(),
26819            wit: "wasi:keyvalue/store".into(),
26820            endpoint: None,
26821            subject: None,
26822            slot: Some("cart/$id".into()),
26823        };
26824        let store_json = serde_json::to_string(&store).unwrap();
26825        let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
26826        assert!(
26827            store_json.contains(&store_quoted),
26828            "serialized store WitContract must carry the lifted \
26829             WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
26830             verbatim in the JSON emission (got: {store_json})",
26831        );
26832    }
26833
26834    #[test]
26835    fn contrato_key_consts_are_pairwise_distinct() {
26836        // Cross-axis drift-detection pin: a future collapse of the six
26837        // canonical [`WitContract`] per-entry byte-strings onto the same
26838        // value (e.g. an accidental copy-paste flip of
26839        // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
26840        // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
26841        // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
26842        // every downstream probe on one axis onto the sibling axis's
26843        // overlay entry and pass every propagation-probe test that
26844        // expected only the stale axis's value. Peer of the sibling
26845        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
26846        // widened here to the six-way axis the `WitContract`
26847        // required-triad + `WitTarget` payload-triad jointly cover.
26848        let all = [
26849            crate::CONTRATO_KEY_DE,
26850            crate::CONTRATO_KEY_PARA,
26851            crate::CONTRATO_KEY_WIT,
26852            WitTarget::HTTP_FIELD_NAME,
26853            WitTarget::PUBSUB_FIELD_NAME,
26854            WitTarget::STORE_FIELD_NAME,
26855        ];
26856        for (i, a) in all.iter().enumerate() {
26857            for b in all.iter().skip(i + 1) {
26858                assert_ne!(
26859                    a, b,
26860                    "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
26861                     must be pairwise-distinct canonical byte-sequences \
26862                     — got `{a}` == `{b}`",
26863                );
26864            }
26865        }
26866    }
26867
26868    #[test]
26869    fn contrato_key_consts_are_lower_camel_case_shape() {
26870        // Shape-pin: every `CONTRATO_KEY_*` (and every peer
26871        // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
26872        // byte-sequence (no `snake_case` underscores, no `kebab-case`
26873        // hyphens, no leading colon, no `PascalCase` leading capital, no
26874        // whitespace / dots) — the canonical shape the
26875        // `#[serde(rename_all = "camelCase")]` derive produces on
26876        // [`WitContract`]. A future flip to a non-camelCase attribute at
26877        // the derive surfaces both here (this test fails on the
26878        // stale-constant shape) and at
26879        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26880        // (that test fails on the mismatch between const and derive).
26881        // Peer with `membro_key_consts_are_lower_camel_case_shape`
26882        // (ce80ca0) on the sibling `Membro` per-entry axis.
26883        for key in [
26884            crate::CONTRATO_KEY_DE,
26885            crate::CONTRATO_KEY_PARA,
26886            crate::CONTRATO_KEY_WIT,
26887            WitTarget::HTTP_FIELD_NAME,
26888            WitTarget::PUBSUB_FIELD_NAME,
26889            WitTarget::STORE_FIELD_NAME,
26890        ] {
26891            assert!(
26892                !key.is_empty(),
26893                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
26894                 non-empty (got {key:?})"
26895            );
26896            let first = key.chars().next().unwrap();
26897            assert!(
26898                first.is_ascii_lowercase(),
26899                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
26900                 with an ASCII-lowercase byte (got {key:?}, leads with \
26901                 {first:?})",
26902            );
26903            assert!(
26904                key.chars().all(|c| c.is_ascii_alphanumeric()),
26905                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
26906                 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
26907                 whitespace (got {key:?})",
26908            );
26909        }
26910    }
26911
26912    // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
26913
26914    #[test]
26915    fn entrada_serde_keys_match_lifted_entrada_key_consts() {
26916        // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
26917        // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
26918        // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
26919        // name the exact camelCase JSON keys the
26920        // `#[serde(rename_all = "camelCase")]` attribute on
26921        // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
26922        // pin that each canonical byte-sequence appears verbatim in the
26923        // JSON — a future accidental `rename_all = "snake_case"` /
26924        // `"kebab-case"` / verbatim-field-name flip at the derive
26925        // attribute (any of which would silently break every downstream
26926        // JSON consumer that reaches for one of the four consts via
26927        // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
26928        // emitter's per-Aplicacao hostname/paths/port projection, the
26929        // future `app-operator` reconciler's per-Aplicacao ingress
26930        // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
26931        // materializer's admission-time cross-check) surfaces here as
26932        // a build-time test failure at `aplicacao.rs`, not as an
26933        // apply-time `.get(<stale-canonical-const>)` returning `None`
26934        // far from the derive-attr drift's commit. Peer with the
26935        // sibling
26936        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26937        // (ca463a4) and
26938        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
26939        // pins on the M3 collection-slot atom axes — same discipline
26940        // both collection-slot lifts established, extended here to the
26941        // singleton `:entrada` mesh-slot atom axis, the last M3
26942        // typed-struct top-level `#[serde(rename_all = "camelCase")]`
26943        // axis on the Aplicacao surface without a lifted serde-key
26944        // peer.
26945        let e = Entrada {
26946            host: "checkout.quero.cloud".into(),
26947            para: "cart".into(),
26948            paths: vec!["/cart".into()],
26949            port: 8080,
26950        };
26951        let json = serde_json::to_string(&e).unwrap();
26952        for key in [
26953            crate::ENTRADA_KEY_HOST,
26954            crate::ENTRADA_KEY_PARA,
26955            crate::ENTRADA_KEY_PATHS,
26956            crate::ENTRADA_KEY_PORT,
26957        ] {
26958            let quoted = format!("\"{key}\"");
26959            assert!(
26960                json.contains(&quoted),
26961                "serialized Entrada must carry the lifted ENTRADA_KEY_* \
26962                 byte-sequence {quoted} verbatim in the JSON emission \
26963                 (got: {json})",
26964            );
26965        }
26966    }
26967
26968    #[test]
26969    fn entrada_key_consts_are_pairwise_distinct() {
26970        // Cross-axis drift-detection pin: a future collapse of the four
26971        // canonical [`Entrada`] singleton byte-strings onto the same
26972        // value (e.g. an accidental copy-paste flip of
26973        // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
26974        // silently reroute every downstream probe on one axis onto the
26975        // sibling axis's overlay entry and pass every propagation-probe
26976        // test that expected only the stale axis's value — the
26977        // Gateway/HTTPRoute emitter would read the hostname string
26978        // where the destination-Servico name was expected (or vice
26979        // versa), the admission-webhook cross-check would compare the
26980        // wrong pair of values, and the resulting Gateway resource
26981        // would either be admitted with garbage or rejected at the
26982        // controller far from the rebrand commit's source. Peer of the
26983        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
26984        // tetrad (40cc4e5), the two-way distinct pin on the
26985        // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
26986        // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
26987        // triad (ca463a4).
26988        let all = [
26989            crate::ENTRADA_KEY_HOST,
26990            crate::ENTRADA_KEY_PARA,
26991            crate::ENTRADA_KEY_PATHS,
26992            crate::ENTRADA_KEY_PORT,
26993        ];
26994        for (i, a) in all.iter().enumerate() {
26995            for b in all.iter().skip(i + 1) {
26996                assert_ne!(
26997                    a, b,
26998                    "ENTRADA_KEY_* consts must be pairwise-distinct \
26999                     canonical byte-sequences — got `{a}` == `{b}`",
27000                );
27001            }
27002        }
27003    }
27004
27005    #[test]
27006    fn entrada_key_consts_are_lower_camel_case_shape() {
27007        // Shape-pin: every `ENTRADA_KEY_*` const must be a
27008        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
27009        // `kebab-case` hyphens, no leading colon, no `PascalCase`
27010        // leading capital, no whitespace / dots) — the canonical shape
27011        // the `#[serde(rename_all = "camelCase")]` derive produces on
27012        // [`Entrada`]. A future flip to a non-camelCase attribute at
27013        // the derive surfaces both here (this test fails on the
27014        // stale-constant shape) and at
27015        // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
27016        // test fails on the mismatch between const and derive). Peer
27017        // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
27018        // and `contrato_key_consts_are_lower_camel_case_shape`
27019        // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
27020        // entry axes.
27021        for key in [
27022            crate::ENTRADA_KEY_HOST,
27023            crate::ENTRADA_KEY_PARA,
27024            crate::ENTRADA_KEY_PATHS,
27025            crate::ENTRADA_KEY_PORT,
27026        ] {
27027            assert!(
27028                !key.is_empty(),
27029                "ENTRADA_KEY_* must be non-empty (got {key:?})"
27030            );
27031            let first = key.chars().next().unwrap();
27032            assert!(
27033                first.is_ascii_lowercase(),
27034                "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
27035                 (got {key:?}, leads with {first:?})",
27036            );
27037            assert!(
27038                key.chars().all(|c| c.is_ascii_alphanumeric()),
27039                "ENTRADA_KEY_* must be ASCII-alphanumeric only \
27040                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
27041            );
27042        }
27043    }
27044
27045    // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
27046
27047    #[test]
27048    fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
27049        // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
27050        // ([`crate::POLITICAS_KEY_TIMEOUT`] /
27051        // [`crate::POLITICAS_KEY_RETRIES`] /
27052        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
27053        // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
27054        // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
27055        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
27056        // on [`MeshPolicy`] emits. Three of the five axes
27057        // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
27058        // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
27059        // camelCase transforms — the derive-attribute is load-bearing
27060        // on those, unlike the sibling `Entrada` / `Membro` /
27061        // `WitContract` structs whose fields are all lowercase-single-
27062        // word and where the derive is a no-op on every axis.
27063        // Serialize a fully-populated [`MeshPolicy`] (every axis
27064        // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
27065        // on none of the five slots) and pin that each canonical
27066        // byte-sequence appears verbatim in the JSON — a future
27067        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
27068        // verbatim-field-name flip at the derive attribute (any of
27069        // which would silently break every downstream JSON consumer
27070        // that reaches for one of the five consts via
27071        // `Value::get(...)` — the future M4 per-edge `:politicas`
27072        // overlay projection onto Cilium `L7Rules` and Gateway API
27073        // `HTTPRoute` backend timeouts, the future
27074        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
27075        // admission-time mesh-policy cross-check, the future
27076        // `feira lint` per-`:politicas` bound-check gate) surfaces here
27077        // as a build-time test failure at `aplicacao.rs`, not as an
27078        // apply-time `.get(<stale-canonical-const>)` returning `None`
27079        // far from the derive-attr drift's commit. Peer with the
27080        // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
27081        // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
27082        // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
27083        // (ce80ca0) pins on the M3 collection-slot / singleton-slot
27084        // atom axes — same discipline every M3 sibling lift
27085        // established, extended here to the singleton `:politicas`
27086        // mesh-slot atom axis, closing the last M3 typed-struct
27087        // top-level `#[serde(rename_all = "camelCase")]` axis on the
27088        // Aplicacao surface without a lifted serde-key peer.
27089        let p = MeshPolicy {
27090            timeout: Some(Duration::from_secs(30)),
27091            retries: Some(3),
27092            circuit_breaker: Some(CircuitBreaker {
27093                max_failures: 5,
27094                window: Duration::from_secs(60),
27095            }),
27096            mtls_required: Some(true),
27097            rate_limit: Some(RateLimit {
27098                rate: 100,
27099                window: Duration::from_secs(1),
27100            }),
27101        };
27102        let json = serde_json::to_string(&p).unwrap();
27103        for key in [
27104            crate::POLITICAS_KEY_TIMEOUT,
27105            crate::POLITICAS_KEY_RETRIES,
27106            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
27107            crate::POLITICAS_KEY_MTLS_REQUIRED,
27108            crate::POLITICAS_KEY_RATE_LIMIT,
27109        ] {
27110            let quoted = format!("\"{key}\"");
27111            assert!(
27112                json.contains(&quoted),
27113                "serialized MeshPolicy must carry the lifted \
27114                 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
27115                 JSON emission (got: {json})",
27116            );
27117        }
27118    }
27119
27120    #[test]
27121    fn politicas_key_consts_are_pairwise_distinct() {
27122        // Cross-axis drift-detection pin: a future collapse of the five
27123        // canonical [`MeshPolicy`] singleton byte-strings onto the same
27124        // value (e.g. an accidental copy-paste flip of
27125        // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
27126        // would silently reroute every downstream probe on one axis
27127        // onto the sibling axis's overlay entry and pass every
27128        // propagation-probe test that expected only the stale axis's
27129        // value — the M4 per-edge `:politicas` overlay projection would
27130        // read the retry-count string where the timeout duration was
27131        // expected (or vice versa), the CR materializer's admission
27132        // cross-check would compare the wrong pair of values, and the
27133        // resulting mesh reconciler would either bind the wrong axis
27134        // or reject the resource at reconcile far from the rebrand
27135        // commit's source. Peer of the sibling four-way distinct pin
27136        // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
27137        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
27138        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
27139        // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
27140        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
27141        let all = [
27142            crate::POLITICAS_KEY_TIMEOUT,
27143            crate::POLITICAS_KEY_RETRIES,
27144            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
27145            crate::POLITICAS_KEY_MTLS_REQUIRED,
27146            crate::POLITICAS_KEY_RATE_LIMIT,
27147        ];
27148        for (i, a) in all.iter().enumerate() {
27149            for b in all.iter().skip(i + 1) {
27150                assert_ne!(
27151                    a, b,
27152                    "POLITICAS_KEY_* consts must be pairwise-distinct \
27153                     canonical byte-sequences — got `{a}` == `{b}`",
27154                );
27155            }
27156        }
27157    }
27158
27159    #[test]
27160    fn politicas_key_consts_are_lower_camel_case_shape() {
27161        // Shape-pin: every `POLITICAS_KEY_*` const must be a
27162        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
27163        // `kebab-case` hyphens, no leading colon, no `PascalCase`
27164        // leading capital, no whitespace / dots) — the canonical shape
27165        // the `#[serde(rename_all = "camelCase")]` derive produces on
27166        // [`MeshPolicy`]. A future flip to a non-camelCase attribute
27167        // at the derive surfaces both here (this test fails on the
27168        // stale-constant shape) and at
27169        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
27170        // (that test fails on the mismatch between const and derive).
27171        // Peer with `entrada_key_consts_are_lower_camel_case_shape`
27172        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
27173        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
27174        // (ca463a4) on the sibling M3 typed-struct axes.
27175        for key in [
27176            crate::POLITICAS_KEY_TIMEOUT,
27177            crate::POLITICAS_KEY_RETRIES,
27178            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
27179            crate::POLITICAS_KEY_MTLS_REQUIRED,
27180            crate::POLITICAS_KEY_RATE_LIMIT,
27181        ] {
27182            assert!(
27183                !key.is_empty(),
27184                "POLITICAS_KEY_* must be non-empty (got {key:?})"
27185            );
27186            let first = key.chars().next().unwrap();
27187            assert!(
27188                first.is_ascii_lowercase(),
27189                "POLITICAS_KEY_* must lead with an ASCII-lowercase \
27190                 byte (got {key:?}, leads with {first:?})",
27191            );
27192            assert!(
27193                key.chars().all(|c| c.is_ascii_alphanumeric()),
27194                "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
27195                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
27196            );
27197        }
27198    }
27199
27200    // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
27201
27202    #[test]
27203    fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
27204        // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
27205        // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
27206        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
27207        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
27208        // [`CircuitBreaker`] emits inside the
27209        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
27210        // two axes (`max_failures` → `maxFailures`) is a non-trivial
27211        // camelCase transform — the derive-attribute is load-bearing on
27212        // that axis, unlike the sibling `window` field where the derive
27213        // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
27214        // pin that each canonical byte-sequence appears verbatim in the
27215        // JSON — a future accidental `rename_all = "snake_case"` /
27216        // `"kebab-case"` / verbatim-field-name flip at the derive
27217        // attribute (any of which would silently break every downstream
27218        // JSON consumer that reaches for one of the two consts via
27219        // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
27220        // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
27221        // per-edge `:politicas` overlay projection onto the mesh's
27222        // per-backend consecutive-failure-counter tripping threshold, the
27223        // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
27224        // admission-time breaker cross-check, the future `feira lint`
27225        // per-`:politicas :circuit-breaker` bound-check gate) surfaces
27226        // here as a build-time test failure at `aplicacao.rs`, not as an
27227        // apply-time `.get(<stale-canonical-const>)` returning `None`
27228        // far from the derive-attr drift's commit. Peer with the sibling
27229        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
27230        // (b55cca7) parent-axis pin — that test pins the outer
27231        // sub-block key the derive on [`MeshPolicy`] emits, this test
27232        // pins the inner keys the derive on the payload type emits, so
27233        // the two together lock the whole [`MeshPolicy`] breaker-tuning
27234        // shape end-to-end at build time.
27235        let cb = CircuitBreaker {
27236            max_failures: 5,
27237            window: Duration::from_secs(60),
27238        };
27239        let json = serde_json::to_string(&cb).unwrap();
27240        for key in [
27241            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
27242            crate::CIRCUIT_BREAKER_KEY_WINDOW,
27243        ] {
27244            let quoted = format!("\"{key}\"");
27245            assert!(
27246                json.contains(&quoted),
27247                "serialized CircuitBreaker must carry the lifted \
27248                 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
27249                 in the JSON emission (got: {json})",
27250            );
27251        }
27252    }
27253
27254    #[test]
27255    fn circuit_breaker_key_consts_are_pairwise_distinct() {
27256        // Cross-axis drift-detection pin: a future collapse of the two
27257        // canonical [`CircuitBreaker`] sub-block byte-strings onto the
27258        // same value (e.g. an accidental copy-paste flip of
27259        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
27260        // `"maxFailures"`) would silently reroute every downstream
27261        // probe on one axis onto the sibling axis's overlay entry and
27262        // pass every propagation-probe test that expected only the
27263        // stale axis's value — the M4 per-edge `:politicas` overlay
27264        // projection would read the failure-count where the window
27265        // duration was expected (or vice versa), the CR materializer's
27266        // admission cross-check would compare the wrong pair of values,
27267        // and the resulting mesh reconciler would either bind the wrong
27268        // axis or reject the resource at reconcile far from the rebrand
27269        // commit's source. Peer of the sibling five-way distinct pin on
27270        // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
27271        // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
27272        // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
27273        // six-way distinct pin on the `CONTRATO_KEY_*` triad +
27274        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
27275        let all = [
27276            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
27277            crate::CIRCUIT_BREAKER_KEY_WINDOW,
27278        ];
27279        for (i, a) in all.iter().enumerate() {
27280            for b in all.iter().skip(i + 1) {
27281                assert_ne!(
27282                    a, b,
27283                    "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
27284                     canonical byte-sequences — got `{a}` == `{b}`",
27285                );
27286            }
27287        }
27288    }
27289
27290    #[test]
27291    fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
27292        // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
27293        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
27294        // `kebab-case` hyphens, no leading colon, no `PascalCase`
27295        // leading capital, no whitespace / dots) — the canonical shape
27296        // the `#[serde(rename_all = "camelCase")]` derive produces on
27297        // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
27298        // at the derive surfaces both here (this test fails on the
27299        // stale-constant shape) and at
27300        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
27301        // (that test fails on the mismatch between const and derive).
27302        // Peer with `politicas_key_consts_are_lower_camel_case_shape`
27303        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
27304        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
27305        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
27306        // (ca463a4) on the sibling M3 typed-struct axes.
27307        for key in [
27308            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
27309            crate::CIRCUIT_BREAKER_KEY_WINDOW,
27310        ] {
27311            assert!(
27312                !key.is_empty(),
27313                "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
27314            );
27315            let first = key.chars().next().unwrap();
27316            assert!(
27317                first.is_ascii_lowercase(),
27318                "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
27319                 byte (got {key:?}, leads with {first:?})",
27320            );
27321            assert!(
27322                key.chars().all(|c| c.is_ascii_alphanumeric()),
27323                "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
27324                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
27325            );
27326        }
27327    }
27328
27329    // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
27330
27331    #[test]
27332    fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
27333        // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
27334        // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
27335        // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
27336        // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
27337        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
27338        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
27339        // [`Placement`] emits. One of the four axes (`shard_key` →
27340        // `shardKey`) is a non-trivial camelCase transform — the
27341        // derive-attribute is load-bearing on that axis, unlike the
27342        // sibling `estrategia` / `clusters` / `affinity` axes whose
27343        // source-side field names carry no `_` and where the derive is a
27344        // no-op. Serialize a fully-populated [`Placement`] (both
27345        // `Option`-carrying axes `Some(_)` so
27346        // `skip_serializing_if = "Option::is_none"` fires on neither of
27347        // the two optional slots) and pin that each canonical
27348        // byte-sequence appears verbatim in the JSON — a future
27349        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
27350        // verbatim-field-name flip at the derive attribute (any of which
27351        // would silently break every downstream consumer that reaches
27352        // for one of the four consts via
27353        // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
27354        // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
27355        // aggregator's per-cluster fanout filter keying off
27356        // `placement.clusters`, the M3 shard-pool dispatch materializer
27357        // keying off `placement.shardKey`, the M3 Adaptive compression
27358        // pass weighting off `placement.affinity`, every downstream
27359        // dispatcher branching on `placement.estrategia`, the future
27360        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
27361        // admission-time placement cross-check, the future `feira lint`
27362        // per-`:placement` bound-check gate) surfaces here as a
27363        // build-time test failure at `aplicacao.rs`, not as an
27364        // apply-time `.get(<stale-canonical-const>)` returning `None`
27365        // far from the derive-attr drift's commit. Peer with the sibling
27366        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
27367        // (b55cca7),
27368        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
27369        // (468e959),
27370        // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
27371        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
27372        // (ca463a4), and
27373        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
27374        // pins on the M3 collection-slot / singleton-slot atom axes —
27375        // closes the last M3 typed-struct top-level
27376        // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
27377        // surface without a drift-detection pin.
27378        let p = Placement {
27379            estrategia: PlacementStrategy::Sharded,
27380            clusters: vec!["rio".into(), "mar".into()],
27381            affinity: Some("data-locality".into()),
27382            shard_key: Some("$tenantId".into()),
27383        };
27384        let json = serde_json::to_string(&p).unwrap();
27385        for key in [
27386            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
27387            crate::M3_PLACEMENT_KEY_CLUSTERS,
27388            crate::M3_PLACEMENT_KEY_AFFINITY,
27389            crate::M3_PLACEMENT_KEY_SHARD_KEY,
27390        ] {
27391            let quoted = format!("\"{key}\"");
27392            assert!(
27393                json.contains(&quoted),
27394                "serialized Placement must carry the lifted \
27395                 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
27396                 the JSON emission (got: {json})",
27397            );
27398        }
27399    }
27400
27401    #[test]
27402    fn m3_placement_key_consts_are_pairwise_distinct() {
27403        // Cross-axis drift-detection pin: a future collapse of the four
27404        // canonical [`Placement`] sub-block byte-strings onto the same
27405        // value (e.g. an accidental copy-paste flip of
27406        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
27407        // `"affinity"`) would silently reroute every downstream probe on
27408        // one axis onto the sibling axis's overlay entry and pass every
27409        // propagation-probe test that expected only the stale axis's
27410        // value — the M3 shard-pool dispatch materializer would read the
27411        // affinity placement-hint where the shard-selection template was
27412        // expected (or vice versa), the M3 Adaptive compression pass's
27413        // cross-check would compare the wrong pair of values, and the
27414        // resulting placement engine would either bind the wrong axis or
27415        // reject the resource at reconcile far from the rebrand commit's
27416        // source. Peer of the sibling two-way distinct pin on the
27417        // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
27418        // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
27419        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
27420        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
27421        // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
27422        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
27423        let all = [
27424            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
27425            crate::M3_PLACEMENT_KEY_CLUSTERS,
27426            crate::M3_PLACEMENT_KEY_AFFINITY,
27427            crate::M3_PLACEMENT_KEY_SHARD_KEY,
27428        ];
27429        for (i, a) in all.iter().enumerate() {
27430            for b in all.iter().skip(i + 1) {
27431                assert_ne!(
27432                    a, b,
27433                    "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
27434                     canonical byte-sequences — got `{a}` == `{b}`",
27435                );
27436            }
27437        }
27438    }
27439
27440    #[test]
27441    fn m3_placement_key_consts_are_lower_camel_case_shape() {
27442        // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
27443        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
27444        // `kebab-case` hyphens, no leading colon, no `PascalCase`
27445        // leading capital, no whitespace / dots) — the canonical shape
27446        // the `#[serde(rename_all = "camelCase")]` derive produces on
27447        // [`Placement`]. A future flip to a non-camelCase attribute at
27448        // the derive surfaces both here (this test fails on the stale-
27449        // constant shape) and at
27450        // `placement_serde_keys_match_lifted_m3_placement_key_consts`
27451        // (that test fails on the mismatch between const and derive).
27452        // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
27453        // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
27454        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
27455        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
27456        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
27457        // (ca463a4) on the sibling M3 typed-struct axes.
27458        for key in [
27459            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
27460            crate::M3_PLACEMENT_KEY_CLUSTERS,
27461            crate::M3_PLACEMENT_KEY_AFFINITY,
27462            crate::M3_PLACEMENT_KEY_SHARD_KEY,
27463        ] {
27464            assert!(
27465                !key.is_empty(),
27466                "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
27467            );
27468            let first = key.chars().next().unwrap();
27469            assert!(
27470                first.is_ascii_lowercase(),
27471                "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
27472                 byte (got {key:?}, leads with {first:?})",
27473            );
27474            assert!(
27475                key.chars().all(|c| c.is_ascii_alphanumeric()),
27476                "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
27477                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
27478            );
27479        }
27480    }
27481
27482    // ── AplicacaoSpec::port_for_destination — the substrate-canonical
27483    //    destination-facing L4 port resolver every per-Aplicacao renderer
27484    //    reaching for a per-destination Servico TCP port axis routes
27485    //    through. The four pin tests below fix the four-way accept-set
27486    //    the resolver must always honor: (:entrada-para-matches,
27487    //    :entrada-para-mismatches, :entrada-none-so-fallback,
27488    //    :entrada-port-non-default-honored) — drift on any arm surfaces
27489    //    at caixa-core build time rather than at cluster-apply time.
27490
27491    #[test]
27492    fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
27493        // The typed `:entrada` block's `:para "cart"` matches the
27494        // queried destination, so the resolver returns the author-
27495        // declared `:port` scalar verbatim — the canonical "the
27496        // destination Servico IS the ingress apex, honor the typed
27497        // listener port" arm of the port-resolution dispatch.
27498        let mut spec = three_member_spec();
27499        if let Some(e) = spec.entrada.as_mut() {
27500            e.para = "cart".into();
27501            e.port = 9090;
27502        }
27503        assert_eq!(
27504            spec.port_for_destination("cart"),
27505            9090,
27506            "port_for_destination(entrada.para) must return entrada.port \
27507             verbatim, not the DEFAULT_SERVICO_PORT fallback"
27508        );
27509    }
27510
27511    #[test]
27512    fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
27513        // The typed `:entrada` block names `:para "cart"`, but the
27514        // queried destination is `"payment"` — a Servico that
27515        // participates in the mesh graph but is not the ingress apex.
27516        // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
27517        // canonical port floor, closing the "non-apex destination reads
27518        // the substrate default" arm. Same fixture the peer
27519        // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
27520        // pin at caixa-mesh exercises through the CNP emit-side path;
27521        // this pin exercises the shared underlying resolver directly.
27522        let spec = three_member_spec();
27523        assert_eq!(
27524            spec.port_for_destination("payment"),
27525            DEFAULT_SERVICO_PORT,
27526            "port_for_destination(non-apex-destination) must route \
27527             through the lifted DEFAULT_SERVICO_PORT canonical port floor"
27528        );
27529    }
27530
27531    #[test]
27532    fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
27533        // Internal-only Aplicacao — no `:entrada` block declared. Every
27534        // per-destination port query falls back to the lifted
27535        // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
27536        // the Aplicacao surface admits `:entrada None` (internal mesh
27537        // with no external gateway); every downstream renderer's per-
27538        // destination port axis must still resolve to a well-defined
27539        // scalar even without an ingress apex.
27540        let mut spec = three_member_spec();
27541        spec.entrada = None;
27542        assert_eq!(
27543            spec.port_for_destination("cart"),
27544            DEFAULT_SERVICO_PORT,
27545            "port_for_destination on an internal-only Aplicacao must \
27546             fall back to the lifted DEFAULT_SERVICO_PORT floor for \
27547             every destination"
27548        );
27549        assert_eq!(
27550            spec.port_for_destination("payment"),
27551            DEFAULT_SERVICO_PORT,
27552            "port_for_destination on an internal-only Aplicacao must \
27553             fall back uniformly across every destination — the fallback \
27554             is not entrada-shape-conditional"
27555        );
27556    }
27557
27558    #[test]
27559    fn port_for_destination_honors_non_default_entrada_port_verbatim() {
27560        // Structural pin against a hypothetical future refactor that
27561        // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
27562        // the resolver (a "normalize to the default when the author's
27563        // port matches the substrate default" collapse) — that would
27564        // break renderer sites that carry meaning on the emitted port
27565        // value beyond bare equality (a future per-cluster listener-
27566        // audit that keys off the author-declared port, not the
27567        // resolved-with-fallback port). Pin that a non-default
27568        // entrada.port is returned verbatim so drift here surfaces at
27569        // caixa-core build time.
27570        let mut spec = three_member_spec();
27571        if let Some(e) = spec.entrada.as_mut() {
27572            e.para = "cart".into();
27573            e.port = 8443;
27574        }
27575        assert_ne!(
27576            8443, DEFAULT_SERVICO_PORT,
27577            "test fixture must probe a port distinct from \
27578             DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
27579        );
27580        assert_eq!(
27581            spec.port_for_destination("cart"),
27582            8443,
27583            "port_for_destination(entrada.para) must return entrada.port \
27584             verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
27585        );
27586    }
27587
27588    #[test]
27589    fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
27590        // Apex-identity pair-invariant pin composing both substrate-
27591        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
27592        // and [`Entrada::destination`] — at the emit-side call shape
27593        // every per-Aplicacao renderer's ingress-apex L4 port reader
27594        // now takes. The invariant:
27595        //
27596        //   spec.port_for_destination(entrada.destination()) == entrada.port
27597        //
27598        // holds by construction under today's single-destination
27599        // `:entrada` slot (`destination()` returns `entrada.para`, and
27600        // the resolver's apex arm matches `para == destination` and
27601        // returns `entrada.port`), and every downstream consumer that
27602        // composes the two accessors at the ingress apex — the
27603        // `caixa_mesh::gateway_routes` HTTPRoute per-rule
27604        // `backendRefs[0].port` emit-site path, the peer future M4 CR
27605        // materializer's admission-webhook that promotes the scalar to
27606        // a per-CR override overlay, every future per-Aplicacao snapshot
27607        // renderer's apex-facing L4 port reader — reaches through the
27608        // same composition. Pin the identity across four permutations
27609        // (`:para` × `:port` including a non-default port to exercise
27610        // the honor-verbatim arm and a non-cart `:para` to exercise
27611        // destination-agnostic identity) so a future refactor that
27612        // silently split either accessor's apex behavior surfaces at
27613        // caixa-core build time — a subtle `destination()` renaming
27614        // that returned `entrada.host.as_str()` instead of
27615        // `entrada.para.as_str()` would blow this pin loudly, closing
27616        // the last quiet failure mode the two lifts admit in composition.
27617        //
27618        // Peer discipline with the sibling caixa-mesh cross-crate pin
27619        // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
27620        // on the two-renderer pair-invariant axis; this pin encodes the
27621        // same two-consumer coherence rule at the substrate-primitive
27622        // level so the invariant survives even if every renderer is
27623        // deleted.
27624        for (para, port) in [
27625            ("cart", DEFAULT_SERVICO_PORT),
27626            ("cart", 8443u16),
27627            ("payment", 9090u16),
27628            ("catalog", 443u16),
27629        ] {
27630            let mut spec = three_member_spec();
27631            if let Some(e) = spec.entrada.as_mut() {
27632                e.para = para.into();
27633                e.port = port;
27634            }
27635            let expected_port = spec
27636                .entrada()
27637                .expect("three_member_spec carries a typed `:entrada` block")
27638                .port();
27639            let composed_port = {
27640                let entrada = spec.entrada().expect("entrada present");
27641                spec.port_for_destination(entrada.destination())
27642            };
27643            assert_eq!(
27644                composed_port, expected_port,
27645                "`spec.port_for_destination(entrada.destination())` must \
27646                 equal `entrada.port` under today's single-destination \
27647                 `:entrada` slot — this is the apex-identity contract \
27648                 every downstream ingress-apex L4 port reader relies on. \
27649                 Input :entrada :para: {para:?}, :entrada :port: {port}"
27650            );
27651        }
27652    }
27653
27654    #[test]
27655    fn port_for_destination_apex_arm_routes_through_destination_accessor() {
27656        // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
27657        // per-`:entrada` apex-arm membership probe must key off
27658        // [`Entrada::destination`], not the raw `.para` field access.
27659        // Structurally: setting ONLY the `:entrada :para` field to a
27660        // fresh non-cart destination on an otherwise-well-formed
27661        // Aplicacao must (1) leave `e.destination()` byte-equal to
27662        // `e.para.as_str()` (the accessor is byte-projective by
27663        // definition), and (2) cause the resolver's apex arm to fire
27664        // and return `entrada.port` at exactly that new destination
27665        // while every other destination string falls through to
27666        // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
27667        // membership check. Pins against a future silent detour that
27668        // (a) re-derived the apex-arm membership probe off
27669        // `e.para == destination` in `port_for_destination` instead of
27670        // `e.destination() == destination`, silently disagreeing with
27671        // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
27672        // consumers (`entrada.destination()` at
27673        // caixa-mesh/src/lib.rs:3173, `c.destination()` at
27674        // caixa-mesh/src/lib.rs:2739) that already reach through the
27675        // accessor, (b) accessor-side introduced a per-tenant alias
27676        // arm the caller was unaware of, silently rewriting an
27677        // author-declared `:para "cart"` value to a canary-aliased
27678        // form — the raw-field-access resolver would fall through to
27679        // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
27680        // while the peer emit-site consumers landed on the aliased
27681        // destination, splitting the ingress-apex L4 port at
27682        // cluster-apply time.
27683        //
27684        // Peer of the sibling
27685        // [`validate_membros_empty_gate_routes_through_nome_accessor`]
27686        // (d0de220) composition pin on the per-`:membros` refusal-arm
27687        // axis — same "the shape-gate predicate must route through the
27688        // substrate-primitive typed dispatch" discipline extended onto
27689        // the per-`:entrada` apex-arm membership-probe axis. Closes
27690        // the last unlifted `.para` production-code read site on
27691        // `Entrada` in `caixa-core` — after this converge every
27692        // `caixa-core` `.para` field access outside the accessor's own
27693        // body and outside the `WitContract` per-`:contratos` sibling
27694        // axis is either a test-side field-setter or a doc-comment
27695        // reference.
27696        for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
27697            let mut spec = three_member_spec();
27698            if let Some(e) = spec.entrada.as_mut() {
27699                e.para = para.into();
27700                e.port = port;
27701            }
27702            let e = spec
27703                .entrada
27704                .as_ref()
27705                .expect("three_member_spec carries a typed `:entrada` block");
27706            assert_eq!(
27707                e.destination(),
27708                e.para.as_str(),
27709                "Entrada::destination must byte-equal the .para field \
27710                 access — an accessor-side detour that no longer \
27711                 projects the raw field would silently split this \
27712                 drift-detection test from the port_for_destination \
27713                 apex-arm membership probe",
27714            );
27715            assert_eq!(
27716                spec.port_for_destination(para),
27717                port,
27718                "port_for_destination must key off the accessor-projected \
27719                 destination and return `entrada.port` on the apex arm — \
27720                 input :entrada :para: {para:?}, :entrada :port: {port}",
27721            );
27722            assert_eq!(
27723                spec.port_for_destination("ghost-destination-never-a-member"),
27724                DEFAULT_SERVICO_PORT,
27725                "port_for_destination must fall through to \
27726                 DEFAULT_SERVICO_PORT on a non-matching destination \
27727                 under the accessor-projected membership check — input \
27728                 :entrada :para: {para:?}, :entrada :port: {port}",
27729            );
27730        }
27731    }
27732
27733    #[test]
27734    fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
27735        // The canonical per-`:politicas :rate-limit` `:rate`
27736        // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
27737        // [`RateLimit::rate`] must return the `:politicas :rate-limit`
27738        // typed `u32` verbatim, byte-equal to the raw field access
27739        // across every representative value in the accept-set — `1` (the
27740        // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
27741        // the surrounding [`AplicacaoSpec::validate_politicas`] gate
27742        // carves out on the sibling `PolicyRateLimitZero` refusal),
27743        // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
27744        // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
27745        // `0` (a past-the-guard sentinel that pins the accessor doesn't
27746        // perform a silent bounds-collapse into `1` on the zero arm —
27747        // validate rejects zero but the accessor must ship the raw slot
27748        // verbatim so a validate-time gate regression surfaces at the
27749        // emit boundary rather than being silently absorbed), `u32::MAX`
27750        // (a past-the-guard sentinel that pins the accessor doesn't
27751        // perform a silent bounds-collapse through
27752        // `POLICY_RATE_LIMIT_MAX` at the return path).
27753        //
27754        // First sub-struct required-scalar accessor pin on the
27755        // `RateLimit` axis — sibling in shape to the peer
27756        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
27757        // required-`u32` accessor pin on the peer per-sub-struct
27758        // required-axis. Pins against a future silent detour that
27759        // re-derived the token capacity from a peer axis (an accidental
27760        // `self.window.as_secs() as u32` collapse that read the
27761        // rate-limit window duration as a token count), a `0 → 1`
27762        // cluster-default projection (which would silently absorb the
27763        // `PolicyRateLimitZero` refusal case at the accessor boundary),
27764        // or a bounds-collapsing accessor that clamped the return
27765        // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
27766        // gate owns the bounds; the accessor must ship the raw slot
27767        // verbatim).
27768        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
27769            let rl = RateLimit {
27770                rate,
27771                window: Duration::from_secs(1),
27772            };
27773            assert_eq!(
27774                rl.rate(),
27775                rate,
27776                "RateLimit::rate must return :politicas :rate-limit :rate \
27777                 verbatim (got {}, expected {rate})",
27778                rl.rate(),
27779            );
27780            assert_eq!(
27781                rl.rate(),
27782                rl.rate,
27783                "RateLimit::rate must byte-equal the raw .rate field \
27784                 access across every value in the u32 accept-set",
27785            );
27786        }
27787    }
27788
27789    #[test]
27790    fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
27791        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
27792        // `:rate-limit :rate` zero-floor arm must key off
27793        // [`RateLimit::rate`], not the raw `.rate` field access.
27794        // Structurally: a `RateLimit { rate: 0, window:
27795        // Duration::from_secs(1) }` embedded in a `:politicas
27796        // :rate-limit` slot must surface the `PolicyRateLimitZero`
27797        // refusal exactly, and a `RateLimit { rate: 1, window:
27798        // Duration::from_secs(1) }` (the lower boundary of the
27799        // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
27800        // The pair jointly pins the accessor + validate-gate composition:
27801        // any future silent detour that had the accessor return a fresh
27802        // `1` on the zero arm (a `.rate().max(1)` collapse) would
27803        // silently absorb the `PolicyRateLimitZero` refusal at the
27804        // accessor boundary and the validate gate would accept a
27805        // struct-literal `RateLimit { rate: 0, .. }` — the composition
27806        // pin catches that at caixa-core build time.
27807        //
27808        // Peer of the sibling per-`CircuitBreaker`
27809        // [`CircuitBreaker::max_failures`] (3a74062) /
27810        // [`CircuitBreaker::window`] (373957f) accessor-composition
27811        // pins on the peer required-scalar axes — same "the validate /
27812        // shape-gate predicate must route through the substrate-primitive
27813        // typed dispatch" discipline extended onto the peer
27814        // per-`RateLimit` required-`u32` composition axis.
27815        let mut spec = three_member_spec();
27816        spec.politicas = MeshPolicy {
27817            rate_limit: Some(RateLimit {
27818                rate: 0,
27819                window: Duration::from_secs(1),
27820            }),
27821            ..MeshPolicy::default()
27822        };
27823        assert!(
27824            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
27825            "validate_politicas must reject rate == 0 with \
27826             PolicyRateLimitZero — the accessor and the validate gate \
27827             must route through the same substrate-primitive typed \
27828             dispatch on the :rate zero-floor arm",
27829        );
27830        spec.politicas = MeshPolicy {
27831            rate_limit: Some(RateLimit {
27832                rate: 1,
27833                window: Duration::from_secs(1),
27834            }),
27835            ..MeshPolicy::default()
27836        };
27837        assert!(
27838            spec.validate().is_ok(),
27839            "validate_politicas must accept rate == 1 (the lower \
27840             boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
27841        );
27842    }
27843
27844    #[test]
27845    fn rate_limit_rate_projects_u32_by_copy() {
27846        // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
27847        // `u32` is `Copy` and the accessor must return by value, not by
27848        // reference. Peer of the sibling per-`CircuitBreaker`
27849        // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
27850        // peer required-scalar `:max-failures` axis, extended onto the
27851        // peer per-`RateLimit` required-`u32` copy-invariant shape —
27852        // the accessor's returned `u32` must outlive `&self` (multiple
27853        // calls must return equal values from a dropped-`&self` copy,
27854        // since the returned scalar carries no borrow), and calling the
27855        // accessor twice on the same RateLimit must yield the same
27856        // `u32` verbatim (idempotent, no side effects on `&self`).
27857        //
27858        // Pins against a future silent detour that returned `&u32`
27859        // (which would type-check but silently break every downstream
27860        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
27861        // first parameter is `u32`, and `&u32` would fold to a detached
27862        // copy at the call site with a `*` deref the sibling accessors
27863        // don't need), an accidental `.rate.wrapping_add(0)` detour that
27864        // returned a fresh copy through an arithmetic no-op (breaking a
27865        // future `const fn` regression), or a one-arm-only accessor
27866        // that returned a saturating value on some sentinel input
27867        // (breaking the pass-through invariant the sibling required-
27868        // scalar accessors carry).
27869        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
27870            let rl = RateLimit {
27871                rate,
27872                window: Duration::from_secs(1),
27873            };
27874            let first = rl.rate();
27875            let second = rl.rate();
27876            assert_eq!(
27877                first, second,
27878                "RateLimit::rate must be idempotent — two successive \
27879                 calls on the same &self must return the same u32",
27880            );
27881            assert_eq!(
27882                first, rate,
27883                "RateLimit::rate must return :politicas :rate-limit :rate \
27884                 verbatim by copy — got {first}, expected {rate}",
27885            );
27886        }
27887    }
27888
27889    #[test]
27890    fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
27891        // The canonical per-`:politicas :rate-limit` `:window`
27892        // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
27893        // pin: [`RateLimit::window`] must return the
27894        // `:politicas :rate-limit :window` typed `Duration` verbatim,
27895        // byte-equal to the raw field access across every
27896        // representative value in the accept-set — `Duration::from_secs(1)`
27897        // (the `"s"` canonical window, the lower row of
27898        // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
27899        // [`AplicacaoSpec::validate_politicas`] gate accepts via
27900        // [`is_canonical_rate_limit_window`]),
27901        // `Duration::from_secs(60)` (the `"m"` canonical window, the
27902        // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
27903        // window, the upper row), `Duration::ZERO` (a past-the-guard
27904        // sentinel that pins the accessor doesn't perform a silent
27905        // bounds-collapse into `Duration::from_secs(1)` on the zero
27906        // arm — validate rejects an off-set window through
27907        // `PolicyRateLimitWindowNotCanonical` but the accessor must
27908        // ship the raw slot verbatim so a validate-time gate
27909        // regression surfaces at the emit boundary rather than being
27910        // silently absorbed), `Duration::from_millis(500)` (a
27911        // sub-canonical past-the-guard sentinel that pins the accessor
27912        // doesn't silently normalize a non-canonical fractional
27913        // magnitude onto the nearest canonical row).
27914        //
27915        // Second sub-struct required-scalar accessor pin on the
27916        // `RateLimit` axis — sibling in shape to the just-landed
27917        // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
27918        // accessor pin on the peer per-sub-struct required-axis,
27919        // extended onto the per-`RateLimit` required-`Duration` axis.
27920        // Pins against a future silent detour that re-derived the
27921        // refill period from a peer axis (an accidental
27922        // `Duration::from_secs(self.rate as u64)` collapse that read
27923        // the rate-limit token capacity as a refill-interval
27924        // duration), a `Duration::ZERO → Duration::from_secs(1)`
27925        // canonical-default projection (which would silently absorb
27926        // the `PolicyRateLimitWindowNotCanonical` refusal case at the
27927        // accessor boundary), or a canonical-set-collapsing accessor
27928        // that clamped the return through [`rate_limit_window_unit`]
27929        // (the `AplicacaoSpec::validate` gate owns the canonical-set
27930        // membership; the accessor must ship the raw slot verbatim).
27931        for window in [
27932            Duration::from_secs(1),
27933            Duration::from_secs(60),
27934            Duration::from_secs(3600),
27935            Duration::ZERO,
27936            Duration::from_millis(500),
27937        ] {
27938            let rl = RateLimit { rate: 100, window };
27939            assert_eq!(
27940                rl.window(),
27941                window,
27942                "RateLimit::window must return :politicas :rate-limit :window \
27943                 verbatim (got {:?}, expected {window:?})",
27944                rl.window(),
27945            );
27946            assert_eq!(
27947                rl.window(),
27948                rl.window,
27949                "RateLimit::window must byte-equal the raw .window field \
27950                 access across every value in the Duration accept-set",
27951            );
27952        }
27953    }
27954
27955    #[test]
27956    fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
27957        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
27958        // `:rate-limit :window` canonical-set arm must key off
27959        // [`RateLimit::window`], not the raw `.window` field access.
27960        // Structurally: a `RateLimit { window: Duration::from_millis(500),
27961        // .. }` embedded in a `:politicas :rate-limit` slot must
27962        // surface the `PolicyRateLimitWindowNotCanonical` refusal
27963        // exactly (with the sub-canonical `Duration::from_millis(500)`
27964        // magnitude carried through verbatim), and a `RateLimit
27965        // { window: Duration::from_secs(1), .. }` (the lower row of
27966        // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
27967        // The pair jointly pins the accessor + validate-gate
27968        // composition: any future silent detour that had the accessor
27969        // normalize the off-set window to the nearest canonical row
27970        // (a `.window().max(Duration::from_secs(1))` collapse, or a
27971        // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
27972        // collapse) would silently absorb the
27973        // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
27974        // boundary — including a drift in the error's `window` payload
27975        // (the emit-side diagnostic reader keys off the offending
27976        // magnitude verbatim, so a normalization at the accessor
27977        // boundary would silently pin the wrong magnitude in the
27978        // refusal). The composition pin catches that at caixa-core
27979        // build time.
27980        //
27981        // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
27982        // (7f81a60) accessor-composition pin on the peer required-
27983        // scalar `:rate` axis — same "the validate / shape-gate
27984        // predicate must route through the substrate-primitive typed
27985        // dispatch, and the error payload must project through the
27986        // same accessor" discipline extended onto the peer
27987        // per-`RateLimit` required-`Duration` composition axis.
27988        let mut spec = three_member_spec();
27989        spec.politicas = MeshPolicy {
27990            rate_limit: Some(RateLimit {
27991                rate: 100,
27992                window: Duration::from_millis(500),
27993            }),
27994            ..MeshPolicy::default()
27995        };
27996        match spec.validate() {
27997            Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
27998                assert_eq!(
27999                    window,
28000                    Duration::from_millis(500),
28001                    "PolicyRateLimitWindowNotCanonical must carry the \
28002                     offending :window magnitude verbatim through the \
28003                     accessor — got {window:?}, expected 500ms",
28004                );
28005            }
28006            other => panic!(
28007                "validate_politicas must reject non-canonical :window \
28008                 with PolicyRateLimitWindowNotCanonical — the accessor \
28009                 and the validate gate must route through the same \
28010                 substrate-primitive typed dispatch on the :window \
28011                 canonical-set arm; got {other:?}",
28012            ),
28013        }
28014        spec.politicas = MeshPolicy {
28015            rate_limit: Some(RateLimit {
28016                rate: 100,
28017                window: Duration::from_secs(1),
28018            }),
28019            ..MeshPolicy::default()
28020        };
28021        assert!(
28022            spec.validate().is_ok(),
28023            "validate_politicas must accept window == Duration::from_secs(1) \
28024             (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
28025        );
28026    }
28027
28028    #[test]
28029    fn rate_limit_window_projects_duration_by_copy() {
28030        // The by-copy pin: [`RateLimit::window`] returns `Duration`
28031        // by copy — `Duration` is `Copy` and the accessor must return
28032        // by value, not by reference. Peer of the sibling per-`RateLimit`
28033        // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
28034        // required-scalar `:rate` axis, extended onto the peer
28035        // per-`RateLimit` required-`Duration` copy-invariant shape —
28036        // the accessor's returned `Duration` must outlive `&self`
28037        // (multiple calls must return equal values from a
28038        // dropped-`&self` copy, since the returned scalar carries no
28039        // borrow), and calling the accessor twice on the same
28040        // RateLimit must yield the same `Duration` verbatim
28041        // (idempotent, no side effects on `&self`).
28042        //
28043        // Pins against a future silent detour that returned
28044        // `&Duration` (which would type-check but silently break every
28045        // downstream `Duration`-by-value consumer —
28046        // [`is_canonical_rate_limit_window`]'s first parameter is
28047        // `Duration`, and `&Duration` would fold to a detached copy at
28048        // the call site with a `*` deref the sibling accessors don't
28049        // need), an accidental `.window + Duration::ZERO` detour that
28050        // returned a fresh copy through an arithmetic no-op (breaking
28051        // a future `const fn` regression), or a one-arm-only accessor
28052        // that returned a canonical fallback on some sentinel input
28053        // (breaking the pass-through invariant the sibling required-
28054        // scalar accessors carry).
28055        for window in [
28056            Duration::from_secs(1),
28057            Duration::from_secs(60),
28058            Duration::from_secs(3600),
28059            Duration::ZERO,
28060            Duration::from_millis(500),
28061        ] {
28062            let rl = RateLimit { rate: 100, window };
28063            let first = rl.window();
28064            let second = rl.window();
28065            assert_eq!(
28066                first, second,
28067                "RateLimit::window must be idempotent — two successive \
28068                 calls on the same &self must return the same Duration",
28069            );
28070            assert_eq!(
28071                first, window,
28072                "RateLimit::window must return :politicas :rate-limit :window \
28073                 verbatim by copy — got {first:?}, expected {window:?}",
28074            );
28075        }
28076    }
28077
28078    #[test]
28079    fn placement_estrategia_default_pins_m3_canonical_value() {
28080        // Pin [`PLACEMENT_ESTRATEGIA_DEFAULT`] at
28081        // [`PlacementStrategy::Replicated`] — MESH-COMPOSITION §II.2's
28082        // active-active-across-every-named-cluster arm, the closest
28083        // canonical M3 production reference the substrate carries and
28084        // the arm the caixa-mesh `programs.yaml` fan-out already keys off
28085        // for every un-`:placement`-declared Aplicacao. Pinning the arm
28086        // here surfaces a future rebrand of the M3-canonical
28087        // distribution default (a widening to `Sharded` once the
28088        // substrate discovers hash-keyed distribution as the more
28089        // common production shape, a tightening to `SingleNode` for
28090        // stateful Erlang/OTP distributed-app-takeover semantics
28091        // MESH-COMPOSITION §II.1 names, a per-cluster overlay the
28092        // operator pins through a future `:placement-overrides` slot)
28093        // as a deliberate test edit, not a silent contract migration.
28094        // Peer of the sibling M2 per-supervisor value pins
28095        // [`crate::supervisor::tests::supervisor_estrategia_default_pins_otp_canonical_value`]
28096        // /
28097        // [`crate::supervisor::tests::supervisor_child_restart_default_pins_otp_canonical_value`]
28098        // extended onto the M3 mesh-primitive-defining `:placement
28099        // :estrategia` axis.
28100        assert_eq!(PLACEMENT_ESTRATEGIA_DEFAULT, PlacementStrategy::Replicated);
28101    }
28102
28103    #[test]
28104    fn placement_strategy_default_routes_through_lifted_default() {
28105        // Composition pin: the [`Default for PlacementStrategy`] impl's
28106        // return arm must route through the substrate-canonical
28107        // [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
28108        // a raw `Self::Replicated` arm. Prior to the lift the impl
28109        // carried an inline `Self::Replicated` arm with no compile-time
28110        // link back to the shared M3-canonical `Replicated` arm the
28111        // paired [`Default for Placement`] impl's struct-literal
28112        // `estrategia` field, the serde-side `#[serde(default)]` on
28113        // [`Placement::estrategia`] that resolves an author-omitted
28114        // wire-form `:placement :estrategia` scalar through the impl,
28115        // and the [`crate::manifest::Caixa::aplicacao_view`] fold's
28116        // `.unwrap_or_default()` `Option<Placement>` collapse arm (which
28117        // routes through [`Placement::default`] which routes through the
28118        // strategy default) all key off — so a future rebrand of the
28119        // M3-canonical distribution default would have had to be threaded
28120        // through the `Default` impl and the three peer routes in
28121        // lockstep or the four consumers would silently split. Byte-
28122        // parity against the lifted constant closes the split. Peer of
28123        // the sibling
28124        // [`crate::supervisor::tests::restart_strategy_default_routes_through_lifted_default`]
28125        // /
28126        // [`crate::supervisor::tests::restart_policy_default_routes_through_lifted_default`]
28127        // composition pins on the M2 per-supervisor axes.
28128        assert_eq!(PlacementStrategy::default(), PLACEMENT_ESTRATEGIA_DEFAULT);
28129    }
28130
28131    #[test]
28132    fn placement_default_estrategia_routes_through_lifted_default() {
28133        // Composition pin: the [`Default for Placement`] impl's
28134        // struct-literal `estrategia` field must route through the
28135        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
28136        // `pub const` (either directly, or via the [`PlacementStrategy::default`]
28137        // impl that the sibling
28138        // `placement_strategy_default_routes_through_lifted_default` pin
28139        // already routes onto the constant). Structurally: every
28140        // `Placement::default()` call must yield an `estrategia` field
28141        // byte-equal to the lifted constant so the two paired defaults —
28142        // the [`Default for PlacementStrategy`] impl arm and the
28143        // struct-literal default arm here — cannot silently split on any
28144        // future M3-canonical distribution-default rebrand. Peer of the
28145        // sibling M2
28146        // [`crate::supervisor::tests::supervisor_spec_default_estrategia_routes_through_lifted_default`]
28147        // byte-parity pin on the [`Default for SupervisorSpec`]
28148        // struct-literal `estrategia` field extended onto the M3
28149        // mesh-primitive-defining slot family.
28150        assert_eq!(
28151            Placement::default().estrategia,
28152            PLACEMENT_ESTRATEGIA_DEFAULT,
28153        );
28154    }
28155
28156    #[test]
28157    fn placement_serde_default_estrategia_routes_through_lifted_default() {
28158        // Composition pin: the serde-side `#[serde(default)]` on
28159        // [`Placement::estrategia`] — the wire-format author-omitted
28160        // `:placement :estrategia` arm — must resolve onto the substrate-
28161        // canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const`
28162        // (via the [`Default for PlacementStrategy`] impl the sibling
28163        // `placement_strategy_default_routes_through_lifted_default` pin
28164        // already routes onto the constant). Structurally: a `Placement`
28165        // deserialized from a payload that omits the `estrategia` key
28166        // must yield an `estrategia` field byte-equal to the lifted
28167        // constant, so the wire-format author-omitted arm and the
28168        // [`PlacementStrategy::default`] impl arm cannot silently split
28169        // on any future M3-canonical distribution-default rebrand. Peer
28170        // of the sibling M2
28171        // [`crate::supervisor::tests::child_spec_serde_default_restart_routes_through_lifted_default`]
28172        // byte-parity pin on the wire-format author-omitted `:children
28173        // :restart` scalar extended onto the M3 mesh-primitive-defining
28174        // slot family.
28175        let omitted: Placement = serde_json::from_str("{}")
28176            .expect("Placement must deserialize with the estrategia key omitted");
28177        assert_eq!(
28178            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
28179            "an author-omitted :placement :estrategia slot must degrade onto \
28180             the PLACEMENT_ESTRATEGIA_DEFAULT typed pub const (got \
28181             {:?}, expected {:?})",
28182            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
28183        );
28184    }
28185}