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#[must_use]
135pub fn wit_shape_matches(wit: &str, prefixes: &[&str]) -> bool {
136    prefixes.iter().any(|p| wit.starts_with(p))
137}
138
139/// True when `wit` — a raw `:contratos :wit` value — targets an
140/// HTTP-shaped WIT world (starts with any prefix in
141/// [`WIT_HTTP_SHAPE_PREFIXES`]). The single dispatch predicate every
142/// consumer routes L7-HTTP emission through, whether they carry a
143/// full [`WitContract`] on hand ([`WitContract::is_http`] delegates
144/// here) or only the raw `wit` string (the positive-sweep test's
145/// payload-dispatch helper, future renderers that classify off a
146/// bare `&str`). Lifting to a free function makes the shape-dispatch
147/// arm reachable without materializing a scratch [`WitContract`] at
148/// every classification point, and pins the six-prefix accept-set at
149/// one place so future additions (e.g. an `"https:"` peer of
150/// `"http:"`) reach every consumer by construction. Routes through
151/// the lifted [`wit_shape_matches`] combinator so the
152/// `PREFIXES.iter().any(|p| wit.starts_with(p))` scan lives at one
153/// canonical primitive, not one open-coded copy per peer arm.
154#[must_use]
155pub fn wit_shape_is_http(wit: &str) -> bool {
156    wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES)
157}
158
159/// True when `wit` — a raw `:contratos :wit` value — targets a
160/// pub-sub-shaped WIT world (starts with any prefix in
161/// [`WIT_PUBSUB_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
162/// [`wit_shape_is_store`] on the shape-dispatch axis; see
163/// [`wit_shape_is_http`] for the lift rationale. Routes through the
164/// lifted [`wit_shape_matches`] combinator.
165#[must_use]
166pub fn wit_shape_is_pubsub(wit: &str) -> bool {
167    wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES)
168}
169
170/// True when `wit` — a raw `:contratos :wit` value — targets a
171/// key/value-store-shaped WIT world (starts with any prefix in
172/// [`WIT_STORE_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
173/// [`wit_shape_is_pubsub`] on the shape-dispatch axis; see
174/// [`wit_shape_is_http`] for the lift rationale. Routes through the
175/// lifted [`wit_shape_matches`] combinator.
176#[must_use]
177pub fn wit_shape_is_store(wit: &str) -> bool {
178    wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES)
179}
180
181/// True when `wit` — a raw `:contratos :wit` value — targets *none* of
182/// the three known payload-shape WIT worlds; the payload-less
183/// capability arm of the 4-way WIT-shape partition on the raw
184/// `:contratos :wit` axis. Peer of [`wit_shape_is_http`] /
185/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] on the shape-
186/// dispatch axis — closes the free-function classifier family the
187/// three payload-arm predicates opened onto the exact-inverse
188/// disjunction of the trio, so any downstream consumer that must
189/// classify a raw `:wit` `&str` onto the payload-less capability arm
190/// (a future substrate-side capability-shape-only emitter — the M4
191/// per-Aplicacao WIT-registry capability-import materializer, the
192/// future `feira app graph --capability` filter, the future per-
193/// cluster capability-scope reconciler that skips L4/L7 emission for
194/// payload-less edges, the future `mesh.pleme.io/v1alpha1/Aplicacao`
195/// CR admission webhook's per-shape histogram) reaches for exactly
196/// one typed dispatch at the substrate primitive rather than an
197/// open-coded per-consumer `!wit_shape_is_http(wit) &&
198/// !wit_shape_is_pubsub(wit) && !wit_shape_is_store(wit)` triplet
199/// negation — each of which would silently misclassify a future 4th
200/// payload-arm addition (a hypothetical `wasi:sockets/*` transport-
201/// layer shape, an `oci:*` capability-import carrier per the sibling
202/// [`wit_shape_matches`] docstring's trajectory bullet) as
203/// capability without a compile-time signal at the consumer site.
204///
205/// Fourth arm on the free-function WIT-shape-predicate family — closes
206/// the {[`wit_shape_is_http`], [`wit_shape_is_pubsub`],
207/// [`wit_shape_is_store`]} trio into a 4-way partition witness on the
208/// raw `:contratos :wit` `&str` axis, mirroring the paired sibling
209/// [`WitContract`]-surface [`WitContract::is_capability`] predicate and
210/// the post-projection [`WitTarget`]-side
211/// `gen_platform::IsVariant`-derived [`WitTarget::is_capability`]
212/// (7f6aa98 `IsVariant` derive lift on the peer arm-set). Every
213/// [`WitTarget`] variant now carries a matched peer predicate on both
214/// the raw `&str` axis (this function + [`wit_shape_is_http`] /
215/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`]) and the
216/// [`WitContract`] surface (the sibling 4-arm predicate family
217/// [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
218/// [`WitContract::is_store`] / [`WitContract::is_capability`]),
219/// pinned in load-bearing by the sibling
220/// [`tests::wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis`]
221/// partition-witness pin and the peer
222/// [`tests::wit_contract_shape_methods_delegate_to_free_functions`]
223/// delegation pin.
224///
225/// Prior to this lift the "not one of the three known payload shapes"
226/// classification only reached the raw `&str` axis by materializing a
227/// scratch [`WitContract`] and delegating through
228/// [`WitContract::is_capability`] — a five-field constructor at every
229/// classification point for a pure `&str → bool` question, and a
230/// dependency on the payload-carrier scalar layout the classifier
231/// does not read. Same "one canonical combinator, thin per-arm
232/// projections" discipline the peer [`wit_shape_is_http`] /
233/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] trio already
234/// established, extended to close the 4-arm partition on the raw
235/// `&str` axis.
236///
237/// Note: purely syntactic classification on the negated `:wit` prefix-
238/// set — unlike [`WitContract::target`], which additionally rejects
239/// value-shape-invalid `:wit` strings (uppercase, hyphen-for-colon
240/// typo, empty package) via [`crate::render::is_wit_world_ref`] and
241/// payload-shape mismatches. An empty or structurally malformed `wit`
242/// string returns `true` here (the prefix set matches nothing), and
243/// the surrounding validate-side gate cascade is where the
244/// [`AplicacaoError::EmptyWit`] / [`AplicacaoError::ContratoWitInvalid`]
245/// diagnostic surfaces — this function is the classifier, not the
246/// validator.
247#[must_use]
248pub fn wit_shape_is_capability(wit: &str) -> bool {
249    !wit_shape_is_http(wit) && !wit_shape_is_pubsub(wit) && !wit_shape_is_store(wit)
250}
251
252impl WitContract {
253    /// Substrate-canonical per-`:contratos` caller-Servico scalar
254    /// accessor every consumer that reads the edge's source endpoint
255    /// keys off — returns the author-declared `:contratos :de`
256    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
257    /// own [`String`] storage.
258    ///
259    /// The `:contratos :de` slot names the caller-side member Servico
260    /// on a typed inter-Servico edge (validated by
261    /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
262    /// Aplicacao declares — a stray `:de` that doesn't name a member is
263    /// [`AplicacaoError::ContratoMemberMissing`], not a silent
264    /// caller-attachment miss at cluster-apply time). Peer of the
265    /// sibling [`WitContract::destination`] accessor on the same
266    /// per-`:contratos` entry — the pair `( source(), destination() )`
267    /// jointly names the typed edge every renderer that fans on the
268    /// caller-callee identity keys off (the
269    /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)`
270    /// grouping, the [`AplicacaoSpec::detect_sync_cycles`] adjacency
271    /// map, the per-edge dedup key, the per-edge membership-lookup
272    /// diagnostic).
273    ///
274    /// Prior to this lift the `.de` byte-string was accessed inline at
275    /// four caixa-core sites (the two validate-side membership lookups
276    /// at `!names.contains(c.de.as_str())`, the per-edge dedup-key
277    /// tuple's caller-arm at
278    /// `(c.de.as_str(), c.para.as_str(), c.wit.as_str(), ...)`, the
279    /// `detect_sync_cycles` adjacency `adj.entry(c.de.as_str())`) and
280    /// one caixa-mesh site (the per-`(:de, :para)` CNP grouping's
281    /// caller-arm at `groups.entry((c.de.as_str(), c.para.as_str()))`)
282    /// — five open-coded `.de.as_str()` field-accesses that expressed
283    /// no compile-time link back to the typed slot. A future extension
284    /// of the `:contratos :de` axis to a richer author surface (a
285    /// multi-caller weighted-fan-in overlay per MESH-COMPOSITION §III.2
286    /// canary flow, a per-cluster caller-alias table the operator pins
287    /// through a future `:placement`-scoped slot, the M4
288    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
289    /// admission-webhook that promotes the scalar to a caller-set
290    /// projection) would have had to be threaded through every
291    /// open-coded copy in lockstep or one consumer would silently
292    /// disagree with the peers on which caller Servico a given edge
293    /// resolves to. Lifting the resolution rule to a typed method on
294    /// the substrate primitive means every downstream caller-facing
295    /// consumer reaches for one typed dispatch — the resolver's
296    /// accept-set migrates as a unit on any future axis addition.
297    ///
298    /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
299    /// (6db982c) accessor on the analogous per-ingress-Servico scalar
300    /// axis — same "one typed dispatch on the substrate primitive,
301    /// thin projections at each consumer" discipline extended onto the
302    /// per-`:contratos` caller-Servico byte-string axis.
303    #[must_use]
304    pub fn source(&self) -> &str {
305        self.de.as_str()
306    }
307
308    /// Substrate-canonical per-`:contratos` callee-Servico scalar
309    /// accessor every consumer that reads the edge's destination
310    /// endpoint keys off — returns the author-declared
311    /// `:contratos :para` byte-string verbatim as a `&str`, borrowed
312    /// from the typed slot's own [`String`] storage.
313    ///
314    /// The `:contratos :para` slot names the callee-side member Servico
315    /// on a typed inter-Servico edge (validated by
316    /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
317    /// Aplicacao declares — a stray `:para` that doesn't name a member
318    /// is [`AplicacaoError::ContratoMemberMissing`], not a silent
319    /// callee-attachment miss at cluster-apply time). Callee-side twin
320    /// of the sibling [`WitContract::source`] accessor — the pair
321    /// jointly names the typed edge every renderer that fans on the
322    /// caller-callee identity keys off, and this accessor is also the
323    /// per-`(:de, :para)` L4 port resolver's canonical destination arg:
324    /// under today's typed surface [`AplicacaoSpec::port_for_destination`]
325    /// composes with `destination()` at every emit site that projects a
326    /// per-edge destination Servico's L4 listener port.
327    ///
328    /// Prior to this lift the `.para` byte-string was accessed inline
329    /// at five sites — four caixa-core (the validate-side membership
330    /// lookup at `!names.contains(c.para.as_str())`, the per-edge
331    /// dedup-key tuple's callee-arm, the `detect_sync_cycles`
332    /// adjacency `.insert(c.para.as_str())`, the CNP grouping's
333    /// callee-arm) and one caixa-mesh (the per-`(:de, :para)` CNP L4
334    /// port resolver's destination arg `spec.port_for_destination(&c.para)`)
335    /// — with no compile-time link back to the typed slot. A future
336    /// extension of the `:contratos :para` axis to a richer author
337    /// surface (a multi-callee weighted-fan-out overlay for canary /
338    /// blue-green routing on typed edges, a per-cluster callee-alias
339    /// table the operator pins through a future `:placement`-scoped
340    /// slot, the M4 CR materializer's per-CR admission-webhook that
341    /// promotes the scalar to a callee-set projection) would have had
342    /// to be threaded through every open-coded copy in lockstep or one
343    /// consumer would silently disagree on which callee Servico a given
344    /// edge resolves to (a per-CNP `endpointSelector` that names a
345    /// different destination than its L4 port resolver reads for, a
346    /// dedup-key that treats `(cart, catalog-v2)` and `(cart, catalog)`
347    /// as distinct while the adjacency map collapses them, or vice
348    /// versa). Lifting to a typed method on the substrate primitive
349    /// means every downstream callee-facing consumer reaches for one
350    /// typed dispatch.
351    ///
352    /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
353    /// (6db982c) accessor — both name the "destination-Servico
354    /// byte-string" concept on their respective mesh-slot atoms (per-
355    /// ingress apex vs. per-typed-edge callee), and both extend the
356    /// substrate-primitive-owns-the-resolver discipline onto the
357    /// per-slot destination-Servico scalar axis. Composes with
358    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) at every
359    /// emit-side per-edge L4 port reader — the composition
360    /// `spec.port_for_destination(c.destination())` pins the CNP per-
361    /// `(:de, :para)` L4 port axis to the same typed dispatch the peer
362    /// `HTTPRoute` `backendRefs[0].port` axis reaches through with
363    /// `spec.port_for_destination(entrada.destination())`.
364    #[must_use]
365    pub fn destination(&self) -> &str {
366        self.para.as_str()
367    }
368
369    /// Substrate-canonical per-`:contratos` WIT-world-reference scalar
370    /// accessor every consumer that reads the edge's WIT world
371    /// discriminator keys off — returns the author-declared
372    /// `:contratos :wit` byte-string verbatim as a `&str`, borrowed from
373    /// the typed slot's own [`String`] storage.
374    ///
375    /// The `:contratos :wit` slot names the WIT world the typed edge
376    /// carries (e.g. `"wasi:http/proxy"`, `"nats:pub-sub"`,
377    /// `"wasi:keyvalue/store"`); validated by [`WitContract::target`] to
378    /// be a well-shaped WIT world reference via
379    /// [`crate::render::is_wit_world_ref`] and by
380    /// [`AplicacaoSpec::validate`] to be non-empty via the narrower
381    /// [`AplicacaoError::EmptyWit`] variant. Peer of the sibling
382    /// [`WitContract::source`] / [`WitContract::destination`] accessors
383    /// on the same per-`:contratos` entry — the triple
384    /// `( source(), destination(), world_ref() )` jointly names the
385    /// typed edge every renderer that fans on the caller-callee-shape
386    /// identity keys off (the per-edge dedup key at
387    /// [`AplicacaoSpec::validate`]'s duplicate-`:contratos` gate, the
388    /// per-`(:de, :para)` CNP grouping's shape-arm classifier at
389    /// [`caixa_mesh::cilium_network_policies`], the
390    /// [`WitContract::is_http`] / [`is_pubsub`][WitContract::is_pubsub]
391    /// / [`is_store`][WitContract::is_store] shape-dispatch predicates,
392    /// the [`feira app graph`][fag] per-edge printer's WIT-shape label).
393    ///
394    /// Prior to this lift the `.wit` byte-string was accessed inline at
395    /// five sites — three caixa-core (the `WitContract::is_*` shape-
396    /// dispatch predicates' `&self.wit` arg, the validate-side empty
397    /// check at `if c.wit.is_empty()`, the per-edge dedup-key tuple's
398    /// shape arm at `c.wit.as_str()`) and one caixa-feira (the app-graph
399    /// printer's `{}` format-slot at `c.wit`) — five open-coded
400    /// `.wit` field-accesses that expressed no compile-time link back to
401    /// the typed slot. A future extension of the `:contratos :wit` axis
402    /// to a richer author surface (an M4 promotion from `String` to a
403    /// typed WIT-world enum once the WIT registry stabilizes in tatara-
404    /// lisp per this struct's own `:wit` field docstring, a per-cluster
405    /// WIT-alias table the operator pins through a future
406    /// `:placement`-scoped slot, a canonicalization pass that lowercases
407    /// `wasi:*` prefixes) would have had to be threaded through every
408    /// open-coded copy in lockstep or one consumer would silently
409    /// disagree with the peers on which WIT shape a given edge resolves
410    /// to (a per-CNP L7 emission that read `wasi:http/proxy` while the
411    /// dedup key read the pre-canonicalized `WASI:HTTP/proxy`, an
412    /// empty-check that missed a whitespace-only string a peer accessor
413    /// stripped, or vice versa). Lifting to a typed method on the
414    /// substrate primitive means every downstream WIT-shape-facing
415    /// consumer reaches for one typed dispatch — the resolver's
416    /// accept-set migrates as a unit on any future axis addition.
417    ///
418    /// Sibling of the peer per-`:contratos` [`WitContract::source`] /
419    /// [`WitContract::destination`] (7f0fd43), per-`:entrada`
420    /// [`Entrada::hostname`] / [`Entrada::destination`] (11f3dfe /
421    /// 6db982c), per-`:membros` [`Membro::nome`] /
422    /// [`Membro::versao_requirement`] (4a32abf / a40b0e3) accessors on
423    /// the mesh-slot-atom scalar-value axes — same "one typed dispatch
424    /// on the substrate primitive, thin projections at each consumer"
425    /// discipline extended onto the last unlifted per-`:contratos`
426    /// scalar (the WIT-world-reference arm).
427    ///
428    /// [fag]: caixa-feira/src/cmd/app.rs
429    #[must_use]
430    pub fn world_ref(&self) -> &str {
431        self.wit.as_str()
432    }
433
434    /// Substrate-canonical per-`:contratos` `:endpoint` HTTP-shaped
435    /// payload-target scalar accessor every consumer that reads the
436    /// edge's L7 HTTP request path payload keys off — returns the
437    /// author-declared `:contratos :endpoint` byte-string verbatim as
438    /// an `Option<&str>`, borrowed from the typed slot's own
439    /// `Option<String>` storage; `None` when the slot is absent (the
440    /// canonical shape of a non-HTTP-`:wit`-world edge — pub-sub
441    /// `nats:*`/`kafka:*` carries `:subject` instead, key/value
442    /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
443    /// [`WitTarget::Capability`] edge carries none of the three).
444    ///
445    /// The `:contratos :endpoint` slot carries the HTTP request path
446    /// payload (Cilium L7 `path:` + Gateway API v1 `PathPrefix` grammar
447    /// — same shape required of `:entrada :paths`, gated by the shared
448    /// [`crate::render::is_gateway_api_http_path`] predicate) that
449    /// [`WitContract::target`] projects onto the [`WitTarget::Http`]
450    /// arm's `endpoint: &'a str` payload when the edge's `:wit` world
451    /// matches the [`WIT_HTTP_SHAPE_PREFIXES`] accept-set. Every
452    /// downstream consumer that reads the payload keys off this scalar
453    /// (the [`WitContract::target`] Http-arm payload extraction that
454    /// materializes [`WitTarget::Http { endpoint }`] under the paired
455    /// [`WitTarget::HTTP_FIELD_NAME`] label, the
456    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
457    /// key's endpoint arm that pins the payload as part of the six-tuple
458    /// dedup key alongside the sibling `:subject`/`:slot` arms, the
459    /// future M4 per-edge WIT registry resolver's HTTP-arm materializer,
460    /// the future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
461    /// per-edge L7 admission webhook, the future caixa-mesh L7 CNP
462    /// emission path that lands the payload verbatim as a Cilium L7
463    /// `path:` rule).
464    ///
465    /// Prior to this lift the `.endpoint` field was accessed inline at
466    /// two production sites in `caixa-core/src/aplicacao.rs` — the
467    /// [`WitContract::target`] payload-shape dispatch's `let endpoint =
468    /// self.endpoint.as_deref();` binding at the top of the method, and
469    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
470    /// tuple's `c.endpoint.as_deref()` HTTP-arm slot — two open-coded
471    /// field-accesses that expressed no compile-time link back to the
472    /// typed slot. A future extension of the `:contratos :endpoint`
473    /// axis to a richer author surface (an M4 promotion from
474    /// `Option<String>` to a typed HTTP path-template enum once the
475    /// WIT registry stabilizes path-parameter shapes in tatara-lisp per
476    /// this struct's own `:wit` field docstring, a per-cluster endpoint-
477    /// alias table the operator pins through a future `:placement`-
478    /// scoped slot, a canonicalization pass that percent-encodes non-
479    /// ASCII path segments, a per-CR fully-qualified rewrite the M4 CR
480    /// materializer applies per-tenant) would have had to be threaded
481    /// through both open-coded copies in lockstep or the two consumers
482    /// would silently disagree on which HTTP path a given edge resolves
483    /// to — the [`WitContract::target`] payload-extraction reading
484    /// `"/lookup"` while the [`AplicacaoSpec::validate`] dedup key read
485    /// the operator-resolved `"/tenant-a/lookup"` would silently split
486    /// the [`WitTarget::Http`]-arm rendered payload from the actual
487    /// dedup-key uniqueness axis, a two-consumer split at the validator
488    /// far from the source `caixa.lisp` with no field naming the
489    /// payload-drift root cause. Lifting the resolution rule to a typed
490    /// method on the substrate primitive means every downstream
491    /// HTTP-payload-facing consumer of the Aplicacao's per-`:contratos`
492    /// L7-payload surface reaches for exactly one typed dispatch — the
493    /// resolver's accept-set migrates as a unit on any future axis
494    /// addition.
495    ///
496    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
497    /// (7cd2a28) / [`Placement::affinity`] (74ec2d3) `Option<&str>`
498    /// accessors on the M3 mesh-slot family — same "one typed dispatch
499    /// on the substrate primitive, thin projections at each consumer"
500    /// discipline extended onto the per-`:contratos` HTTP-shaped
501    /// payload-carrier `Option<String>` optional-scalar axis. First
502    /// `Option<&str>`-return accessor on the per-`:contratos` mesh-slot
503    /// atom — opens the "optional per-slot payload-carrier scalar"
504    /// projection pattern the sibling per-`:contratos` `:subject` /
505    /// `:slot` future lifts fold on, matching the closed
506    /// per-`:contratos` scalar-value accessor family
507    /// ([`WitContract::source`] / [`WitContract::destination`] /
508    /// [`WitContract::world_ref`]) already lifted onto the mandatory-
509    /// scalar `String` axes. Named `endpoint()` to match the storage
510    /// field's name and the paired [`WitTarget::HTTP_FIELD_NAME`]
511    /// author-facing label const; the accessor's identity name maps
512    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
513    /// docstring already carries.
514    #[must_use]
515    pub fn endpoint(&self) -> Option<&str> {
516        self.endpoint.as_deref()
517    }
518
519    /// Substrate-canonical per-`:contratos` `:subject` pub-sub-shaped
520    /// payload-target scalar accessor every consumer that reads the
521    /// edge's NATS / Kafka publish subject payload keys off — returns
522    /// the author-declared `:contratos :subject` byte-string verbatim
523    /// as an `Option<&str>`, borrowed from the typed slot's own
524    /// `Option<String>` storage; `None` when the slot is absent (the
525    /// canonical shape of a non-pub-sub-`:wit`-world edge — HTTP
526    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, key/value
527    /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
528    /// [`WitTarget::Capability`] edge carries none of the three).
529    ///
530    /// The `:contratos :subject` slot carries the NATS / Kafka publish
531    /// subject payload (the [`WIT_PUBSUB_SHAPE_PREFIXES`] dispatch arm's
532    /// per-edge target selector — `orders.paid`, `events.>`, whatever
533    /// subject namespace the author names on the pub-sub edge) that
534    /// [`WitContract::target`] projects onto the [`WitTarget::PubSub`]
535    /// arm's `subject: &'a str` payload when the edge's `:wit` world
536    /// matches the [`WIT_PUBSUB_SHAPE_PREFIXES`] accept-set. Every
537    /// downstream consumer that reads the payload keys off this scalar
538    /// (the [`WitContract::target`] PubSub-arm payload extraction that
539    /// materializes [`WitTarget::PubSub { subject }`] under the paired
540    /// [`WitTarget::PUBSUB_FIELD_NAME`] label, the
541    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
542    /// key's subject arm that pins the payload as part of the six-tuple
543    /// dedup key alongside the sibling `:endpoint`/`:slot` arms, the
544    /// future M4 per-edge WIT registry resolver's pub-sub-arm
545    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
546    /// materializer's per-edge NATS admission webhook, the future
547    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
548    /// as a NATS subject the operator pins per-CR).
549    ///
550    /// Prior to this lift the `.subject` field was accessed inline at
551    /// two production sites in `caixa-core/src/aplicacao.rs` — the
552    /// [`WitContract::target`] payload-shape dispatch's `let subject =
553    /// self.subject.as_deref();` binding at the top of the method, and
554    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
555    /// tuple's `c.subject.as_deref()` pub-sub-arm slot — two open-coded
556    /// field-accesses that expressed no compile-time link back to the
557    /// typed slot. A future extension of the `:contratos :subject` axis
558    /// to a richer author surface (an M4 promotion from `Option<String>`
559    /// to a typed NATS-subject-template enum once the WIT registry
560    /// stabilizes wildcard / hierarchy shapes in tatara-lisp per this
561    /// struct's own `:wit` field docstring, a per-cluster subject-alias
562    /// table the operator pins through a future `:placement`-scoped
563    /// slot, a canonicalization pass that lowercases / dedupes wildcard
564    /// segments, a per-CR fully-qualified rewrite the M4 CR materializer
565    /// applies per-tenant) would have had to be threaded through both
566    /// open-coded copies in lockstep or the two consumers would silently
567    /// disagree on which NATS subject a given edge resolves to — the
568    /// [`WitContract::target`] payload-extraction reading `"orders.paid"`
569    /// while the [`AplicacaoSpec::validate`] dedup key read the operator-
570    /// resolved `"tenant-a.orders.paid"` would silently split the
571    /// [`WitTarget::PubSub`]-arm rendered payload from the actual dedup-
572    /// key uniqueness axis, a two-consumer split at the validator far
573    /// from the source `caixa.lisp` with no field naming the payload-
574    /// drift root cause. Lifting the resolution rule to a typed method
575    /// on the substrate primitive means every downstream pub-sub-payload-
576    /// facing consumer of the Aplicacao's per-`:contratos` L4-payload
577    /// surface reaches for exactly one typed dispatch — the resolver's
578    /// accept-set migrates as a unit on any future axis addition.
579    ///
580    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
581    /// (7020470) `Option<&str>` accessor on the M3 mesh-slot payload-
582    /// carrier axis — second `Option<&str>`-return accessor on the
583    /// per-`:contratos` mesh-slot atom, extending the "optional per-slot
584    /// payload-carrier scalar" projection pattern the [`WitContract::endpoint`]
585    /// HTTP-arm lift opened onto the pub-sub arm; leaves the [`WitContract::slot`]
586    /// key/value-store arm as the last unlifted per-`:contratos`
587    /// `Option<String>` axis. Named `subject()` to match the storage
588    /// field's name and the paired [`WitTarget::PUBSUB_FIELD_NAME`]
589    /// author-facing label const; the accessor's identity name maps
590    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
591    /// docstring already carries.
592    #[must_use]
593    pub fn subject(&self) -> Option<&str> {
594        self.subject.as_deref()
595    }
596
597    /// Substrate-canonical per-`:contratos` `:slot` key/value-store-
598    /// shaped payload-target scalar accessor every consumer that reads
599    /// the edge's `wasi:keyvalue/*` / `kv:*` key-template payload keys
600    /// off — returns the author-declared `:contratos :slot` byte-string
601    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
602    /// own `Option<String>` storage; `None` when the slot is absent
603    /// (the canonical shape of a non-store-`:wit`-world edge — HTTP
604    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, pub-sub
605    /// `nats:*`/`kafka:*` carries `:subject` instead, and a plain
606    /// [`WitTarget::Capability`] edge carries none of the three).
607    ///
608    /// The `:contratos :slot` slot carries the key/value store
609    /// key-template payload (the [`WIT_STORE_SHAPE_PREFIXES`] dispatch
610    /// arm's per-edge target selector — `carts/{cart_id}`,
611    /// `sessions/{tenant}/{sid}`, whatever key-template the author
612    /// names on the store edge) that [`WitContract::target`] projects
613    /// onto the [`WitTarget::Store`] arm's `slot: &'a str` payload when
614    /// the edge's `:wit` world matches the [`WIT_STORE_SHAPE_PREFIXES`]
615    /// accept-set. Every downstream consumer that reads the payload
616    /// keys off this scalar (the [`WitContract::target`] Store-arm
617    /// payload extraction that materializes [`WitTarget::Store { slot }`]
618    /// under the paired [`WitTarget::STORE_FIELD_NAME`] label, the
619    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
620    /// key's store arm that pins the payload as part of the six-tuple
621    /// dedup key alongside the sibling `:endpoint`/`:subject` arms,
622    /// the future M4 per-edge WIT registry resolver's store-arm
623    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
624    /// materializer's per-edge key/value admission webhook, the future
625    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
626    /// as a key-template the operator pins per-CR).
627    ///
628    /// Prior to this lift the `.slot` field was accessed inline at two
629    /// production sites in `caixa-core/src/aplicacao.rs` — the
630    /// [`WitContract::target`] payload-shape dispatch's `let slot =
631    /// self.slot.as_deref();` binding at the top of the method, and
632    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
633    /// tuple's `c.slot.as_deref()` store-arm slot — two open-coded
634    /// field-accesses that expressed no compile-time link back to the
635    /// typed slot. A future extension of the `:contratos :slot` axis
636    /// to a richer author surface (an M4 promotion from `Option<String>`
637    /// to a typed key-template enum once the WIT registry stabilizes
638    /// key-template parameter shapes in tatara-lisp per this struct's
639    /// own `:wit` field docstring, a per-cluster slot-alias table the
640    /// operator pins through a future `:placement`-scoped slot, a
641    /// canonicalization pass that lowercases the bucket prefix, a
642    /// per-CR fully-qualified rewrite the M4 CR materializer applies
643    /// per-tenant) would have had to be threaded through both
644    /// open-coded copies in lockstep or the two consumers would
645    /// silently disagree on which key-template a given edge resolves
646    /// to — the [`WitContract::target`] payload-extraction reading
647    /// `"carts/{cart_id}"` while the [`AplicacaoSpec::validate`] dedup
648    /// key read the operator-resolved `"tenant-a/carts/{cart_id}"`
649    /// would silently split the [`WitTarget::Store`]-arm rendered
650    /// payload from the actual dedup-key uniqueness axis, a
651    /// two-consumer split at the validator far from the source
652    /// `caixa.lisp` with no field naming the payload-drift root cause.
653    /// Lifting the resolution rule to a typed method on the substrate
654    /// primitive means every downstream store-payload-facing consumer
655    /// of the Aplicacao's per-`:contratos` payload surface reaches for
656    /// exactly one typed dispatch — the resolver's accept-set migrates
657    /// as a unit on any future axis addition.
658    ///
659    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
660    /// (7020470) / [`WitContract::subject`] (90de675) `Option<&str>`
661    /// accessors on the M3 mesh-slot payload-carrier axis — third and
662    /// final `Option<&str>`-return accessor on the per-`:contratos`
663    /// mesh-slot atom, closes the last unlifted per-`:contratos`
664    /// `Option<String>` axis and completes the "optional per-slot
665    /// payload-carrier scalar" projection pattern the peer HTTP /
666    /// pub-sub arms established across the three payload-shape
667    /// dispatch arms. Named `slot()` to match the storage field's
668    /// name and the paired [`WitTarget::STORE_FIELD_NAME`]
669    /// author-facing label const; the accessor's identity name maps
670    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
671    /// docstring already carries.
672    #[must_use]
673    pub fn slot(&self) -> Option<&str> {
674        self.slot.as_deref()
675    }
676
677    /// Substrate-canonical per-`:contratos` `(caller, callee)` owned-form
678    /// caller-callee-pair accessor every consumer that constructs an
679    /// [`AplicacaoError`] variant carrying the per-edge `(de, para)`
680    /// caller-callee pair keys off — returns the author-declared
681    /// `:contratos :de` / `:contratos :para` byte-strings verbatim as an
682    /// owned `(String, String)` tuple, projected through the lifted
683    /// [`WitContract::source`] / [`WitContract::destination`] scalar
684    /// accessors so any future rebrand on the caller-arm / callee-arm
685    /// projection axis (an M4 per-cluster caller-alias table the
686    /// operator pins through a future `:placement`-scoped slot, a
687    /// namespace-qualified rewrite the M4 CR materializer applies per-CR,
688    /// a per-`:membros` alias overlay from the future `:membros
689    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
690    /// acknowledges) reaches every diagnostic-construction site by
691    /// construction.
692    ///
693    /// The `(de, para)` pair is the "typed-edge caller-callee identity in
694    /// owned form" primitive every per-`:contratos` diagnostic variant on
695    /// [`AplicacaoError`] carries alongside its payload-shape arm — the
696    /// nine variants [`AplicacaoError::EmptyWit`],
697    /// [`AplicacaoError::ContratoEndpointEmpty`],
698    /// [`AplicacaoError::ContratoEndpointNotAbsolute`],
699    /// [`AplicacaoError::ContratoEndpointInvalid`],
700    /// [`AplicacaoError::ContratoSubjectEmpty`],
701    /// [`AplicacaoError::ContratoSubjectInvalid`],
702    /// [`AplicacaoError::ContratoSlotEmpty`],
703    /// [`AplicacaoError::ContratoSlotInvalid`], and
704    /// [`AplicacaoError::ContratoDuplicate`] each carry a `de: String,
705    /// para: String` field pair the constructor site reads verbatim off
706    /// the [`WitContract`] the diagnostic points at, so a diagnostic
707    /// whose `de:` and `para:` labels silently drift off the source
708    /// caller/callee — a per-cluster caller-alias rewrite that landed on
709    /// one variant's inline `de: c.de.clone()` field access but not on
710    /// its sibling variant's, an accidental swap of the `de:` and `para:`
711    /// arms in a copy-paste of the constructor block — would emit a
712    /// build-time error whose "which caixa is at fault" question the
713    /// operator answers wrongly, far from the source `caixa.lisp`.
714    ///
715    /// Prior to this lift the `(self.de.clone(), self.para.clone())`
716    /// pair was inlined at seven [`WitContract::target`] error-
717    /// construction sites (the [`AplicacaoError::ContratoEndpointEmpty`]
718    /// / [`AplicacaoError::ContratoEndpointNotAbsolute`] /
719    /// [`AplicacaoError::ContratoEndpointInvalid`] HTTP-arm variants,
720    /// the [`AplicacaoError::ContratoSubjectEmpty`] /
721    /// [`AplicacaoError::ContratoSubjectInvalid`] pub-sub-arm variants,
722    /// the [`AplicacaoError::ContratoSlotEmpty`] /
723    /// [`AplicacaoError::ContratoSlotInvalid`] store-arm variants) and
724    /// two [`AplicacaoSpec::validate`] error-construction sites (the
725    /// [`AplicacaoError::EmptyWit`] empty-`:wit` gate, the
726    /// [`AplicacaoError::ContratoDuplicate`] duplicate-`:contratos`
727    /// insert-first-seen closure) — nine open-coded `.de.clone() +
728    /// .para.clone()` pairs that expressed no compile-time contract that
729    /// the caller-arm and callee-arm arms of the same diagnostic
730    /// construction reach for the same [`WitContract`] instance or that
731    /// the `de:` and `para:` label pair binds to the fields the author
732    /// declared. Any future rebrand on the axis — an M4 per-cluster
733    /// caller/callee-alias rewrite the operator pins through a future
734    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
735    /// per-CR fully-qualified namespace prefix the M4
736    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
737    /// per-tenant, a canonicalization pass that lowercases the caller +
738    /// callee identifiers post-parse — would have had to be threaded
739    /// through every open-coded copy in lockstep or one variant's
740    /// diagnostic would silently name a different caller/callee pair
741    /// than its peer, silently degrading the "which caixa is at fault"
742    /// self-locating signal every operator-facing typed diagnostic
743    /// exists to carry. Lifting the pair to a typed method on the
744    /// substrate primitive means every downstream diagnostic-construction
745    /// site reaches for exactly one typed dispatch — the resolver's
746    /// projection migrates as a unit on any future axis addition.
747    ///
748    /// Peer of the sibling per-`:contratos` scalar accessor family
749    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43)
750    /// / [`WitContract::world_ref`] (6226bf4) on the mesh-slot-atom
751    /// scalar-value axes — first composite-projection accessor on the
752    /// per-`:contratos` mesh-slot atom, folds the two open-coded owned-
753    /// form `.clone()` field-accesses that pair the sibling
754    /// caller/callee accessors' `&str`-return borrowed-form outputs onto
755    /// one typed dispatch. Named `edge_pair()` to reflect the identity
756    /// name of the projected tuple (the typed-edge caller-callee pair,
757    /// distinct from the sibling triple-projection
758    /// [`WitContract::edge_triple`] accessor that folds the local `edge`
759    /// closure in [`WitContract::target`] + the paired
760    /// [`AplicacaoError::ContratoDuplicate`] diagnostic constructor
761    /// site's `(de, para, wit)` triple onto one typed dispatch).
762    #[must_use]
763    pub fn edge_pair(&self) -> (String, String) {
764        (self.source().to_string(), self.destination().to_string())
765    }
766
767    /// Owned form of the `(:contratos :de, :contratos :para, :contratos
768    /// :wit)` triple every per-edge diagnostic constructor that names
769    /// all three axes threads verbatim into its `de:` / `para:` /
770    /// `wit:` fields — the [`WitTarget::target`] dispatch's wrong-target
771    /// / missing-target / invalid-wit / capability-with-payload arms
772    /// (eight sites all shape `let (de, para, wit) = edge();
773    /// AplicacaoError::Contrato* { de, para, wit, .. }` before this
774    /// accessor landed) and the sibling
775    /// [`AplicacaoError::ContratoDuplicate`] duplicate-gate diagnostic
776    /// constructor (which paired `edge_pair()` for the `(de, para)`
777    /// prefix with a raw `c.wit.clone()` for the `wit:` tail — a mixed
778    /// typed-dispatch + raw-field-access shape the sibling accessor
779    /// family already flagged as a drift risk). Nine total call sites
780    /// collapse onto this helper.
781    ///
782    /// Lifted with the same one-source-of-truth discipline
783    /// [`WitContract::edge_pair`] carries on the paired
784    /// caller-callee-only axis: the returned tuple's `.0` / `.1` / `.2`
785    /// arms compose through the lifted [`WitContract::source`] /
786    /// [`WitContract::destination`] / [`WitContract::world_ref`]
787    /// scalar accessors byte-for-byte (pinned by the paired
788    /// [`tests::wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`]
789    /// composition-pin), so any future rebrand on the per-`:contratos`
790    /// caller / callee / world-ref axis (an M4 per-cluster
791    /// caller/callee-alias rewrite the operator pins through a future
792    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
793    /// per-CR fully-qualified namespace prefix the M4
794    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
795    /// per-tenant, an M4-typed-caller-enum `Display` re-canonicalization
796    /// on `source()` / `destination()`, a per-CR canonicalization pass
797    /// that lowercases the WIT world ref post-parse) migrates as a
798    /// single caixa-core edit rather than a coordinated rewrite of
799    /// nine open-coded triple-constructors.
800    ///
801    /// Peer of the sibling per-`:contratos` composite-projection
802    /// [`WitContract::edge_pair`] accessor on the mesh-slot-atom
803    /// composite-value axes — closes the last unlifted owned-form
804    /// composite-tuple axis on the per-`:contratos` diagnostic-
805    /// construction surface. Named `edge_triple()` to reflect the
806    /// identity name of the projected tuple (the typed-edge
807    /// caller-callee-wit triple, sibling to the caller-callee-only
808    /// pair `edge_pair()` returns).
809    #[must_use]
810    pub fn edge_triple(&self) -> (String, String, String) {
811        (
812            self.source().to_string(),
813            self.destination().to_string(),
814            self.world_ref().to_string(),
815        )
816    }
817
818    /// Borrowed [`ContratoIdentity`] six-tuple every consumer that
819    /// dedups typed edges keys off — routes through the lifted
820    /// [`WitContract::source`] / [`WitContract::destination`] /
821    /// [`WitContract::world_ref`] / [`WitContract::endpoint`] /
822    /// [`WitContract::subject`] / [`WitContract::slot`] scalar
823    /// accessors so the tuple's six arms and the [`ContratoIdentity`]
824    /// type alias's six axes migrate as a unit on any future axis
825    /// addition (adding a seventh field to [`WitContract`] is one
826    /// [`ContratoIdentity`] alias edit + one accessor addition + one
827    /// arm here, not a coordinated rewrite of every open-coded
828    /// six-tuple builder that dedups on the identity axis).
829    ///
830    /// Sibling of [`WitContract::edge_pair`] /
831    /// [`WitContract::edge_triple`] on the composite-projection axis:
832    /// the pair projects the caller-callee axes, the triple extends it
833    /// with the world-ref, this method extends it with the three
834    /// payload-carrier axes. Every projection returns the same six
835    /// scalar accessors' outputs; the three methods differ only in
836    /// which arms they surface.
837    #[must_use]
838    pub fn identity(&self) -> ContratoIdentity<'_> {
839        (
840            self.source(),
841            self.destination(),
842            self.world_ref(),
843            self.endpoint(),
844            self.subject(),
845            self.slot(),
846        )
847    }
848
849    /// True when this contract targets an HTTP-shaped WIT world.
850    #[must_use]
851    pub fn is_http(&self) -> bool {
852        wit_shape_is_http(self.world_ref())
853    }
854
855    /// True when this contract targets a pub-sub-shaped WIT world.
856    #[must_use]
857    pub fn is_pubsub(&self) -> bool {
858        wit_shape_is_pubsub(self.world_ref())
859    }
860
861    /// True when this contract targets a key/value-shaped WIT world.
862    #[must_use]
863    pub fn is_store(&self) -> bool {
864        wit_shape_is_store(self.world_ref())
865    }
866
867    /// True when this contract targets *none* of the three known payload-
868    /// shape WIT worlds — the fourth (payload-less) arm of the WIT-shape
869    /// partition [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
870    /// open on the [`WitContract`] surface. Returns the exact-inverse
871    /// disjunction of the peer trio — `true` when none of the three
872    /// prefix-set predicates matches the raw `:contratos :wit` value; the
873    /// author-declared WIT world is a pure typed capability edge with no
874    /// payload selector (the shape [`WitContract::target`] projects onto
875    /// the payload-less [`WitTarget::Capability`] arm, MESH-COMPOSITION
876    /// §II.3 — the fourth typed [`WitTarget`] arm the substrate admits).
877    ///
878    /// The `:contratos :wit` shape-space is closed at four arms
879    /// ([`WIT_HTTP_SHAPE_PREFIXES`] / [`WIT_PUBSUB_SHAPE_PREFIXES`] /
880    /// [`WIT_STORE_SHAPE_PREFIXES`] on the payload-carrying arms;
881    /// everything else on the payload-less capability arm), and every
882    /// downstream consumer that must filter contratos by shape-class
883    /// keys off the four sibling predicates (the [`WitContract::target`]
884    /// dispatch's implicit `else` after the three payload-shape arm
885    /// checks at aplicacao.rs:959–1129 that admits [`WitTarget::Capability`],
886    /// every future substrate-side capability-shape-only emitter — the
887    /// M4 per-Aplicacao WIT-registry capability-import materializer, the
888    /// future `feira app graph --capability` per-Aplicacao capability-
889    /// column filter, the future per-cluster capability-scope reconciler
890    /// that skips L4/L7 emission for payload-less edges since Cilium
891    /// can't introspect WASI capability calls, the future
892    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook's per-
893    /// shape shape-count histogram). Every such consumer reaches for one
894    /// typed dispatch on the substrate primitive so the "which arm
895    /// carries the capability-only shape?" answer lives at one caixa-core
896    /// edit rather than open-coded across per-consumer
897    /// `!c.is_http() && !c.is_pubsub() && !c.is_store()` triplet
898    /// negations, each of which would silently drop a future fourth
899    /// payload-arm addition without a compile-time signal at the
900    /// consumer site.
901    ///
902    /// Prior to this lift the "not one of the three known payload
903    /// shapes" classification sat inline at [`WitContract::target`]'s
904    /// implicit `else`-branch (aplicacao.rs:1131 — the payload-less
905    /// [`WitTarget::Capability`] admission arm after the three `if
906    /// self.is_http() { … } if self.is_pubsub() { … } if self.is_store()
907    /// { … }` guards) with no named accessor for downstream consumers
908    /// to reach through. A future substrate-side capability-only
909    /// filter or a future capability-scope reconciler would have had to
910    /// re-inline the same triplet negation at every emit site with no
911    /// compile-time link back to the sibling trio, and a future arm
912    /// addition (a hypothetical fourth payload-shape prefix set — a
913    /// `wasi:sockets/*` transport-layer shape or an `oci:*` capability-
914    /// import carrier per the sibling [`wit_shape_matches`] docstring's
915    /// trajectory bullet) would land the new predicate on the payload-
916    /// carrying trio and silently misclassify the new shape as
917    /// capability at every triplet-negation consumer site, propagating
918    /// the drift far from the caixa-core prefix-set commit.
919    ///
920    /// Fourth arm on the [`WitContract`] WIT-shape-predicate family —
921    /// closes the {[`Self::is_http`], [`Self::is_pubsub`], [`Self::is_store`]}
922    /// trio into a 4-way partition witness on the raw `:contratos :wit`
923    /// axis, mirroring the paired post-projection [`WitTarget`]
924    /// `gen_platform::IsVariant`-derived 4-way predicate set
925    /// ([`WitTarget::is_http`] / [`WitTarget::is_pubsub`] /
926    /// [`WitTarget::is_store`] / [`WitTarget::is_capability`]) on the
927    /// typed-view surface (7f6aa98 `IsVariant` derive lift on the peer
928    /// arm-set). The two typed axes — pre-projection on the raw
929    /// `:contratos :wit` string, post-projection on the validated typed
930    /// view — now carry a matched 4-arm predicate discipline: every
931    /// arm on the closed [`WitTarget`] set has a peer pre-projection
932    /// predicate on the [`WitContract`] surface, and any future
933    /// [`WitTarget`] variant addition (an M4 `Rest` / `Grpc` split of
934    /// [`WitTarget::Http`] once the WIT registry stabilizes gRPC-shaped
935    /// worlds per [`WitTarget`]'s own docstring at aplicacao.rs:1341-1343,
936    /// a `Queue`-shaped peer of [`WitTarget::Store`]) reaches this
937    /// pre-projection axis through a matching peer prefix-set + peer
938    /// predicate lift by construction — the compile-time exhaustiveness
939    /// on [`WitTarget::payload_pair`]'s single dispatch already enforces
940    /// the post-projection accessor family stays in sync, and the sibling
941    /// [`tests::wit_contract_is_capability_partitions_the_wit_shape_space`]
942    /// partition-witness pin locks the pre-projection classification in
943    /// load-bearing so a peer prefix-set addition that widened one arm's
944    /// accept-set without shrinking the [`Self::is_capability`] accept-set
945    /// surfaces as a test failure at caixa-core build time rather than a
946    /// silent per-consumer split at renderer emit time.
947    ///
948    /// Composes byte-for-byte through the lifted peer trio
949    /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] so
950    /// any future rebrand of any prefix-set const flows through this
951    /// method by construction without a coordinated per-consumer rewrite
952    /// (pinned by the sibling
953    /// [`tests::wit_contract_is_capability_composes_through_shape_predicate_negation`]
954    /// composition-witness).
955    ///
956    /// Note: purely syntactic classification on the `:wit` prefix-set —
957    /// unlike [`Self::target`], which additionally rejects value-shape-
958    /// invalid `:wit` strings (uppercase, hyphen-for-colon typo, empty
959    /// package) via [`crate::render::is_wit_world_ref`] and payload-
960    /// shape mismatches. A [`WitContract`] whose `:wit` is empty or
961    /// structurally malformed returns `true` from `is_capability()` (the
962    /// prefix set matches nothing), and the surrounding
963    /// [`AplicacaoSpec::validate`] / [`WitContract::target`] gate cascade
964    /// is where the [`AplicacaoError::EmptyWit`] /
965    /// [`AplicacaoError::ContratoWitInvalid`] diagnostic surfaces — this
966    /// predicate is the classifier, not the validator.
967    #[must_use]
968    pub fn is_capability(&self) -> bool {
969        wit_shape_is_capability(self.world_ref())
970    }
971
972    /// True when this contract's caller equals its callee — a
973    /// structurally degenerate typed edge that no `:contratos` entry can
974    /// legitimately carry (MESH-COMPOSITION §III.1 — "Servico A calls
975    /// Servico B" is an *inter*-Servico contract between two distinct
976    /// graph nodes). A Servico contracting with itself resolves to an
977    /// in-process call the wasm-engine never routes through the mesh at
978    /// all, so no rendered `CiliumNetworkPolicy` / `HTTPRoute` /
979    /// per-edge policy can express the intended shape — the pub-sub
980    /// path silently rendered a self-allow rule that is a no-op (intra-
981    /// pod traffic bypasses the mesh entirely), and the synchronous
982    /// paths surfaced as a misleading `ContratoCycle` whose path was
983    /// `["cart", "cart"]` — framing a self-edge as a multi-node
984    /// deadlock. Every downstream consumer that must reject the shape
985    /// (the [`AplicacaoSpec::validate`] per-`:contratos` self-loop
986    /// gate at caixa-core/src/aplicacao.rs:5559, every future
987    /// per-`:contratos`-edge policy resolver on the M4 CR materializer
988    /// axis, every future adjacency-graph builder that must skip self-
989    /// edges rather than fold them into an incidental cycle) now keys
990    /// off exactly one typed dispatch on the substrate primitive, so
991    /// any future rebrand on the axis (an M4-typed-caller enum whose
992    /// identity comparison rule the accessor could route through, an
993    /// operator-side per-cluster caller/callee-alias table the
994    /// materializer resolves per-CR before the equality probe, a
995    /// promotion of the pointwise `==` to a set-membership check once
996    /// SimpleOneForOne-shaped dynamic replicas come into typed scope
997    /// so a per-replica self-edge is rejected under the same predicate)
998    /// migrates as a single caixa-core edit rather than a coordinated
999    /// rewrite of every downstream self-edge consumer. Composes
1000    /// byte-for-byte through the lifted [`Self::source`] /
1001    /// [`Self::destination`] scalar accessors — the accessor pair every
1002    /// per-`:contratos` scalar-value axis already routes through — so
1003    /// any future rebrand of the underlying `:de` / `:para` storage
1004    /// (a lift from `String` to a typed `ServicoName(String)` newtype,
1005    /// a per-Aplicacao interning arena the M4 CR materializer authors,
1006    /// a `smol_str::SmolStr` inline-buffer swap) flows through the
1007    /// same one body without a coordinated per-consumer rewrite.
1008    ///
1009    /// Sibling in shape to the peer per-`:contratos` shape-predicate
1010    /// family [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
1011    /// on the `:wit` world-ref axis — extended onto the per-edge
1012    /// endpoint-equality axis: `is_http` / `is_pubsub` / `is_store`
1013    /// partition the WIT-shape-space; `is_self_loop` partitions the
1014    /// caller-callee identity-space. Named `is_self_loop()` to reflect
1015    /// the graph-theoretic identity of the shape (a loop from a graph
1016    /// node to itself, distinct from the sibling multi-node
1017    /// `ContratoCycle` shape [`Self::detect_sync_cycles`] rejects) and
1018    /// to match the [`AplicacaoError::ContratoSelfLoop`] diagnostic
1019    /// variant already carrying the term.
1020    #[must_use]
1021    pub fn is_self_loop(&self) -> bool {
1022        self.source() == self.destination()
1023    }
1024
1025    /// Typed view of the contract's payload target. Enforces that the
1026    /// `:wit` shape and the carried `:endpoint`/`:subject`/`:slot`
1027    /// fields agree, and that each carried value is itself
1028    /// value-shape valid:
1029    ///
1030    ///   - HTTP world (`wasi:http/*`, `http:*`) ⇒ exactly `:endpoint`,
1031    ///     non-empty, leading-`/` (Cilium L7 `path` + Gateway API
1032    ///     `PathPrefix` invariant — same shape required of `:entrada
1033    ///     :paths`)
1034    ///   - `PubSub` world (`nats:*`, `kafka:*`) ⇒ exactly `:subject`,
1035    ///     non-empty (NATS / Kafka publish without a subject is a
1036    ///     no-op subscribe, never the author's intent)
1037    ///   - Store world (`wasi:keyvalue/*`, `kv:*`) ⇒ exactly `:slot`,
1038    ///     non-empty (an empty slot template addresses the bucket
1039    ///     root, defeating the per-key isolation the slot exists for)
1040    ///   - Anything else ⇒ none of the three; the contract is a pure
1041    ///     typed capability edge with no payload selector.
1042    ///
1043    /// Translates the Apollo Federation discipline ("conflicts are
1044    /// errors at compile time, not warnings at runtime";
1045    /// MESH-COMPOSITION §II.3) onto pleme-io's typed Aplicacao surface:
1046    /// a contract whose WIT shape disagrees with its target field, or
1047    /// whose target field carries a value-shape-invalid string, is a
1048    /// build error — not a silent renderer drop. The returned
1049    /// [`WitTarget`] view's `&str` payload is therefore guaranteed
1050    /// non-empty (and absolute, for `Http`); every downstream consumer
1051    /// (caixa-mesh's L7 emission, the M3 Gateway/HTTPRoute renderer,
1052    /// the M4 per-edge policy resolver) can rely on that without
1053    /// re-checking.
1054    pub fn target(&self) -> Result<WitTarget<'_>, AplicacaoError> {
1055        // Route the HTTP-shaped payload-target extraction through the
1056        // lifted [`WitContract::endpoint`] accessor rather than the raw
1057        // `self.endpoint.as_deref()` field access — the two production
1058        // consumers of the per-`:contratos :endpoint` HTTP-shaped
1059        // payload-carrier scalar (this method's Http-arm payload
1060        // extraction, the [`AplicacaoSpec::validate`] duplicate-
1061        // `:contratos` [`ContratoIdentity`] dedup-key HTTP arm) now key
1062        // off exactly one typed dispatch on the substrate primitive, so
1063        // any future rebrand on the axis (an M4 per-cluster endpoint-
1064        // alias rewrite, a per-CR fully-qualified path prefix the M4
1065        // materializer applies per-tenant, an M4 promotion from
1066        // `Option<String>` to a typed HTTP path-template enum) migrates
1067        // as a single caixa-core edit rather than a coordinated rewrite
1068        // of the two call sites — peer of the sibling M3 per-`:placement`
1069        // [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
1070        // (74ec2d3) `Option<&str>` typed-dispatch discipline extended
1071        // onto the per-`:contratos` HTTP-shaped payload-carrier axis.
1072        let endpoint = self.endpoint();
1073        let subject = self.subject();
1074        // Route the store-arm payload-carrier scalar through the
1075        // lifted [`WitContract::slot`] accessor rather than the raw
1076        // `self.slot.as_deref()` field access — the two production
1077        // consumers of the per-`:contratos :slot` key/value-store-
1078        // shaped payload-carrier scalar (this method's Store-arm
1079        // payload extraction, the [`AplicacaoSpec::validate`]
1080        // duplicate-`:contratos` [`ContratoIdentity`] dedup-key store
1081        // arm) now key off exactly one typed dispatch on the substrate
1082        // primitive. Closes the last unlifted per-`:contratos`
1083        // `Option<String>` axis, completing the payload-carrier
1084        // accessor family peer of the sibling per-`:contratos`
1085        // [`WitContract::endpoint`] (7020470) / [`WitContract::subject`]
1086        // (90de675) lifts across the HTTP / pub-sub arms.
1087        let slot = self.slot();
1088        // Route the local `(de, para, wit)` triple-projection closure
1089        // through the lifted [`WitContract::edge_triple`] typed accessor
1090        // rather than re-inlining `(self.de.clone(), self.para.clone(),
1091        // self.wit.clone())` — the eight [`AplicacaoError::Contrato*`]
1092        // triple-carrying diagnostic constructors below (wrong-target /
1093        // missing-target on all three payload arms + capability-with-
1094        // payload + invalid-wit) now key off exactly one typed dispatch
1095        // on the substrate-primitive composite projection, sibling to
1096        // the peer [`WitContract::edge_pair`]-routed
1097        // [`AplicacaoError::Empty*`]/`ContratoEndpointEmpty`/
1098        // `ContratoSubjectEmpty`/`ContratoSlotEmpty` pair-carrying
1099        // diagnostic constructors on the same per-`:contratos`
1100        // diagnostic-construction surface.
1101        let edge = || self.edge_triple();
1102
1103        // The `:wit` value drives every downstream dispatch — the
1104        // is_http/is_pubsub/is_store prefix matchers below, the
1105        // caixa-mesh L7-vs-L4 emission, the cycle-detector's pub-sub
1106        // exclusion. Until this gate landed `target()` accepted any
1107        // non-empty string and silently demoted unrecognized shapes to
1108        // a capability-only edge (`:wit "WASI:HTTP/proxy"` — uppercase
1109        // typo, `:wit "wasi-http/proxy"` — hyphen-instead-of-colon typo,
1110        // `:wit "wasi:http proxy"` — whitespace, `:wit "wasi:"` — empty
1111        // package, the paste-from-binary footgun a multi-line blob
1112        // accidentally landing in the slot, the un-percent-encoded
1113        // non-ASCII byte) — the canonical "I thought I had L7 HTTP
1114        // routing, got L4-only" footgun. Empty is still pre-checked at
1115        // the [`AplicacaoSpec::validate`] call site via the narrower
1116        // [`AplicacaoError::EmptyWit`] variant (and fires first at the
1117        // validate layer); the value-shape gate here picks up the
1118        // structurally-invalid non-empty cases the empty check misses,
1119        // and remains correct under direct `target()` calls outside
1120        // validate (the predicate's defensive empty arm returns a
1121        // parser-shaped reason rather than silently falling through to
1122        // the Capability arm). Same trajectory as c4213a4 (WitContract
1123        // endpoint/subject/slot value-shape gates lifted into
1124        // `target()`) on the peer payload axes.
1125        if let Err(reason) = crate::render::is_wit_world_ref(&self.wit) {
1126            let (de, para, wit) = edge();
1127            return Err(AplicacaoError::ContratoWitInvalid {
1128                de,
1129                para,
1130                wit,
1131                reason,
1132            });
1133        }
1134
1135        if self.is_http() {
1136            if subject.is_some() || slot.is_some() {
1137                let (de, para, wit) = edge();
1138                return Err(AplicacaoError::ContratoWrongTarget {
1139                    de,
1140                    para,
1141                    wit,
1142                    expected: WitTarget::HTTP_FIELD_NAME,
1143                });
1144            }
1145            let ep = endpoint.ok_or_else(|| {
1146                let (de, para, wit) = edge();
1147                AplicacaoError::ContratoMissingTarget {
1148                    de,
1149                    para,
1150                    wit,
1151                    expected: WitTarget::HTTP_FIELD_NAME,
1152                }
1153            })?;
1154            if ep.is_empty() {
1155                let (de, para) = self.edge_pair();
1156                return Err(AplicacaoError::ContratoEndpointEmpty { de, para });
1157            }
1158            if !ep.starts_with('/') {
1159                let (de, para) = self.edge_pair();
1160                return Err(AplicacaoError::ContratoEndpointNotAbsolute {
1161                    de,
1162                    para,
1163                    endpoint: ep.to_string(),
1164                });
1165            }
1166            // The `:endpoint` lands verbatim as a Cilium L7 `path:` rule
1167            // (caixa-mesh/src/lib.rs:311) and shares the K8s Gateway
1168            // API v1 HTTPPathMatch.value admission grammar with the
1169            // sibling `:entrada :paths` axis. Until this gate landed
1170            // `target()` only refused the empty string + the missing-
1171            // leading-`/` form; a structurally invalid endpoint
1172            // (`"/charge?token=X"` — query in path slot, `"/foo bar"` —
1173            // un-percent-encoded whitespace, `"/api/café"` — non-ASCII,
1174            // `"/api//bar"` — consecutive slash, `"/api/../etc"` —
1175            // path-traversal segment, the >1024-byte slug) silently
1176            // passed validate and the failure surfaced at apply time
1177            // as a Cilium policy rejection / silent traffic drop, far
1178            // from the source caixa.lisp. Same Gateway API HTTPPathMatch
1179            // grammar `:entrada :paths` already gates (55410e4), now
1180            // shared with `:contratos :endpoint` through the lifted
1181            // `crate::render::is_gateway_api_http_path` predicate.
1182            if let Err(reason) = crate::render::is_gateway_api_http_path(ep) {
1183                let (de, para) = self.edge_pair();
1184                return Err(AplicacaoError::ContratoEndpointInvalid {
1185                    de,
1186                    para,
1187                    endpoint: ep.to_string(),
1188                    reason,
1189                });
1190            }
1191            return Ok(WitTarget::Http { endpoint: ep });
1192        }
1193        if self.is_pubsub() {
1194            if endpoint.is_some() || slot.is_some() {
1195                let (de, para, wit) = edge();
1196                return Err(AplicacaoError::ContratoWrongTarget {
1197                    de,
1198                    para,
1199                    wit,
1200                    expected: WitTarget::PUBSUB_FIELD_NAME,
1201                });
1202            }
1203            let s = subject.ok_or_else(|| {
1204                let (de, para, wit) = edge();
1205                AplicacaoError::ContratoMissingTarget {
1206                    de,
1207                    para,
1208                    wit,
1209                    expected: WitTarget::PUBSUB_FIELD_NAME,
1210                }
1211            })?;
1212            if s.is_empty() {
1213                let (de, para) = self.edge_pair();
1214                return Err(AplicacaoError::ContratoSubjectEmpty { de, para });
1215            }
1216            // The `:subject` lands at runtime as the NATS subject the
1217            // producer publishes to and the consumer subscribes from.
1218            // Until this gate landed `target()` only refused the
1219            // empty string; a structurally invalid subject
1220            // (`"foo..bar"` — empty token between separators,
1221            // `"foo.>.bar"` — non-trailing `>` wildcard the NATS
1222            // server's subject parser rejects, `"foo bar"` —
1223            // un-percent-encoded whitespace, `"foo.café"` —
1224            // un-percent-encoded non-ASCII, `".foo"` / `"foo."` —
1225            // empty leading/trailing tokens, the >256-byte
1226            // paste-from-binary slug) silently passed validate and
1227            // the failure surfaced at runtime as a NATS server-side
1228            // `-ERR 'Invalid Subject'` on publish / subscribe, or as
1229            // a silent message drop, far from the source caixa.lisp.
1230            // Same Gateway API HTTPPathMatch / WIT-IDL grammar
1231            // trajectory `:contratos :endpoint` (4f0390b) and
1232            // `:contratos :wit` (6226bf4) already gate, now shared
1233            // with `:contratos :subject` through the lifted
1234            // `crate::render::is_nats_subject` predicate.
1235            if let Err(reason) = crate::render::is_nats_subject(s) {
1236                let (de, para) = self.edge_pair();
1237                return Err(AplicacaoError::ContratoSubjectInvalid {
1238                    de,
1239                    para,
1240                    subject: s.to_string(),
1241                    reason,
1242                });
1243            }
1244            return Ok(WitTarget::PubSub { subject: s });
1245        }
1246        if self.is_store() {
1247            if endpoint.is_some() || subject.is_some() {
1248                let (de, para, wit) = edge();
1249                return Err(AplicacaoError::ContratoWrongTarget {
1250                    de,
1251                    para,
1252                    wit,
1253                    expected: WitTarget::STORE_FIELD_NAME,
1254                });
1255            }
1256            let sl = slot.ok_or_else(|| {
1257                let (de, para, wit) = edge();
1258                AplicacaoError::ContratoMissingTarget {
1259                    de,
1260                    para,
1261                    wit,
1262                    expected: WitTarget::STORE_FIELD_NAME,
1263                }
1264            })?;
1265            if sl.is_empty() {
1266                let (de, para) = self.edge_pair();
1267                return Err(AplicacaoError::ContratoSlotEmpty { de, para });
1268            }
1269            // Value-shape gate on the third (and last) typed payload
1270            // axis the `WitContract::target` dispatch carries — the
1271            // peer of [`crate::render::is_gateway_api_http_path`] for
1272            // `:endpoint` (4f0390b) and [`crate::render::is_nats_subject`]
1273            // for `:subject` (63e18a0). Until this gate landed
1274            // `target()` only refused the empty string; a structurally
1275            // invalid slot (`"check out/$order"` — un-percent-encoded
1276            // whitespace whose runtime behavior varies unpredictably
1277            // across kv backends, `"checkout/\x01order"` — control
1278            // character that Redis admits but corrupts on next read
1279            // and DynamoDB rejects outright, `"chéckout/$order"` —
1280            // un-percent-encoded non-ASCII byte each backend re-encodes
1281            // differently, `"checkout\n/$order"` — embedded newline,
1282            // the 513-byte paste-from-binary slug) silently passed
1283            // validate and surfaced at runtime as a per-backend kv
1284            // write rejection (DynamoDB / etcd) or as a silent
1285            // next-read corruption (Redis-via-RESP3), far from the
1286            // source caixa.lisp with no field naming which `:contratos`
1287            // edge carried the typo. The lifted predicate makes the
1288            // kv-backend intersection-floor a substrate-level
1289            // invariant at validate time, not a runtime "this passed
1290            // validate but the kv backend rejected on first write"
1291            // surprise — closes the typed payload-axis value-shape
1292            // trajectory across all three legs of the four
1293            // [`WitTarget`] arms (HTTP / PubSub / Store / Capability)
1294            // that caixa-mesh + the future kv emitters land in.
1295            if let Err(reason) = crate::render::is_wasi_keyvalue_slot(sl) {
1296                let (de, para) = self.edge_pair();
1297                return Err(AplicacaoError::ContratoSlotInvalid {
1298                    de,
1299                    para,
1300                    slot: sl.to_string(),
1301                    reason,
1302                });
1303            }
1304            return Ok(WitTarget::Store { slot: sl });
1305        }
1306
1307        // Unrecognized WIT world — must not carry any payload target.
1308        if endpoint.is_some() || subject.is_some() || slot.is_some() {
1309            let (de, para, wit) = edge();
1310            return Err(AplicacaoError::ContratoWrongTarget {
1311                de,
1312                para,
1313                wit,
1314                expected: WitTarget::CAPABILITY_EXPECTED,
1315            });
1316        }
1317        Ok(WitTarget::Capability)
1318    }
1319}
1320
1321/// Borrowed identity key for the typed-graph duplicate-`:contratos`
1322/// gate (see [`AplicacaoSpec::validate`]): every field that
1323/// distinguishes one contract from another, in declaration order
1324/// (`(de, para, wit, endpoint, subject, slot)`). Two [`WitContract`]s
1325/// with equal [`ContratoIdentity`]s are the same typed edge declared
1326/// twice — the graph-edge analogue of duplicate `:membros` /
1327/// `:placement :clusters` / `:entrada :paths` entries. Lifted as a
1328/// type alias so the duplicate-gate's `HashSet<…>` type doesn't trip
1329/// clippy's `type_complexity` lint (and so a future axis added to
1330/// `WitContract` is one alias edit, not a coordinated rewrite of
1331/// every set instantiation).
1332pub type ContratoIdentity<'a> = (
1333    &'a str,
1334    &'a str,
1335    &'a str,
1336    Option<&'a str>,
1337    Option<&'a str>,
1338    Option<&'a str>,
1339);
1340
1341/// Typed view of a [`WitContract`]'s payload target. Each variant
1342/// carries the field its WIT shape requires; constructing a `Http`
1343/// view without an endpoint is impossible by the type system.
1344///
1345/// Renderers (caixa-mesh L7 rules, feira app graph) match on this
1346/// instead of probing `Option<String>` fields one by one — the
1347/// "which payload field is set?" question is answered once, at
1348/// validation time.
1349#[derive(Debug, Clone, Copy, PartialEq, Eq, gen_platform::IsVariant)]
1350pub enum WitTarget<'a> {
1351    /// HTTP-shaped WIT world. Carries the configured request path.
1352    Http { endpoint: &'a str },
1353    /// Pub-sub-shaped WIT world. Carries the event-stream subject.
1354    ///
1355    /// The `IsVariant` derive would auto-name the predicate `is_pub_sub`
1356    /// (`discriminant_to_snake("PubSub") == "pub_sub"`); the explicit
1357    /// `#[is_variant(name = "pubsub")]` override keeps the emitted
1358    /// method name byte-identical to the sibling
1359    /// [`WitContract::is_pubsub`] predicate (the paired shape-side
1360    /// arm-discriminator that routes through
1361    /// [`wit_shape_is_pubsub`] on the wit-world-ref scalar rather than
1362    /// through `matches!` on the variant), so the two arm-discriminator
1363    /// axes — target-side variant-arm and shape-side ref-prefix — reach
1364    /// every downstream consumer through the same `is_pubsub()` name.
1365    #[is_variant(name = "pubsub")]
1366    PubSub { subject: &'a str },
1367    /// Key-value-shaped WIT world. Carries the slot template.
1368    Store { slot: &'a str },
1369    /// A typed capability edge with no payload selector — the WIT
1370    /// world stands on its own (rare; reserved for plain capability
1371    /// imports or M4-and-later WIT worlds we haven't shaped yet).
1372    Capability,
1373}
1374
1375impl<'a> WitTarget<'a> {
1376    /// Canonical author-facing `:contratos` payload field name for the
1377    /// HTTP-shaped arm — the `expected: &'static str` scalar the
1378    /// [`AplicacaoError::ContratoMissingTarget`] /
1379    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1380    /// through, the `:endpoint "…"` keyword the [`WitTarget::label`]
1381    /// duplicate-edge diagnostic emits, and the `endpoint=…` prefix
1382    /// the `feira app graph` verb prints. Peer of
1383    /// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
1384    /// on the payload-field-name axis; declared as a peer const next
1385    /// to the [`WitTarget::Http`] variant so a future rename on the
1386    /// author-surface `(defcaixa … :contratos ((:de … :para … :wit …
1387    /// :endpoint …)))` field lands in exactly one place, not scattered
1388    /// across the [`WitContract::target`] gate's six `expected:`
1389    /// literals, the label template, and every downstream consumer
1390    /// that prints a per-arm prefix. Same trajectory as the peer
1391    /// [`WitTarget::label`] lift (174e96a): a single source of truth
1392    /// for the arm's shape, next to the variant declaration.
1393    pub const HTTP_FIELD_NAME: &'static str = "endpoint";
1394    /// Canonical author-facing `:contratos` payload field name for the
1395    /// pub-sub-shaped arm. Peer of [`WitTarget::HTTP_FIELD_NAME`] /
1396    /// [`WitTarget::STORE_FIELD_NAME`] on the payload-field-name axis;
1397    /// see [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1398    pub const PUBSUB_FIELD_NAME: &'static str = "subject";
1399    /// Canonical author-facing `:contratos` payload field name for the
1400    /// key/value-store-shaped arm. Peer of
1401    /// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`]
1402    /// on the payload-field-name axis; see
1403    /// [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1404    pub const STORE_FIELD_NAME: &'static str = "slot";
1405
1406    /// Canonical stable human-readable label the payload-less
1407    /// [`WitTarget::Capability`] arm renders as under [`Self::label`] —
1408    /// the byte-string every consumer that formats a payload-less
1409    /// typed capability edge as text lands on (the
1410    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` diagnostic
1411    /// naming which identical edge was declared twice, the future
1412    /// `feira app graph` verb's per-arm prefix, the future M4 per-edge
1413    /// policy resolver's audit view, the operator's mesh-graph audit).
1414    /// Peer of the payload-arm [`Self::HTTP_FIELD_NAME`] /
1415    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`]
1416    /// author-facing label-scalar consts — the same
1417    /// "one canonical declaration per arm, next to the variant, so a
1418    /// future rename lands in one place" discipline extended to the
1419    /// payload-less arm. Until this lift landed the byte-string sat
1420    /// twice — once inline in [`Self::label`]'s [`WitTarget::Capability`]
1421    /// match arm, once in the pin test asserting the label's
1422    /// [`WitTarget::Capability`] output — with no compile-time link
1423    /// between the two: a rebrand on either side (an operator-facing
1424    /// vocabulary shift, a per-consumer disambiguation like
1425    /// `"(capability — no payload; typed edge only)"`) would silently
1426    /// desynchronize until a downstream consumer surfaced the drift at
1427    /// runtime.
1428    pub const CAPABILITY_LABEL: &'static str = "(capability — no payload)";
1429
1430    /// Canonical `expected:` scalar the
1431    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1432    /// through for the payload-less [`WitTarget::Capability`] arm — the
1433    /// byte-string authors read as "this WIT world's shape is not one
1434    /// of {`HTTP`, `PubSub`, `Store`}, so it must not carry
1435    /// `:endpoint` / `:subject` / `:slot`". Peer of the payload-arm
1436    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1437    /// [`Self::STORE_FIELD_NAME`] consts on the
1438    /// `ContratoWrongTarget::expected` axis — the fourth arm of the
1439    /// same "which payload field name goes in the diagnostic" dispatch
1440    /// the three payload-arm consts cover, extended to the payload-less
1441    /// arm. Until this lift landed the byte-string sat twice — once
1442    /// inline in the [`Self::target`] Capability-arm rejection at the
1443    /// production dispatch, once in the pin test asserting the
1444    /// diagnostic's `expected:` scalar carries `"none"` verbatim — with
1445    /// no compile-time link between the two: a rebrand on either side
1446    /// (an author-facing vocabulary shift to `"capability"` /
1447    /// `"(none)"` / `"no-payload"` as the WIT registry's shape
1448    /// vocabulary sharpens, a per-consumer disambiguation as M4 splits
1449    /// [`WitTarget::Capability`] into per-shape peers) would silently
1450    /// desynchronize until a downstream consumer surfaced the drift at
1451    /// runtime. Same "one canonical declaration per arm, next to the
1452    /// variant, so a future rename lands in one place" discipline the
1453    /// peer [`Self::CAPABILITY_LABEL`] lift (7ed03a3-era) already
1454    /// established for the payload-less arm's human-readable label
1455    /// axis; this lift extends it onto the peer diagnostic-scalar axis
1456    /// so both halves of the "how does the Capability arm surface at
1457    /// its two consumer axes (human-readable label, wrong-target
1458    /// diagnostic)" pipeline route through peer consts declared next
1459    /// to the variant.
1460    ///
1461    /// Pairwise-distinctness against the three payload-arm scalars
1462    /// ([`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1463    /// [`Self::STORE_FIELD_NAME`]) is pinned by the sibling
1464    /// `wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`
1465    /// test — the 4-way closure of the 3-way
1466    /// `wit_target_field_names_are_pairwise_distinct` sibling pin onto
1467    /// the `ContratoWrongTarget::expected` axis, matching the peer
1468    /// `m3_placement_estrategia_consts_are_pairwise_distinct` closed-set
1469    /// scalar-value distinctness discipline the sibling M3 typed-enum
1470    /// discriminator axis already carries.
1471    pub const CAPABILITY_EXPECTED: &'static str = "none";
1472
1473    /// Canonical `feira app graph` per-`:contratos`-edge payload-column
1474    /// byte-string the payload-less [`WitTarget::Capability`] arm renders
1475    /// as under [`Self::graph_label`] — the sibling
1476    /// [`WitTarget::CAPABILITY_LABEL`] scalar on the peer graph-verb
1477    /// payload-column axis (the graph verb spells payload-less as
1478    /// `(capability-only)`, distinct from the duplicate-`:contratos`
1479    /// diagnostic's `(capability — no payload)` on the human-readable
1480    /// [`Self::label`] axis). Peer of [`Self::CAPABILITY_LABEL`] /
1481    /// [`Self::CAPABILITY_EXPECTED`] on the payload-less-arm scalar-const
1482    /// family — extends the "one canonical declaration per arm, next to
1483    /// the variant, so a future rename lands in one place" discipline
1484    /// onto the third payload-less-arm consumer axis (`feira app graph`
1485    /// payload column, joining the [`Self::label`] duplicate-`:contratos`
1486    /// diagnostic axis and the [`Self::target`] wrong-target diagnostic
1487    /// axis).
1488    ///
1489    /// Until this lift landed the byte-string sat inline in
1490    /// [`caixa-feira`]'s `cmd::app::GraphArgs::run` per-`:contratos` payload-
1491    /// column match at `caixa-feira/src/cmd/app.rs:111` as a raw
1492    /// `"(capability-only)".to_string()` literal, with no compile-time link
1493    /// back to the [`WitTarget::Capability`] variant declaration nor to
1494    /// the sibling [`Self::CAPABILITY_LABEL`] / [`Self::CAPABILITY_EXPECTED`]
1495    /// peer consts already carrying the "one canonical declaration per
1496    /// payload-less-arm consumer axis" discipline. A rebrand on either
1497    /// side (the graph verb's operator-facing vocabulary tightening from
1498    /// `"(capability-only)"` to `"capability"` / `"(capability edge)"` as
1499    /// the WIT registry vocabulary sharpens, an M4 split of
1500    /// [`Self::Capability`] into per-shape peers) would silently
1501    /// desynchronize the graph-verb byte-string from the paired
1502    /// per-arm-adjacent const and land two spellings of the same axis in
1503    /// two spots.
1504    pub const CAPABILITY_GRAPH_LABEL: &'static str = "(capability-only)";
1505
1506    /// The `(author-facing field name, payload)` pair this typed target
1507    /// arm carries — `Some((HTTP_FIELD_NAME, endpoint))` for
1508    /// [`Self::Http`], `Some((PUBSUB_FIELD_NAME, subject))` for
1509    /// [`Self::PubSub`], `Some((STORE_FIELD_NAME, slot))` for
1510    /// [`Self::Store`], `None` for the payload-less
1511    /// [`Self::Capability`] arm.
1512    ///
1513    /// Lifted as the single 4-arm dispatch that both [`Self::label`]
1514    /// (formats `":{field} {payload:?}"` on `Some`, falls to
1515    /// [`Self::CAPABILITY_LABEL`] on `None`) and [`Self::field_name`]
1516    /// (returns the first component) route through, so a future
1517    /// [`WitTarget`] variant addition — the M4-and-later per-edge WIT
1518    /// registry may split [`Self::Http`] into `Rest` / `Grpc` peers,
1519    /// or extend [`Self::Store`] with a `Queue`-shaped peer — becomes
1520    /// exactly one new match-arm here (a compile-time exhaustiveness
1521    /// error otherwise), not a coordinated three-way rewrite of the
1522    /// prior [`Self::label`] template + [`Self::field_name`] dispatch
1523    /// + every downstream consumer that reaches for the pair.
1524    ///
1525    /// Until this lift landed the three payload arms sat in
1526    /// [`Self::label`] as three near-identical `format!(":{} {…:?}", …)`
1527    /// invocations (one per variant, each hand-quoting the paired
1528    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1529    /// [`Self::STORE_FIELD_NAME`] const) — the canonical
1530    /// "same shape, written N times" duplication THEORY.md §I.3.5
1531    /// ("Generation first, composition second, hand-authoring last;
1532    /// the duplication budget is zero") promotes to a build-time
1533    /// concern, with each per-arm site paired to its own const with no
1534    /// compile-time link between the format template and the arm's
1535    /// payload extraction.
1536    #[must_use]
1537    pub const fn payload_pair(&self) -> Option<(&'static str, &'a str)> {
1538        match *self {
1539            WitTarget::Http { endpoint } => Some((Self::HTTP_FIELD_NAME, endpoint)),
1540            WitTarget::PubSub { subject } => Some((Self::PUBSUB_FIELD_NAME, subject)),
1541            WitTarget::Store { slot } => Some((Self::STORE_FIELD_NAME, slot)),
1542            WitTarget::Capability => None,
1543        }
1544    }
1545
1546    /// The canonical author-facing `:contratos` payload field name
1547    /// this typed target arm carries (`Http` → `Some("endpoint")`,
1548    /// `PubSub` → `Some("subject")`, `Store` → `Some("slot")`), or
1549    /// `None` for the payload-less `Capability` arm.
1550    ///
1551    /// Routes through [`Self::payload_pair`] — the single 4-arm
1552    /// dispatch [`Self::label`] also reads — so a future variant
1553    /// addition is one match-arm edit at [`Self::payload_pair`], not a
1554    /// per-consumer rewrite. Same "exhaustive-match at one canonical
1555    /// dispatch, thin projections at each consumer" trajectory the
1556    /// peer [`PlacementStrategy::as_str`] / [`std::fmt::Display`]
1557    /// pair (0a2f653) landed on the sibling M3 typed-enum axis.
1558    #[must_use]
1559    pub const fn field_name(&self) -> Option<&'static str> {
1560        match self.payload_pair() {
1561            Some((f, _)) => Some(f),
1562            None => None,
1563        }
1564    }
1565
1566    /// The underlying scalar the payload-carrying arm carries — the
1567    /// per-arm request path ([`Self::Http`] `:endpoint`), event-stream
1568    /// subject ([`Self::PubSub`] `:subject`), or slot template
1569    /// ([`Self::Store`] `:slot`), borrowed from the typed slot's own
1570    /// `&'a str` storage — or `None` on the payload-less
1571    /// [`Self::Capability`] arm.
1572    ///
1573    /// Thin projection onto the single 4-arm [`Self::payload_pair`]
1574    /// dispatch (`self.payload_pair().map(|(_, p)| p)` in `const fn`
1575    /// form) — peer of [`Self::field_name`] (`.payload_pair().0`) on
1576    /// the paired sub-selector axis. Both per-half accessors read from
1577    /// one authoritative match, so a future [`WitTarget`] variant
1578    /// addition (`Rest`/`Grpc` split of [`Self::Http`], `Queue`-shaped
1579    /// peer of [`Self::Store`]) lands at exactly one caixa-core edit
1580    /// on [`Self::payload_pair`] and both per-half projections + every
1581    /// downstream consumer picks the new arm up by construction — no
1582    /// coordinated N-way rewrite across the paired accessor dispatches,
1583    /// the [`Self::label`] / [`Self::graph_label`] format templates,
1584    /// and every future WIT-registry-shaped consumer.
1585    ///
1586    /// Peer of the sibling [`caixa-flux`][caixa-flux-crate]
1587    /// `GitRefSpec::ref_value` projection on the `FluxCD` source-
1588    /// controller `spec.ref.<field>` axis — same "one paired dispatch,
1589    /// both per-half projections as thin readers, every downstream
1590    /// consumer through the same match" discipline extended onto the
1591    /// M3 `:contratos` payload-arm axis. Closes the discipline-parity
1592    /// gap between the two paired-dispatch surfaces: the peer
1593    /// [`Self::payload_pair`] + [`Self::field_name`] pair carried only
1594    /// the first-component projection until this lift; the second-
1595    /// component sibling now sits alongside so both halves reach every
1596    /// future consumer through the same substrate-primitive dispatch.
1597    ///
1598    /// [caixa-flux-crate]: https://docs.rs/caixa-flux/latest/caixa_flux/enum.GitRefSpec.html#method.ref_value
1599    #[must_use]
1600    pub const fn payload(&self) -> Option<&'a str> {
1601        match self.payload_pair() {
1602            Some((_, p)) => Some(p),
1603            None => None,
1604        }
1605    }
1606
1607    /// Substrate-canonical per-arm HTTP-endpoint scalar accessor every
1608    /// consumer that fans on the L7-HTTP-shaped payload keys off —
1609    /// returns the [`Self::Http`]-arm's author-declared request path
1610    /// verbatim as an `Option<&'a str>`, `Some(endpoint)` when the
1611    /// projected target is [`Self::Http { endpoint }`], `None` on the
1612    /// three sibling arms ([`Self::PubSub`] / [`Self::Store`] /
1613    /// [`Self::Capability`], each of which carries no HTTP endpoint by
1614    /// definition).
1615    ///
1616    /// The [`Self::Http`] arm carries the Cilium L7 `HTTPNetworkPolicy`
1617    /// `path:` rule payload every substrate-side L7-introspecting
1618    /// per-`(:de, :para)` `CiliumNetworkPolicy` emitter reads (today: the
1619    /// [`caixa_mesh::cilium_network_policies`] per-edge `toPorts[].rules
1620    /// .http[0].path` scalar the HTTP-shape-only L7 rule builder emits
1621    /// on the L7 introspection branch; every peer WIT shape stays
1622    /// L4-only because Cilium can't introspect NATS / key-value / plain
1623    /// capability edges), and every future L7-introspecting consumer
1624    /// of the projected target's HTTP endpoint (the future M4
1625    /// per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao` CR
1626    /// materializer's per-edge L7 admission-webhook overlay, the
1627    /// future Envoy-side `local_rate_limit.descriptor_entries` per-HTTP-
1628    /// path bucket-key resolver, the future per-`:contratos`-edge
1629    /// mTLS-required overlay's HTTP-shape scope filter, the future
1630    /// `feira app graph --l7` per-Aplicacao HTTP-path column) reaches
1631    /// through the same typed dispatch.
1632    ///
1633    /// Prior to this lift the sole production consumer of the projected-
1634    /// target HTTP endpoint — the [`caixa_mesh::cilium_network_policies`]
1635    /// per-edge L7 introspection branch at `caixa-mesh/src/lib.rs:2759`
1636    /// (`if let WitTarget::Http { endpoint } = c.target().expect(…) {
1637    /// http_rule.insert_string(CILIUM_KEY_PATH, endpoint.to_string()); …
1638    /// }`) — reached the payload through a raw per-arm `if let` pattern-
1639    /// match that expressed no compile-time link back to the substrate
1640    /// primitive's typed dispatch, sibling to the [`WitContract`] pre-
1641    /// projection [`WitContract::endpoint`] (7020470) `Option<&str>`
1642    /// scalar accessor on the peer per-`:contratos` raw-field axis but
1643    /// with no post-projection peer on the typed-view surface. A future
1644    /// [`WitTarget`] variant addition that splits [`Self::Http`] into
1645    /// peers (a `Rest`/`Grpc` split once the WIT registry stabilizes
1646    /// gRPC-shaped worlds per this enum's own docstring at
1647    /// aplicacao.rs:1341-1343 — with a `Rest`-arm `endpoint: &'a str`
1648    /// payload alongside a `Grpc`-arm `service_method: &'a str` payload)
1649    /// would have had to be threaded through the caixa-mesh L7 emit
1650    /// branch's raw `if let` in lockstep — either coalescing the two
1651    /// L7-HTTP-family arms under a shared `path:` emit, or splitting the
1652    /// emit path per-arm — with no substrate-primitive dispatch making
1653    /// the "which arms count as L7-HTTP-shaped for path-emission
1654    /// purposes" question the substrate's answer to give. Lifting the
1655    /// resolution to a typed method on the substrate primitive means
1656    /// every downstream L7-HTTP-facing consumer of the Aplicacao's
1657    /// projected-target HTTP endpoint reaches for exactly one typed
1658    /// dispatch — the resolver's accept-set migrates as a unit on any
1659    /// future arm-family widening, and the caixa-mesh L7 emit branch
1660    /// reads through the same substrate primitive.
1661    ///
1662    /// Peer of the sibling pre-projection [`WitContract::endpoint`]
1663    /// (7020470) `Option<&str>` scalar accessor on the raw
1664    /// `:contratos :endpoint` field-access axis — same "one typed
1665    /// dispatch on the substrate primitive, thin projections at each
1666    /// consumer" discipline extended onto the peer post-projection typed-
1667    /// view surface (the [`WitContract::endpoint`] pre-projection
1668    /// accessor returns `Some` for any author-declared `:endpoint`
1669    /// value regardless of the paired `:wit` world's HTTP-shape
1670    /// classification — the raw slot before validation crosses it —
1671    /// while this post-projection [`Self::http_endpoint`] accessor
1672    /// returns `Some` iff the target has been projected onto the
1673    /// [`Self::Http`] arm, i.e. only after the [`WitContract::target`]
1674    /// gate has admitted the `(:wit, :endpoint/:subject/:slot)` shape
1675    /// coherence; the two accessors close the pre-projection /
1676    /// post-projection pair on the HTTP-endpoint axis). Sibling of the
1677    /// unified pan-arm [`Self::payload`] (`Option<&'a str>` for any of
1678    /// the three payload-carrying arms) — extends the per-arm
1679    /// projection family onto the [`Self::Http`] specialization axis
1680    /// that the pan-arm accessor's shape blends into a single arm-
1681    /// agnostic view; paired with [`Self::pubsub_subject`] /
1682    /// [`Self::store_slot`] on the sibling per-arm axes so every
1683    /// per-payload-arm shape carries a named post-projection accessor
1684    /// on the same shape as `http_endpoint`, closing the per-arm-shape
1685    /// accept-set the substrate primitive owns.
1686    #[must_use]
1687    pub const fn http_endpoint(&self) -> Option<&'a str> {
1688        match *self {
1689            WitTarget::Http { endpoint } => Some(endpoint),
1690            WitTarget::PubSub { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
1691        }
1692    }
1693
1694    /// Substrate-canonical per-arm pub-sub-subject scalar accessor every
1695    /// consumer that fans on the pub-sub-shaped payload keys off —
1696    /// returns the [`Self::PubSub`]-arm's author-declared event-stream
1697    /// subject verbatim as an `Option<&'a str>`, `Some(subject)` when
1698    /// the projected target is [`Self::PubSub { subject }`], `None` on
1699    /// the three sibling arms ([`Self::Http`] / [`Self::Store`] /
1700    /// [`Self::Capability`], each of which carries no NATS-shaped
1701    /// subject by definition).
1702    ///
1703    /// The [`Self::PubSub`] arm carries the NATS-server-accepted subject
1704    /// the future substrate-side pub-sub-introspecting per-`(:de, :para)`
1705    /// consumer keys off (the M4 per-Aplicacao NATS `Stream` / `Consumer`
1706    /// CR materializer's `spec.subjects[]` projection, the future
1707    /// Envoy-side per-subject `local_rate_limit.descriptor_entries`
1708    /// bucket-key resolver, the future `feira app graph --pubsub`
1709    /// per-Aplicacao subject column, any future substrate-lifted
1710    /// pub-sub-shape emitter that reads a projected `WitTarget` in the
1711    /// same shape [`caixa_mesh::cilium_network_policies`] reads the
1712    /// HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today). Every
1713    /// future pub-sub-shape consumer reaches for the same typed
1714    /// dispatch this accessor exposes so the "which arm carries the
1715    /// subject scalar?" answer lives at one caixa-core edit rather
1716    /// than open-coded across per-consumer `if let WitTarget::PubSub
1717    /// { subject } = c.target()…` pattern-matches.
1718    ///
1719    /// Peer of the sibling [`Self::http_endpoint`] (5d6dc92 trajectory)
1720    /// per-arm HTTP-endpoint accessor on the peer per-arm axis and of
1721    /// the pre-projection [`WitContract::subject`] scalar accessor on
1722    /// the raw `:contratos :subject` field-access axis — same "one
1723    /// typed dispatch on the substrate primitive, thin projections at
1724    /// each consumer" discipline extended onto the per-arm pub-sub
1725    /// post-projection axis. The pre-projection accessor returns
1726    /// `Some` for any author-declared `:subject` value regardless of
1727    /// the paired `:wit` world's pub-sub-shape classification (the raw
1728    /// slot before validation crosses it); this post-projection
1729    /// accessor returns `Some` iff the target has been projected onto
1730    /// the [`Self::PubSub`] arm, i.e. only after the
1731    /// [`WitContract::target`] gate has admitted the
1732    /// `(:wit, :endpoint/:subject/:slot)` shape coherence — closing
1733    /// the pre-/post-projection pair on the pub-sub-subject axis to
1734    /// match the pair the [`WitContract::endpoint`] +
1735    /// [`Self::http_endpoint`] surfaces already close on the peer
1736    /// HTTP-endpoint axis.
1737    ///
1738    /// Sibling of the unified pan-arm [`Self::payload`]
1739    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
1740    /// extends the per-arm projection family onto the [`Self::PubSub`]
1741    /// specialization axis that the pan-arm accessor's shape blends
1742    /// into a single arm-agnostic view; the pair
1743    /// (`pubsub_subject`, `store_slot`) closes the trio
1744    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) so every
1745    /// payload arm now carries its own per-arm-shape post-projection
1746    /// accessor.
1747    #[must_use]
1748    pub const fn pubsub_subject(&self) -> Option<&'a str> {
1749        match *self {
1750            WitTarget::PubSub { subject } => Some(subject),
1751            WitTarget::Http { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
1752        }
1753    }
1754
1755    /// Substrate-canonical per-arm key/value-store-slot scalar accessor
1756    /// every consumer that fans on the store-shaped payload keys off —
1757    /// returns the [`Self::Store`]-arm's author-declared slot template
1758    /// verbatim as an `Option<&'a str>`, `Some(slot)` when the
1759    /// projected target is [`Self::Store { slot }`], `None` on the
1760    /// three sibling arms ([`Self::Http`] / [`Self::PubSub`] /
1761    /// [`Self::Capability`], each of which carries no
1762    /// key/value-store slot by definition).
1763    ///
1764    /// The [`Self::Store`] arm carries the WASI-key/value-accepted slot
1765    /// template (validated by [`crate::render::is_wasi_keyvalue_slot`])
1766    /// every future substrate-side store-introspecting per-`(:de,
1767    /// :para)` consumer keys off (the M4 per-Aplicacao WASI-key/value
1768    /// namespace / prefix reconciler's per-slot projection, the future
1769    /// per-store-backend routing overlay's slot-shape gate, the future
1770    /// `feira app graph --store` per-Aplicacao slot column, any future
1771    /// substrate-lifted store-shape emitter that reads a projected
1772    /// `WitTarget` in the same shape [`caixa_mesh::cilium_network_policies`]
1773    /// reads the HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today).
1774    /// Every future store-shape consumer reaches for the same typed
1775    /// dispatch this accessor exposes so the "which arm carries the
1776    /// slot scalar?" answer lives at one caixa-core edit rather than
1777    /// open-coded across per-consumer
1778    /// `if let WitTarget::Store { slot } = c.target()…`
1779    /// pattern-matches.
1780    ///
1781    /// Peer of the sibling [`Self::http_endpoint`] +
1782    /// [`Self::pubsub_subject`] per-arm accessors on the peer per-arm
1783    /// axes and of the pre-projection [`WitContract::slot`] scalar
1784    /// accessor on the raw `:contratos :slot` field-access axis — same
1785    /// "one typed dispatch on the substrate primitive, thin projections
1786    /// at each consumer" discipline extended onto the per-arm store
1787    /// post-projection axis. Closes the pre-/post-projection pair on
1788    /// the store-slot axis to match the pairs the
1789    /// [`WitContract::endpoint`] + [`Self::http_endpoint`] and
1790    /// [`WitContract::subject`] + [`Self::pubsub_subject`] surfaces
1791    /// already close on the peer HTTP-endpoint and pub-sub-subject
1792    /// axes; the substrate-side pre-/post-projection accessor family
1793    /// now spans all three payload arms as a matched trio, so any
1794    /// future arm-shape widening (a `Rest`/`Grpc` split of
1795    /// [`Self::Http`], a `Queue`-shaped peer of [`Self::Store`]) that
1796    /// lands one accessor without threading through the sibling
1797    /// pre-projection or the peer per-arm post-projection surfaces a
1798    /// compile-time exhaustiveness error at the substrate primitive,
1799    /// not a silent per-consumer split at renderer emit time.
1800    ///
1801    /// Sibling of the unified pan-arm [`Self::payload`]
1802    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
1803    /// closes the per-arm projection family onto the [`Self::Store`]
1804    /// specialization axis that the pan-arm accessor's shape blends
1805    /// into a single arm-agnostic view. The trio
1806    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) partitions the
1807    /// pan-arm accept-set on every payload-carrying arm: exactly one
1808    /// per-arm accessor returns `Some(payload)` and the two peers
1809    /// return `None`, and every payload-less [`Self::Capability`]
1810    /// input returns `None` on all three — the partition the sibling
1811    /// `wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`
1812    /// pin locks in load-bearing.
1813    #[must_use]
1814    pub const fn store_slot(&self) -> Option<&'a str> {
1815        match *self {
1816            WitTarget::Store { slot } => Some(slot),
1817            WitTarget::Http { .. } | WitTarget::PubSub { .. } | WitTarget::Capability => None,
1818        }
1819    }
1820
1821    /// Render this typed target as a stable human-readable label
1822    /// (`:endpoint "/charge"`, `:subject "events.x"`,
1823    /// `:slot "checkout/$order"`, or `(capability — no payload)` when
1824    /// the WIT world is a pure capability edge).
1825    ///
1826    /// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
1827    /// gate so the diagnostic names *which* identical edge was
1828    /// declared twice (not just which `(de, para, wit)` triple).
1829    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
1830    /// on the payload-carrying arms (`Some((field, payload)) →
1831    /// format!(":{field} {payload:?}")`) and through the lifted
1832    /// [`Self::CAPABILITY_LABEL`] const on the payload-less
1833    /// [`Self::Capability`] arm — so a future variant addition (the
1834    /// M4-and-later per-edge WIT registry may split [`Self::Http`]
1835    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
1836    /// `Queue`-shaped peer) becomes a single new match-arm on
1837    /// [`Self::payload_pair`] rather than a rewrite of this template
1838    /// (and every downstream consumer that reaches for the label
1839    /// shape: the per-edge policy resolver in M4, the `feira app
1840    /// graph` view, the operator's mesh-graph audit). Until this
1841    /// lift landed the three payload arms carried three near-identical
1842    /// per-arm `format!(":{} {…:?}", …)` invocations, and the
1843    /// [`Self::Capability`] arm carried the payload-less byte-string
1844    /// twice (once inline here, once in the pin test) — closing the
1845    /// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
1846    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
1847    /// / 4a1e490) peer-const lifts already established for the
1848    /// payload-carrying arms.
1849    #[must_use]
1850    pub fn label(&self) -> String {
1851        match self.payload_pair() {
1852            Some((field, payload)) => format!(":{field} {payload:?}"),
1853            None => Self::CAPABILITY_LABEL.to_string(),
1854        }
1855    }
1856
1857    /// Render this typed target as the `feira app graph` per-`:contratos`
1858    /// payload-column byte-string (`endpoint=/charge`, `subject=events.x`,
1859    /// `slot=checkout/$order`, or [`Self::CAPABILITY_GRAPH_LABEL`] on the
1860    /// payload-less arm).
1861    ///
1862    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
1863    /// on the payload-carrying arms (`Some((field, payload)) →
1864    /// format!("{field}={payload}")`) and through the lifted
1865    /// [`Self::CAPABILITY_GRAPH_LABEL`] const on the payload-less
1866    /// [`Self::Capability`] arm — so a future variant addition
1867    /// (the M4-and-later per-edge WIT registry may split [`Self::Http`]
1868    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
1869    /// `Queue`-shaped peer) becomes one match-arm edit at
1870    /// [`Self::payload_pair`], propagating through this graph-verb
1871    /// projection at zero call-site cost, sibling to the peer
1872    /// [`Self::label`] duplicate-`:contratos` diagnostic emission on the
1873    /// same 4-arm dispatch.
1874    ///
1875    /// Until this lift landed the [`caixa-feira`]
1876    /// `cmd::app::GraphArgs::run` per-`:contratos` payload column
1877    /// (`caixa-feira/src/cmd/app.rs:101-112`) hand-rolled the same 4-arm
1878    /// dispatch inline, re-projecting `HTTP_FIELD_NAME` /
1879    /// `PUBSUB_FIELD_NAME` / `STORE_FIELD_NAME` under a per-arm
1880    /// `format!("{}={endpoint}", ...)` template and hard-coding
1881    /// `"(capability-only)"` as a fifth payload-less scalar with no link
1882    /// back to the paired [`WitTarget::Capability`] variant declaration.
1883    /// A future variant addition would have had to be threaded through
1884    /// both [`Self::label`] (via [`Self::payload_pair`]) *and* the graph
1885    /// verb's inline match in lockstep or the two projections would
1886    /// silently disagree on the arm-set the graph verb prints — the
1887    /// duplicate-`:contratos` diagnostic reading one shape while the
1888    /// graph verb's payload column silently dropped the new arm to
1889    /// `(capability-only)`. Lifting the graph-verb projection onto the
1890    /// same substrate-primitive [`Self::payload_pair`] dispatch closes
1891    /// the axis: both projections migrate as a unit.
1892    ///
1893    /// The `field=payload` (no colon prefix, `=` separator, no `Debug`
1894    /// quoting) shape is graph-verb-canonical — distinct from the
1895    /// sibling [`Self::label`] `":{field} {payload:?}"` shape the
1896    /// duplicate-`:contratos` diagnostic seeds (see
1897    /// [`Self::CAPABILITY_LABEL`] vs. [`Self::CAPABILITY_GRAPH_LABEL`]
1898    /// on the payload-less axis for the paired distinction).
1899    #[must_use]
1900    pub fn graph_label(&self) -> String {
1901        match self.payload_pair() {
1902            Some((field, payload)) => format!("{field}={payload}"),
1903            None => Self::CAPABILITY_GRAPH_LABEL.to_string(),
1904        }
1905    }
1906}
1907
1908/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
1909/// pretty-printed byte-string every consumer that formats a typed
1910/// payload target as user-facing text lands on (the
1911/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
1912/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
1913/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
1914/// graph` per-`:contratos`-edge payload column that reaches the graph
1915/// verb through `format!("{target}")`, the future M4 per-edge policy
1916/// resolver's per-edge audit-log line, the operator's mesh-graph
1917/// per-edge inspection view) reaches for the same lifted
1918/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
1919/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
1920/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
1921/// routes through — extending the three-path-convergence
1922/// (`Debug` for structural inspection, `Display` for user-facing text,
1923/// per-arm typed accessor for the canonical byte-string) discipline the
1924/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
1925/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
1926/// onto the fourth (and only remaining) typed-shape-discriminator axis
1927/// on the caixa surface.
1928///
1929/// Pre-lift the two paths were structurally independent — every consumer
1930/// reaching for a payload byte-string past the [`WitTarget::label`]
1931/// helper had to pick between three paths ([`WitTarget::label`],
1932/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
1933/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
1934/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
1935/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
1936/// that reached for `format!("{target}")` — the canonical shape every
1937/// user-facing pretty-print site on the sibling typed-enum axes already
1938/// uses — would silently land on the `Debug` derive's structural output
1939/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
1940/// than the `label()` helper's stable byte-string (`:endpoint
1941/// "/charge"` — the author-facing `:contratos` keyword form) the
1942/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
1943/// already threads through. The two spellings would diverge silently in
1944/// every downstream diagnostic / graph / audit line reached through
1945/// `format!` rather than through the `label()` helper. Routing
1946/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
1947/// path: every `format!("{v}")` call reaches the same
1948/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
1949/// and the duplicate-`:contratos` gate already route through, so a
1950/// future variant addition (the M4-and-later per-edge WIT registry may
1951/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
1952/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
1953/// consumer at exactly one place — the [`WitTarget::payload_pair`]
1954/// match — rather than fanning out through hand-rolled per-arm
1955/// [`std::fmt::Display`] arms.
1956///
1957/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
1958/// is the typed view returned by [`WitContract::target`], not a
1959/// closed-set discriminator enum with a gen-platform Discriminant
1960/// registration, so the `Debug` derive's structural output (which every
1961/// `{v:?}` consumer still reaches) stays distinct from the `Display`
1962/// helper's stable pretty-printed byte-string. `Debug` reveals variant
1963/// shape for structural inspection; `Display` (via `label`) reveals the
1964/// stable author-facing payload projection.
1965///
1966/// Pin tests
1967/// [`tests::wit_target_display_routes_through_label_helper`] and
1968/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
1969/// assert the two paths agree byte-for-byte on every variant, so a
1970/// future variant addition or `label()` reimplementation that hand-rolls
1971/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
1972/// build error visible at caixa-core test time, not a silent
1973/// per-consumer dispatch miss at diagnostic / audit / graph time.
1974impl std::fmt::Display for WitTarget<'_> {
1975    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1976        f.write_str(&self.label())
1977    }
1978}
1979
1980// ── one Aplicacao member ─────────────────────────────────────────────
1981
1982/// A Servico participating in the Aplicacao. Same shape as
1983/// `crate::supervisor::ChildSpec` but without a restart policy —
1984/// supervision is per-Servico (each member has its own
1985/// `:supervisor`), the Aplicacao orchestrates *placement*.
1986#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1987#[serde(rename_all = "camelCase")]
1988pub struct Membro {
1989    /// Member caixa's `:nome`. Resolves through the same dep
1990    /// resolution path as `crate::dep::Dep`.
1991    pub caixa: String,
1992
1993    /// Semver constraint.
1994    pub versao: String,
1995}
1996
1997impl Membro {
1998    /// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
1999    /// accessor every consumer that reads the member's Servico identity
2000    /// keys off — returns the author-declared `:membros :caixa`
2001    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
2002    /// own [`String`] storage.
2003    ///
2004    /// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
2005    /// participating in the Aplicacao — validated by
2006    /// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
2007    /// (via [`validate_membro_caixa`]), unique across the Aplicacao's
2008    /// `:membros` list, distinct from the Aplicacao's own `:nome` (via
2009    /// [`validate_no_self_membership`]) — and every downstream consumer
2010    /// that fans on the member's identity keys off this scalar (the
2011    /// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
2012    /// lookup, the per-`:membros` duplicate gate's dedup key, the
2013    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
2014    /// identity, the self-membership gate, the
2015    /// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
2016    /// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
2017    /// CR materializer's per-member resolver).
2018    ///
2019    /// Prior to this lift the `.caixa` byte-string was read inline at
2020    /// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
2021    /// set collector at
2022    /// `self.membros.iter().map(|m| m.caixa.as_str())`, the
2023    /// [`validate_membros`] validation-side member-caixa gate at
2024    /// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
2025    /// per-member duplicate-gate dedup key at
2026    /// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
2027    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
2028    /// `adj.entry(m.caixa.as_str()).or_default()`, and the
2029    /// [`validate_no_self_membership`] self-loop gate at
2030    /// `m.caixa == parent_nome`) — five open-coded field-accesses that
2031    /// expressed no compile-time link back to the typed slot. Every
2032    /// caixa-mesh `metadata.name` derived from a `:membros :caixa`
2033    /// value flows through the [`caixa_mesh::fleet_programs`] per-entry
2034    /// `name:` axis, so a future extension of the `:membros :caixa`
2035    /// axis to a richer author surface — a per-cluster alias table the
2036    /// operator pins through a future `:placement`-scoped slot, a
2037    /// namespace-qualified rewrite the M4 CR materializer applies
2038    /// per-CR, a per-member overlay from the future `:membros
2039    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
2040    /// acknowledges — would have had to be threaded through every
2041    /// open-coded copy in lockstep or one consumer would silently
2042    /// disagree with the peers on which caixa a given member resolves
2043    /// to. A member-set lookup that treated the name as `"cart"` while
2044    /// the peer adjacency map treated it as `"tenant-a/cart"` would
2045    /// silently split the `:contratos` membership-lookup diagnostic from
2046    /// the cycle-detector's node identity — a two-consumer split at the
2047    /// validator far from the source `caixa.lisp` with no field naming
2048    /// the identity-drift root cause. Lifting the resolution rule to a
2049    /// typed method on the substrate primitive means every downstream
2050    /// consumer of the Aplicacao's per-`:membros` identity surface
2051    /// reaches for exactly one typed dispatch — the resolver's
2052    /// accept-set migrates as a unit on any future axis addition.
2053    ///
2054    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2055    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2056    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2057    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2058    /// destination-Servico scalar accessors — same "one typed dispatch
2059    /// on the substrate primitive, thin projections at each consumer"
2060    /// discipline extended onto the per-`:membros` member-caixa `:nome`
2061    /// byte-string axis. Named `nome()` to match the tatara-lisp
2062    /// author-surface term the field's docstring already reaches for
2063    /// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
2064    /// [`crate::dep::Dep::nome`] field-name discipline the substrate
2065    /// already carries — the accessor's name maps directly onto the
2066    /// canonical caixa-identity vocabulary rather than shadowing the
2067    /// field's storage-side `caixa` label.
2068    #[must_use]
2069    pub fn nome(&self) -> &str {
2070        self.caixa.as_str()
2071    }
2072
2073    /// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
2074    /// requirement scalar accessor every consumer that reads the
2075    /// member's version pin keys off — returns the author-declared
2076    /// `:membros :versao` byte-string verbatim as a `&str`, borrowed
2077    /// from the typed slot's own [`String`] storage.
2078    ///
2079    /// The `:membros :versao` slot carries the Cargo-shaped semver
2080    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
2081    /// pins which release of the member-caixa the Aplicacao composes
2082    /// against — the same requirement grammar the peer `:deps :versao`
2083    /// / `:children :versao` axes carry, resolved through the shared
2084    /// [`crate::render::require_valid_versao_requirement`] cascade and
2085    /// the shared [`crate::version::parse_requirement`] parser. Every
2086    /// downstream consumer that fans on the member's version pin keys
2087    /// off this scalar (the [`validate_membros`] per-member requirement
2088    /// gate at `require_valid_versao_requirement(m.versao_requirement(),
2089    /// …)`, the [`feira app graph`] per-member `println!("    - {} {}",
2090    /// m.nome(), m.versao_requirement())` line, every future per-cluster
2091    /// version-lock overlay the operator pins through a future
2092    /// `:placement`-scoped slot, the future
2093    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
2094    /// version resolver, the future `feira app deploy` pipeline's
2095    /// per-member lacre BLAKE3-closure lookup).
2096    ///
2097    /// Prior to this lift the `.versao` byte-string was accessed inline
2098    /// at two `&str`-shaped sites — the [`validate_membros`]
2099    /// requirement-gate call `require_valid_versao_requirement(&m.versao,
2100    /// …)` and the `feira app graph` per-member printer's `println!(
2101    /// "    - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
2102    /// prior to this lift) — two open-coded field-accesses that expressed
2103    /// no compile-time link back to the typed slot. A future extension of
2104    /// the `:membros :versao` axis to a richer author surface (a
2105    /// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2106    /// flow, a lacre-projected concrete-version rewrite the operator
2107    /// materializes at CR-admission time, a future `:membros :versao-lock`
2108    /// per-cluster override slot) would have had to be threaded through
2109    /// every open-coded copy in lockstep or one consumer would silently
2110    /// disagree with the peers on which release constraint a given
2111    /// member resolves to. Lifting the resolution rule to a typed method
2112    /// on the substrate primitive means every downstream requirement-
2113    /// facing consumer reaches for exactly one typed dispatch — the
2114    /// resolver's accept-set migrates as a unit on any future axis
2115    /// addition.
2116    ///
2117    /// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
2118    /// member-caixa `:nome` scalar accessor — the pair
2119    /// `(nome(), versao_requirement())` jointly projects the
2120    /// `(caixa, versao)` field pair every renderer that fans on
2121    /// per-member identity + version pin keys off, closing the last
2122    /// unlifted per-`:membros` scalar axis so every downstream
2123    /// per-`:membros` reader now routes through a typed dispatch on the
2124    /// substrate primitive. Named `versao_requirement()` rather than
2125    /// `versao()` because the field's storage-side `.versao` label is
2126    /// already the author-surface term (`:versao`); the accessor's name
2127    /// carries the semantic role — the semver *requirement* string the
2128    /// shared [`crate::version::parse_requirement`] entry-point consumes
2129    /// — so a raw field access and a typed dispatch read differently at
2130    /// every consumer site.
2131    ///
2132    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2133    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2134    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2135    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2136    /// destination-Servico scalar accessors — same "one typed dispatch
2137    /// on the substrate primitive, thin projections at each consumer"
2138    /// discipline extended onto the per-`:membros` member-`:versao`
2139    /// semver-requirement byte-string axis.
2140    #[must_use]
2141    pub fn versao_requirement(&self) -> &str {
2142        self.versao.as_str()
2143    }
2144}
2145
2146// ── mesh-level policies ──────────────────────────────────────────────
2147
2148/// Mesh policies that apply to every `:contratos` edge unless
2149/// overridden per-edge in M4. V0 is a single global policy block.
2150#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
2151#[serde(rename_all = "camelCase")]
2152pub struct MeshPolicy {
2153    /// Per-call timeout. Authored as a duration string (`"30s"`).
2154    #[serde(
2155        default,
2156        skip_serializing_if = "Option::is_none",
2157        with = "supervisor::duration_codec"
2158    )]
2159    pub timeout: Option<Duration>,
2160
2161    /// Number of retries on transient failure. None = no retries.
2162    #[serde(default, skip_serializing_if = "Option::is_none")]
2163    pub retries: Option<u32>,
2164
2165    /// Circuit breaker config. Trips after N failures within W
2166    /// duration; closes after a cooldown.
2167    #[serde(default, skip_serializing_if = "Option::is_none")]
2168    pub circuit_breaker: Option<CircuitBreaker>,
2169
2170    /// Whether mTLS is required for every contrato. Default: true
2171    /// (sandboxing-by-default; explicit opt-out only).
2172    #[serde(default, skip_serializing_if = "Option::is_none")]
2173    pub mtls_required: Option<bool>,
2174
2175    /// Token-bucket rate limit. Authored as `"100/s"` or
2176    /// `"5000/m"`; stored as `(rate, window)`.
2177    #[serde(
2178        default,
2179        skip_serializing_if = "Option::is_none",
2180        with = "rate_limit_codec"
2181    )]
2182    pub rate_limit: Option<RateLimit>,
2183}
2184
2185impl MeshPolicy {
2186    /// True when no `:politicas` axis carries a value — every field is
2187    /// `None`. The same emptiness contract every other M2/M3 typed
2188    /// surface carries ([`crate::LimitsSpec::is_empty`],
2189    /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
2190    /// typed slot onto a cluster artifact key off this predicate to
2191    /// decide "emit the slot" vs "skip the slot entirely", so an
2192    /// authored-but-unset `:politicas (())` round-trips to a rendered
2193    /// artifact that's structurally identical to one that omits the
2194    /// slot. Lifted as a typed predicate (rather than per-renderer
2195    /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
2196    /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
2197    /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
2198    /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
2199    /// not a coordinated rewrite of every consumer that's reaching
2200    /// for the emptiness semantic.
2201    #[must_use]
2202    pub const fn is_empty(&self) -> bool {
2203        self.timeout().is_none()
2204            && self.retries().is_none()
2205            && self.circuit_breaker().is_none()
2206            && self.mtls_required().is_none()
2207            && self.rate_limit().is_none()
2208    }
2209
2210    /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
2211    /// per-call-deadline scalar accessor every consumer of the
2212    /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
2213    /// returns the author-declared `:politicas :timeout` typed
2214    /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
2215    /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
2216    /// is `Copy`, so the accessor returns by value; no borrow of
2217    /// `&self` past the call). `None` when the slot is absent (the
2218    /// "cluster default applies — typically the gateway class's
2219    /// implementation-side per-request wall-clock cap" arm caixa-mesh's
2220    /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
2221    /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
2222    /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
2223    /// round-trips to a rendered `HTTPRoute` structurally identical to
2224    /// one that omits the slot).
2225    ///
2226    /// The `:politicas :timeout` slot carries the "no infinite blocking"
2227    /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
2228    /// the typed slot's `Option<Duration>` accept-set (zero-floor
2229    /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
2230    /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
2231    /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
2232    /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
2233    /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
2234    /// Every downstream consumer that reads the per-call cap keys off
2235    /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
2236    /// renderers key off to decide "emit :politicas overlay" vs "skip
2237    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
2238    /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
2239    /// fans the deadline into every rule via
2240    /// [`crate::render::single_field_overlay`], the future M4 per-
2241    /// Aplicacao Gateway API reconciler materialization pass, the
2242    /// future per-`:contratos`-edge timeout-override overlay the
2243    /// MESH-COMPOSITION §III.2 roadmap acknowledges).
2244    ///
2245    /// Prior to this lift the `.timeout` field was accessed inline at
2246    /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
2247    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
2248    /// …)` call — two open-coded field-accesses that expressed no
2249    /// compile-time link back to the typed slot. A future extension of
2250    /// the `:politicas :timeout` axis to a richer author surface — a
2251    /// per-`:contratos`-edge timeout override the operator pins through
2252    /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
2253    /// roadmap acknowledges, a per-cluster timeout-default overlay the
2254    /// M4 CR materializer resolves per-CR, a split of the single
2255    /// per-call `Duration` into a richer `{request, backendRequest}`
2256    /// pair once the Gateway API's per-rule `timeouts` block grows the
2257    /// upstream-facing backendRequest arm alongside the client-facing
2258    /// request arm — would have had to be threaded through both open-
2259    /// coded copies in lockstep or the emptiness predicate and the
2260    /// caixa-mesh emit path would silently disagree on which per-call
2261    /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
2262    /// whose only axis is a `Some :timeout` would satisfy `is_empty()
2263    /// == false` while the renderer's overlay-emit path silently read
2264    /// a drifted other value, or vice versa: an author's `:timeout
2265    /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
2266    /// the emptiness predicate still classified the policy as non-
2267    /// empty, and every `kubectl -n tatara-system get httproute -o yaml
2268    /// | grep -A2 timeouts` audit would land on a route whose author's
2269    /// typed slot value silently vanished at the renderer layer).
2270    /// Lifting the resolution to a typed method on the substrate
2271    /// primitive means every downstream consumer of the Aplicacao's
2272    /// per-`:politicas` deadline surface reaches for exactly one typed
2273    /// dispatch — the resolver's accept-set migrates as a unit on any
2274    /// future axis addition.
2275    ///
2276    /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
2277    /// family (sibling of the peer per-`:politicas`
2278    /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
2279    /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
2280    /// `Option<bool>` accessor — same "one typed dispatch on the
2281    /// substrate primitive, thin projections at each consumer"
2282    /// discipline extended onto the peer per-`:politicas` typed-
2283    /// [`Duration`] optional-scalar axis; closes the "optional per-slot
2284    /// numeric-Copy-T scalar" projection pattern the sibling
2285    /// `Option<u32>` / `Option<bool>` lifts opened, since every
2286    /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
2287    /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
2288    /// than a scalar). Named `timeout()` to match the storage field's
2289    /// name; the accessor's identity maps onto the canonical MESH-
2290    /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
2291    #[must_use]
2292    pub const fn timeout(&self) -> Option<Duration> {
2293        self.timeout
2294    }
2295
2296    /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
2297    /// retry-budget scalar accessor every consumer of the Aplicacao's
2298    /// Gateway API v1.x per-rule retry-cap keys off — returns the
2299    /// author-declared `:politicas :retries` typed `u32` verbatim as an
2300    /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
2301    /// storage (`Option<u32>` is `Copy`, so the accessor returns by
2302    /// value; no borrow of `&self` past the call). `None` when the slot
2303    /// is absent (the "cluster default applies — typically 'no retries
2304    /// beyond a single dispatch attempt'" arm the caixa-mesh
2305    /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
2306    /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
2307    /// this predicate too, so an authored-but-unset `:politicas
2308    /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
2309    /// identical to one that omits the slot).
2310    ///
2311    /// The `:politicas :retries` slot carries the "transient failure
2312    /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
2313    /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
2314    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
2315    /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
2316    /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
2317    /// count scalar the caixa-mesh `retry_overlay` builder writes.
2318    /// Every downstream consumer that reads the retry cap keys off this
2319    /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
2320    /// renderers key off to decide "emit :politicas overlay" vs "skip
2321    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
2322    /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
2323    /// the value into every rule via [`crate::render::single_field_overlay`],
2324    /// the future M4 per-Aplicacao Gateway API reconciler
2325    /// materialization pass, the future per-`:contratos`-edge retry-
2326    /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
2327    /// acknowledges).
2328    ///
2329    /// Prior to this lift the `.retries` field was accessed inline at
2330    /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
2331    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
2332    /// …)` call — two open-coded field-accesses that expressed no
2333    /// compile-time link back to the typed slot. A future extension of
2334    /// the `:politicas :retries` axis to a richer author surface — a
2335    /// per-`:contratos`-edge retry override the operator pins through a
2336    /// future `:contratos :retries` slot, a per-cluster retry-default
2337    /// overlay the M4 CR materializer resolves per-CR, a promotion of
2338    /// the plain `u32` attempt-count to a richer `{attempts, codes,
2339    /// backoff}` sub-block once the Gateway API grows the peer
2340    /// `retry.codes` / `retry.backoff` axes — would have had to be
2341    /// threaded through both open-coded copies in lockstep or the
2342    /// emptiness predicate and the caixa-mesh emit path would silently
2343    /// disagree on which retry budget a given [`MeshPolicy`] resolves to
2344    /// (a `:politicas` block whose only axis is a `Some :retries` would
2345    /// satisfy `is_empty() == false` while the renderer's overlay-emit
2346    /// path silently read a drifted other value, or vice versa: an
2347    /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
2348    /// block while the emptiness predicate still classified the policy
2349    /// as non-empty). Lifting the resolution to a typed method on the
2350    /// substrate primitive means every downstream consumer of the
2351    /// Aplicacao's per-`:politicas` retry surface reaches for exactly
2352    /// one typed dispatch — the resolver's accept-set migrates as a
2353    /// unit on any future axis addition.
2354    ///
2355    /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
2356    /// family (sibling of the peer per-`:politicas`
2357    /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
2358    /// same "one typed dispatch on the substrate primitive, thin
2359    /// projections at each consumer" discipline extended onto the
2360    /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
2361    /// the "optional per-slot numeric-Copy-T scalar" projection pattern
2362    /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
2363    /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
2364    /// fold on). Named `retries()` to match the storage field's name;
2365    /// the accessor's identity maps onto the canonical MESH-COMPOSITION
2366    /// §III.2 vocabulary the slot's docstring already carries.
2367    #[must_use]
2368    pub const fn retries(&self) -> Option<u32> {
2369        self.retries
2370    }
2371
2372    /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
2373    /// enforcement-toggle scalar accessor every consumer of the
2374    /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
2375    /// — returns the author-declared `:politicas :mtls-required` typed
2376    /// bool verbatim as an `Option<bool>`, copied out of the typed
2377    /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
2378    /// the accessor returns by value; no borrow of `&self` past the
2379    /// call). `None` when the slot is absent (the "cluster default
2380    /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
2381    /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
2382    /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
2383    /// this predicate too, so an authored-but-unset `:politicas
2384    /// (:mtls-required ())` round-trips to a rendered
2385    /// `CiliumNetworkPolicy` structurally identical to one that omits
2386    /// the slot).
2387    ///
2388    /// The `:politicas :mtls-required` slot carries the "explicit opt-
2389    /// out only, sandboxing-by-default" mTLS-enforcement toggle
2390    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
2391    /// `{None, Some(true), Some(false)}` accept-set maps onto the
2392    /// Cilium `authentication.mode` bijection through
2393    /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
2394    /// handshake enforced), `Some(false) → "disabled"` (handshake
2395    /// skipped — the debug-edge opt-out), `None` → omit the block
2396    /// (cluster default applies). Every downstream consumer that
2397    /// reads the toggle keys off this scalar (the
2398    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2399    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2400    /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
2401    /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
2402    /// ingress rule via [`crate::render::single_field_overlay`], the
2403    /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
2404    /// materialization pass, the future per-`:contratos`-edge mTLS
2405    /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2406    ///
2407    /// Prior to this lift the `.mtls_required` field was accessed
2408    /// inline at two sites — [`MeshPolicy::is_empty`]'s
2409    /// `self.mtls_required.is_none()` arm and caixa-mesh's
2410    /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
2411    /// two open-coded field-accesses that expressed no compile-time
2412    /// link back to the typed slot. A future extension of the
2413    /// `:politicas :mtls-required` axis to a richer author surface —
2414    /// a per-`:contratos`-edge mTLS override the operator pins through
2415    /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
2416    /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
2417    /// M4 CR materializer resolves per-CR, a three-valued
2418    /// `{None, Some(true), Some(false), Some(Optional)}` promotion
2419    /// once Cilium's `authentication.mode` grows an `"optional"` arm —
2420    /// would have had to be threaded through both open-coded copies in
2421    /// lockstep or the emptiness predicate and the caixa-mesh emit
2422    /// path would silently disagree on which toggle a given
2423    /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
2424    /// axis is a `Some`
2425    /// `:mtls-required` would satisfy `is_empty() == false` while the
2426    /// renderer's overlay-emit path silently read a drifted other
2427    /// value, or vice versa). Lifting the resolution to a typed method
2428    /// on the substrate primitive means every downstream consumer of
2429    /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
2430    /// for exactly one typed dispatch — the resolver's accept-set
2431    /// migrates as a unit on any future axis addition.
2432    ///
2433    /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
2434    /// family (peer of the sibling per-`:placement`
2435    /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
2436    /// same "one typed dispatch on the substrate primitive, thin
2437    /// projections at each consumer" discipline extended onto the
2438    /// peer per-`:politicas` typed-bool optional-scalar axis; opens
2439    /// the "optional per-slot Copy-T scalar" projection pattern the
2440    /// sibling per-`:politicas` `:retries` (Option<u32>) /
2441    /// `:timeout` (Option<Duration>) future lifts fold on). Named
2442    /// `mtls_required()` to match the storage field's name; the
2443    /// accessor's identity maps onto the canonical MESH-COMPOSITION
2444    /// §III.2 vocabulary the slot's docstring already carries.
2445    #[must_use]
2446    pub const fn mtls_required(&self) -> Option<bool> {
2447        self.mtls_required
2448    }
2449
2450    /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
2451    /// `local_rate_limit`-mesh token-bucket-declaration scalar
2452    /// accessor every consumer of the Aplicacao's per-`:politicas`
2453    /// per-`(rate, window)` rate-limit surface keys off — returns the
2454    /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
2455    /// verbatim as an `Option<RateLimit>`, copied out of the typed
2456    /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
2457    /// `Copy`, so the accessor returns by value; no borrow of `&self`
2458    /// past the call). `None` when the slot is absent (the "cluster
2459    /// default applies — typically 'no per-Aplicacao rate declaration,
2460    /// gateway-class per-listener default applies'" arm the future
2461    /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
2462    /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
2463    /// `rate_limit().is_none()` arm reads this predicate too, so an
2464    /// authored-but-unset `:politicas (:rate-limit ())` round-trips
2465    /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
2466    /// identical to one that omits the slot).
2467    ///
2468    /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
2469    /// token-bucket rate declaration" contract (MESH-COMPOSITION
2470    /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
2471    /// (rate lower-bounded by 1 through
2472    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
2473    /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
2474    /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
2475    /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
2476    /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
2477    /// bijection the future `CiliumClusterwideEnvoyConfig` per-
2478    /// `:politicas` overlay emits. Every downstream consumer that
2479    /// reads the rate declaration keys off this scalar (the
2480    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2481    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2482    /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
2483    /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
2484    /// `rl.window` against [`is_canonical_rate_limit_window`], the
2485    /// future M4 per-Aplicacao Envoy reconciler materialization pass,
2486    /// the future per-`:contratos`-edge rate-limit override the
2487    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2488    ///
2489    /// Prior to this lift the `.rate_limit` field was accessed inline
2490    /// at two sites — [`MeshPolicy::is_empty`]'s
2491    /// `self.rate_limit.is_none()` arm and the `validate_politicas`
2492    /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
2493    /// field-accesses that expressed no compile-time link back to the
2494    /// typed slot. A future extension of the `:politicas :rate-limit`
2495    /// axis to a richer author surface — a per-`:contratos`-edge
2496    /// rate-limit override the operator pins through a future
2497    /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
2498    /// roadmap acknowledges, a per-cluster rate-limit-default overlay
2499    /// the M4 CR materializer resolves per-CR, a promotion of the
2500    /// plain `(rate, window)` scalar pair to a richer
2501    /// `{rate, window, burst, key}` sub-block once Envoy's
2502    /// `local_rate_limit` grows the peer `burst_size` /
2503    /// `descriptor_key` axes — would have had to be threaded through
2504    /// both open-coded copies in lockstep or the emptiness predicate
2505    /// and the validate gate would silently disagree on which rate
2506    /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
2507    /// block whose only axis is a `Some :rate-limit` would satisfy
2508    /// `is_empty() == false` while the validate path silently read a
2509    /// drifted other value, or vice versa: an author's
2510    /// `:rate-limit "100/s"` would omit the value-shape gate while the
2511    /// emptiness predicate still classified the policy as non-empty).
2512    /// Lifting the resolution to a typed method on the substrate
2513    /// primitive means every downstream consumer of the Aplicacao's
2514    /// per-`:politicas` rate-limit surface reaches for exactly one
2515    /// typed dispatch — the resolver's accept-set migrates as a unit
2516    /// on any future axis addition.
2517    ///
2518    /// First `Option<Copy-composite-T>`-return accessor on the M3
2519    /// mesh-slot family — closes the last un-lifted per-`:politicas`
2520    /// scalar-value axis. Peer of the sibling per-`:politicas`
2521    /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
2522    /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
2523    /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
2524    /// "one typed dispatch on the substrate primitive, thin
2525    /// projections at each consumer" discipline extended onto the
2526    /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
2527    /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
2528    /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
2529    /// sub-accessors rather than a top-level accessor because
2530    /// consumers reach for the axes not the aggregate). Named
2531    /// `rate_limit()` to match the storage field's name; the
2532    /// accessor's identity maps onto the canonical MESH-COMPOSITION
2533    /// §III.2 vocabulary the slot's docstring already carries.
2534    #[must_use]
2535    pub const fn rate_limit(&self) -> Option<RateLimit> {
2536        self.rate_limit
2537    }
2538
2539    /// Substrate-canonical per-`:politicas` `:circuit-breaker`
2540    /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
2541    /// declaration scalar accessor every consumer of the Aplicacao's
2542    /// per-`:politicas` breaker declaration keys off — returns the
2543    /// author-declared `:politicas :circuit-breaker` typed
2544    /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
2545    /// copied out of the typed slot's own `Option<CircuitBreaker>`
2546    /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
2547    /// by value; no borrow of `&self` past the call). `None` when the
2548    /// slot is absent (the "cluster default applies — typically 'no
2549    /// per-Aplicacao breaker declaration, gateway-class per-listener
2550    /// default applies'" arm the future caixa-mesh
2551    /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
2552    /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
2553    /// arm reads this predicate too, so an authored-but-unset
2554    /// `:politicas (:circuit-breaker ())` round-trips to a rendered
2555    /// `CiliumClusterwideEnvoyConfig` structurally identical to one
2556    /// that omits the slot).
2557    ///
2558    /// The `:politicas :circuit-breaker` slot carries the
2559    /// "per-Aplicacao consecutive-transient-failure trip declaration"
2560    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2561    /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
2562    /// zero-floor rejected through
2563    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2564    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
2565    /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
2566    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
2567    /// canonical-form pinned through
2568    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
2569    /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
2570    /// bijection the future `CiliumClusterwideEnvoyConfig`
2571    /// per-`:politicas` overlay emits. Every downstream consumer that
2572    /// reads the breaker declaration keys off this scalar (the
2573    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2574    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2575    /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
2576    /// that brackets `cb.max_failures()` against
2577    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
2578    /// [`POLICY_BREAKER_WINDOW_MAX`] via
2579    /// [`crate::render::require_positive_canonical_bounded_duration`],
2580    /// the future M4 per-Aplicacao Envoy reconciler materialization
2581    /// pass, the future per-`:contratos`-edge breaker override the
2582    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2583    ///
2584    /// Prior to this lift the `.circuit_breaker` field was accessed
2585    /// inline at two sites — [`MeshPolicy::is_empty`]'s
2586    /// `self.circuit_breaker.is_none()` arm and the
2587    /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
2588    /// bind — two open-coded field-accesses that expressed no
2589    /// compile-time link back to the typed slot. A future extension of
2590    /// the `:politicas :circuit-breaker` axis to a richer author
2591    /// surface — a per-`:contratos`-edge breaker override the operator
2592    /// pins through a future `:contratos :circuit-breaker` slot the
2593    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
2594    /// breaker-default overlay the M4 CR materializer resolves per-CR,
2595    /// a promotion of the plain `(max_failures, window)` scalar pair to
2596    /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
2597    /// sub-block once Envoy's `outlier_detection` grows the peer
2598    /// ejection-percentage / ejection-time axes — would have had to be
2599    /// threaded through both open-coded copies in lockstep or the
2600    /// emptiness predicate and the validate gate would silently
2601    /// disagree on which breaker declaration a given [`MeshPolicy`]
2602    /// resolves to (a `:politicas` block whose only axis is a
2603    /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
2604    /// the validate path silently read a drifted other value, or vice
2605    /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
2606    /// "60s"))` would omit the value-shape gate while the emptiness
2607    /// predicate still classified the policy as non-empty). Lifting
2608    /// the resolution to a typed method on the substrate primitive
2609    /// means every downstream consumer of the Aplicacao's
2610    /// per-`:politicas` breaker surface reaches for exactly one typed
2611    /// dispatch — the resolver's accept-set migrates as a unit on any
2612    /// future axis addition.
2613    ///
2614    /// Second `Option<Copy-composite-T>`-return accessor on the M3
2615    /// mesh-slot family (sibling of the peer per-`:politicas`
2616    /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
2617    /// on the same composite-Copy shape, and of the sibling per-
2618    /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
2619    /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
2620    /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
2621    /// `Option<bool>` accessors on the sibling primitive-Copy axes —
2622    /// same "one typed dispatch on the substrate primitive, thin
2623    /// projections at each consumer" discipline extended onto the last
2624    /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
2625    /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
2626    /// match the storage field's name; the accessor's identity maps
2627    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2628    /// docstring already carries. Closes the last unlifted
2629    /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
2630    /// reader now routes through a typed dispatch on the substrate
2631    /// primitive.
2632    #[must_use]
2633    pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
2634        self.circuit_breaker
2635    }
2636}
2637
2638#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2639#[serde(rename_all = "camelCase")]
2640pub struct CircuitBreaker {
2641    pub max_failures: u32,
2642    #[serde(with = "supervisor::duration_codec_required")]
2643    pub window: Duration,
2644}
2645
2646impl CircuitBreaker {
2647    /// Substrate-canonical per-`:politicas :circuit-breaker`
2648    /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
2649    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2650    /// breaker trip-count keys off — returns the author-declared
2651    /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
2652    /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
2653    /// so the accessor returns by value; no borrow of `&self` past the
2654    /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
2655    /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
2656    /// axis; a `CircuitBreaker` past pattern-match is definitionally
2657    /// present, and its `:max-failures` field carries the trip count as a
2658    /// required-axis scalar).
2659    ///
2660    /// The `:politicas :circuit-breaker :max-failures` axis carries the
2661    /// "consecutive-transient-failure trip threshold" contract
2662    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
2663    /// (zero-floor rejected through
2664    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2665    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
2666    /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
2667    /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
2668    /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
2669    /// Every downstream consumer that reads the trip threshold keys off
2670    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2671    /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
2672    /// canonical `require_positive_bounded_u32` helper, the future M4
2673    /// per-Aplicacao Envoy config reconciler materialization pass, the
2674    /// future per-`:contratos`-edge breaker-override overlay the
2675    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2676    ///
2677    /// Prior to this lift the `.max_failures` field was accessed inline
2678    /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
2679    /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
2680    /// open-coded field-access that expressed no compile-time link back
2681    /// to the typed sub-struct axis. A future extension of the
2682    /// `:max-failures` axis to a richer author surface — a
2683    /// per-`:contratos`-edge breaker override the operator pins through a
2684    /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
2685    /// #3 roadmap acknowledges, a per-cluster max-failures-default
2686    /// overlay the M4 CR materializer resolves per-CR, a promotion of the
2687    /// plain `u32` trip count to a richer
2688    /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
2689    /// tuple once Envoy's `outlier_detection` block's peer axes come into
2690    /// scope, a per-Envoy-cluster minimum-request-volume gate before the
2691    /// count arms — would have had to be threaded through every open-
2692    /// coded copy in lockstep or the validate gate and the future M4
2693    /// emit path would silently disagree on which trip threshold a given
2694    /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
2695    /// would satisfy validate while the emit path silently read a drifted
2696    /// other value, or vice versa: a validated typed slot would land at
2697    /// the emit boundary as a no-op breaker whose trip threshold is
2698    /// structurally never reached). Lifting the resolution to a typed
2699    /// method on the substrate primitive means every downstream consumer
2700    /// of the Aplicacao's per-`:politicas :circuit-breaker`
2701    /// trip-threshold surface reaches for exactly one typed dispatch —
2702    /// the resolver's accept-set migrates as a unit on any future axis
2703    /// addition.
2704    ///
2705    /// First sub-struct scalar accessor on the M3 mesh-slot family
2706    /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
2707    /// scalar" projection pattern the sibling `CircuitBreaker::window` /
2708    /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
2709    /// closes the last unlifted per-`:politicas` scalar-value axis after
2710    /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
2711    /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
2712    /// Same "one typed dispatch on the substrate primitive, thin
2713    /// projections at each consumer" discipline the peer
2714    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
2715    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
2716    /// [`Membro::versao_requirement`] (a40b0e3),
2717    /// [`Entrada::destination`] (6db982c) accessors carry on their
2718    /// respective per-mesh-slot-atom scalar-value axes, extended onto the
2719    /// per-sub-struct required-`u32` axis. Named `max_failures()` to
2720    /// match the storage field's name; the accessor's identity maps onto
2721    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2722    /// docstring already carries.
2723    #[must_use]
2724    pub const fn max_failures(&self) -> u32 {
2725        self.max_failures
2726    }
2727
2728    /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
2729    /// Envoy-outlier-detection rolling-observation-interval scalar
2730    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2731    /// breaker rolling-window duration keys off — returns the
2732    /// author-declared `:politicas :circuit-breaker :window` typed
2733    /// `Duration` verbatim, copied out of the typed slot's own
2734    /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
2735    /// by value; no borrow of `&self` past the call). Non-optional (the
2736    /// surrounding `Option<CircuitBreaker>` is the "slot present?"
2737    /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
2738    /// `CircuitBreaker` past pattern-match is definitionally present,
2739    /// and its `:window` field carries the rolling-observation interval
2740    /// as a required-axis scalar).
2741    ///
2742    /// The `:politicas :circuit-breaker :window` axis carries the
2743    /// "consecutive-transient-failure rolling-observation interval"
2744    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2745    /// `Duration` accept-set (zero-floor rejected through
2746    /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
2747    /// residue rejected through
2748    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
2749    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
2750    /// Envoy `outlier_detection.interval` per-cluster
2751    /// ejection-observation-interval scalar (equivalently the future
2752    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2753    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2754    /// consumer that reads the rolling-observation interval keys off
2755    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2756    /// integer-millisecond canonical-form + cap bracket at
2757    /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
2758    /// [`crate::render::require_positive_canonical_bounded_duration`]
2759    /// helper, the future M4 per-Aplicacao Envoy config reconciler
2760    /// materialization pass, the future per-`:contratos`-edge
2761    /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
2762    /// acknowledges).
2763    ///
2764    /// Prior to this lift the `.window` field was accessed inline at
2765    /// one production site — [`AplicacaoSpec::validate_politicas`]'s
2766    /// `require_positive_canonical_bounded_duration(cb.window, …)`
2767    /// call — one open-coded field-access that expressed no compile-
2768    /// time link back to the typed sub-struct axis. A future extension
2769    /// of the `:window` axis to a richer author surface — a
2770    /// per-`:contratos`-edge window override the operator pins through
2771    /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
2772    /// #3 roadmap acknowledges, a per-cluster window-default overlay
2773    /// the M4 CR materializer resolves per-CR, a promotion of the plain
2774    /// `Duration` observation interval to a richer
2775    /// `{interval, base_ejection_time, max_ejection_percent}` tuple
2776    /// once Envoy's `outlier_detection` block's peer axes come into
2777    /// scope, a per-Envoy-cluster minimum-request-volume gate before
2778    /// the window arms — would have had to be threaded through every
2779    /// open-coded copy in lockstep or the validate gate and the future
2780    /// M4 emit path would silently disagree on which observation
2781    /// interval a given [`CircuitBreaker`] resolves to (an author's
2782    /// `:window "60s"` would satisfy validate while the emit path
2783    /// silently read a drifted other value, or vice versa: a validated
2784    /// typed slot would land at the emit boundary as a breaker whose
2785    /// observation window is structurally so wide that no realistic
2786    /// failure-rate shape can trip it). Lifting the resolution to a
2787    /// typed method on the substrate primitive means every downstream
2788    /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
2789    /// observation-window surface reaches for exactly one typed
2790    /// dispatch — the resolver's accept-set migrates as a unit on any
2791    /// future axis addition.
2792    ///
2793    /// Second sub-struct scalar accessor on the M3 mesh-slot family —
2794    /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
2795    /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
2796    /// required-axis, extended onto the per-sub-struct required-`Duration`
2797    /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
2798    /// axis. Same "one typed dispatch on the substrate primitive, thin
2799    /// projections at each consumer" discipline the peer
2800    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
2801    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
2802    /// [`Membro::versao_requirement`] (a40b0e3),
2803    /// [`Entrada::destination`] (6db982c) accessors carry on their
2804    /// respective per-mesh-slot-atom scalar-value axes, extended onto
2805    /// the per-sub-struct required-`Duration` axis. Named `window()` to
2806    /// match the storage field's name; the accessor's identity maps onto
2807    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2808    /// docstring already carries.
2809    #[must_use]
2810    pub const fn window(&self) -> Duration {
2811        self.window
2812    }
2813}
2814
2815#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2816pub struct RateLimit {
2817    /// Requests per window.
2818    pub rate: u32,
2819    /// Window duration.
2820    pub window: Duration,
2821}
2822
2823impl RateLimit {
2824    /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
2825    /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
2826    /// every consumer of the Aplicacao's per-`:contratos`-edge
2827    /// rate-limit-bucket capacity keys off — returns the author-declared
2828    /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
2829    /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
2830    /// returns by value; no borrow of `&self` past the call). Non-optional
2831    /// (the surrounding `Option<RateLimit>` is the "slot present?"
2832    /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
2833    /// `RateLimit` past pattern-match is definitionally present, and its
2834    /// `:rate` field carries the token-bucket capacity as a required-axis
2835    /// scalar).
2836    ///
2837    /// The `:politicas :rate-limit` `:rate` axis carries the
2838    /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
2839    /// the typed slot's `u32` accept-set (zero-floor rejected through
2840    /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
2841    /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
2842    /// `local_rate_limit.token_bucket.max_tokens` per-cluster
2843    /// token-bucket-capacity scalar (equivalently the future
2844    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2845    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2846    /// consumer that reads the token-bucket capacity keys off this
2847    /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2848    /// cap bracket that gates on the canonical
2849    /// [`crate::render::require_positive_bounded_u32`] helper, the
2850    /// [`rate_limit_codec::render`] `Duration → unit` projection that
2851    /// emits the `<n>/<s|m|h>` author surface, the future M4
2852    /// per-Aplicacao Envoy config reconciler materialization pass, the
2853    /// future per-`:contratos`-edge rate-limit-override overlay the
2854    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2855    ///
2856    /// Prior to this lift the `.rate` field was accessed inline at three
2857    /// production sites — [`AplicacaoSpec::validate_politicas`]'s
2858    /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
2859    /// [`rate_limit_codec::render`] format-arm arms (canonical-window
2860    /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
2861    /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
2862    /// field-accesses that expressed no compile-time link back to the
2863    /// typed sub-struct axis. A future extension of the `:rate` axis
2864    /// to a richer author surface — a per-`:contratos`-edge rate
2865    /// override the operator pins through a future `:contratos :rate`
2866    /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
2867    /// per-cluster rate-default overlay the M4 CR materializer resolves
2868    /// per-CR, a promotion of the plain `u32` token capacity to a
2869    /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
2870    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
2871    /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
2872    /// before the token arms — would have had to be threaded through
2873    /// every open-coded copy in lockstep or the validate gate, the
2874    /// codec's render path, and the future M4 emit path would silently
2875    /// disagree on which token capacity a given [`RateLimit`] resolves
2876    /// to (an author's `:rate-limit "100/s"` would satisfy validate
2877    /// while the render / emit paths silently read a drifted other
2878    /// value, or vice versa: a validated typed slot would land at the
2879    /// emit boundary as a no-op limiter whose token capacity is
2880    /// structurally so high that no realistic per-edge traffic shape
2881    /// can drain it). Lifting the resolution to a typed method on the
2882    /// substrate primitive means every downstream consumer of the
2883    /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
2884    /// reaches for exactly one typed dispatch — the resolver's
2885    /// accept-set migrates as a unit on any future axis addition.
2886    ///
2887    /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
2888    /// in shape to the peer per-`CircuitBreaker`
2889    /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
2890    /// on the peer per-sub-struct required-axis, extended onto the
2891    /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
2892    /// required-axis scalar" projection pattern the sibling
2893    /// [`RateLimit::window`] future lift folds on. Same "one typed
2894    /// dispatch on the substrate primitive, thin projections at each
2895    /// consumer" discipline the peer [`WitContract::source`] /
2896    /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
2897    /// (0804823), [`Membro::nome`] (4a32abf),
2898    /// [`Membro::versao_requirement`] (a40b0e3),
2899    /// [`Entrada::destination`] (6db982c),
2900    /// [`CircuitBreaker::max_failures`] (3a74062),
2901    /// [`CircuitBreaker::window`] (373957f) accessors carry on their
2902    /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
2903    /// to match the storage field's name; the accessor's identity maps
2904    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2905    /// docstring already carries.
2906    #[must_use]
2907    pub const fn rate(&self) -> u32 {
2908        self.rate
2909    }
2910
2911    /// Substrate-canonical per-`:politicas :rate-limit` `:window`
2912    /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
2913    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2914    /// rate-limit-bucket refill period keys off — returns the
2915    /// author-declared `:politicas :rate-limit` typed `Duration`
2916    /// verbatim, copied out of the typed slot's own `Duration` storage
2917    /// (`Duration` is `Copy`, so the accessor returns by value; no
2918    /// borrow of `&self` past the call). Non-optional (the surrounding
2919    /// `Option<RateLimit>` is the "slot present?" projection at the
2920    /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
2921    /// pattern-match is definitionally present, and its `:window`
2922    /// field carries the token-bucket refill period as a required-axis
2923    /// scalar).
2924    ///
2925    /// The `:politicas :rate-limit` `:window` axis carries the
2926    /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
2927    /// — the typed slot's `Duration` accept-set (constrained to the
2928    /// three canonical windows `{1s, 60s, 3600s}` the
2929    /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
2930    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
2931    /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
2932    /// per-cluster token-bucket-refill-period scalar (equivalently the
2933    /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2934    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2935    /// consumer that reads the token-bucket refill period keys off
2936    /// this scalar (the [`AplicacaoSpec::validate_politicas`]
2937    /// canonical-window gate that keys off
2938    /// [`is_canonical_rate_limit_window`], the
2939    /// [`rate_limit_codec::render`] `Duration → unit` projection that
2940    /// emits the `<n>/<s|m|h>` author surface — canonical arm via
2941    /// [`rate_limit_window_unit`] and non-canonical fallback via
2942    /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
2943    /// reconciler materialization pass, the future per-`:contratos`-
2944    /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
2945    /// roadmap acknowledges).
2946    ///
2947    /// Prior to this lift the `.window` field was accessed inline at
2948    /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
2949    /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
2950    /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
2951    /// error-payload construction on refusal, and the two
2952    /// [`rate_limit_codec::render`] arms
2953    /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
2954    /// and non-canonical-window `rl.window.as_secs()` fallback). Three
2955    /// open-coded field-accesses that expressed no compile-time link
2956    /// back to the typed sub-struct axis. A future extension of the
2957    /// `:window` axis to a richer author surface — a per-`:contratos`-
2958    /// edge window override the operator pins through a future
2959    /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
2960    /// acknowledges, a per-cluster window-default overlay the M4 CR
2961    /// materializer resolves per-CR, a promotion of the plain
2962    /// `Duration` refill period to a richer
2963    /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
2964    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
2965    /// axis comes into scope, an addition of a `"d"` day suffix once
2966    /// Envoy's `rate_limit_action` grows daily-bucket support — would
2967    /// have had to be threaded through every open-coded copy in
2968    /// lockstep or the validate gate, the codec's render path, and
2969    /// the future M4 emit path would silently disagree on which
2970    /// refill period a given [`RateLimit`] resolves to (an author's
2971    /// `:rate-limit "100/s"` would satisfy validate while the render
2972    /// / emit paths silently read a drifted other value, or vice
2973    /// versa: a validated typed slot would land at the emit boundary
2974    /// as a limiter whose refill period is structurally so long that
2975    /// no realistic per-edge traffic shape stays inside the token
2976    /// budget). Lifting the resolution to a typed method on the
2977    /// substrate primitive means every downstream consumer of the
2978    /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
2979    /// reaches for exactly one typed dispatch — the resolver's
2980    /// accept-set migrates as a unit on any future axis addition.
2981    ///
2982    /// Second sub-struct scalar accessor on the `RateLimit` axis —
2983    /// sibling in shape to the just-landed [`RateLimit::rate`]
2984    /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
2985    /// required-axis, extended onto the per-sub-struct
2986    /// required-`Duration` axis; closes the last unlifted
2987    /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
2988    /// per-sub-struct accessor coverage is now complete across both
2989    /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
2990    /// the substrate primitive, thin projections at each consumer"
2991    /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
2992    /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
2993    /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
2994    /// (7f0fd43), [`WitContract::world_ref`] (0804823),
2995    /// [`Membro::nome`] (4a32abf),
2996    /// [`Membro::versao_requirement`] (a40b0e3),
2997    /// [`Entrada::destination`] (6db982c) accessors carry on their
2998    /// respective per-mesh-slot-atom scalar-value axes. Named
2999    /// `window()` to match the storage field's name; the accessor's
3000    /// identity maps onto the canonical MESH-COMPOSITION §III.2
3001    /// vocabulary the slot's docstring already carries.
3002    #[must_use]
3003    pub const fn window(&self) -> Duration {
3004        self.window
3005    }
3006
3007    /// Recognize this rate-limit's `:window` as a canonical
3008    /// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
3009    /// exactly matches one of the three closed-set arm-Durations
3010    /// (`1s` / `60s` / `3600s`), `None` when the window carries a
3011    /// non-canonical magnitude the codec's round-trip would break on
3012    /// (sub-second residue, or a second-magnitude outside the set
3013    /// [`RateLimitUnit::ALL`] enumerates).
3014    ///
3015    /// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
3016    /// returns `Some` here — the validate gate's
3017    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
3018    /// rejects every window this accessor returns `None` on. Downstream
3019    /// consumers past validate (the codec's [`rate_limit_codec::render`]
3020    /// path, the future M4 per-Aplicacao Envoy config reconciler's
3021    /// materialization pass, the future per-`:contratos`-edge rate-limit-
3022    /// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
3023    /// acknowledges) that read the typed unit off a validated slot can
3024    /// pattern-match on the returned `Some` without re-checking
3025    /// canonicality at the consumer layer — the typed enum surface is
3026    /// the load-bearing carrier of the canonicality invariant.
3027    ///
3028    /// Preferred over the free [`is_canonical_rate_limit_window`]
3029    /// module-private helper at any call site that has the typed
3030    /// [`RateLimit`] in hand (the codec's `render` arm at
3031    /// [`rate_limit_codec::render`], the validate gate's canonical-form
3032    /// arm in [`AplicacaoSpec::validate_politicas`], any future
3033    /// per-`:contratos` edge-override overlay resolver): those consumers
3034    /// reach for the typed enum without going through the
3035    /// `.window()` scalar-projection layer, and get the enum value
3036    /// directly (which the codec's render arm can then format via
3037    /// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
3038    /// "typed sub-struct scalar accessor, one dispatch on the substrate
3039    /// primitive" discipline the sibling [`RateLimit::rate`] and
3040    /// [`RateLimit::window`] accessors carry on the peer per-sub-struct
3041    /// scalar-value axes, extended onto the per-`RateLimit` typed-unit
3042    /// projection axis (the third scalar accessor on the [`RateLimit`]
3043    /// axis, first typed-enum-return projection).
3044    ///
3045    /// `pub const fn` — the typed-`RateLimit`-projection dispatch onto
3046    /// the canonical [`RateLimitUnit`] arm now carries the same
3047    /// `const`-eval-surface posture the sibling `pub const fn`
3048    /// [`Self::rate`] / [`Self::window`] scalar-projection accessors on
3049    /// this typed sub-struct already carry, composing through the
3050    /// peer-lifted `pub const fn` [`RateLimitUnit::from_window`]
3051    /// reverse-resolver in `const` context. Any downstream substrate-
3052    /// side `const`-context consumer of the typed unit (a module-scope
3053    /// `const _:() = assert!(matches!(rl.canonical_unit(), Some(RateLimitUnit::Second)))`
3054    /// invariant pin on a typed fixture, a future M4 admission-webhook
3055    /// `const fn` per-`:politicas :rate-limit :window` canonical-arm
3056    /// resolver over a typed [`RateLimit`], any future `const fn`
3057    /// per-`:contratos`-edge rate-limit-override overlay resolver over
3058    /// the substrate primitive) now reaches the same typed dispatch on
3059    /// the substrate primitive at const-eval time as at runtime.
3060    ///
3061    /// Pinned load-bearing at the substrate-primitive level by
3062    /// [`tests::rate_limit_canonical_unit_accessor_is_const_fn`] (const-
3063    /// eval-surface pin via `const fn` wrapper).
3064    #[must_use]
3065    pub const fn canonical_unit(&self) -> Option<RateLimitUnit> {
3066        RateLimitUnit::from_window(self.window)
3067    }
3068}
3069
3070/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
3071/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
3072/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
3073///
3074/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
3075/// the `:politicas :rate-limit` unit surface reads from
3076/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
3077/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
3078/// [`is_canonical_rate_limit_window`] predicate the
3079/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
3080/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
3081/// projection) now lives inside this typed enum's `match self` arms — a
3082/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
3083/// `rate_limit_action` grows daily-bucket support) is one new variant
3084/// plus the exhaustiveness arms on the four methods, so every consumer
3085/// picks it up by compile-time construction rather than a runtime
3086/// table-scan miss.
3087///
3088/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
3089/// scanned via `find_map` at every projection call — an untyped runtime
3090/// walk that carried no compile-time link between the parse arm's
3091/// accepted suffixes, the render arm's emitted suffixes, and the
3092/// validate gate's accepted windows. A future rate-limit-unit addition
3093/// that landed one row without threading through the other consumers
3094/// (or a copy-paste flip that collapsed two rows onto one suffix) would
3095/// silently split the accepted-set across the three consumers — the
3096/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
3097/// for a 24h window that parse can't round-trip, the validate gate
3098/// misses one canonical window. Lifting the pairs onto a typed
3099/// closed-set enum with exhaustive `match` arms makes any such
3100/// half-landed extension a caixa-core build error (the compiler enforces
3101/// arm coverage on every method), not a silent per-consumer drift
3102/// surfacing at apply time. Same "closed-set typed-enum discriminator"
3103/// discipline the sibling [`PlacementStrategy`] (cc8f749),
3104/// [`crate::supervisor::RestartStrategy`],
3105/// [`crate::supervisor::RestartPolicy`],
3106/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
3107/// closed-set typed enums carry on their respective closed-set axes —
3108/// extended onto the seventh closed-set typed-enum discriminator axis
3109/// on the caixa typed surface (the `:politicas :rate-limit :window`
3110/// canonical-unit axis).
3111#[derive(
3112    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
3113)]
3114pub enum RateLimitUnit {
3115    /// 1-second window — canonical author-surface suffix `"s"`
3116    /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3117    /// with a 1s magnitude.
3118    Second,
3119    /// 1-minute window — canonical author-surface suffix `"m"`
3120    /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3121    /// with a 60s magnitude.
3122    Minute,
3123    /// 1-hour window — canonical author-surface suffix `"h"`
3124    /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3125    /// with a 3600s magnitude.
3126    Hour,
3127}
3128
3129impl RateLimitUnit {
3130    /// Exhaustive iteration surface for every consumer that reads the
3131    /// full canonical-unit set (the byte-parity witness against the
3132    /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
3133    /// webhook's accepted-suffix listing in its rejection body, any
3134    /// future round-trip fuzz harness). A future variant addition to
3135    /// [`RateLimitUnit`] extends this slice as a single edit and every
3136    /// consumer picks up the new entry by construction — the compiler-
3137    /// checked exhaustiveness on the sibling method `match` arms is the
3138    /// build-time guarantee that no arm forgets to grow.
3139    pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
3140
3141    /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
3142    /// string every `<n>/<unit>` rate-limit shape carries after its
3143    /// `/` separator. The single source of truth the codec's parse and
3144    /// render arms both dispatch on: the parse arm matches an incoming
3145    /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
3146    /// output; the render arm emits the entry's `as_suffix` verbatim
3147    /// after the rate magnitude.
3148    #[must_use]
3149    pub const fn as_suffix(self) -> &'static str {
3150        match self {
3151            Self::Second => "s",
3152            Self::Minute => "m",
3153            Self::Hour => "h",
3154        }
3155    }
3156
3157    /// Canonical `Duration` for this unit — the token-bucket refill
3158    /// period the [`RateLimit::window`] axis carries when the surrounding
3159    /// slot's `:rate-limit` author surface named this unit.
3160    #[must_use]
3161    pub const fn window(self) -> Duration {
3162        Duration::from_secs(match self {
3163            Self::Second => 1,
3164            Self::Minute => 60,
3165            Self::Hour => 3_600,
3166        })
3167    }
3168
3169    /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
3170    /// `None` when `suffix` is outside the closed-set arm-string set
3171    /// [`Self::as_suffix`] emits. The single `str → Self` projection
3172    /// [`rate_limit_codec::parse`] consumes.
3173    #[must_use]
3174    pub fn from_suffix(suffix: &str) -> Option<Self> {
3175        Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
3176    }
3177
3178    /// Recognize a canonical rate-limit `Duration` as one of the three
3179    /// arms, or `None` when `window` carries sub-second residue or a
3180    /// second-magnitude outside the closed-set arm-window set
3181    /// [`Self::window`] emits. The single `Duration → Self` projection
3182    /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
3183    /// both consume.
3184    ///
3185    /// `pub const fn` — the reverse `Duration → Self` projection now
3186    /// carries the same `const`-eval-surface posture the sibling
3187    /// `pub const fn` [`Self::as_suffix`] / [`Self::window`] scalar-
3188    /// projection accessors on this closed-set typed enum already
3189    /// carry, and the paired `pub const fn` [`RateLimit::canonical_unit`]
3190    /// typed-`RateLimit`-projection sibling composes through in `const`
3191    /// context. Routes byte-for-byte through the peer `pub const fn`
3192    /// [`Self::window`] canonical-`Duration` projection so any future
3193    /// arm-magnitude edit on the sibling accessor reaches this reverse
3194    /// resolver by construction — the `s == Self::<Arm>.window().as_secs()`
3195    /// per-arm probes each dispatch through one `pub const fn` on the
3196    /// substrate primitive rather than a hand-authored per-arm second-
3197    /// magnitude literal that would silently drift on any future
3198    /// [`Self::window`] arm-magnitude edit.
3199    ///
3200    /// Prior to the `const` lift the body dispatched through
3201    /// `Self::ALL.iter().copied().find(|u| u.window() == window)` — an
3202    /// iterator-driven linear scan whose iterator methods
3203    /// (`.iter()` / `.copied()` / `.find()`) and `Duration`-side
3204    /// `PartialEq` dispatch each carry non-`const` bounds on stable
3205    /// Rust 1.94, so any downstream substrate-side `const`-context
3206    /// consumer of the reverse resolver (a module-scope
3207    /// `const _:() = assert!(RateLimitUnit::from_window(<canonical>).is_some())`
3208    /// invariant pin on a typed fixture, a future M4
3209    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
3210    /// webhook `const fn` per-`:politicas` canonical-window floor over a
3211    /// typed [`RateLimit`] scalar, any future `const fn`
3212    /// per-`:contratos`-edge rate-limit-override overlay resolver over
3213    /// the substrate primitive that wants to fan on the canonical unit
3214    /// at compile time) surfaced as a downstream E0015 far from the
3215    /// resolver's own declaration. The `pub const fn` posture closes
3216    /// the drift structurally at caixa-core build time.
3217    ///
3218    /// Pinned load-bearing at the substrate-primitive level by
3219    /// [`tests::rate_limit_unit_from_window_accessor_is_const_fn`] (const-
3220    /// eval-surface pin via `const fn` wrapper) and
3221    /// [`tests::rate_limit_unit_from_window_composes_through_window_accessor`]
3222    /// (composition-witness pin against the peer `Self::window` scalar
3223    /// dispatch).
3224    #[must_use]
3225    pub const fn from_window(window: Duration) -> Option<Self> {
3226        if window.subsec_nanos() != 0 {
3227            return None;
3228        }
3229        // Route through the peer `pub const fn` [`Self::window`]
3230        // canonical-`Duration` projection so any future arm-magnitude
3231        // edit on the sibling accessor reaches this reverse resolver by
3232        // construction — the per-arm `secs` comparison keys off
3233        // `Duration::as_secs` (`pub const fn`), not a hand-authored
3234        // per-arm second-magnitude literal that would silently drift.
3235        let secs = window.as_secs();
3236        if secs == Self::Second.window().as_secs() {
3237            Some(Self::Second)
3238        } else if secs == Self::Minute.window().as_secs() {
3239            Some(Self::Minute)
3240        } else if secs == Self::Hour.window().as_secs() {
3241            Some(Self::Hour)
3242        } else {
3243            None
3244        }
3245    }
3246
3247    /// Canonical rate-limit `Duration` for a unit suffix, or `None` when
3248    /// `suffix` is outside the closed-set arm-string set [`Self::as_suffix`]
3249    /// emits. Composes [`Self::from_suffix`] with [`Self::window`] — the
3250    /// single `&str → Duration` projection [`rate_limit_codec::parse`]
3251    /// consumes.
3252    ///
3253    /// The peer `Duration → &'static str` axis folded onto the substrate
3254    /// primitive [`RateLimit::canonical_unit`] typed accessor once both
3255    /// production consumers ([`rate_limit_codec::render`] and
3256    /// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
3257    /// migrated (61421a6): the free helper's `Duration → &str` projection
3258    /// is now the two-step composition
3259    /// `rl.canonical_unit().map(RateLimitUnit::as_suffix)` every consumer
3260    /// reads through the typed accessor. This lift closes the peer
3261    /// `&str → Duration` axis by folding the vestigial module-private
3262    /// `rate_limit_window_from_unit` delegate onto this associated method
3263    /// — the codec's parse arm and every future wire-side consumer of the
3264    /// `&str → Duration` projection (a future admission-webhook that
3265    /// reads a `:rate-limit` shape off a CR spec's `raw string` value
3266    /// before it's promoted to a validated typed slot, a future
3267    /// `feira lint` shape-probe that reads the author-surface bytes
3268    /// verbatim) now reach for exactly one typed dispatch on the
3269    /// substrate primitive.
3270    ///
3271    /// Same "closed-set typed-enum discriminator with canonical
3272    /// projections per axis" discipline the sibling [`Self::as_suffix`]
3273    /// / [`Self::window`] / [`Self::from_suffix`] / [`Self::from_window`]
3274    /// methods carry — this associated method closes the fifth (and last
3275    /// unlifted) projection axis on the arm-table, so the closed-set enum
3276    /// now owns every `str ↔ Duration ↔ Self` typed dispatch every
3277    /// consumer of the `:politicas :rate-limit :window` axis reaches
3278    /// through. A future rate-limit-unit addition (a `"d"` day suffix
3279    /// once Envoy's `rate_limit_action` grows daily-bucket support, a
3280    /// `"ms"` sub-second window once high-throughput per-edge policies
3281    /// come into scope per MESH-COMPOSITION §III.2 #3) is one new
3282    /// variant plus one arm per method — the compiler enforces
3283    /// exhaustiveness on every consumer's `match self` arms and picks
3284    /// the new unit up by construction across all five projections.
3285    #[must_use]
3286    pub fn window_from_suffix(suffix: &str) -> Option<Duration> {
3287        Self::from_suffix(suffix).map(Self::window)
3288    }
3289}
3290
3291/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
3292/// every consumer that formats a canonical rate-limit unit as user-
3293/// facing text (future M4 admission-webhook rejection bodies naming
3294/// the accepted-suffix set, future `feira app graph` per-`:politicas`
3295/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
3296/// codec's parse arm accepts and the render arm emits. Same
3297/// as_str-through-Display convergence discipline the sibling
3298/// [`PlacementStrategy`], [`crate::CaixaKind`],
3299/// [`crate::supervisor::RestartStrategy`], and
3300/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
3301impl std::fmt::Display for RateLimitUnit {
3302    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3303        f.write_str(self.as_suffix())
3304    }
3305}
3306
3307/// Upper-bound ceiling on the `:politicas :timeout` axis — every
3308/// validated [`MeshPolicy::timeout`] past
3309/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
3310/// (inclusive on both ends, integer-millisecond magnitudes by the
3311/// canonical-form gate immediately preceding).
3312///
3313/// The typed field is `Option<Duration>` (the zero-floor arm
3314/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
3315/// `Duration::ZERO`, and the canonical-form arm
3316/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
3317/// sub-millisecond residue), so a programmatic struct literal
3318/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
3319/// 24h) and the equivalent author-surface form
3320/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
3321/// integer-hour magnitude) both round-trip cleanly through serde — a
3322/// structurally unbounded `Duration` ceiling. A `:timeout` value far
3323/// above the documented production-playbook band (Envoy default `15s`,
3324/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
3325/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
3326/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
3327/// at `~3600s`) silently degenerates the mesh-policy contract: the
3328/// per-call deadline is structurally so long that no realistic
3329/// synchronous-`:contratos` traversal can reach it, so the typed slot
3330/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
3331/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
3332/// blocking" degenerates to a nominal-only contract on the
3333/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
3334/// the sibling `:politicas :retries` axis and the
3335/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
3336/// `:politicas :circuit-breaker :max-failures` axis — all three close
3337/// the "structurally unbounded ceiling on a typed `:politicas` axis"
3338/// footgun the prior zero-floor-and-canonical-form-only checks left
3339/// open.
3340///
3341/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
3342/// shared duration codec emits (`"<n>h"` for any integer-hour
3343/// magnitude) — every value in the canonical authoring form's
3344/// `<integer><unit>` grammar at or below this cap renders to a clean
3345/// canonical string. The cap sits an order of magnitude above every
3346/// documented production-playbook recommendation band (Envoy default
3347/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
3348/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
3349/// configured maximum (`proxy_read_timeout` typical max `3600s`),
3350/// below the clearly-pathological "effectively no timeout" floor
3351/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
3352/// want for a long-running synchronous workflow, but a hard wall above
3353/// which the mesh-level deadline is structurally a non-deadline.
3354/// Lifted as a typed `pub const` so the bound has exactly one source
3355/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3356/// materializer's admission webhook and the caixa-mesh-side
3357/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3358/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3359/// other typed upper bound in this crate carries
3360/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3361/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3362/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3363/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3364pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
3365
3366/// Upper-bound ceiling on the `:politicas :retries` axis — every
3367/// validated [`MeshPolicy::retries`] past
3368/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
3369///
3370/// The typed slot is `Option<u32>` (`None` = no retries on transient
3371/// failure; `Some(0)` already rejected by the
3372/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
3373/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
3374/// .. }`) and the equivalent author-surface form
3375/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
3376/// serde / the codec — a structurally unbounded `u32` ceiling. The
3377/// runtime substrate that consumes the value (Envoy's
3378/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
3379/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
3380/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
3381/// admission cap is 10) translates a four-billion-retry policy into a
3382/// thundering-herd amplification vector on transient failure — the
3383/// caller's one request fans out to `retries` server-side calls per
3384/// edge per traversal, multiplying load by `(retries+1)^depth` across
3385/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
3386/// invariant "no infinite blocking" pairs with a no-runaway-amplification
3387/// invariant on the retry axis; both belong at the typed-slot layer.
3388///
3389/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
3390/// upstream mesh-policy schema that documents one) and sits above the
3391/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
3392/// every documented production playbook): a value the author can
3393/// plausibly want, but a hard wall above which the policy is
3394/// structurally a footgun. Lifted as a typed `pub const` so the bound
3395/// has exactly one source of truth — a future axis reaching for the
3396/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3397/// materializer's admission webhook, the caixa-mesh-side
3398/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
3399/// one place. Same shape every other typed upper bound in this crate
3400/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3401/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3402/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
3403/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3404pub const POLICY_RETRIES_MAX: u32 = 10;
3405
3406/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
3407/// axis — every validated [`CircuitBreaker::max_failures`] past
3408/// [`AplicacaoSpec::validate_politicas`] lies in
3409/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
3410///
3411/// The typed field is `u32` (the zero-floor arm
3412/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
3413/// `0` — a breaker that trips on the first call), so a programmatic
3414/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
3415/// and the equivalent author-surface form
3416/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
3417/// cleanly through serde — a structurally unbounded `u32` ceiling. A
3418/// `max_failures` value far above the documented production-playbook
3419/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
3420/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
3421/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
3422/// typical 5–50) silently disables the breaker's protection role:
3423/// the threshold is structurally so high that no realistic
3424/// failures-per-`:window` traffic shape can reach it, so the breaker
3425/// never trips and the typed slot becomes a no-op carried on every
3426/// emitted Envoy / Cilium L7 overlay. Pairs with the
3427/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
3428/// axis — both close the "structurally unbounded `u32` ceiling on a
3429/// typed policy axis" footgun the prior zero-floor-only checks left
3430/// open.
3431///
3432/// The `1000` ceiling sits an order of magnitude above every
3433/// documented upstream production-playbook recommendation band (the
3434/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
3435/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
3436/// the clearly-pathological "effectively no protection"
3437/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
3438/// plausibly want at hyperscale, but a hard wall above which the
3439/// policy is structurally a no-op. Lifted as a typed `pub const` so
3440/// the bound has exactly one source of truth — the future M4
3441/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3442/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3443/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3444/// one place. Same shape every other typed upper bound in this crate
3445/// carries ([`POLICY_RETRIES_MAX`],
3446/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3447/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3448/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3449pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
3450
3451/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
3452/// every validated [`CircuitBreaker::window`] past
3453/// [`AplicacaoSpec::validate_politicas`] lies in
3454/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
3455/// integer-millisecond magnitudes by the canonical-form gate
3456/// immediately preceding).
3457///
3458/// The typed field is `Duration` (the zero-floor arm
3459/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
3460/// `Duration::ZERO`, and the canonical-form arm
3461/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
3462/// sub-millisecond residue), so a programmatic struct literal
3463/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
3464/// and the equivalent author-surface form
3465/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
3466/// integer-hour magnitude) both round-trip cleanly through serde — a
3467/// structurally unbounded `Duration` ceiling. A `:window` value far
3468/// above the documented production-playbook band (Hystrix
3469/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
3470/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
3471/// Istio `outlierDetection.interval` default `10s`, Envoy
3472/// `outlier_detection.interval` default `10s`, AWS App Mesh
3473/// circuit-breaker time-window typical `30s..=300s`) degenerates the
3474/// breaker's role: a rolling-window failure counter whose window is
3475/// hours long is operationally a lifetime counter, the breaker's
3476/// "recent failures" memory is structurally so long that transient
3477/// failures are never forgotten, and the typed slot becomes a no-op
3478/// trigger that trips once and stays tripped for the lifetime of the
3479/// component carried on every emitted Envoy / Cilium L7 overlay.
3480///
3481/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
3482/// shared duration codec emits (`"<n>h"` for any integer-hour
3483/// magnitude) — every value in the canonical authoring form's
3484/// `<integer><unit>` grammar at or below this cap renders to a clean
3485/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
3486/// cap on the first typed-`Duration` `:politicas` axis: the two
3487/// duration-typed `:politicas` axes now share a single uniform top
3488/// edge so the next typed-slot wiring (the future caixa-mesh
3489/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
3490/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
3491/// admission webhook) reaches for either field knowing the value is
3492/// in `1ms..=1h` without re-validating at the renderer layer. The cap
3493/// sits two orders of magnitude above every documented upstream
3494/// production-playbook recommendation band (Hystrix / resilience4j /
3495/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
3496/// and below the clearly-pathological "rolling window degenerates to
3497/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
3498/// author can plausibly want for a very-low-traffic long-tail
3499/// failure-detection window, but a hard wall above which the breaker's
3500/// rolling-window contract is structurally a lifetime-counter contract.
3501/// Lifted as a typed `pub const` so the bound has exactly one source
3502/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3503/// materializer's admission webhook and the caixa-mesh-side
3504/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3505/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3506/// other typed upper bound in this crate carries
3507/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3508/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3509/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3510/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3511/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3512pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
3513
3514/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
3515/// every validated [`RateLimit::rate`] past
3516/// [`AplicacaoSpec::validate_politicas`] lies in
3517/// `1..=POLICY_RATE_LIMIT_MAX`.
3518///
3519/// The typed field is `u32` (the zero-floor arm
3520/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
3521/// zero-rate limit denies every request, the canonical "I forgot
3522/// that 0 means deny-everything" footgun), so a programmatic struct
3523/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
3524/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
3525/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
3526/// round-trip cleanly through serde — a structurally unbounded `u32`
3527/// ceiling. The runtime substrate consuming the value (Envoy's
3528/// `local_rate_limit.token_bucket.max_tokens`, the future
3529/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3530/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
3531/// rate-limit into a no-op rate-limiter: the bucket capacity is
3532/// structurally so high no realistic per-edge traffic shape can
3533/// drain it, the limiter never trips, and the typed slot becomes a
3534/// "rate-limit declared, no enforcement" footgun — the canonical
3535/// declared-but-inert shape every other `:politicas` cap arm
3536/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
3537/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
3538///
3539/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
3540/// above every documented upstream production-playbook recommendation
3541/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
3542/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
3543/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
3544/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
3545/// `limit_req_zone` typical `1..=1_000` RPS) and below the
3546/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
3547/// `u32::MAX`): a value the author can plausibly want at hyperscale
3548/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
3549/// /h-window arm), but a hard wall above which the policy is
3550/// structurally a no-op carried verbatim on every emitted Envoy /
3551/// Cilium L7 overlay. The cap brackets all three canonical windows
3552/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
3553/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
3554/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
3555/// per-endpoint API band). Lifted as a typed `pub const` so the bound
3556/// has exactly one source of truth — the future M4
3557/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3558/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3559/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3560/// one place. Same shape every other typed upper bound in this crate
3561/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3562/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
3563/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3564/// [`crate::LIMITS_WALL_CLOCK_MAX`],
3565/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3566/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3567pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
3568
3569// `:entrada :host` total-length and per-label cap axes route through
3570// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
3571// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
3572// pair of aplicacao-private aliases the previous `validate_entrada_host`
3573// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
3574// = 63`) were structurally the same K8s Gateway API v1 Hostname
3575// admission-schema bounds — the total-length cap on the OpenAPI
3576// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
3577// same regex — that the peer axes at the caixa-core::render level pin,
3578// so hoisting both readers onto the shared lifted constants closes the
3579// third-occurrence duplication threshold structurally: the M4
3580// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
3581// label validator, the future per-`Certificate` SAN emitter, and every
3582// other per-Gateway-API-Hostname landing site reach the same one place
3583// as the `:entrada :host` gate does — no per-axis alias drift surface
3584// between them, by construction.
3585
3586/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
3587/// extractor expression — the upper bound `validate_placement_shard_key`
3588/// enforces on every well-shaped shard-key past validate. The realistic
3589/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
3590/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
3591/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
3592/// `:placement :affinity` / `:placement :clusters` identifier-shaped
3593/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
3594/// in `:shard-key`" footgun at validate time rather than at the future
3595/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
3596const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
3597
3598/// Reject `:membros :caixa` values the K8s apiserver would refuse at
3599/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3600/// that maps the shared parser-shaped reason into the
3601/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
3602/// is self-locating (the offending `caixa:` is named verbatim) and
3603/// the author can grep their caixa.lisp for `:caixa "<name>"` and
3604/// fix it in one edit. Same diagnostic shape as
3605/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
3606/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
3607fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
3608    // Empty is already gated by `MembroCaixaEmpty` at the call site;
3609    // re-checking here keeps the predicate usable from any future
3610    // call site (the M4 CR materializer) without an empty-check
3611    // footgun. The shared
3612    // [`crate::render::require_valid_dns_1123_label`] helper brackets
3613    // the empty-first + shape cascade every peer name axis
3614    // (`:placement :clusters`, `:placement :affinity`, `:contratos
3615    // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
3616    // `:upgrade-from :module`) routes through, so drift between the
3617    // eight axes' accepted DNS-1123-label sets is structurally
3618    // impossible.
3619    crate::render::require_valid_dns_1123_label(
3620        caixa,
3621        || AplicacaoError::MembroCaixaEmpty,
3622        |reason| AplicacaoError::MembroCaixaInvalid {
3623            caixa: caixa.to_string(),
3624            reason,
3625        },
3626    )
3627}
3628
3629/// Reject `:placement :clusters` entries the K8s apiserver would refuse
3630/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3631/// that maps the shared parser-shaped reason into the
3632/// [`AplicacaoError::PlacementClusterInvalid`] variant.
3633///
3634/// Cluster names land in DNS-1123-label territory across every consumer:
3635/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
3636/// the `lareira-fleet-programs` aggregator applies to scope programs to
3637/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
3638/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
3639/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
3640/// cluster identity the M4 CR materializer round-trips. Each apiserver-
3641/// side schema enforces the DNS-1123 label rule on admission; a
3642/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
3643/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
3644/// mistaken-identity slug) silently passes the prior empty-/duplicate-
3645/// only gate and the failure surfaces as a no-match at filter time —
3646/// the workload doesn't land in the named cluster, with no diagnostic
3647/// naming the offending `:clusters` entry. Lifting the gate to caixa-
3648/// build time mirrors the `:membros :caixa` value-shape trajectory
3649/// (3f9d7a0) on the peer name axis.
3650///
3651/// The diagnostic carries the offending `cluster:` verbatim plus a
3652/// parser-shaped `reason:` naming the specific violation, so the
3653/// author can grep their caixa.lisp for `:clusters` and fix it in
3654/// one edit. Same diagnostic shape as
3655/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
3656fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
3657    // Empty is already gated by `PlacementClusterEmpty` at the call
3658    // site; re-checking here keeps the predicate usable from any
3659    // future call site (the M4 CR materializer's per-cluster validator)
3660    // without an empty-check footgun. Routes through the shared
3661    // [`crate::render::require_valid_dns_1123_label`] gate the peer
3662    // name axes each land on.
3663    crate::render::require_valid_dns_1123_label(
3664        cluster,
3665        || AplicacaoError::PlacementClusterEmpty,
3666        |reason| AplicacaoError::PlacementClusterInvalid {
3667            cluster: cluster.to_string(),
3668            reason,
3669        },
3670    )
3671}
3672
3673/// Reject `:placement :affinity` hints whose shape can never legitimately
3674/// land in any downstream selector or label-keyed routing axis. Thin
3675/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
3676/// shared parser-shaped reason into the
3677/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
3678/// diagnostic is self-locating (the offending `:affinity` is named
3679/// verbatim) and the author can grep their caixa.lisp for
3680/// `:affinity "<hint>"` and fix it in one edit.
3681///
3682/// The `:affinity` slot carries a placement-engine hint — canonical
3683/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
3684/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
3685/// compression overlay and the future M4 placement-engine's per-hint
3686/// routing axis. Each downstream consumer (caixa-mesh's
3687/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
3688/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3689/// `spec.placement.affinity` admission rule, the future M4 per-hint
3690/// node-affinity / pod-affinity rule generator keying off the same
3691/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
3692/// selector) requires the value to be a DNS-1123 label — K8s label
3693/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
3694/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
3695/// admission rule the apiserver enforces.
3696///
3697/// Until this gate landed an `:affinity "DataLocality"` (the canonical
3698/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
3699/// Python-module-name leak), `:affinity "data.locality"` (the
3700/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
3701/// `:affinity "data-locality-"` (boundary-hyphen violation),
3702/// `:affinity "data locality"` (paste-from-doc whitespace),
3703/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
3704/// 64-byte over-cap slug silently passed the empty-only check and the
3705/// failure surfaced as a no-match at the M3 Adaptive compression
3706/// overlay's filter time (`placement.affinity` carried a malformed
3707/// value, no node matched, the workload landed on the default
3708/// heuristic) — the canonical "declared-but-inert" footgun mirroring
3709/// the empty-:affinity / empty-shard-key / zero-:politicas /
3710/// empty-:contratos-target gates already close on every other
3711/// declare-but-no-opinion axis. Lifting the rejection to a build-time
3712/// gate closes the fifth typed slot on the Aplicacao surface to land
3713/// on the canonical DNS-1123 label floor (after the four Servico-name
3714/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
3715/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
3716/// b0e8748).
3717///
3718/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
3719/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
3720/// validated values are guaranteed-accepted by the apiserver without
3721/// re-validation at any downstream renderer or admission layer.
3722fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
3723    // Empty is gated separately at the call site for a self-locating
3724    // diagnostic; re-checking here keeps the predicate usable from any
3725    // future call site (the M4 CR materializer's per-affinity
3726    // validator) without an empty-check footgun. Routes through the
3727    // shared [`crate::render::require_valid_dns_1123_label`] gate the
3728    // peer name axes each land on.
3729    crate::render::require_valid_dns_1123_label(
3730        affinity,
3731        || AplicacaoError::PlacementAffinityEmpty,
3732        |reason| AplicacaoError::PlacementAffinityInvalid {
3733            affinity: affinity.to_string(),
3734            reason,
3735        },
3736    )
3737}
3738
3739/// Reject `:placement :shard-key` extractor expressions whose shape can
3740/// never legitimately drive the future M4 Akka-style cluster-sharding
3741/// reconciler's hash-extractor pass. Maps the per-byte / length checks
3742/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
3743/// diagnostic is self-locating (the offending `:shard-key` value is
3744/// named verbatim alongside the parser-shaped reason) and the author can
3745/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
3746/// edit.
3747///
3748/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
3749/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
3750/// expression naming the message property to hash on. The realistic
3751/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
3752/// property name; `$tenantId` — Akka entity-id placeholder;
3753/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
3754/// `${tenant}` — interpolation-style template) all sit in the printable
3755/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
3756/// multi-line blob landing in `:shard-key`, an embedded space from a
3757/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
3758/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
3759/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
3760/// check and the failure surfaces at the future M4 reconciler's hash
3761/// pass as a runtime extractor-evaluation error far from the source
3762/// `caixa.lisp`, with no field naming which member's `:shard-key`
3763/// carried the offending value.
3764///
3765/// The contract — the printable ASCII single-token intersection-floor
3766/// every Akka-style entity-id extractor implementation admits:
3767///
3768///   - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
3769///     peer DNS-1123-label-shaped `:placement :affinity` /
3770///     `:placement :clusters` identifier axes; realistic shard-keys sit
3771///     well under 32 bytes, the cap surfaces paste-from-doc multi-line
3772///     blob footguns at validate time;
3773///   - every byte in the printable ASCII range `0x21..=0x7E` —
3774///     rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
3775///     `"$tenantId\n"` from paste-from-aligned-doc /
3776///     paste-from-shell-heredoc), control characters (`\x00..\x1F`,
3777///     `\x7F` — the canonical "embedded null from a copy-paste-binary
3778///     footgun"), and non-ASCII bytes (`"$tenàntId"` —
3779///     un-Punycode-encoded IDN that round-trips inconsistently across
3780///     NFC/NFD normalization).
3781///
3782/// The accepted set is broader than the DNS-1123 label floor the peer
3783/// `:placement :clusters` / `:placement :affinity` axes use because the
3784/// `:shard-key` value is not a K8s `metadata.name` / label-selector
3785/// landing site; it's an extractor expression the future Akka-style
3786/// reconciler reads as a property reference. The realistic forms
3787/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
3788/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
3789/// but every Akka-style entity-id extractor parses. The
3790/// printable-ASCII-token floor accepts every shape any such extractor
3791/// would accept while rejecting the cross-implementation footguns
3792/// (whitespace breaks token boundaries; non-ASCII round-trips
3793/// inconsistently across YAML emitters and NFC/NFD normalization;
3794/// control characters silently corrupt the next read).
3795///
3796/// Until this gate landed `validate_placement` only refused the
3797/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
3798/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
3799/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
3800/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
3801/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
3802/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
3803/// control character from paste-from-binary, the 64-byte over-cap
3804/// paste-from-doc multi-line slug) silently passed validate. The future
3805/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
3806/// would then surface the malformed value either as a runtime
3807/// extractor-evaluation error (whitespace breaks the extractor's token
3808/// boundary, no match) or as a silently-different shard assignment
3809/// across YAML emitters (non-ASCII normalizes differently between the
3810/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
3811/// parser, the same entity ID maps to two distinct shards on a
3812/// re-render). Lifting the shape gate to caixa-build time makes the
3813/// extractor-floor invariant a structural property of every validated
3814/// `Placement`: every `Sharded` placement past `validate_placement` has
3815/// a `:shard-key` the future M4 reconciler can hash without
3816/// re-validating at the runtime layer.
3817///
3818/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
3819/// [`AplicacaoError::ContratoSubjectInvalid`] /
3820/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
3821/// on the peer `:contratos` payload axes — each lifts the
3822/// runtime-side parser's intersection-floor to a caixa-build-time gate,
3823/// closing the canonical "this passed validate but the runtime parser
3824/// rejected it" surprise.
3825fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
3826    // Empty is gated separately at the call site via the more
3827    // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
3828    // re-checking here keeps the predicate usable from any future call
3829    // site (the M4 CR materializer's per-shard-key validator) without
3830    // an empty-check footgun.
3831    if key.is_empty() {
3832        return Err(AplicacaoError::ShardedKeyEmpty);
3833    }
3834    if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
3835        return Err(AplicacaoError::ShardKeyInvalid {
3836            shard_key: key.to_string(),
3837            reason: format!(
3838                "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
3839                 (got {} bytes; realistic Akka-style entity-id extractor expressions \
3840                 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
3841                 well under 32 bytes, this length suggests a paste-from-doc \
3842                 multi-line blob landed in `:shard-key` instead of a single-token \
3843                 extractor expression)",
3844                key.len()
3845            ),
3846        });
3847    }
3848    for &b in key.as_bytes() {
3849        if (0x21..=0x7E).contains(&b) {
3850            continue;
3851        }
3852        let reason = if b == b' ' {
3853            "contains a space (Akka-style entity-id extractor expressions are \
3854             single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
3855             whitespace breaks the extractor's token boundary at the runtime layer, \
3856             and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
3857             a multi-token blob in one `:shard-key` slot)"
3858                .to_string()
3859        } else if b == b'\t' {
3860            "contains a tab character (paste-from-aligned-doc footgun; the \
3861             Akka-style entity-id extractor reads `:shard-key` as a single-token \
3862             reference, embedded whitespace breaks the token boundary at the \
3863             runtime hash-extractor pass)"
3864                .to_string()
3865        } else if b == b'\n' || b == b'\r' {
3866            format!(
3867                "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
3868                 paste-from-multiline-doc footgun; the Akka-style entity-id \
3869                 extractor reads `:shard-key` as a single-token reference, embedded \
3870                 newlines either truncate the value at the YAML emitter layer or \
3871                 break the token boundary at the runtime hash-extractor pass)"
3872            )
3873        } else if b < 0x20 || b == 0x7F {
3874            format!(
3875                "contains control character 0x{b:02x} (the canonical \
3876                 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
3877                 control characters silently corrupt round-trip serialization \
3878                 across YAML emitters and break the runtime hash-extractor's \
3879                 single-token parser)"
3880            )
3881        } else {
3882            format!(
3883                "contains non-ASCII byte 0x{b:02x} (the canonical \
3884                 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
3885                 inconsistently across NFC/NFD normalization on APFS / ext4 / \
3886                 across YAML emitter implementations — the same entity ID can \
3887                 silently map to two distinct shards on a re-render. Use a \
3888                 printable-ASCII extractor expression like `tenantId`, \
3889                 `$tenantId`, or `metadata.tenantId`)"
3890            )
3891        };
3892        return Err(AplicacaoError::ShardKeyInvalid {
3893            shard_key: key.to_string(),
3894            reason,
3895        });
3896    }
3897    Ok(())
3898}
3899
3900/// Reject `:contratos :de` / `:contratos :para` values whose shape
3901/// can never legitimately match a validated `:membros :caixa`. Thin
3902/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
3903/// shared parser-shaped reason into the
3904/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
3905/// diagnostic is self-locating (which slot — `:de` or `:para` — and
3906/// the offending value verbatim) and the author can grep their
3907/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
3908/// one edit.
3909///
3910/// Until this gate landed an empty or DNS-1123-malformed `:de` /
3911/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
3912/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
3913/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
3914/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
3915/// un-Punycode-encoded IDN) silently passed the per-axis check and
3916/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
3917/// membership lookup — diagnostic-framed as "this caixa is not in
3918/// `:membros`" when the root cause is "this `:de` value is not a
3919/// well-shaped Servico-name identifier and could never legitimately
3920/// match any validated member". Because every `:membros :caixa` is
3921/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
3922/// `names` HashSet structurally never contains an empty / malformed
3923/// string, so the membership lookup arm misframes every empty /
3924/// malformed input. Lifting the shape arm ahead of the lookup
3925/// preserves the legitimate `ContratoMemberMissing` arm (a
3926/// well-shaped `:de` that simply isn't in `:membros` — a phantom
3927/// reference) while routing every structurally-impossible-to-match
3928/// input through the narrower self-locating shape diagnostic.
3929///
3930/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
3931/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
3932/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
3933/// to land on the canonical [`crate::render::is_dns_1123_label`]
3934/// floor. The `slot: &'static str` field carries the kebab-case
3935/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
3936/// per-callback-slot diagnostic shape and the
3937/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
3938/// (85f102c) cross-list-tag pattern.
3939fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
3940    // Routes through the shared
3941    // [`crate::render::require_valid_dns_1123_label`] gate the peer
3942    // name axes each land on. The `slot: &'static str` field flows
3943    // through both error variants so the diagnostic names which
3944    // per-edge axis (`:de` vs `:para`) the offending value came from.
3945    crate::render::require_valid_dns_1123_label(
3946        caixa,
3947        || AplicacaoError::ContratoCaixaEmpty { slot },
3948        |reason| AplicacaoError::ContratoCaixaInvalid {
3949            slot,
3950            caixa: caixa.to_string(),
3951            reason,
3952        },
3953    )
3954}
3955
3956/// Reject `:entrada :para` values whose shape can never legitimately
3957/// match a validated `:membros :caixa`. Thin wrapper around
3958/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
3959/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
3960/// variant, so the diagnostic is self-locating (the offending
3961/// `:entrada :para` value is named verbatim) and the author can grep
3962/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
3963///
3964/// Until this gate landed an empty or DNS-1123-malformed `:entrada
3965/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
3966/// ADR typo, `:para "my_cart"` the Python-module-name leak,
3967/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
3968/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
3969/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
3970/// silently passed the per-axis check and surfaced as
3971/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
3972/// — diagnostic-framed as "this caixa is not in `:membros`" when the
3973/// root cause is "this `:entrada :para` value is not a well-shaped
3974/// Servico-name identifier and could never legitimately match any
3975/// validated member". Because every `:membros :caixa` is shape-
3976/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
3977/// `HashSet` structurally never contains an empty / malformed string,
3978/// so the membership lookup arm misframes every empty / malformed
3979/// input. Lifting the shape arm ahead of the lookup preserves the
3980/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
3981/// simply isn't in `:membros` — a phantom reference) while routing
3982/// every structurally-impossible-to-match input through the narrower
3983/// self-locating shape diagnostic.
3984///
3985/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
3986/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
3987/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
3988/// fourth and last Aplicacao-level Servico-name reference axis to
3989/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
3990/// No `slot: &'static str` field because there is only one axis
3991/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
3992/// the simpler shape mirrors [`validate_membro_caixa`] and
3993/// [`validate_placement_cluster`].
3994fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
3995    // Empty is gated separately at the call site for a self-locating
3996    // diagnostic; re-checking here keeps the predicate usable from any
3997    // future call site (the M4 CR materializer's per-`:entrada`
3998    // validator) without an empty-check footgun. Routes through the
3999    // shared [`crate::render::require_valid_dns_1123_label`] gate the
4000    // peer name axes each land on.
4001    crate::render::require_valid_dns_1123_label(
4002        para,
4003        || AplicacaoError::EntradaParaEmpty,
4004        |reason| AplicacaoError::EntradaParaInvalid {
4005            para: para.to_string(),
4006            reason,
4007        },
4008    )
4009}
4010
4011/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
4012/// would refuse at admission time. The contract — exactly the regex
4013/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
4014/// and `HTTPRoute.spec.hostnames[]`,
4015/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
4016/// (max length 253; per-label max length 63):
4017///
4018///   - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
4019///     uppercase, no underscore, no Unicode/IDN — IDN must be
4020///     pre-encoded as Punycode `xn--…` by the author);
4021///   - exactly one optional leading wildcard label (`*.`); a wildcard
4022///     in any non-leading label position is rejected;
4023///   - each `.`-separated label is 1..=63 bytes, with non-hyphen
4024///     alphanumeric at both boundaries (no `-foo`, no `foo-`);
4025///   - total length 1..=253 bytes;
4026///   - no IPv4 literal (Gateway API forbids IP literals);
4027///   - no scheme (`https://`, `http://`), no port (`:8080`), no
4028///     whitespace, no path (`/`).
4029///
4030/// Lifted as a typed gate (rather than an inline cascade in
4031/// `validate()`) so the contract lives in one place — every future
4032/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4033/// materializer's host validator, the future per-`:entrada` SAN
4034/// emission for cert-manager Certificates, the multi-`:entrada`
4035/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
4036/// for the same predicate, not its own. Same compounding shape as
4037/// `is_canonical_rate_limit_window` (808017c) and
4038/// [`WitTarget::label`] (previously the free `contrato_target_label`
4039/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
4040/// per-variant label match is compiler-checked-exhaustive).
4041///
4042/// The diagnostic carries the offending `host:` verbatim plus a
4043/// parser-shaped `reason:` naming the specific violation, so the
4044/// author can grep their caixa.lisp for `:host "<host>"` and fix it
4045/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
4046/// (9888b13).
4047fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
4048    // Empty is already gated by `EmptyEntradaHost` at the call site;
4049    // re-checking here keeps the predicate usable from any future
4050    // call site (M4 CR materializer) without an empty-check footgun.
4051    if host.is_empty() {
4052        return Err(AplicacaoError::EmptyEntradaHost);
4053    }
4054    if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
4055        return Err(AplicacaoError::EntradaHostInvalid {
4056            host: host.to_string(),
4057            reason: format!(
4058                "exceeds Gateway API v1 Hostname max length of {cap} bytes \
4059                 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
4060                host.len(),
4061                cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
4062            ),
4063        });
4064    }
4065    if host.contains("://") {
4066        return Err(AplicacaoError::EntradaHostInvalid {
4067            host: host.to_string(),
4068            reason: "must not carry a scheme (drop the `https://` or `http://` prefix; \
4069                     Gateway API takes the bare hostname)"
4070                .to_string(),
4071        });
4072    }
4073    if host.contains('/') {
4074        return Err(AplicacaoError::EntradaHostInvalid {
4075            host: host.to_string(),
4076            reason: "must not carry a path (drop the `/…` suffix; Gateway API path \
4077                     matching is in `:entrada :paths`)"
4078                .to_string(),
4079        });
4080    }
4081    // After the `://` scheme-prefix and `/` path arms have ruled out the
4082    // two `:`-bearing shapes the Gateway API actively rejects with
4083    // location-shaped diagnostics, any remaining `:` in the host body is
4084    // either the canonical "I put the port in the `:host` slot"
4085    // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
4086    // slot lives one axis away on the same `:entrada` block) or an
4087    // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
4088    // Hostname forbids identically to the IPv4-literal arm below. Both
4089    // shapes silently fell through the `://` and `/` arms before this
4090    // lift and surfaced as a deep `label "<rest>:<port>" contains
4091    // invalid character ':'` diagnostic from the per-byte loop near the
4092    // bottom of this predicate, which named the offending byte but not
4093    // the canonical authoring fix — for the port case the author has to
4094    // know the `:entrada` block carries a separate `:port u16` slot
4095    // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
4096    // move the value over; for the IPv6 case the author has to know
4097    // Gateway API v1 forbids IP literals across the board. The contract
4098    // doc-comment above already promises "no port (`:8080`)" verbatim
4099    // in the rejected-shape enumeration but the predicate's
4100    // implementation refused the `:` only as a side-effect of the
4101    // per-label `[a-z0-9-]` character-class loop; this arm brings the
4102    // implementation in line with the documented contract by surfacing
4103    // the canonical fix at the top-level shape gate, peer with how the
4104    // `://` arm names the scheme prefix and the `/` arm names the
4105    // `:entrada :paths` axis. Same compounding trajectory the recent
4106    // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
4107    // — the typed slot's rejected set matches the apiserver's rejected
4108    // set, structurally, with a self-locating diagnostic at the
4109    // offending axis instead of a deep parser-shape leak.
4110    if host.contains(':') {
4111        return Err(AplicacaoError::EntradaHostInvalid {
4112            host: host.to_string(),
4113            reason: "must not contain `:` (the port belongs in the `:entrada :port` \
4114                     slot — a separate `u16` axis on the same `:entrada` block, \
4115                     defaulting to 8080 — not in the host body; drop the `:<port>` \
4116                     suffix and author the bare hostname. If you intended an IPv6 \
4117                     literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
4118                     Hostname forbids IP literals identically to the IPv4-literal \
4119                     arm — use a DNS name)"
4120                .to_string(),
4121        });
4122    }
4123    // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
4124    // predicate — the same single source of truth every peer
4125    // ASCII-whitespace scan in caixa-core flows through: the four
4126    // typed-magnitude codec sites (`limits::parse_byte_size` backing
4127    // `:limits :memory`, `limits::parse_duration` backing `:limits
4128    // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
4129    // `aplicacao::rate_limit_codec::parse` backing `:politicas
4130    // :rate-limit`) and the shared duration codec
4131    // (`supervisor::duration_codec::parse`) backing `:supervisor
4132    // :restart-window` / `:politicas :timeout` / `:politicas
4133    // :circuit-breaker :window`. This landing closes the last string-typed
4134    // slot in caixa-core still calling `.bytes().any(|b|
4135    // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
4136    // across every typed slot now shares one predicate, so a future
4137    // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
4138    // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
4139    // deliberately excluded from the peer non-ASCII predicate) can
4140    // extend at this shared site in one edit rather than seven
4141    // independent scans diverging over time. Naming the offending byte
4142    // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
4143    // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
4144    // the offending byte verbatim" discipline every peer codec site
4145    // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
4146    // / `supervisor.rs:823` / `aplicacao.rs:1640`).
4147    if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
4148        return Err(AplicacaoError::EntradaHostInvalid {
4149            host: host.to_string(),
4150            reason: format!(
4151                "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
4152                 Hostname is a single-token DNS name — leading, trailing, \
4153                 or embedded whitespace breaks the K8s apiserver's Hostname \
4154                 regex at admission time; the paste-from-aligned-doc / \
4155                 paste-from-shell-history / paste-from-CSV footgun silently \
4156                 lands a multi-token blob in `:entrada :host`. Strip every \
4157                 whitespace byte and author the bare hostname — space \
4158                 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
4159                 refuse identically)"
4160            ),
4161        });
4162    }
4163    // Peer of the ASCII-whitespace scan above: route the non-ASCII
4164    // subset of Unicode `White_Space` through the shared
4165    // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
4166    // single source of truth every peer non-ASCII-whitespace scan in
4167    // caixa-core flows through: `limits::parse_byte_size` (`:limits
4168    // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
4169    // `limits::parse_millicores` (`:limits :cpu`),
4170    // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
4171    // and `supervisor::duration_codec::parse` (`:supervisor
4172    // :restart-window` / `:politicas :timeout` / `:politicas
4173    // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
4174    // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
4175    // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
4176    // paste-from-web-doc), or an EM-SPACE-split host
4177    // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
4178    // survived this predicate's ASCII byte-scan (none of the UTF-8
4179    // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
4180    // `u8::is_ascii_whitespace`), then landed on the per-label
4181    // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
4182    // predicate with the generic `label "…" must start and end with an
4183    // alphanumeric` diagnostic — a "far from source at build-time"
4184    // leak that names the label-shape violation but not the
4185    // paste-from-typography origin the author actually needs to fix.
4186    // Peer with the four codec sites the 1b75b38 landing pinned: the
4187    // typed slot's diagnostic axis names the offending codepoint
4188    // (`U+XXXX`) verbatim rather than laundering the value through a
4189    // downstream label-shape arm, so the author can grep their
4190    // caixa.lisp for the invisible codepoint at the surfaced position
4191    // rather than eyeball a multi-byte host for embedded NBSP / LINE
4192    // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
4193    // discipline the peer ASCII-whitespace arm (720ac3b) carries:
4194    // drift between any two typed-slot sites' non-ASCII-whitespace
4195    // rejection set becomes a single-edit fix at the shared predicate
4196    // rather than N independent inline scans diverging over time, and
4197    // a future stricter classification (BOM `\u{FEFF}` / ZWSP
4198    // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
4199    // `char::is_whitespace`" class the peer non-ASCII predicate's
4200    // doc-comment names as the follow-up trajectory) extends at the
4201    // shared predicate in one edit rather than seven.
4202    if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
4203        return Err(AplicacaoError::EntradaHostInvalid {
4204            host: host.to_string(),
4205            reason: format!(
4206                "contains non-ASCII Unicode whitespace character {ch:?} \
4207                 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
4208                 single-token DNS name limited to `[a-z0-9-]` labels; \
4209                 the paste-from-typography footgun silently lands an \
4210                 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
4211                 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
4212                 `U+3000`, and every other member of the Unicode \
4213                 `White_Space` property outside the ASCII byte range) \
4214                 in `:entrada :host`, which the K8s apiserver's \
4215                 Hostname regex refuses at admission time far from the \
4216                 caixa.lisp source line. Strip every non-ASCII \
4217                 whitespace character and author the bare hostname \
4218                 with only ASCII bytes (write \"checkout.quero.cloud\" \
4219                 verbatim)",
4220                codepoint = ch as u32,
4221            ),
4222        });
4223    }
4224
4225    // Strip the optional single leading wildcard label *before* the
4226    // trailing-dot check so the bare `"*."` form surfaces the more
4227    // self-locating "wildcard without domain" diagnostic instead of
4228    // the generic "trailing dot" one.
4229    let (had_wildcard, rest) = match host.strip_prefix("*.") {
4230        Some(r) => (true, r),
4231        None => (false, host),
4232    };
4233    if had_wildcard && rest.is_empty() {
4234        return Err(AplicacaoError::EntradaHostInvalid {
4235            host: host.to_string(),
4236            reason: "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)".to_string(),
4237        });
4238    }
4239    if rest.contains('*') {
4240        return Err(AplicacaoError::EntradaHostInvalid {
4241            host: host.to_string(),
4242            reason: "wildcard `*` is allowed only as the first label (`*.example.com`); \
4243                     no inner or trailing `*` labels"
4244                .to_string(),
4245        });
4246    }
4247    if rest.ends_with('.') {
4248        return Err(AplicacaoError::EntradaHostInvalid {
4249            host: host.to_string(),
4250            reason: "must not have a trailing `.` (Gateway API hostnames are not \
4251                     fully-qualified with a root dot; the apiserver regex rejects \
4252                     trailing dots)"
4253                .to_string(),
4254        });
4255    }
4256
4257    // Reject pure IPv4 literals: four dot-separated labels, every
4258    // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
4259    // literals as Hostnames.
4260    let labels: Vec<&str> = rest.split('.').collect();
4261    if labels.len() == 4
4262        && labels
4263            .iter()
4264            .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
4265    {
4266        return Err(AplicacaoError::EntradaHostInvalid {
4267            host: host.to_string(),
4268            reason: "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
4269                     literals; use a DNS name)"
4270                .to_string(),
4271        });
4272    }
4273
4274    // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
4275    // hyphen, with non-hyphen at both boundaries.
4276    for label in &labels {
4277        if label.is_empty() {
4278            return Err(AplicacaoError::EntradaHostInvalid {
4279                host: host.to_string(),
4280                reason: "has an empty label (consecutive `..` or a leading `.`)".to_string(),
4281            });
4282        }
4283        if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
4284            return Err(AplicacaoError::EntradaHostInvalid {
4285                host: host.to_string(),
4286                reason: format!(
4287                    "label {label:?} exceeds DNS-1123 label max length of \
4288                     {cap} bytes (got {} bytes)",
4289                    label.len(),
4290                    cap = crate::render::DNS_1123_LABEL_MAX_LEN,
4291                ),
4292            });
4293        }
4294        let bytes = label.as_bytes();
4295        if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
4296            return Err(AplicacaoError::EntradaHostInvalid {
4297                host: host.to_string(),
4298                reason: format!(
4299                    "label {label:?} must start and end with an alphanumeric \
4300                     (no leading or trailing `-`)"
4301                ),
4302            });
4303        }
4304        for &b in bytes {
4305            let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
4306            if !valid {
4307                let msg = if b.is_ascii_uppercase() {
4308                    format!(
4309                        "label {label:?} contains uppercase character {ch:?} \
4310                         (Gateway API hostnames are lowercase-only; use {lower:?})",
4311                        ch = b as char,
4312                        lower = label.to_ascii_lowercase()
4313                    )
4314                } else if b == b'_' {
4315                    format!(
4316                        "label {label:?} contains `_` (Gateway API hostnames \
4317                         allow only `[a-z0-9-]`; use `-` instead)"
4318                    )
4319                } else {
4320                    format!(
4321                        "label {label:?} contains invalid character {ch:?} \
4322                         (Gateway API hostnames allow only `[a-z0-9-]`)",
4323                        ch = b as char
4324                    )
4325                };
4326                return Err(AplicacaoError::EntradaHostInvalid {
4327                    host: host.to_string(),
4328                    reason: msg,
4329                });
4330            }
4331        }
4332    }
4333    Ok(())
4334}
4335
4336/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
4337/// would refuse at admission time. Thin wrapper around
4338/// [`crate::render::is_gateway_api_http_path`] that maps the shared
4339/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
4340/// variant, preserving the more self-locating
4341/// [`AplicacaoError::EntradaPathEmpty`] /
4342/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
4343/// path fails those narrower invariants first.
4344///
4345/// The contract is the canonical HTTP-path grammar — `1..=
4346/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
4347/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
4348/// whitespace/control/non-ASCII bytes — shared with the
4349/// `:contratos :endpoint` axis through the lifted predicate so drift
4350/// between either landing site and the K8s apiserver-side
4351/// HTTPPathMatch.value OpenAPI schema is a build error visible at
4352/// the predicate, not a per-renderer "this passed validate but failed
4353/// admission" surprise. The diagnostic carries the offending `path:`
4354/// verbatim plus a parser-shaped `reason:` naming the specific
4355/// violation, so the author can grep their caixa.lisp for `:paths`
4356/// and fix it in one edit. Same diagnostic shape as
4357/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
4358/// axis.
4359fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
4360    // Empty and missing-leading-`/` are already gated at the call
4361    // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
4362    // checking here keeps the per-axis narrower diagnostics in force
4363    // when the predicate is reached directly (and `is_gateway_api_http_path`
4364    // itself defends against `bytes[0]`-style indexing on empty
4365    // input).
4366    if path.is_empty() {
4367        return Err(AplicacaoError::EntradaPathEmpty);
4368    }
4369    if !path.starts_with('/') {
4370        return Err(AplicacaoError::EntradaPathNotAbsolute {
4371            path: path.to_string(),
4372        });
4373    }
4374    crate::render::is_gateway_api_http_path(path).map_err(|reason| {
4375        AplicacaoError::EntradaPathInvalid {
4376            path: path.to_string(),
4377            reason,
4378        }
4379    })
4380}
4381
4382mod rate_limit_codec {
4383    // `Duration` is no longer named here — the codec routes through
4384    // the substrate primitive [`super::RateLimitUnit::window_from_suffix`]
4385    // (parse arm, `&str → Duration`) and [`super::RateLimit::canonical_unit`]
4386    // (render arm, `Duration → RateLimitUnit`) typed dispatches that carry
4387    // the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection on the
4388    // closed-set enum's arm-table rather than through vestigial free-helper
4389    // delegates.
4390    use super::{RateLimit, RateLimitUnit};
4391    use serde::{Deserialize, Deserializer, Serializer};
4392
4393    pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
4394        match v {
4395            Some(rl) => s.serialize_str(&render(*rl)),
4396            None => s.serialize_none(),
4397        }
4398    }
4399
4400    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
4401        let opt: Option<String> = Option::deserialize(d)?;
4402        match opt {
4403            None => Ok(None),
4404            Some(s) => parse(&s).map(Some).map_err(serde::de::Error::custom),
4405        }
4406    }
4407
4408    fn parse(s: &str) -> Result<RateLimit, String> {
4409        // Whitespace-rejection arm — peer with the leading-`+`
4410        // (`"+100/s"`) and leading-zero (`"0100/s"`) arms below on the
4411        // same canonical-form render-determinism axis. Until this gate
4412        // landed the parser silently tolerated leading / trailing /
4413        // internal whitespace via the top-level `s.trim()` and the
4414        // per-part `rate_str.trim()` / `unit.trim()` calls, so every
4415        // whitespace-carrying shape (`" 100/s"`, `"100/s "`,
4416        // `"100 /s"`, `"100/ s"`, `"100 / s"`, `"100/s\n"`,
4417        // `"\t100/s"`) parsed to the same `RateLimit { 100, 1s }` and
4418        // serde silently round-tripped to `"100/s"` on the next emit
4419        // (a *different* canonical string) — breaking the THEORY.md
4420        // Part V render-determinism contract on the same
4421        // canonical-form-drift axis the leading-`+` arm below (the
4422        // 4eeae98 predecessor) and the leading-zero arm below (the
4423        // 4f46830 predecessor) already close.
4424        //
4425        // The canonical author shape is `<integer>/<s|m|h>` with no
4426        // whitespace bytes anywhere — every string [`render`] emits
4427        // carries none, so the parser's accepted set must match for
4428        // serialize / deserialize to round-trip losslessly. This gate
4429        // makes the pre-existing `s.trim()` / `rate_str.trim()` /
4430        // `unit.trim()` calls below strict no-ops on the accepted set
4431        // (every byte-position match they would perform is now already
4432        // trimmed away by the accepted set itself), while the arm
4433        // surfaces every rejected whitespace-carrying shape with a
4434        // self-locating diagnostic naming the offending byte and the
4435        // canonical form the author intended, peer with every prior
4436        // canonical-form-drift arm on this codec.
4437        //
4438        // Routed through the lifted
4439        // [`crate::render::find_ascii_whitespace_byte`] predicate — the
4440        // same source of truth the four peer typed-magnitude codec
4441        // sites (`limits::parse_byte_size`, `limits::parse_duration`,
4442        // `limits::parse_millicores`, `supervisor::duration_codec`)
4443        // share. `u8::is_ascii_whitespace()` at the predicate covers
4444        // the five WhatWG-conformant ASCII whitespace bytes (space,
4445        // tab, LF, FF, CR); the "single lifted predicate" discipline
4446        // the peer non-ASCII arm below carries on the strictly-
4447        // complementary Unicode `White_Space` class extends here to
4448        // the ASCII byte set as well.
4449        if let Some(b) = crate::render::find_ascii_whitespace_byte(s) {
4450            return Err(format!(
4451                "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
4452                 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
4453                 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
4454                 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
4455                 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
4456                 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
4457                 on first serialize — breaking the THEORY.md Part V render-determinism \
4458                 contract every typed slot carries. Strip every whitespace byte (write \
4459                 `\"100/s\"` verbatim)"
4460            ));
4461        }
4462        // Non-ASCII Unicode `White_Space` arm — the strictly-
4463        // complementary class the ASCII arm above cannot see.
4464        // `str::trim` at the top of every peer codec uses
4465        // `char::is_whitespace` (Unicode `White_Space`, strictly
4466        // wider than the ASCII byte set), so an NBSP (`\u{00A0}`) /
4467        // LINE SEPARATOR (`\u{2028}`) / EM-SPACE (`\u{2003}`)
4468        // survives the byte-scan (its UTF-8 bytes are not in
4469        // `is_ascii_whitespace`), gets silently stripped by the
4470        // top-level `s.trim()` below, and the value round-trips
4471        // through `render` to a *different* canonical form
4472        // (`\"100/s\"`) on next emit — breaking the THEORY.md Part V
4473        // render-determinism contract every typed slot carries.
4474        // Closed here (`:politicas :rate-limit`) and at the three
4475        // peer codec sites (`limits::parse_byte_size`,
4476        // `limits::parse_duration`, `supervisor::duration_codec`)
4477        // through the shared
4478        // [`crate::render::find_non_ascii_whitespace_char`] predicate
4479        // — the "single lifted predicate across all four codec sites
4480        // in one follow-up run" the 24a8ad4 commit body's `Forward
4481        // compounding` bullet named as the next compounding step.
4482        if let Some(ch) = crate::render::find_non_ascii_whitespace_char(s) {
4483            return Err(format!(
4484                "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
4485                 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
4486                 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
4487                 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
4488                 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
4489                 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
4490                 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
4491                 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
4492                 silently strips it at parse entry, and the value round-trips through \
4493                 `render` to a *different* canonical form (`\"100/s\"`) on first \
4494                 serialize — breaking the THEORY.md Part V render-determinism contract \
4495                 every typed slot carries. Strip every non-ASCII whitespace character \
4496                 (write `\"100/s\"` verbatim with only ASCII bytes)",
4497                cp = ch as u32
4498            ));
4499        }
4500        let s = s.trim();
4501        let (rate_str, unit) = s
4502            .split_once('/')
4503            .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
4504        let rate_trim = rate_str.trim();
4505        // The canonical authoring form for `:politicas :rate-limit` is
4506        // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
4507        // non-negative integer with no decimal point and no leading
4508        // sign, so the parser's accepted set must match for
4509        // serialize/deserialize to round-trip without canonical-form
4510        // drift. Until this gate landed the parser accepted any
4511        // `u32::from_str`-shaped magnitude — and current Rust
4512        // `u32::from_str` permissively accepts a leading `+` (`"+100"`
4513        // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
4514        // serde silently round-tripped to `"100/s"` on the next emit
4515        // (a *different* canonical string) — breaking the THEORY.md
4516        // Part V render-determinism contract on the fifth typed-codec
4517        // surface in caixa-core (peer with the four duration codecs the
4518        // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
4519        // already covered: `supervisor::duration_codec` backing three
4520        // typed-duration slots, `limits::parse_duration` backing
4521        // `:limits :wall-clock`, `limits::parse_byte_size` backing
4522        // `:limits :memory`). The fractional / decimal-shaped sibling
4523        // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
4524        // existing rejection arm, but the diagnostic is value-laundered
4525        // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
4526        // doesn't name the canonical-form remediation or the round-trip
4527        // drift the next emit would produce); this gate lifts the
4528        // fractional arm onto the same canonical-form diagnostic the
4529        // peer codecs carry.
4530        //
4531        // Strict canonical form: every byte of the magnitude is an
4532        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
4533        // inputs the gate distinguishes "non-canonical-but-numeric"
4534        // (parses as f64 or i64 — surfaced with a self-locating
4535        // diagnostic naming the canonical authoring form and the
4536        // round-trip drift the rejected shape would produce on first
4537        // serialize) from "garbage" (parses as neither — surfaced with
4538        // the existing narrower `"not a u32"` wording so its
4539        // diagnostic shape remains stable for the parser-shape footgun
4540        // case).
4541        //
4542        // Routed through the lifted
4543        // [`crate::render::is_digit_only_magnitude`] predicate — the
4544        // same source of truth the four peer typed-magnitude codec
4545        // sites share.
4546        let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
4547        if !digit_only {
4548            let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
4549            if numeric {
4550                return Err(format!(
4551                    "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
4552                     canonical authoring form for `:politicas :rate-limit` is \
4553                     `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4554                     with no decimal point and no leading `+` / `-` sign. A fractional / \
4555                     signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
4556                     through `render` to a *different* canonical form (`\"1/s\"`, \
4557                     `\"100/s\"`, parser-reject) on first serialize — breaking the \
4558                     THEORY.md Part V render-determinism contract every typed slot \
4559                     carries. Pick an integer rate that fits the desired window \
4560                     (write `\"6000/m\"` instead of `\"1.66/s\"`)"
4561                ));
4562            }
4563            return Err(format!("rate-limit rate {rate_str:?} not a u32"));
4564        }
4565        // Leading-zero arm — peer with the prior `"+100/s"` arm above
4566        // (4eeae98's predecessor) on the same canonical-form
4567        // render-determinism axis. The digit-only gate accepts
4568        // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
4569        // them losslessly (= 100, 0, 7), but `render` emits the
4570        // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
4571        // a *different* canonical string on the next emit, breaking
4572        // the THEORY.md Part V render-determinism contract the same
4573        // way `"+100/s"` did before the leading-`+` arm landed. The
4574        // single-byte magnitude `"0"` itself round-trips losslessly
4575        // through `render` (`render(0)` emits `"0/s"`) — the
4576        // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
4577        // what refuses rate-zero authoring, so `"0/s"` stays in the
4578        // accepted set at this codec layer and the diagnostic
4579        // partitioning between canonical-form drift (this arm) and
4580        // semantic-zero (the downstream gate) remains stable.
4581        // Peer with the future leading-zero arms on the three peer
4582        // typed-magnitude codecs the trajectory acknowledges:
4583        // `supervisor::duration_codec`, `limits::parse_duration`,
4584        // `limits::parse_byte_size` — each carries the same
4585        // canonical-form-drift class today; this gate lands the
4586        // discipline on the fourth typed-magnitude codec in
4587        // caixa-core first because the peer `"+100/s"` arm above is
4588        // the closest predecessor on the trajectory.
4589        //
4590        // Routed through the lifted
4591        // [`crate::render::is_leading_zero_padded_magnitude`]
4592        // predicate — the same source of truth the four peer
4593        // typed-magnitude codec sites share.
4594        if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
4595            return Err(format!(
4596                "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
4597                 canonical authoring form for `:politicas :rate-limit` is \
4598                 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4599                 with no leading-zero padding on the magnitude. A leading-zero magnitude \
4600                 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
4601                 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
4602                 first serialize — breaking the THEORY.md Part V render-determinism \
4603                 contract every typed slot carries. Strip the leading zeros (write \
4604                 `\"100/s\"` instead of `\"0100/s\"`)"
4605            ));
4606        }
4607        // The digit-only gate guarantees every byte is `[0-9]`, and
4608        // the leading-zero arm above guarantees the magnitude is
4609        // either the single byte `"0"` or starts with `[1-9]`, so
4610        // the only way `u32::from_str` can fail here is overflow
4611        // (the magnitude exceeds `u32::MAX`). Surface that with an
4612        // overflow-shaped wording so the diagnostic names the
4613        // offending magnitude verbatim rather than collapsing onto
4614        // the non-canonical arm. Same shape
4615        // `supervisor::duration_codec` (1c55a2a) carries on the peer
4616        // duration-codec axis.
4617        let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
4618            format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
4619        })?;
4620        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives on
4621        // the closed-set typed enum [`super::RateLimitUnit`]; this parse
4622        // arm reads the `&str → Duration` projection through the
4623        // substrate primitive [`super::RateLimitUnit::window_from_suffix`]
4624        // (a two-step typed dispatch composing [`super::RateLimitUnit::from_suffix`]
4625        // with [`super::RateLimitUnit::window`]) rather than the vestigial
4626        // module-private `rate_limit_window_from_unit` free helper the
4627        // predecessor 61421a6 left as the last unlifted delegate on this
4628        // axis. One typed dispatch on the substrate primitive instead of
4629        // one runtime call through the free-helper delegate; the sole
4630        // production consumer of the `&str → Duration` axis (this parse
4631        // arm) now reaches for exactly one typed method on the closed-set
4632        // enum, sibling to the codec's render arm's
4633        // [`super::RateLimit::canonical_unit`] dispatch on the paired
4634        // `Duration → RateLimitUnit` axis and to the validate gate's
4635        // [`super::RateLimit::canonical_unit`] shape-probe on the
4636        // canonical-window axis. A future rate-limit-unit addition (a
4637        // `"d"` day suffix once Envoy's `rate_limit_action` grows
4638        // daily-bucket support, a `"ms"` sub-second window once
4639        // high-throughput per-edge policies come into scope per
4640        // MESH-COMPOSITION §III.2 #3) is one variant + one arm per method
4641        // on the closed-set enum, and the compiler enforces exhaustiveness
4642        // on every consumer's `match self` arms — this parse arm's
4643        // accepted-suffix set, the render arm's emitted-suffix set, the
4644        // validate gate's canonical-window set, and every future
4645        // per-`:contratos`-edge rate-limit-override overlay all pick it up
4646        // by construction.
4647        let unit = unit.trim();
4648        let window = RateLimitUnit::window_from_suffix(unit)
4649            .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
4650        Ok(RateLimit { rate, window })
4651    }
4652
4653    fn render(rl: RateLimit) -> String {
4654        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
4655        // module scope on the closed-set typed enum [`super::RateLimitUnit`];
4656        // this render arm reads the `Duration → RateLimitUnit` projection
4657        // through the substrate primitive [`super::RateLimit::canonical_unit`]
4658        // (returns `None` on every non-canonical window — the sub-second /
4659        // non-`{1, 60, 3600}` shapes the validate gate rejects), then
4660        // formats the returned typed enum through its
4661        // [`std::fmt::Display`] impl (which routes through
4662        // [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
4663        // the substrate primitive instead of one runtime `find_map`
4664        // walk through the free-helper delegate chain
4665        // [`super::rate_limit_window_unit`] (the vestigial free helper's
4666        // sole production consumer was this arm; every other consumer of
4667        // the `Duration → unit` axis — the validate gate below and the
4668        // future M4 per-Aplicacao Envoy config reconciler — now reads
4669        // the same typed method).
4670        //
4671        // A future rate-limit-unit addition (a `"d"` day suffix once
4672        // Envoy's `rate_limit_action` grows daily-bucket support) is
4673        // one variant + one arm per method on the closed-set enum, and
4674        // the compiler enforces exhaustiveness on every consumer's
4675        // `match self` arms — the codec's `parse` accepted-suffix set,
4676        // this render arm's emitted-suffix set, the validate gate's
4677        // canonical-window set, and every future per-`:contratos`-edge
4678        // rate-limit-override overlay all pick it up by construction.
4679        if let Some(unit) = rl.canonical_unit() {
4680            format!("{}/{unit}", rl.rate())
4681        } else {
4682            // Defensive fallback for non-canonical windows. Note:
4683            // [`AplicacaoSpec::validate_politicas`] rejects any
4684            // non-canonical `:rate-limit :window` via
4685            // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
4686            // a validated `RateLimit` never reaches this branch. The
4687            // emitted `<n>/<k>s` form is *not* round-trippable through
4688            // [`parse`] (which accepts only the closed-set
4689            // [`super::RateLimitUnit`] suffixes, not `<k>s` with an
4690            // explicit count) — the validate gate is what makes the
4691            // round-trip a structural property; this branch exists only
4692            // so a programmatic non-validated serialize doesn't panic.
4693            format!("{}/{}s", rl.rate(), rl.window().as_secs())
4694        }
4695    }
4696}
4697
4698// ── placement strategy ───────────────────────────────────────────────
4699
4700/// How the Aplicacao distributes across clusters. Three options:
4701///
4702/// - `SingleNode` — one cluster runs the app at a time; takeover on
4703///   death (Erlang/OTP distributed-app semantics).
4704/// - `Replicated` — every named cluster runs an instance (active-active).
4705/// - `Sharded` — entities distribute by hash key across clusters
4706///   (Akka cluster sharding).
4707#[derive(
4708    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
4709)]
4710pub enum PlacementStrategy {
4711    SingleNode,
4712    Replicated,
4713    Sharded,
4714}
4715
4716/// Substrate-canonical M3-mesh-shaped per-`:placement :estrategia`
4717/// distribution-strategy default for the `:placement :estrategia` axis —
4718/// the [`PlacementStrategy::Replicated`] active-active-across-every-named-
4719/// cluster arm (MESH-COMPOSITION §II.2), extracted as a typed `pub const`
4720/// so every substrate-side consumer that resolves "what
4721/// [`PlacementStrategy`] variant does an author-omitted `:placement
4722/// :estrategia` slot degrade onto?" reaches for exactly one substrate-
4723/// primitive [`PlacementStrategy`].
4724///
4725/// The `:placement :estrategia` default axis has three production
4726/// consumers on the substrate side today: the [`Default for
4727/// PlacementStrategy`] impl's return arm, the [`Default for Placement`]
4728/// impl's struct-literal `estrategia` field, and the serde-side
4729/// `#[serde(default)]` on [`Placement::estrategia`] that resolves an
4730/// author-omitted `:placement :estrategia` scalar through the [`Default
4731/// for PlacementStrategy`] impl. Prior to this lift the three folded onto
4732/// a raw `Self::Replicated` arm at the [`Default for PlacementStrategy`]
4733/// impl and implicit `PlacementStrategy::default()` routes at the sibling
4734/// consumers, with no compile-time link back to the paired
4735/// [`crate::manifest::Caixa::aplicacao_view`] fold's
4736/// `.unwrap_or_default()` `Option<Placement>` collapse arm — the fourth
4737/// production consumer that resolves an author-omitted `:placement` slot
4738/// (entirely omitted, not just the `:estrategia` scalar within a declared
4739/// `:placement` block) through [`Placement::default`] which then routes
4740/// through this same discriminator. A future coherent rebrand of the
4741/// `:placement :estrategia` default (a widening to `Sharded` once the
4742/// substrate discovers hash-keyed distribution as the more common
4743/// production shape, a tightening to `SingleNode` for stateful Erlang/OTP
4744/// distributed-app-takeover semantics MESH-COMPOSITION §II.1 already
4745/// names, a per-cluster overlay the operator pins through a future
4746/// `:placement-overrides` slot) would have had to migrate a lifted
4747/// discriminator on one path and open-coded discriminators on the peers
4748/// in lockstep or the four consumers would silently drift out of
4749/// pairing. Lifting the resolution rule to a typed `pub const` on the
4750/// substrate primitive means the M3-mesh-canonical `:placement
4751/// :estrategia` default migrates as one unit on any future axis change.
4752///
4753/// The [`PlacementStrategy::Replicated`] value pins MESH-COMPOSITION
4754/// §II.2's active-active-across-every-named-cluster arm — the closest
4755/// canonical M3 production reference the substrate carries, matching the
4756/// caixa-mesh default axis every M3 renderer already keys off (a
4757/// `programs.yaml` fan-out that emits one `HelmRelease` per cluster is
4758/// the canonical shape a `:membros`+`:contratos`-declared Aplicacao lands on
4759/// under the substrate's fleet-programs aggregator without an explicit
4760/// `:placement :estrategia` override). The two alternatives the closed
4761/// [`PlacementStrategy::ALL`] accept-set carries
4762/// ([`PlacementStrategy::SingleNode`] — Erlang/OTP distributed-app
4763/// takeover, MESH-COMPOSITION §II.1; [`PlacementStrategy::Sharded`] —
4764/// Akka-style hash-keyed distribution across clusters,
4765/// MESH-COMPOSITION §II.4) express deliberate takeover / hash-keyed
4766/// postures an author declares explicitly, never a posture an omitted
4767/// slot should silently assume.
4768///
4769/// Lifted as a typed `pub const` so the M3-mesh-canonical default has
4770/// exactly one source of truth on the `:placement :estrategia` axis, on
4771/// the same substrate-primitive lift discipline the sibling M2
4772/// per-supervisor default set carries
4773/// ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`],
4774/// [`crate::supervisor::SUPERVISOR_MAX_RESTARTS_DEFAULT`],
4775/// [`crate::supervisor::SUPERVISOR_RESTART_WINDOW_DEFAULT`],
4776/// [`crate::supervisor::SUPERVISOR_CHILD_RESTART_DEFAULT`]) and the peer
4777/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes
4778/// ([`crate::render::DEFAULT_NAMESPACE`],
4779/// [`crate::render::DEFAULT_LIBRARY_NAME`],
4780/// [`crate::render::DEFAULT_SERVICO_PORT`]). The first typed default on
4781/// the M3 mesh-primitive-defining slot family to converge onto the
4782/// substrate-primitive-lift discipline the M2 supervisor-slot family
4783/// already carries end-to-end.
4784pub const PLACEMENT_ESTRATEGIA_DEFAULT: PlacementStrategy = PlacementStrategy::Replicated;
4785
4786impl Default for PlacementStrategy {
4787    fn default() -> Self {
4788        // Route the [`Default for PlacementStrategy`] impl through the
4789        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
4790        // `pub const` rather than a raw `Self::Replicated` arm — one
4791        // source of truth for the M3-mesh-canonical active-active-
4792        // across-every-named-cluster `:placement :estrategia` default
4793        // (MESH-COMPOSITION §II.2), on the same substrate-primitive
4794        // lift discipline the sibling M2 per-supervisor default set
4795        // ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`] +
4796        // paired halves) carries end-to-end. Pinned by
4797        // `placement_strategy_default_routes_through_lifted_default`.
4798        PLACEMENT_ESTRATEGIA_DEFAULT
4799    }
4800}
4801
4802impl PlacementStrategy {
4803    /// Exhaustive iteration surface for every consumer that reads the
4804    /// full closed-set (the future M4 admission-webhook's accepted-
4805    /// strategy listing in its rejection body, a future `feira app
4806    /// placement --list` CLI-side surfacing of the accepted arm-set,
4807    /// any future round-trip fuzz harness). A future variant addition
4808    /// (an `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint
4809    /// names as a trajectory item) extends this slice as a single edit
4810    /// and every consumer picks up the new entry by construction — the
4811    /// compiler-checked exhaustiveness on the sibling method `match`
4812    /// arms is the build-time guarantee that no arm forgets to grow.
4813    /// Same shape as the sibling closed-set typed enums'
4814    /// [`RateLimitUnit::ALL`] (6bce03d) and
4815    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
4816    /// surfaces — the third closed-set typed enum on the caixa surface
4817    /// to converge onto the same discipline.
4818    pub const ALL: &'static [Self] = &[Self::SingleNode, Self::Replicated, Self::Sharded];
4819
4820    /// Canonical camelCase-schema discriminator scalar this variant
4821    /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
4822    /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
4823    /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4824    /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
4825    /// every substrate consumer that dispatches on the strategy (the
4826    /// `lareira-fleet-programs` aggregator, the future `app-operator`
4827    /// reconciler, the M3 Adaptive compression pass) reads the same
4828    /// byte-string the `Serialize` derive emits — the pin test in
4829    /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
4830    /// asserts the two paths agree.
4831    #[must_use]
4832    pub const fn as_str(self) -> &'static str {
4833        match self {
4834            Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
4835            Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
4836            Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
4837        }
4838    }
4839
4840    /// Substrate-canonical reverse projection on the `:placement
4841    /// :estrategia` closed-set axis — parses the camelCase-schema
4842    /// discriminator scalar back to the typed variant, or `None` when
4843    /// `s` is outside the closed-set arm-string set [`Self::as_str`]
4844    /// emits. Dispatches on the same lifted
4845    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
4846    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4847    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] constants the
4848    /// [`Self::as_str`] emitter walks, so the parse and emit halves of
4849    /// the round-trip migrate through one caixa-core edit on any future
4850    /// arm addition (an `Anycast` mesh-anycast arm the MESH-COMPOSITION
4851    /// §II.5 hint names as a trajectory item lands one variant + one
4852    /// arm per method and the compiler enforces exhaustiveness on every
4853    /// consumer's `match self` arms).
4854    ///
4855    /// Prior to this lift the substrate carried only the forward
4856    /// `Self → &str` projection (the [`Self::as_str`] emitter, the
4857    /// [`std::fmt::Display`] impl routed through it, the `Serialize`
4858    /// derive that emits the same byte-string under
4859    /// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]) — every non-serde
4860    /// consumer that wanted to parse a wire-form strategy scalar had to
4861    /// re-inline a three-arm `match s { "SingleNode" => …, "Replicated"
4862    /// => …, "Sharded" => …, _ => … }` cascade that expressed no
4863    /// compile-time link back to the typed variant's canonical lifted
4864    /// constant. A future variant rename or a per-arm serde-attribute
4865    /// drift would silently split the wire byte-string one non-serde
4866    /// consumer parsed from the one the emitter wrote, with the
4867    /// failure surfacing at parse time far from the rebrand commit.
4868    ///
4869    /// Same closed-set-reverse-projection discipline the sibling
4870    /// [`crate::CaixaKind::from_wire`] (2aa6d23) and
4871    /// [`RateLimitUnit::from_suffix`] typed enums carry on the peer
4872    /// wire-side `str → Self` axes — extended onto the M3 mesh-primitive-
4873    /// defining `:placement :estrategia` closed-set axis, the third
4874    /// substrate-side closed-set typed enum to converge on the two-way
4875    /// `str ↔ Self` round-trip. Method-named `from_wire` (not `from_str`)
4876    /// to match the peer [`crate::CaixaKind::from_wire`] shape verbatim
4877    /// and side-step the [`std::str::FromStr`]-collision clippy
4878    /// (`clippy::should_implement_trait`) the plain `from_str` name
4879    /// carries; a future explicit [`std::str::FromStr`] impl can layer
4880    /// on top by delegating to this canonical arm-dispatch method.
4881    ///
4882    /// Returns `Option<Self>` (rather than `Result<Self, _>`) to match
4883    /// the sibling [`crate::CaixaKind::from_wire`] shape: the caller
4884    /// picks the diagnostic form appropriate for its use site — a
4885    /// future `feira app placement --set` CLI-side arg-parse that wants
4886    /// an `"unknown strategy: {s} (accepted: SingleNode, Replicated,
4887    /// Sharded)"` diagnostic builds one on top by iterating
4888    /// [`Self::ALL`], while the future M4 admission-webhook's rejection
4889    /// path folds `None` onto its per-CR structured refusal body.
4890    #[must_use]
4891    pub fn from_wire(s: &str) -> Option<Self> {
4892        match s {
4893            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE => Some(Self::SingleNode),
4894            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED => Some(Self::Replicated),
4895            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED => Some(Self::Sharded),
4896            _ => None,
4897        }
4898    }
4899
4900    /// Substrate-canonical per-arm predicate naming the cross-slot
4901    /// `:placement :estrategia` ↔ `:placement :shard-key` invariant on the
4902    /// closed-set typed [`PlacementStrategy`] enum: `true` iff the strategy
4903    /// consumes the paired [`Placement::shard_key`] axis (and therefore
4904    /// requires — and is the only strategy that permits — a non-empty
4905    /// `:shard-key` on the paired slot). Today the accept-set is the
4906    /// singleton `{Sharded}` — `Sharded` is the sole Akka-style
4907    /// hash-keyed distribution arm (MESH-COMPOSITION §II.4) that keys off a
4908    /// per-entity extractor expression; `SingleNode` (Erlang/OTP
4909    /// distributed-app takeover — §II.1) and `Replicated` (active-active
4910    /// across every named cluster) have no hash-keyed routing axis to
4911    /// consume the slot and refuse a declared-but-inert `:shard-key`
4912    /// through [`AplicacaoError::ShardKeyOnNonSharded`].
4913    ///
4914    /// Every validated [`Placement`] past [`AplicacaoSpec::validate_placement`]
4915    /// satisfies `placement.shard_key().is_some() ==
4916    /// placement.estrategia().requires_shard_key()` by construction — the
4917    /// cross-slot partition the pin
4918    /// [`tests::validate_placement_admits_paired_shape_iff_strategy_requires_shard_key`]
4919    /// locks load-bearing, so every downstream consumer that reaches for
4920    /// the paired shape (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
4921    /// CR materializer's per-CR shard-key resolver, the future
4922    /// [`feira app graph --shard-key`] per-Aplicacao column, the future
4923    /// per-cluster Akka-style cluster-sharding reconciler's per-entity
4924    /// hash-routing gate, the M5 adaptive-placement engine's per-strategy
4925    /// shard-key requirement probe, a future author-facing tatara-lisp
4926    /// linter that flags `(:placement (:estrategia Replicated :shard-key
4927    /// "tenantId"))` shapes before `feira lint` reaches
4928    /// [`AplicacaoSpec::validate`]) can reach for one typed dispatch on
4929    /// the substrate primitive — the predicate names *the cross-slot
4930    /// invariant*, not the arm identity.
4931    ///
4932    /// Prior to this lift the "does this strategy consume `:shard-key`"
4933    /// classification lived under the `gen_platform::IsVariant`-derived
4934    /// [`Self::is_sharded`] predicate at three fixture-builder sites in
4935    /// this crate (the [`tests::placement_strategy_variants_round_trip`]
4936    /// per-variant `Placement`-builder's `if s.is_sharded() { Some("$key"…)
4937    /// } else { None }` cascade, the
4938    /// [`tests::estrategia_returns_placement_estrategia_verbatim_across_permutations`]
4939    /// per-variant `Placement`-builder's `estrategia.is_sharded().then(||
4940    /// "tenantId".to_string())` cascade, and the
4941    /// [`tests::validate_placement_reads_through_lifted_estrategia_accessor`]
4942    /// per-variant spec-mutator's identical `.is_sharded().then(…)`
4943    /// cascade). Each site conflated two semantically distinct questions:
4944    /// "is the variant `Sharded`?" (arm-identity, what
4945    /// [`Self::is_sharded`] answers) and "does the variant consume
4946    /// `:shard-key`?" (cross-slot-invariant, what this predicate answers).
4947    /// The two questions land on the same three-way answer under today's
4948    /// closed accept-set (both trip on the singleton `{Sharded}`), but a
4949    /// future arm addition that consumed `:shard-key` under a different
4950    /// name (a hypothetical `Anycast` mesh-anycast arm the MESH-COMPOSITION
4951    /// §II.5 roadmap-hint names that hash-partitions across the cluster
4952    /// pool by client-IP hash rather than an author-declared extractor
4953    /// expression, a hypothetical `WeightedShard` variant that carries a
4954    /// shard-key + per-cluster weight table under a promoted M5
4955    /// adaptive-placement engine) or an addition that did *not* consume
4956    /// `:shard-key` on a semantically Sharded-shaped arm would silently
4957    /// split the two questions. Any consumer that read
4958    /// `.is_sharded().then(…)` for the shard-key requirement gate would
4959    /// silently misclassify the new arm as non-consuming — a fixture
4960    /// builder would omit `:shard-key` where the new arm required one and
4961    /// [`AplicacaoSpec::validate_placement`] would refuse the fixture with
4962    /// [`AplicacaoError::ShardedWithoutKey`] far from the arm-addition
4963    /// commit, a future M4 CR materializer would fall through the
4964    /// `.is_sharded()`-only branch to the non-shard-key resolver arm and
4965    /// silently emit an empty extractor at the Akka reconciler layer.
4966    ///
4967    /// Lifting the classification as a substrate-primitive method on the
4968    /// closed-set typed enum names the cross-slot invariant on the
4969    /// primitive that owns the partition: every future arm addition
4970    /// declares its `:shard-key` consumption in one place (this predicate's
4971    /// `match self` arm-set), and every downstream consumer that reaches
4972    /// for the paired shape reads through one typed dispatch. Same
4973    /// discipline as the sibling [`WitContract::is_capability`] (7b97d26)
4974    /// per-arm predicate on the pre-projection WIT-shape axis and the
4975    /// [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
4976    /// paired predicate on the post-projection typed-view axis — a
4977    /// per-arm semantic-classification predicate paired with the
4978    /// arm-identity predicate the derive already emits, closing the drift
4979    /// footgun on the cross-slot invariant axis.
4980    ///
4981    /// Method-named `requires_shard_key` (not `has_shard_key`, not
4982    /// `is_shard_keyed`, not `takes_shard_key`) because the cross-slot
4983    /// invariant reads as "this strategy *requires* the paired
4984    /// `:shard-key` axis" — the `SingleNode`/`Replicated` arms *refuse*
4985    /// the axis through [`AplicacaoError::ShardKeyOnNonSharded`], not
4986    /// merely omit it. The `has_*` framing would read as an accessor
4987    /// (returning the presence of an already-carried value) rather than a
4988    /// requirement (naming the invariant the paired slot must satisfy).
4989    /// Returns `bool` (not `Option<()>` or a marker-type witness), same
4990    /// shape as the sibling [`WitContract::is_capability`] /
4991    /// [`Self::is_sharded`] per-arm boolean predicates on the closed-set
4992    /// arm-family, so every consumer reaches for `.requires_shard_key()`
4993    /// as a drop-in replacement for the `.is_sharded()` conflated read
4994    /// without a return-shape migration.
4995    #[must_use]
4996    pub const fn requires_shard_key(self) -> bool {
4997        match self {
4998            Self::Sharded => true,
4999            Self::SingleNode | Self::Replicated => false,
5000        }
5001    }
5002}
5003
5004// Compile-time pins on the [`PlacementStrategy::requires_shard_key`]
5005// cross-slot-invariant per-arm predicate: the module-scope const-eval
5006// assertions below trip at caixa-core build time (not test time) if a
5007// future edit rewires the predicate's arm-set away from the singleton
5008// `{Sharded}` accept-set MESH-COMPOSITION §II.4 pins. The
5009// [`tests::placement_strategy_requires_shard_key_partitions_the_arm_set`]
5010// runtime pin covers the same truth-table with a more descriptive
5011// diagnostic on failure; these const-eval items add a build-time failure
5012// surface strictly stronger than the runtime pin (a downstream renderer's
5013// `const`-context reader that composed against a rebound predicate would
5014// still surface here before the test suite even ran) and side-step the
5015// `clippy::assertions_on_constants` lint the runtime `assert!(CONST)` pin
5016// would otherwise accumulate on the caixa-core module baseline.
5017const _: () = assert!(!PlacementStrategy::SingleNode.requires_shard_key());
5018const _: () = assert!(!PlacementStrategy::Replicated.requires_shard_key());
5019const _: () = assert!(PlacementStrategy::Sharded.requires_shard_key());
5020
5021/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
5022/// the pretty-printed byte-string every consumer that formats the strategy
5023/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
5024/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
5025/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
5026/// per-Aplicacao strategy line, the future M4 CR materializer's per-
5027/// admission-webhook rejection body) reaches for the same lifted
5028/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
5029/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5030/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
5031/// `Serialize` derive already emits under
5032/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
5033/// [`PlacementStrategy::as_str`] helper already returns.
5034///
5035/// Until this lift landed the sibling OTP-shape typed enums —
5036/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
5037/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
5038/// so [`std::fmt::Display`] routes through the same discriminant string
5039/// the wire format emits) — carried a stable [`std::fmt::Display`]
5040/// surface but [`PlacementStrategy`] did not; every consumer reaching
5041/// for a strategy byte-string past the wire format had to pick between
5042/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
5043/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
5044/// derive), any two of which a future variant rename or
5045/// `#[serde(rename_all = "kebab-case")]` attribute would silently
5046/// desynchronize — with the failure surfacing as a downstream renderer /
5047/// operator's per-strategy dispatch reading one spelling while the wire
5048/// format emitted another, far from the source rebrand commit and with
5049/// no field naming the drift. Routing `Display` through
5050/// [`PlacementStrategy::as_str`] makes the three paths
5051/// (`Debug` for structural inspection, `Display` for user-facing text,
5052/// `Serialize` for the wire format) converge on the same lifted
5053/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
5054/// the diagnostic byte-string, and the pretty-printed byte-string move
5055/// as a single unit through one canonical declaration each, by
5056/// construction. Same trajectory as [`PlacementStrategy::as_str`]
5057/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
5058/// closes the third path.
5059///
5060/// Pin tests
5061/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
5062/// and
5063/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
5064/// assert the three paths agree byte-for-byte on every variant, so a
5065/// future variant rename or per-arm serde attribute drift is a build
5066/// error visible at caixa-core test time, not a silent per-consumer
5067/// dispatch miss at apply / reconcile time.
5068impl std::fmt::Display for PlacementStrategy {
5069    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5070        f.write_str(self.as_str())
5071    }
5072}
5073
5074/// Where the Aplicacao runs.
5075#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5076#[serde(rename_all = "camelCase")]
5077pub struct Placement {
5078    /// Distribution strategy.
5079    #[serde(default)]
5080    pub estrategia: PlacementStrategy,
5081
5082    /// Named clusters that host this Aplicacao. Required for
5083    /// `Replicated` and `SingleNode`; for `Sharded` declares the
5084    /// shard pool.
5085    #[serde(default)]
5086    pub clusters: Vec<String>,
5087
5088    /// Optional hint to the placement engine: `"data-locality"`,
5089    /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
5090    #[serde(default, skip_serializing_if = "Option::is_none")]
5091    pub affinity: Option<String>,
5092
5093    /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
5094    #[serde(default, skip_serializing_if = "Option::is_none")]
5095    pub shard_key: Option<String>,
5096}
5097
5098impl Placement {
5099    /// Substrate-canonical per-`:placement` Akka-cluster-sharding
5100    /// `:shard-key` extractor-expression scalar accessor every consumer
5101    /// of the Aplicacao's hash-keyed distribution routing keys off —
5102    /// returns the author-declared `:placement :shard-key` byte-string
5103    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
5104    /// own `Option<String>` storage; `None` when the slot is absent
5105    /// (the canonical shape under `:estrategia Replicated` /
5106    /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
5107    /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
5108    /// partition — `validate` refuses any `Placement` past this call
5109    /// that lands `Some` on a non-`Sharded` strategy or `None` on
5110    /// `Sharded`).
5111    ///
5112    /// The `:placement :shard-key` slot carries the Akka-style
5113    /// cluster-sharding entity-id extractor expression
5114    /// (MESH-COMPOSITION §II.4) — validated by
5115    /// [`validate_placement_shard_key`] to be a non-empty printable-
5116    /// ASCII single-token reference (`tenantId`, `$tenantId`,
5117    /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
5118    /// future M4 Akka-style cluster-sharding reconciler hashes without
5119    /// re-validating at the runtime layer), and every downstream
5120    /// consumer that reads the key keys off this scalar (the
5121    /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
5122    /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
5123    /// declared-but-inert refusal diagnostic, the caixa-mesh
5124    /// per-Aplicacao `placement.shardKey` emit path the substrate
5125    /// operator's per-entity hash-routing reader consumes, the future
5126    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5127    /// per-shard-key resolver).
5128    ///
5129    /// Prior to this lift the `.shard_key` field was accessed inline at
5130    /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
5131    /// `Sharded` arm's `match &self.placement.shard_key { None => …,
5132    /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
5133    /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
5134    /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
5135    /// — two open-coded field-accesses that expressed no compile-time
5136    /// link back to the typed slot. A future extension of the
5137    /// `:placement :shard-key` axis to a richer author surface — a
5138    /// per-cluster override the operator pins through a future
5139    /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
5140    /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
5141    /// alias table the M4 CR materializer resolves per-CR, a
5142    /// per-Aplicacao dynamic `:shard-key` derivation the future
5143    /// adaptive placement engine computes from `:affinity` weights —
5144    /// would have had to be threaded through both open-coded copies in
5145    /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
5146    /// arm refusal would silently disagree on which extractor
5147    /// expression a given Placement resolves to. Lifting the resolution
5148    /// rule to a typed method on the substrate primitive means every
5149    /// downstream consumer of the Aplicacao's per-`:placement`
5150    /// hash-key surface reaches for exactly one typed dispatch — the
5151    /// resolver's accept-set migrates as a unit on any future axis
5152    /// addition.
5153    ///
5154    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
5155    /// [`WitContract::destination`] / [`WitContract::world_ref`]
5156    /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
5157    /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
5158    /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
5159    /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
5160    /// typed dispatch on the substrate primitive, thin projections at
5161    /// each consumer" discipline extended onto the per-`:placement`
5162    /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
5163    /// First `Option<&str>`-return accessor on the M3 mesh-slot family
5164    /// — opens the "optional per-slot scalar" projection pattern the
5165    /// sibling per-`:placement` `:affinity`, per-`:politicas`
5166    /// `:rate-limit` future lifts fold on. Named `shard_key()` to
5167    /// match the storage field's name; the accessor's identity name
5168    /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
5169    /// slot's docstring already carries.
5170    #[must_use]
5171    pub fn shard_key(&self) -> Option<&str> {
5172        self.shard_key.as_deref()
5173    }
5174
5175    /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
5176    /// compression-hint scalar accessor every weighting-consumer of the
5177    /// Aplicacao's per-hint routing surface keys off — returns the
5178    /// author-declared `:placement :affinity` byte-string verbatim as
5179    /// an `Option<&str>`, borrowed from the typed slot's own
5180    /// `Option<String>` storage; `None` when the slot is absent (the
5181    /// canonical shape of an Aplicacao that leaves the compression
5182    /// weighting up to the placement engine's cluster-default arm — no
5183    /// author-authored `data-locality` / `low-latency` / etc. hint
5184    /// biases the routing).
5185    ///
5186    /// The `:placement :affinity` slot carries the M3 Adaptive-
5187    /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
5188    /// by [`validate_placement_affinity`] to be a DNS-1123 label
5189    /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
5190    /// K8s-conformant label-selector shape every apiserver-side pod-
5191    /// affinity / node-affinity materializer already gates on
5192    /// admission), and every downstream consumer that reads the hint
5193    /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
5194    /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
5195    /// `placement.affinity` overlay emit path the substrate operator's
5196    /// per-hint weighting-consumer reads, the future M4
5197    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
5198    /// pod-affinity / node-affinity selector resolver).
5199    ///
5200    /// Prior to this lift the `.affinity` field was accessed inline at
5201    /// the sole caixa-core site — the
5202    /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
5203    /// `if let Some(a) = &self.placement.affinity { …
5204    /// validate_placement_affinity(a)? … }` cascade — one open-coded
5205    /// field-access that expressed no compile-time link back to the
5206    /// typed slot. A future extension of the `:placement :affinity`
5207    /// axis to a richer author surface — a per-cluster override the
5208    /// operator pins through a future `:placement :affinity-overrides`
5209    /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
5210    /// tenant hint alias table the M4 CR materializer resolves per-CR,
5211    /// a per-Aplicacao dynamic `:affinity` derivation the future
5212    /// adaptive placement engine computes from `:clusters` topology —
5213    /// would have had to be threaded through the open-coded copy in
5214    /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
5215    /// materializer reader that landed on the axis, or the per-hint
5216    /// value-shape gate and its downstream weighting consumers would
5217    /// silently disagree on which hint a given Placement resolves to.
5218    /// Lifting the resolution rule to a typed method on the substrate
5219    /// primitive means every downstream consumer of the Aplicacao's
5220    /// per-`:placement` compression-hint surface reaches for exactly
5221    /// one typed dispatch — the resolver's accept-set migrates as a
5222    /// unit on any future axis addition.
5223    ///
5224    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
5225    /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
5226    /// optional-scalar axis — same "one typed dispatch on the substrate
5227    /// primitive, thin projections at each consumer" discipline extended
5228    /// onto the per-`:placement` M3-Adaptive-compression-hint
5229    /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
5230    /// return accessor on the M3 mesh-slot family; closes the last
5231    /// un-lifted per-`:placement` `Option<String>` axis. Named
5232    /// `affinity()` to match the storage field's name; the accessor's
5233    /// identity name maps onto the canonical MESH-COMPOSITION §II.4
5234    /// vocabulary the slot's docstring already carries.
5235    #[must_use]
5236    pub fn affinity(&self) -> Option<&str> {
5237        self.affinity.as_deref()
5238    }
5239
5240    /// Substrate-canonical per-`:placement` `:estrategia` distribution-
5241    /// strategy scalar accessor every consumer that dispatches on the
5242    /// Aplicacao's per-cluster distribution shape keys off — returns the
5243    /// author-declared `:placement :estrategia` variant verbatim as a
5244    /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
5245    /// `PlacementStrategy` storage.
5246    ///
5247    /// The `:placement :estrategia` slot carries the closed-set
5248    /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
5249    /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
5250    /// `Replicated` — active-active across every named cluster; `Sharded`
5251    /// — Akka-style hash-keyed entity distribution across the cluster pool
5252    /// per §II.4) that every downstream consumer of the Aplicacao's
5253    /// per-cluster fan-out shape keys off. Validated by
5254    /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
5255    /// the sibling `:shard-key` axis (`shard_key.is_some() ==
5256    /// matches!(estrategia, Sharded)` — the cross-slot partition the
5257    /// [`Placement::shard_key`] accessor's docstring pins), and every
5258    /// downstream consumer that reads the strategy keys off this scalar
5259    /// (the [`AplicacaoSpec::validate_placement`]
5260    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
5261    /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
5262    /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
5263    /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
5264    /// declared-but-inert refusal's
5265    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
5266    /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
5267    /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
5268    /// emit path the substrate operator's per-strategy fan-out reader
5269    /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5270    /// materializer's per-strategy admission-webhook resolver).
5271    ///
5272    /// Prior to this lift the `.estrategia` field was accessed inline at
5273    /// four sites — the [`AplicacaoSpec::validate_placement`]
5274    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
5275    /// `estrategia: self.placement.estrategia`, the same method's
5276    /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
5277    /// partition dispatch, the non-`Sharded`-arm
5278    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
5279    /// `estrategia: self.placement.estrategia`, and the `feira app graph`
5280    /// per-Aplicacao strategy print line at
5281    /// `println!("… {} …", spec.placement.estrategia, …)`
5282    /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
5283    /// expressed no compile-time link back to the typed slot. A future
5284    /// extension of the `:placement :estrategia` axis to a richer author
5285    /// surface (a per-cluster override the operator pins through a future
5286    /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
5287    /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
5288    /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
5289    /// derivation the future adaptive placement engine computes from
5290    /// `:affinity` + `:clusters` topology) would have had to be threaded
5291    /// through every open-coded copy in lockstep — one consumer reading
5292    /// the raw variant while a peer read the operator-resolved variant
5293    /// would silently split the `PlacementWithoutClusters` /
5294    /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
5295    /// partition-dispatch input, a two-consumer split at the validator
5296    /// far from the source `caixa.lisp` with no field naming the
5297    /// strategy-drift root cause. Lifting the resolution rule to a typed
5298    /// method on the substrate primitive means every downstream consumer
5299    /// of the Aplicacao's per-`:placement` distribution-strategy surface
5300    /// reaches for exactly one typed dispatch — the resolver's accept-set
5301    /// migrates as a unit on any future axis addition.
5302    ///
5303    /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
5304    /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
5305    /// same "one typed dispatch on the substrate primitive, thin
5306    /// projections at each consumer" discipline extended onto the
5307    /// per-`:placement` distribution-strategy `Copy`-composite-enum
5308    /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
5309    /// family; first `Copy`-return accessor on the M3 mesh-slot
5310    /// `Placement` type — companion to the sibling per-`:placement`
5311    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
5312    /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
5313    /// optional-scalar axes, closing the last unlifted per-`:placement`
5314    /// scalar-value axis (the closed-set `PlacementStrategy`
5315    /// distribution-strategy discriminator) so every downstream
5316    /// per-`:placement` reader now routes through a typed dispatch on
5317    /// the substrate primitive. Named `estrategia()` to match the storage
5318    /// field's name; the accessor's identity name maps onto the
5319    /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
5320    /// already carries. Declared `pub const fn` (matching the peer M3
5321    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
5322    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
5323    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
5324    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
5325    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
5326    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
5327    /// [`RateLimit`] — every one a `pub const fn`) so every future
5328    /// substrate-side `const`-context consumer of the resolved
5329    /// distribution-strategy variant (a `const _: () = assert!(…)`
5330    /// module-scope invariant pin on a per-fixture typed [`Placement`],
5331    /// a future M4 admission-webhook `const fn` resolver over a typed
5332    /// [`Placement`], any `const fn` composer that fans on the strategy
5333    /// at compile time) reaches through the same typed dispatch on the
5334    /// substrate primitive at const-eval time as at runtime. Pinned by
5335    /// [`placement_estrategia_accessor_is_const_fn`] which witnesses the
5336    /// const-eval posture at module scope via `const _:() = …` items so
5337    /// any future accidental downgrade to non-`const` trips at caixa-core
5338    /// build time.
5339    #[must_use]
5340    pub const fn estrategia(&self) -> PlacementStrategy {
5341        self.estrategia
5342    }
5343
5344    /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
5345    /// per-cluster distribution-target slice accessor every consumer that
5346    /// walks the Aplicacao's declared cluster-pool keys off — returns the
5347    /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
5348    /// `&[String]` slice-view, borrowed from the typed slot's own
5349    /// `Vec<String>` storage (a zero-copy slice-view over the same
5350    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
5351    /// through). Non-optional: the empty slice is the load-bearing
5352    /// pre-validation sentinel every downstream consumer of the paired
5353    /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
5354    /// off — every strategy in the closed
5355    /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
5356    /// requires a non-empty list (`SingleNode` / `Replicated` use the
5357    /// list as hosting / takeover candidates per Erlang/OTP distributed-
5358    /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
5359    /// shard pool per Akka cluster-sharding convention, §II.4), so the
5360    /// `.is_empty()` probe is the shared pre-condition every
5361    /// [`AplicacaoSpec::validate_placement`] arm heads on.
5362    ///
5363    /// The `:placement :clusters` slot carries the K8s-conformant DNS-
5364    /// 1123-label per-cluster distribution-target list — the same
5365    /// set-not-multiset shape the sibling `:membros :caixa` /
5366    /// `:children :caixa` axes carry (`validate_placement`'s per-entry
5367    /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
5368    /// pins the shape). Every downstream consumer that fans on the list
5369    /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
5370    /// pre-flight `.is_empty()` probe that trips
5371    /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
5372    /// per-cluster value-shape + duplicate-detection fan-out loop, the
5373    /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
5374    /// that materializes the list verbatim onto every
5375    /// programs.yaml entry the substrate operator's per-cluster
5376    /// `placement.clusters | contains .Values.cluster` filter reads,
5377    /// the `feira app graph` per-Aplicacao cluster print line, the
5378    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5379    /// per-cluster admission-webhook fan-out, the future M5 adaptive-
5380    /// placement engine's cluster-topology reader).
5381    ///
5382    /// Prior to this lift the `.clusters` `Vec<String>` was accessed
5383    /// inline at three production sites — the
5384    /// [`AplicacaoSpec::validate_placement`] pre-flight
5385    /// `self.placement.clusters.is_empty()` refusal probe, the same
5386    /// method's per-cluster validate loop's
5387    /// `for c in &self.placement.clusters` traversal head, and the
5388    /// `feira app graph` per-Aplicacao print line's
5389    /// `spec.placement.clusters` `{:?}` formatter argument
5390    /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
5391    /// that expressed no compile-time link back to the typed slot. A
5392    /// future extension of the `:placement :clusters` axis to a richer
5393    /// author surface (a per-tenant cluster-pool overlay the operator
5394    /// pins through a future `:placement :clusters-overrides` slot the
5395    /// MESH-COMPOSITION §V cross-cluster-federation roadmap
5396    /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
5397    /// the future M5 adaptive-placement engine computes from
5398    /// `:affinity` weights + live cluster-topology probes, a promotion
5399    /// of the plain `Vec<String>` to a richer `{static, dynamic}`
5400    /// partition once the substrate operator's cluster-membership
5401    /// reconciler comes into typed scope) would have had to be threaded
5402    /// through all three open-coded copies in lockstep or one consumer
5403    /// would silently disagree with the peers on which cluster-pool a
5404    /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
5405    /// reading the raw slot while the peer per-cluster validate loop
5406    /// read an operator-resolved slot would silently split the paired
5407    /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
5408    /// `PlacementClusterDuplicate` refusal cascade's actual traversal
5409    /// input from the pre-flight input, a three-consumer split at the
5410    /// validator and formatter far from the source `caixa.lisp` with
5411    /// no field naming the cluster-pool-drift root cause. Lifting the
5412    /// resolution rule to a typed method on the substrate primitive
5413    /// means every downstream consumer of the Aplicacao's
5414    /// per-`:placement` cluster-pool surface reaches for exactly one
5415    /// typed dispatch — the resolver's accept-set migrates as a unit
5416    /// on any future axis addition.
5417    ///
5418    /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
5419    /// slot — sibling to the seed M2
5420    /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
5421    /// slice-return accessor on the peer per-`:supervisor` static-
5422    /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
5423    /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
5424    /// primitive, thin projections at each consumer" discipline. The
5425    /// three peer `Vec`-carry axes still unlifted at the time of this
5426    /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
5427    /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
5428    /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
5429    /// [`crate::UpgradeFromEntry::instructions`]
5430    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
5431    /// — inherit this accessor's discipline as future compounding runs
5432    /// migrate their consumers onto the shared slice-return shape.
5433    /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
5434    /// type, sibling to the two `Option<&str>`-return
5435    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
5436    /// (74ec2d3) accessors and the `Copy`-return
5437    /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
5438    /// unlifted per-`:placement` field axis (the `Vec<String>`
5439    /// distribution-target-list carrier) so every downstream
5440    /// per-`:placement` reader now routes through a typed dispatch on
5441    /// the substrate primitive. Named `clusters()` to match the storage
5442    /// field's name verbatim and the tatara-lisp author-surface term
5443    /// (`:clusters`) the field's own docstring already carries; the
5444    /// accessor's identity maps onto the canonical MESH-COMPOSITION
5445    /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
5446    /// for. Returns `&[String]` (not `&Vec<String>`) because every
5447    /// downstream consumer of the cluster list treats it as a read-only
5448    /// sequence — the slice-view is the narrowest borrow that supports
5449    /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
5450    /// `.len()`) without leaking the backing `Vec`'s
5451    /// grow/push/reserve surface that no consumer of the typed view
5452    /// reaches for (the storage-side `Vec` remains reachable through
5453    /// the `pub clusters` field for the mutation-carrying serde
5454    /// round-trip and per-test fixture-mutation paths).
5455    #[must_use]
5456    pub fn clusters(&self) -> &[String] {
5457        self.clusters.as_slice()
5458    }
5459}
5460
5461impl Default for Placement {
5462    fn default() -> Self {
5463        Self {
5464            // Route the struct-literal `estrategia` default arm through
5465            // the substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`]
5466            // typed `pub const` rather than the transitively-derived
5467            // [`PlacementStrategy::default`] route — one source of truth
5468            // for the M3-mesh-canonical [`PlacementStrategy::Replicated`]
5469            // active-active-across-every-named-cluster arm
5470            // (MESH-COMPOSITION §II.2) that both this struct-literal
5471            // altitude and the sibling [`Default for PlacementStrategy`]
5472            // impl already key off through the same substrate primitive.
5473            // Pinned by
5474            // `placement_default_estrategia_routes_through_lifted_default`.
5475            estrategia: PLACEMENT_ESTRATEGIA_DEFAULT,
5476            clusters: Vec::new(),
5477            affinity: None,
5478            shard_key: None,
5479        }
5480    }
5481}
5482
5483// ── external entry point ─────────────────────────────────────────────
5484
5485/// External entry point — what an outside caller sees. Renders to a
5486/// Gateway / Ingress + a route to the named member Servico.
5487#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5488#[serde(rename_all = "camelCase")]
5489pub struct Entrada {
5490    /// Public hostname (e.g. `"checkout.quero.cloud"`).
5491    pub host: String,
5492
5493    /// Member Servico the gateway routes to. Must be in `:membros`.
5494    pub para: String,
5495
5496    /// Optional path filter — if set, only matching paths route to
5497    /// this Aplicacao (the rest fall through to other route rules).
5498    #[serde(default)]
5499    pub paths: Vec<String>,
5500
5501    /// Default port on the destination Servico (the trigger.service.port).
5502    #[serde(default = "default_port")]
5503    pub port: u16,
5504}
5505
5506impl Entrada {
5507    /// Substrate-canonical per-`:entrada` URL-path fallback resolver
5508    /// every HTTPRoute-aware renderer keys off — returns the author-
5509    /// declared `:entrada :paths` list verbatim when non-empty, and the
5510    /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
5511    /// all fallback otherwise (so an Aplicacao author who declares an
5512    /// external `:entrada` block but no per-path rule surface still
5513    /// gets a route whose sole `HTTPPathMatch` matches every incoming
5514    /// request under the paired
5515    /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
5516    ///
5517    /// Prior to this lift the "if `:entrada :paths` is empty use the
5518    /// substrate catch-all; else return each declared path verbatim"
5519    /// cascade lived inline at
5520    /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
5521    /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
5522    /// per-Aplicacao HTTPRoute per-rule path-list emit site the
5523    /// substrate ships today, with no typed method on the substrate
5524    /// primitive that named the rule. A future path-resolution axis
5525    /// addition — a per-cluster `:entrada :default-path` override the
5526    /// operator pins through a future `:placement`-scoped slot, an
5527    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
5528    /// admission-webhook floor that materializes the catch-all before
5529    /// the CR lands, a future per-`:entrada :paths` overlay from a
5530    /// per-cluster policy the future `feira app deploy` pipeline
5531    /// consumes — would have to be threaded through every renderer's
5532    /// inline copy of the cascade in lockstep or one consumer would
5533    /// silently disagree with the peers on which path list a given
5534    /// `:entrada` block resolves to. Lifting the rule to a typed
5535    /// method on the substrate primitive means every downstream
5536    /// HTTPRoute-aware consumer (the M4 CR materializer, the future
5537    /// per-cluster overlay resolver, every future per-Aplicacao
5538    /// snapshot renderer) reaches for exactly one typed dispatch —
5539    /// the resolver's accept-set moves as a unit on any future axis
5540    /// addition.
5541    ///
5542    /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
5543    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
5544    /// per-`:entrada` scalar-value axes — extends the "one typed
5545    /// dispatch on the substrate primitive, thin projections at each
5546    /// consumer" discipline onto the per-`:entrada` path-list
5547    /// resolution axis every HTTPRoute-aware renderer consumes. Same
5548    /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
5549    /// sibling `:politicas` primitive — one typed method on the
5550    /// substrate primitive that names the cascade every renderer
5551    /// otherwise re-inlines.
5552    #[must_use]
5553    pub fn resolved_paths(&self) -> Vec<&str> {
5554        // Route the internal cascade-head + per-entry projection reads
5555        // through the lifted [`Self::paths`] slice accessor rather than
5556        // the raw `self.paths` field access — the substrate-primitive
5557        // per-`:entrada` path-list resolver's two internal reads now
5558        // key off the canonical raw-slot surface every downstream
5559        // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
5560        // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
5561        // entrada summary line's `{:?}` Debug print) routes through, so
5562        // any future rebrand on the typed slot's raw-slot reader lands
5563        // at exactly one place. Same two-consumer coherence discipline
5564        // the sibling `Placement::clusters` (a6e18d7) accessor pins on
5565        // the peer M3 mesh-slot `Vec<String>`-carry axis.
5566        if self.paths().is_empty() {
5567            vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
5568        } else {
5569            self.paths().iter().map(String::as_str).collect()
5570        }
5571    }
5572
5573    /// Substrate-canonical per-`:entrada` DNS-hostname singular
5574    /// accessor every Gateway-API `Listener.hostname` reader keys off
5575    /// — returns the author-declared `:entrada :host` byte-string
5576    /// verbatim as a `&str`, borrowed from the typed slot's own
5577    /// [`String`] storage.
5578    ///
5579    /// Named the "singular" half of the DNS-hostname resolver pair on
5580    /// the substrate primitive: the parent-Gateway per-listener
5581    /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
5582    /// (`Listener.hostname: Option<PreciseHostname>` — at most one
5583    /// hostname per listener), and this accessor is the typed dispatch
5584    /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
5585    /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
5586    /// the per-HTTPRoute `spec.hostnames[]` list axis the same
5587    /// per-Aplicacao ingress-hostname surface projects onto.
5588    ///
5589    /// Prior to this lift the `entrada.host.clone()` byte-string was
5590    /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
5591    /// per-listener singular `hostname:` axis
5592    /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
5593    /// per-HTTPRoute plural `spec.hostnames[]` axis
5594    /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
5595    /// consumers read the same `entrada.host` field but the two-site
5596    /// duplication expressed no compile-time contract that the singular
5597    /// Gateway-listener filter and the plural `HTTPRoute` filter list
5598    /// stay in lockstep on future extensions of the `:entrada` slot to
5599    /// a multi-hostname author surface (an `:entrada :alt-hosts` list
5600    /// overlay, a per-cluster SNI fan-out the operator pins through a
5601    /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
5602    /// Aplicacao` CR materializer's per-listener virtual-host filter
5603    /// admission-webhook overlay). Any such extension would have to be
5604    /// threaded through every renderer's inline copy of the resolution
5605    /// in lockstep or the Gateway listener's `hostname:` filter would
5606    /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
5607    /// — a Gateway-API-conformance divergence whose apply-time symptom
5608    /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
5609    /// `NoMatchingParent` — the API server rejects the route because
5610    /// its `hostnames[]` filter doesn't intersect the parent listener's
5611    /// `hostname` filter) is far from the source `caixa.lisp` and never
5612    /// surfaces in the emitted YAML. Lifting the singular and plural
5613    /// resolvers to typed methods on the substrate primitive means
5614    /// every consumer of the Aplicacao's ingress-hostname surface
5615    /// reaches for exactly one typed dispatch, and the pair-invariant
5616    /// `hostnames() == vec![hostname()]` pinned by the sibling
5617    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
5618    /// keeps the two axes in lockstep by construction.
5619    ///
5620    /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
5621    /// (1449891) path-list resolver on the per-HTTPRoute per-rule
5622    /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
5623    /// the substrate primitive, thin projections at each consumer"
5624    /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
5625    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
5626    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
5627    /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
5628    /// `:entrada` scalar-value + list-value axes.
5629    #[must_use]
5630    pub fn hostname(&self) -> &str {
5631        self.host.as_str()
5632    }
5633
5634    /// Substrate-canonical per-`:entrada` DNS-hostname plural
5635    /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
5636    /// keys off — returns the singleton `[hostname()]` list under
5637    /// today's single-hostname-per-Aplicacao author surface, and the
5638    /// authoritative multi-hostname list under a future
5639    /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
5640    ///
5641    /// Plural half of the DNS-hostname resolver pair — see the
5642    /// companion [`Entrada::hostname`] docstring for the two-consumer
5643    /// lift + pair-invariant discipline (`hostnames() ==
5644    /// vec![hostname()]`, pinned load-bearing by the sibling
5645    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
5646    /// test).
5647    ///
5648    /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
5649    /// per-`:entrada` plural-list resolver on the per-HTTPRoute
5650    /// per-rule path-list axis — same `Vec<&str>` shape, same
5651    /// substrate-primitive-owns-the-resolver discipline extended to
5652    /// the per-HTTPRoute virtual-host filter-list axis.
5653    #[must_use]
5654    pub fn hostnames(&self) -> Vec<&str> {
5655        vec![self.hostname()]
5656    }
5657
5658    /// Substrate-canonical per-`:entrada` destination-Servico scalar
5659    /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
5660    /// the author-declared `:entrada :para` byte-string verbatim as a
5661    /// `&str`, borrowed from the typed slot's own [`String`] storage.
5662    ///
5663    /// The `:entrada :para` slot names the single member Servico the
5664    /// external Gateway routes to (validated by
5665    /// [`AplicacaoSpec::validate`] to be a
5666    /// [`Membro::caixa`] the Aplicacao declares — a stray
5667    /// `:para` that doesn't name a member is
5668    /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
5669    /// backend-attachment miss at cluster-apply time). Under today's
5670    /// single-destination author surface `:entrada :para` is the ingress
5671    /// apex Servico's canonical identity; under a hypothetical
5672    /// future multi-backend author surface (a `:entrada
5673    /// :split :backends` weighted-fan-out overlay for canary /
5674    /// blue-green traffic-split rollouts, per-path override for
5675    /// path-based per-Servico routing beyond the single-apex model,
5676    /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5677    /// per-CR admission-webhook that promotes the scalar to a
5678    /// weighted list) this accessor is the substrate primitive's typed
5679    /// dispatch every downstream `HTTPRoute`-aware consumer routes
5680    /// through, so the resolution shape migrates as a unit on one
5681    /// caixa-core edit rather than a coordinated rewrite across every
5682    /// renderer's inline field-access.
5683    ///
5684    /// Prior to this lift the `entrada.para` byte-string was accessed
5685    /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
5686    /// `metadata.name` composer's per-destination discriminator arg
5687    /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
5688    /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
5689    /// per-HTTPRoute per-rule `backendRefs[0].name` axis
5690    /// (`entrada.para.clone()`,
5691    /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
5692    /// consumers read the same `entrada.para` field but the two-site
5693    /// duplication expressed no compile-time contract that the HTTPRoute
5694    /// name-discriminator and the per-rule backend name stay in
5695    /// lockstep on future extensions of the `:entrada` slot to a
5696    /// multi-destination author surface. Any such extension would have
5697    /// to be threaded through every renderer's inline copy of the
5698    /// destination projection in lockstep or the HTTPRoute
5699    /// `metadata.name` would silently reference a different destination
5700    /// than its own `backendRefs[]` — an operator-side
5701    /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
5702    /// grep-by-name lookup would land on a route whose `backendRefs[]`
5703    /// silently point at a peer Servico, dropping every external
5704    /// `:entrada` flow at the gateway with the destination-drift root
5705    /// cause invisible in the emitted YAML.
5706    ///
5707    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
5708    /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
5709    /// the per-listener singular / per-HTTPRoute plural filter axes and
5710    /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
5711    /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
5712    /// typed dispatch on the substrate primitive, thin projections at
5713    /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
5714    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
5715    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
5716    /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
5717    /// sibling per-`:entrada` scalar-value + list-value axes — this
5718    /// accessor closes the last unlifted per-`:entrada` scalar axis
5719    /// (the destination-Servico byte-string) so every downstream
5720    /// per-`:entrada` reader now routes through a typed dispatch on
5721    /// the substrate primitive.
5722    #[must_use]
5723    pub fn destination(&self) -> &str {
5724        self.para.as_str()
5725    }
5726
5727    /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
5728    /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
5729    /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
5730    /// reader keys off — returns the author-declared `:entrada :port`
5731    /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
5732    /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
5733    /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
5734    /// [`AplicacaoError::EntradaPortZero`], not a silent
5735    /// admission-webhook rejection at cluster-apply time).
5736    ///
5737    /// The `:entrada :port` slot carries the destination Servico's
5738    /// canonical in-cluster L4 listener port (`trigger.service.port` on
5739    /// the `pleme-computeunit` library chart), and every downstream
5740    /// consumer that reads the port keys off this scalar (the
5741    /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
5742    /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
5743    /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
5744    /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5745    /// CR materializer's per-Aplicacao gateway port resolver).
5746    ///
5747    /// Prior to this lift the `.port` field was accessed inline at two
5748    /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
5749    /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
5750    /// the [`AplicacaoSpec::port_for_destination`] resolver's
5751    /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
5752    /// open-coded field-accesses that expressed no compile-time link
5753    /// back to the typed slot. A future extension of the `:entrada :port`
5754    /// axis to a richer author surface — a per-cluster override the
5755    /// operator pins through a future `:placement :default-port` slot the
5756    /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
5757    /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
5758    /// heterogeneous listener ports, an M4
5759    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
5760    /// admission-webhook floor that promotes the scalar to a
5761    /// per-destination map — would have had to be threaded through both
5762    /// open-coded copies in lockstep or the structural-floor validator
5763    /// and the [`AplicacaoSpec::port_for_destination`] resolver would
5764    /// silently disagree on which port a given [`Entrada`] resolves to.
5765    /// Lifting the resolution rule to a typed method on the substrate
5766    /// primitive means every downstream consumer of the Aplicacao's
5767    /// per-`:entrada` L4-port surface reaches for exactly one typed
5768    /// dispatch — the resolver's accept-set migrates as a unit on any
5769    /// future axis addition.
5770    ///
5771    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
5772    /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
5773    /// accessors on the per-`:entrada` scalar-value axis — same "one
5774    /// typed dispatch on the substrate primitive, thin projections at
5775    /// each consumer" discipline extended onto the per-`:entrada`
5776    /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
5777    /// the M3 mesh-slot `Entrada` type — closes the last unlifted
5778    /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
5779    /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
5780    /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
5781    /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
5782    /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
5783    /// storage field's name; the accessor's identity name maps onto the
5784    /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
5785    /// already carries. Declared `pub const fn` (matching the peer M3
5786    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
5787    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
5788    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
5789    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
5790    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
5791    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
5792    /// [`RateLimit`], and the sibling per-`:placement`
5793    /// [`Placement::estrategia`] on the peer M3 mesh-slot `Copy`-composite-
5794    /// enum scalar axis — every one a `pub const fn`) so every future
5795    /// substrate-side `const`-context consumer of the resolved
5796    /// per-`:entrada` L4-port scalar (a `const _: () = assert!(…)`
5797    /// module-scope pin on a per-fixture typed [`Entrada`] anchoring
5798    /// `entrada.port() >= SERVICO_PORT_MIN` at compile time, a future M4
5799    /// admission-webhook `const fn` per-CR gateway-port floor over a
5800    /// typed [`Entrada`], any `const fn` composer that fans on the port
5801    /// at compile time) reaches through the same typed dispatch on the
5802    /// substrate primitive at const-eval time as at runtime. Pinned by
5803    /// [`entrada_port_accessor_is_const_fn`] which witnesses the
5804    /// const-eval posture at module scope via `const _:() = …` items so
5805    /// any future accidental downgrade to non-`const` trips at caixa-core
5806    /// build time.
5807    #[must_use]
5808    pub const fn port(&self) -> u16 {
5809        self.port
5810    }
5811
5812    /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
5813    /// slice accessor every HTTPRoute-aware renderer keys off when it
5814    /// wants the raw author-declared path-list (not the fallback-
5815    /// applied projection [`Self::resolved_paths`] returns) — returns
5816    /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
5817    /// borrowed from the typed slot's own [`Vec<String>`] storage.
5818    ///
5819    /// Named the "raw slot" half of the per-`:entrada` path-list resolver
5820    /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
5821    /// (1449891) closes the fallback-applying arm every per-Aplicacao
5822    /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
5823    /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
5824    /// catch-all; non-empty slot → per-entry verbatim projection); this
5825    /// accessor closes the raw-slot arm every consumer that must see the
5826    /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
5827    /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
5828    /// not `Err(EntradaPathEmpty)`, so it cannot route through the
5829    /// fallback-applying sibling; the `feira app graph` per-Aplicacao
5830    /// external-gateway summary line's `{:?}` Debug print — which must
5831    /// name the author's declaration, not the substrate's fallback, so
5832    /// an author reading their graph output can grep their caixa.lisp
5833    /// for the exact list they authored) routes through.
5834    ///
5835    /// Prior to this lift the `.paths` field was accessed inline at four
5836    /// production sites: the two internal reads in [`Self::resolved_paths`]
5837    /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
5838    /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
5839    /// value-shape gate's `for p in &e.paths` traversal head, and the
5840    /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
5841    /// Debug print — four open-coded field-accesses that expressed no
5842    /// compile-time link back to the typed slot. A future extension of
5843    /// the `:entrada :paths` axis to a richer author surface — a
5844    /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
5845    /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
5846    /// spec supports through `matches[].method`), a per-path per-header
5847    /// filter overlay (`matches[].headers[]`), a per-cluster override
5848    /// the operator pins through a future `:placement :path-overlay`
5849    /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5850    /// per-CR admission-webhook that normalized the list at admission
5851    /// time — would have had to be threaded through every open-coded
5852    /// copy in lockstep or the validator's per-entry gate would silently
5853    /// disagree with the renderer's per-entry emit on which list a given
5854    /// `:entrada` block resolves to. Lifting the resolution to a typed
5855    /// method on the substrate primitive means every downstream consumer
5856    /// of the Aplicacao's per-`:entrada` path-list surface reaches for
5857    /// exactly one typed dispatch — the resolver's accept-set migrates
5858    /// as a unit on any future axis addition.
5859    ///
5860    /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
5861    /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
5862    /// carry axis — same "one typed dispatch on the substrate primitive,
5863    /// thin projections at each consumer" discipline extended onto the
5864    /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
5865    /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
5866    /// carrier) so every downstream per-`:entrada` reader now routes
5867    /// through a typed dispatch on the substrate primitive. Returns
5868    /// `&[String]` (not `&Vec<String>`) because every downstream consumer
5869    /// treats the list as a read-only sequence — the slice-view is the
5870    /// narrowest borrow that supports every present + roadmapped consumer
5871    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
5872    /// `Vec`'s grow/push/reserve surface that no consumer of the typed
5873    /// view reaches for (the storage-side `Vec` remains reachable through
5874    /// the `pub paths` field for the mutation-carrying serde round-trip
5875    /// and per-test fixture-mutation paths).
5876    #[must_use]
5877    pub fn paths(&self) -> &[String] {
5878        self.paths.as_slice()
5879    }
5880}
5881
5882/// Canonical default L4 port every typed Servico exposes on its
5883/// in-cluster K8s Service (the `trigger.service.port` axis the
5884/// `pleme-computeunit` library chart emits, the `:entrada :port` author
5885/// surface defaults to when the author omits the slot, and the
5886/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
5887/// `:entrada` block matches the per-`:contratos` destination Servico).
5888/// The single source of truth all three typed-port consumers reach for:
5889///
5890///   - [`Entrada::port`]'s serde default (via the
5891///     [`default_port`] helper this constant feeds); the author surface
5892///     `(:entrada (:host … :para …))` without an explicit `:port` slot
5893///     reads back as a typed [`Entrada`] carrying this exact value;
5894///   - the
5895///     [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
5896///     emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
5897///     fallback, fired when the typed `:entrada` block doesn't name
5898///     the per-`:contratos` destination Servico — the typed
5899///     `:contratos` graph carries no per-destination port axis (the
5900///     destination port is the destination Servico's
5901///     `lareira-<nome>` chart's `trigger.service.port`, which the
5902///     Aplicacao-level renderer has no visibility into without a
5903///     resolver round-trip), so the renderer falls back to the
5904///     substrate's canonical Servico-port assumption — by
5905///     construction the same value the destination's own
5906///     `pleme-computeunit` chart emits, the same value the
5907///     destination's own typed `:entrada :port` slot defaults to;
5908///   - every future per-Servico renderer the absorption-roadmap
5909///     acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5910///     CR materializer's per-edge port resolver, the future
5911///     per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
5912///     emitter's per-route bucket key, the future caixa-otel
5913///     collector-pipeline emitter's per-Servico scrape port).
5914///
5915/// Until this lift landed the value `8080` lived at two production-code
5916/// call-sites: the [`default_port`] helper at
5917/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
5918/// and the `.unwrap_or(8080)` literal at
5919/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
5920/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
5921/// resolver). A future Servico-port rebrand — the substrate moving the
5922/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
5923/// gateway grows direct `:80` listeners, to `8443` once the substrate
5924/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
5925/// override the operator pins through a future
5926/// `:placement :default-port` slot — without a coordinated edit on
5927/// both sides would silently emit Servicos listening on one port and
5928/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
5929/// The CNP's apply-time symptom (the policy is admitted but every L4
5930/// flow on the destination Servico's actual port silently drops because
5931/// it doesn't match the whitelisted port) is far from the rebrand
5932/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
5933/// in hubble traces, not in `kubectl describe`. Lifting the literal to
5934/// a shared constant closes the drift footgun structurally — both
5935/// consumers read from the same `u16`, so any rebrand reaches both
5936/// sites by construction.
5937///
5938/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
5939/// per-renderer canonical-K8s-axis constant — the namespace string
5940/// and the canonical Servico port both lived as duplicated literals
5941/// across caixa-core / caixa-mesh / caixa-flux before their respective
5942/// lifts. Same "the typed constant lives in one place" discipline the
5943/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
5944/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
5945/// shared-string axes.
5946///
5947/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
5948pub const DEFAULT_SERVICO_PORT: u16 = 8080;
5949
5950/// Structural floor for the typed `:entrada :port` axis — every
5951/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
5952/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
5953///
5954/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
5955/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
5956/// interprets as "let the kernel pick a free port at bind time", not a
5957/// well-defined destination the substrate's per-`:entrada` Gateway API
5958/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
5959/// carrying `port: 0` degenerates to a nominal-only routing target: the
5960/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
5961/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
5962/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
5963/// at build time rather than at `kubectl apply` time), and the
5964/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
5965/// (caixa-mesh/src/lib.rs:2657 through
5966/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
5967/// [`Entrada::port`] typed value — silently emits a policy whose
5968/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
5969/// actual listener, dropping every L4 flow at the eBPF data plane far
5970/// from the source caixa.lisp with no field naming the port-zero-drift
5971/// root cause.
5972///
5973/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
5974/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
5975/// on the top edge (unlike the peer capped-`u32` `:politicas` /
5976/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
5977/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
5978/// well below `u32::MAX` and therefore need explicit typed caps).
5979///
5980/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
5981/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
5982/// scalar every `(:entrada (:host … :para …))` slot without an explicit
5983/// `:port` inherits through the serde default hook; this constant names
5984/// the accept-set floor every declared port must satisfy. The pair is
5985/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
5986/// substrate's default must satisfy its own accept-set floor by
5987/// construction) — a future rebrand that accidentally moved
5988/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
5989/// negative-cast typo, a per-cluster override the operator pins through
5990/// a future `:placement :default-port` slot that lands out-of-range)
5991/// would silently invalidate the serde-default emission at every
5992/// author-side `(:entrada (:host … :para …))` slot — the compile-time
5993/// invariant pin
5994/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
5995/// closes the drift footgun at caixa-core build time.
5996///
5997/// Lifted as a typed `pub const` (rather than an inline `0` literal at
5998/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
5999/// has exactly one source of truth — the future M4
6000/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
6001/// gateway resolver, the future per-Servico
6002/// `computeunit.trigger.service.port` renderer's per-CR port-value
6003/// validator, and every downstream test-fixture navigator asserting
6004/// the accept-set floor all read from one place. Same shape every
6005/// other typed bracket-floor / bracket-ceiling in this crate carries
6006/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
6007/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
6008/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
6009/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
6010/// [`POLICY_RATE_LIMIT_MAX`]).
6011pub const SERVICO_PORT_MIN: u16 = 1;
6012
6013const fn default_port() -> u16 {
6014    DEFAULT_SERVICO_PORT
6015}
6016
6017// ── the typed view ───────────────────────────────────────────────────
6018
6019/// Typed composition view of the flat Aplicacao slots on
6020/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
6021/// validation + downstream renderer consumption.
6022#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
6023#[serde(rename_all = "camelCase")]
6024pub struct AplicacaoSpec {
6025    pub membros: Vec<Membro>,
6026    pub contratos: Vec<WitContract>,
6027    pub politicas: MeshPolicy,
6028    pub placement: Placement,
6029    pub entrada: Option<Entrada>,
6030}
6031
6032impl AplicacaoSpec {
6033    /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
6034    /// per-Aplicacao member-list slice-return accessor every
6035    /// per-Aplicacao member-list reader keys off — returns the author-
6036    /// declared `:membros` list verbatim as a `&[Membro]` slice-view
6037    /// over the same backing buffer the raw `self.membros.as_slice()`
6038    /// field access borrows from.
6039    ///
6040    /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
6041    /// member list — the load-bearing identity of the application graph
6042    /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
6043    /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
6044    /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
6045    /// accessor) with a `:versao` semver-requirement string (through
6046    /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
6047    /// and every downstream consumer that fans on the member-set keys
6048    /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
6049    /// membership-lookup `HashSet<&str>` seed's collect input, the
6050    /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
6051    /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
6052    /// per-member DNS-1123 / semver-requirement / duplicate-detection
6053    /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
6054    /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
6055    /// programs.yaml per-`:membros` fan-out emitter's per-entry
6056    /// mapping-composition loop, the `feira app graph` per-Aplicacao
6057    /// member-count print line and per-member tree traversal,
6058    /// every future wasm-operator (M4) per-Aplicacao CR materializer's
6059    /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
6060    /// placement engine's per-member weight-topology reader).
6061    ///
6062    /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
6063    /// inline at six production sites — the [`AplicacaoSpec::validate`]
6064    /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
6065    /// [`AplicacaoSpec::validate_membros`]'s pre-flight
6066    /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
6067    /// probe, the same method's per-member `for m in &self.membros`
6068    /// validate-loop traversal head, the
6069    /// [`AplicacaoSpec::detect_sync_cycles`]'s
6070    /// `for m in &self.membros` adjacency-list seed, the
6071    /// [`caixa_mesh::programs_for_aplicacao`] emitter's
6072    /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
6073    /// paired with the peer `for m in &spec.membros` per-entry fan-out
6074    /// loop, and the `feira app graph` per-Aplicacao print line's
6075    /// `spec.membros.len()` count formatter argument paired with the
6076    /// peer `for m in &spec.membros` per-member tree traversal — six
6077    /// open-coded field-accesses that expressed no compile-time link
6078    /// back to the typed slot. A future extension of the `:membros`
6079    /// axis to a richer author surface (a per-cluster member-set
6080    /// overlay the operator pins through a future
6081    /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
6082    /// roadmap acknowledges, a per-tenant member-alias table the M4
6083    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
6084    /// CR at admission time, a per-Aplicacao dynamic member-set
6085    /// derivation the future adaptive-placement engine computes from
6086    /// weighted membership topology, a promotion of the plain
6087    /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
6088    /// Orleans-style virtual-actor dynamic-membership comes into typed
6089    /// scope) would have had to be threaded through all six open-coded
6090    /// copies in lockstep or one consumer would silently disagree with
6091    /// the peers on which member-set a given Aplicacao resolves to —
6092    /// the `HashSet<&str>` name-set seed reading the raw slot while
6093    /// the peer `.is_empty()` refusal probe read an operator-resolved
6094    /// slot would silently split the `:contratos` membership-lookup
6095    /// input from the pre-flight-refusal input, a six-consumer split
6096    /// at the validator + programs.yaml emitter + graph printer far
6097    /// from the source `caixa.lisp` with no field naming the member-
6098    /// set-drift root cause. Lifting the resolution rule to a typed
6099    /// method on the substrate primitive means every downstream
6100    /// consumer of the Aplicacao's per-`:membros` member-list surface
6101    /// reaches for exactly one typed dispatch — the resolver's accept-
6102    /// set migrates as a unit on any future axis addition.
6103    ///
6104    /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
6105    /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
6106    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
6107    /// static-child-list `Vec`-carry axis, and to the M3
6108    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
6109    /// on the peer per-`:placement` distribution-target-list `Vec`-
6110    /// carry axis. Same "one typed dispatch on the substrate primitive,
6111    /// thin projections at each consumer" discipline. The two peer
6112    /// `Vec`-carry axes still unlifted at the time of this lift —
6113    /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
6114    /// WIT-typed edge list) and
6115    /// [`crate::UpgradeFromEntry::instructions`]
6116    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
6117    /// — inherit this accessor's discipline as future compounding runs
6118    /// migrate their consumers onto the shared slice-return shape.
6119    /// First `&[T]`-return accessor on the top-level M3 mesh-slot
6120    /// `AplicacaoSpec` type itself, extending the discipline beyond
6121    /// the inner per-slot types ([`crate::Placement`],
6122    /// [`crate::SupervisorSpec`]) onto the outermost typed composition
6123    /// view every renderer consumes. Named `membros()` to match the
6124    /// storage field's name verbatim and the tatara-lisp author-
6125    /// surface term (`:membros`) the field's own docstring already
6126    /// carries; the accessor's identity maps onto the canonical
6127    /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
6128    /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
6129    /// every downstream consumer of the member list treats it as a
6130    /// read-only sequence — the slice-view is the narrowest borrow
6131    /// that supports every present + roadmapped consumer
6132    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
6133    /// backing `Vec`'s grow/push/reserve surface that no consumer of
6134    /// the typed view reaches for (the storage-side `Vec` remains
6135    /// reachable through the `pub membros` field for the mutation-
6136    /// carrying serde round-trip and per-test fixture-mutation paths).
6137    #[must_use]
6138    pub fn membros(&self) -> &[Membro] {
6139        self.membros.as_slice()
6140    }
6141
6142    /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
6143    /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
6144    /// accessor every per-Aplicacao contract-list reader keys off —
6145    /// returns the author-declared `:contratos` list verbatim as a
6146    /// `&[WitContract]` slice-view over the same backing buffer the raw
6147    /// `self.contratos.as_slice()` field access borrows from.
6148    ///
6149    /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
6150    /// WIT-typed edge list — the load-bearing set of directed edges
6151    /// on the application graph whose nodes are the `:membros` entries
6152    /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
6153    /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
6154    /// six-tuple is the edge identity every downstream duplicate gate
6155    /// keys off). Every per-`:contratos` entry pairs a `:de` source-
6156    /// Servico caller name + a `:para` destination-Servico callee name
6157    /// (through the lifted [`WitContract::source`] +
6158    /// [`WitContract::destination`] (7f0fd43) accessor pair on the
6159    /// caller/callee-Servico axis) with a `:wit` world-reference
6160    /// (through the lifted [`WitContract::world_ref`] (0804823)
6161    /// accessor) and the target-shape-appropriate payload-carrier
6162    /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
6163    /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
6164    /// (ed22b66) accessor on the per-target-shape payload-carrier
6165    /// axis). Every downstream consumer that fans on the edge-set
6166    /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
6167    /// name-set / self-edge / target-shape / dedup fan-out loop, the
6168    /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
6169    /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
6170    /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
6171    /// grouping loop, the `feira app graph` per-Aplicacao contract-
6172    /// count print line and per-contract tree traversal, every future
6173    /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
6174    /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
6175    /// mesh-policy overlay resolver's per-contract typed-edge weight
6176    /// reader).
6177    ///
6178    /// Prior to this lift the `.contratos` `Vec<WitContract>` was
6179    /// accessed inline at four production sites — the
6180    /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
6181    /// per-edge validate-loop traversal head (which drives every
6182    /// per-edge name-set membership lookup, self-edge check,
6183    /// target-shape dispatch, and dedup `HashSet` insert), the
6184    /// [`AplicacaoSpec::detect_sync_cycles`]'s
6185    /// `for c in &self.contratos` adjacency-list seed head (which
6186    /// drives every per-edge sync-vs-pub-sub partition and per-edge
6187    /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
6188    /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
6189    /// `BTreeMap` grouping loop head (which drives every per-CNP
6190    /// fan-out emit), and the `feira app graph` per-Aplicacao print
6191    /// line's `spec.contratos.len()` count formatter argument paired
6192    /// with the peer `for c in &spec.contratos` per-contract tree
6193    /// traversal — four open-coded field-accesses that expressed no
6194    /// compile-time link back to the typed slot. A future extension
6195    /// of the `:contratos` axis to a richer author surface (a
6196    /// per-cluster contract overlay the operator pins through a
6197    /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
6198    /// federation roadmap acknowledges, a per-tenant edge-policy
6199    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
6200    /// materializer resolves per-CR at admission time, a per-edge
6201    /// weight scalar the future adaptive-placement engine reads to
6202    /// bias sync-subgraph routing, a promotion of the plain
6203    /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
6204    /// once virtual-actor-style dynamic-edge composition comes into
6205    /// typed scope) would have had to be threaded through all four
6206    /// open-coded copies in lockstep or one consumer would silently
6207    /// disagree with the peers on which edge-set a given Aplicacao
6208    /// resolves to — the validator's per-edge dedup `HashSet` seed
6209    /// reading the raw slot while the peer sync-cycle adjacency-list
6210    /// seed read an operator-resolved slot would silently split the
6211    /// build-time edge-set gate from the runtime deadlock-detection
6212    /// gate, a four-consumer split at the validator, the cycle
6213    /// detector, the CNP emitter, and the graph printer far from
6214    /// the source `caixa.lisp` with no field naming the edge-set-
6215    /// drift root cause. Lifting the resolution rule to a typed method on the
6216    /// substrate primitive means every downstream consumer of the
6217    /// Aplicacao's per-`:contratos` edge-list surface reaches for
6218    /// exactly one typed dispatch — the resolver's accept-set
6219    /// migrates as a unit on any future axis addition.
6220    ///
6221    /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
6222    /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
6223    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
6224    /// static-child-list `Vec`-carry axis, to the M3
6225    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
6226    /// on the peer per-`:placement` distribution-target-list `Vec`-
6227    /// carry axis, and to the immediately-adjacent sibling M3
6228    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
6229    /// the peer per-`:membros` node-list `Vec`-carry axis — the
6230    /// per-`:contratos` edge-list accessor is the natural pair of
6231    /// the per-`:membros` node-list accessor (graph edges over graph
6232    /// nodes; every graph-shaped consumer reads both). Same "one
6233    /// typed dispatch on the substrate primitive, thin projections
6234    /// at each consumer" discipline. The last remaining `Vec`-carry
6235    /// axis still unlifted at the time of this lift —
6236    /// [`crate::UpgradeFromEntry::instructions`]
6237    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
6238    /// list) — inherits this accessor's discipline as future
6239    /// compounding runs migrate its consumers onto the shared slice-
6240    /// return shape. Second `&[T]`-return accessor on the top-level
6241    /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
6242    /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
6243    /// `:contratos` are the two `Vec` fields on the outer typed
6244    /// composition view — `:politicas`, `:placement`, `:entrada` are
6245    /// scalar/option-shaped and already route through their per-slot
6246    /// accessor families). Named `contratos()` to match the storage
6247    /// field's name verbatim and the tatara-lisp author-surface term
6248    /// (`:contratos`) the field's own docstring already carries; the
6249    /// accessor's identity maps onto the canonical MESH-COMPOSITION
6250    /// §III.1 vocabulary the slot's docstring already reaches for.
6251    /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
6252    /// every downstream consumer of the contract list treats it as a
6253    /// read-only sequence — the slice-view is the narrowest borrow
6254    /// that supports every present + roadmapped consumer
6255    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
6256    /// backing `Vec`'s grow/push/reserve surface that no consumer of
6257    /// the typed view reaches for (the storage-side `Vec` remains
6258    /// reachable through the `pub contratos` field for the mutation-
6259    /// carrying serde round-trip and per-test fixture-mutation paths).
6260    #[must_use]
6261    pub fn contratos(&self) -> &[WitContract] {
6262        self.contratos.as_slice()
6263    }
6264
6265    /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
6266    /// per-Aplicacao mesh-policy composite-reference accessor every
6267    /// per-Aplicacao policy-block reader keys off — returns the author-
6268    /// declared `:politicas` composite verbatim as a `&MeshPolicy`
6269    /// reference over the same backing storage the raw `&self.politicas`
6270    /// field access borrows from.
6271    ///
6272    /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
6273    /// mesh-policy composite — the load-bearing container of every
6274    /// mesh-level operational-policy axis every downstream mesh-artifact
6275    /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
6276    /// mesh-policy overlay is the single typed surface a
6277    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
6278    /// from). Every per-`:politicas` axis threads through a lifted
6279    /// per-slot accessor on the [`MeshPolicy`] type: the
6280    /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
6281    /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
6282    /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
6283    /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
6284    /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
6285    /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
6286    /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
6287    /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
6288    /// accessor. Every downstream consumer that reaches for a policy
6289    /// axis first passes through this outer accessor onto the composite
6290    /// and then dispatches onto the per-axis accessor — the two-level
6291    /// dispatch means every per-`:politicas` reader now routes through
6292    /// a typed dispatch on the substrate primitive at both altitudes.
6293    ///
6294    /// Prior to this lift the `.politicas` `MeshPolicy` composite was
6295    /// accessed inline at four production sites — the
6296    /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
6297    /// &self.politicas;` traversal seed (which drives every per-axis
6298    /// zero-floor + upper-cap + canonical-form bracket dispatch through
6299    /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
6300    /// `p.rate_limit()` on the axis-level lifted accessors), the
6301    /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
6302    /// emitter's `spec.politicas.mtls_required()` field-then-accessor
6303    /// chain (which drives every per-`(:de, :para)` CNP
6304    /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
6305    /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
6306    /// timeout + retry overlay emitter's paired
6307    /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
6308    /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
6309    /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
6310    /// open-coded outer-field accesses that expressed no compile-time
6311    /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
6312    /// future extension of the `:politicas` outer axis to a richer
6313    /// author surface (a per-cluster policy overlay the operator pins
6314    /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
6315    /// §V federation roadmap acknowledges, a per-tenant policy-alias
6316    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
6317    /// resolves per-CR at admission time, a per-Aplicacao dynamic
6318    /// policy-composite derivation the future adaptive-placement engine
6319    /// computes from a per-cluster load-topology reader, a promotion of
6320    /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
6321    /// partition once virtual-actor-style dynamic-mesh-policy
6322    /// composition comes into typed scope) would have had to be threaded
6323    /// through all four open-coded copies in lockstep or one consumer
6324    /// would silently disagree with the peers on which mesh-policy
6325    /// composite a given Aplicacao resolves to — the validator's
6326    /// per-axis bracket-dispatch seed reading the raw slot while the
6327    /// peer CNP mTLS-overlay emitter read an operator-resolved slot
6328    /// would silently split the build-time policy-shape gate from the
6329    /// runtime CNP-emission gate, a four-consumer split at the
6330    /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
6331    /// the source `caixa.lisp` with no field naming the policy-drift
6332    /// root cause. Lifting the resolution rule to a typed method on the
6333    /// substrate primitive means every downstream consumer of the
6334    /// Aplicacao's per-`:politicas` mesh-policy composite surface
6335    /// reaches for exactly one typed dispatch — the resolver's accept-
6336    /// set migrates as a unit on any future axis addition.
6337    ///
6338    /// First `&Composite`-return accessor on the top-level M3 mesh-slot
6339    /// `AplicacaoSpec` type itself — sibling to the seed slice-return
6340    /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
6341    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
6342    /// close the two `Vec`-carry axes on the outer typed composition
6343    /// view; the outer `:politicas` composite-reference axis is the
6344    /// natural pair to the paired outer `Vec`-carry accessors on the
6345    /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
6346    /// emitter reads all four axes as one unit (graph nodes + graph
6347    /// edges + mesh policy + placement pool). Peer to the same
6348    /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
6349    /// slot: every M2 `SupervisorSpec`-scoped composite reader
6350    /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
6351    /// `restart_window`, `children`) already routes through the M2
6352    /// `SupervisorSpec` accessor family — this lift extends the same
6353    /// "one typed dispatch on the substrate primitive at the outer
6354    /// composition altitude" discipline to the M3 mesh-slot
6355    /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
6356    /// remaining peer outer-composite axes still unlifted at the time
6357    /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
6358    /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
6359    /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
6360    /// inherit this accessor's discipline as future compounding runs
6361    /// migrate their consumers onto the shared reference-return shape.
6362    /// Named `politicas()` to match the storage field's name verbatim
6363    /// and the tatara-lisp author-surface term (`:politicas`) the
6364    /// field's own docstring already carries; the accessor's identity
6365    /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
6366    /// slot's docstring already reaches for. Returns `&MeshPolicy`
6367    /// (not the owning composite by copy or clone) because every
6368    /// downstream consumer of the mesh-policy composite treats it as a
6369    /// read-only per-axis dispatch source — the reference-view is the
6370    /// narrowest borrow that supports every present + roadmapped
6371    /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
6372    /// emptiness probe) without cloning the composite through every
6373    /// consumer's fast path.
6374    #[must_use]
6375    pub fn politicas(&self) -> &MeshPolicy {
6376        &self.politicas
6377    }
6378
6379    /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
6380    /// per-Aplicacao distribution-composite composite-reference accessor
6381    /// every per-Aplicacao placement-block reader keys off — returns the
6382    /// author-declared `:placement` composite verbatim as a `&Placement`
6383    /// reference over the same backing storage the raw `&self.placement`
6384    /// field access borrows from.
6385    ///
6386    /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
6387    /// distribution composite — the load-bearing container of every
6388    /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
6389    /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
6390    /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
6391    /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
6392    /// hosting-pool identity, §V for the `M3-Adaptive`-compression
6393    /// `:affinity` hint). Every per-`:placement` axis threads through a
6394    /// lifted per-slot accessor on the [`Placement`] type: the
6395    /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
6396    /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
6397    /// per-cluster distribution-target slice-return accessor, the
6398    /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
6399    /// optional-scalar accessor, and the [`Placement::shard_key`]
6400    /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
6401    /// downstream consumer that reaches for a placement axis first passes
6402    /// through this outer accessor onto the composite and then dispatches
6403    /// onto the per-axis accessor — the two-level dispatch means every
6404    /// per-`:placement` reader now routes through a typed dispatch on the
6405    /// substrate primitive at both altitudes.
6406    ///
6407    /// Prior to this lift the `.placement` `Placement` composite was
6408    /// accessed inline at three production sites — the
6409    /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
6410    /// seed (six `self.placement.<axis>()` field-then-inner-accessor
6411    /// chains: the pre-flight `.clusters().is_empty()` refusal probe
6412    /// paired with the `.estrategia()` diagnostic-carry copy, the per-
6413    /// cluster `.clusters()` validate-loop traversal head, the per-
6414    /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
6415    /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
6416    /// paired with the shape-gate cascade's `.shard_key()` /
6417    /// `.estrategia()` diagnostic-carry pair), the
6418    /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
6419    /// per-entry placement-block emitter's outer
6420    /// `serde_yaml::to_value(&spec.placement)` composite-serialization
6421    /// seed (which fans onto every per-cluster `programs[]` entry as a
6422    /// self-describing distribution overlay the aggregator filters by),
6423    /// and the `feira app graph` per-Aplicacao print line's paired
6424    /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
6425    /// then-inner-accessor chains (which drive the human-readable
6426    /// distribution summary of the typed Aplicacao view) — three open-
6427    /// coded outer-field accesses that expressed no compile-time link
6428    /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
6429    /// extension of the `:placement` outer axis to a richer author surface
6430    /// (a per-cluster placement overlay the operator pins through a
6431    /// future `:placement-overrides` slot the MESH-COMPOSITION §V
6432    /// federation roadmap acknowledges, a per-tenant placement-alias
6433    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
6434    /// resolves per-CR at admission time, a per-Aplicacao dynamic
6435    /// placement-composite derivation the future M5 adaptive-placement
6436    /// engine computes from a per-cluster load-topology reader, a
6437    /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
6438    /// partition once Orleans-style virtual-actor dynamic-placement comes
6439    /// into typed scope) would have had to be threaded through all three
6440    /// open-coded copies in lockstep or one consumer would silently
6441    /// disagree with the peers on which placement composite a given
6442    /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
6443    /// seed reading the raw slot while the peer
6444    /// `programs_for_aplicacao` emitter read an operator-resolved slot
6445    /// would silently split the build-time distribution-shape gate from
6446    /// the runtime programs.yaml distribution-annotation gate, a three-
6447    /// consumer split at the validator, the programs.yaml emitter, and
6448    /// the `feira app graph` printer far from the source `caixa.lisp`
6449    /// with no field naming the placement-drift root cause. Lifting the
6450    /// resolution rule to a typed method on the substrate primitive
6451    /// means every downstream consumer of the Aplicacao's per-
6452    /// `:placement` distribution composite surface reaches for exactly
6453    /// one typed dispatch — the resolver's accept-set migrates as a unit
6454    /// on any future axis addition.
6455    ///
6456    /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
6457    /// `AplicacaoSpec` type itself — sibling to the seed
6458    /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
6459    /// composite-reference accessor on the peer per-`:politicas` outer-
6460    /// composite axis, and to the paired slice-return accessors
6461    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
6462    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
6463    /// the two `Vec`-carry axes on the outer typed composition view; the
6464    /// outer `:placement` composite-reference axis is the natural pair
6465    /// to the peer `:politicas` composite-reference axis on the two
6466    /// operationally-symmetric M3 mesh slots (`:politicas` carries the
6467    /// how-to-run policy overlay, `:placement` carries the where-to-run
6468    /// distribution composite — every whole-Aplicacao mesh-artifact
6469    /// emitter reads both as one unit). Same "one typed dispatch on the
6470    /// substrate primitive, thin projections at each consumer"
6471    /// discipline the peer per-`:politicas` composite-reference axis
6472    /// already routes through. The one remaining outer-composite axis
6473    /// still unlifted at the time of this lift —
6474    /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
6475    /// external-gateway composite) — inherits this accessor's discipline
6476    /// as the next compounding run migrates its consumers onto the shared
6477    /// reference-return shape, closing the outer-composite altitude on
6478    /// every M3 mesh-slot axis. Named `placement()` to match the storage
6479    /// field's name verbatim and the tatara-lisp author-surface term
6480    /// (`:placement`) the field's own docstring already carries; the
6481    /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
6482    /// vocabulary the slot's docstring already reaches for. Returns
6483    /// `&Placement` (not the owning composite by copy or clone) because
6484    /// every downstream consumer of the placement composite treats it as
6485    /// a read-only per-axis dispatch source — the reference-view is the
6486    /// narrowest borrow that supports every present + roadmapped consumer
6487    /// (per-axis accessor dispatch, serde composite-serialization) without
6488    /// cloning the composite through every consumer's fast path.
6489    #[must_use]
6490    pub fn placement(&self) -> &Placement {
6491        &self.placement
6492    }
6493
6494    /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
6495    /// per-Aplicacao external-gateway composite optional-composite-
6496    /// reference accessor every per-Aplicacao gateway-block reader
6497    /// keys off — returns the author-declared `:entrada` composite
6498    /// verbatim as an `Option<&Entrada>` reference over the same
6499    /// backing storage the raw `self.entrada.as_ref()` field access
6500    /// borrows from, with `None` naming the internal-only mesh shape
6501    /// (the author-omitted `:entrada` slot the K8s Gateway API v1
6502    /// gateway_routes emitter treats as "emit nothing" and the peer
6503    /// `feira app graph` printer treats as "internal-only mesh").
6504    ///
6505    /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
6506    /// external-gateway composite — the load-bearing container of
6507    /// every does-this-Aplicacao-expose-a-public-endpoint axis every
6508    /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
6509    /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
6510    /// hostname axis, §III.4 for the `:para` destination-Servico
6511    /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
6512    /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
6513    /// axis threads through a lifted per-slot accessor on the
6514    /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
6515    /// Gateway-API `Listener.hostname` scalar accessor, the paired
6516    /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
6517    /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
6518    /// backendRefs destination-Servico scalar accessor, the
6519    /// [`Entrada::resolved_paths`] path-fallback resolver, and the
6520    /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
6521    /// scalar accessor. Every downstream consumer that reaches for
6522    /// an entrada axis first passes through this outer accessor onto
6523    /// the composite and then dispatches onto the per-axis accessor
6524    /// — the two-level dispatch means every per-`:entrada` reader
6525    /// now routes through a typed dispatch on the substrate primitive
6526    /// at both altitudes.
6527    ///
6528    /// Prior to this lift the `.entrada` `Option<Entrada>` composite
6529    /// was accessed inline at four production sites — the
6530    /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
6531    /// gate's `if let Some(e) = &self.entrada { … }` traversal head
6532    /// (which drives every per-axis refusal on the composite: the
6533    /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
6534    /// `EntradaMemberMissing` membership lookup against the
6535    /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
6536    /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
6537    /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
6538    /// per-path shape gate on each entry of `e.paths`), the
6539    /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
6540    /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
6541    /// composite-projection seed (which drives the destination-
6542    /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
6543    /// backendRefs port emitter fans on), the
6544    /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
6545    /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
6546    /// early-return seed (which drives the "no `:entrada` ⇒ no
6547    /// external artifacts" partition on the whole-Aplicacao Gateway-
6548    /// API emitter's fan-out), and the `feira app graph` per-
6549    /// Aplicacao print line's `if let Some(e) = &spec.entrada`
6550    /// external-gateway summary emitter (which drives the human-
6551    /// readable `entrada: host → para (paths=…, port=…)` /
6552    /// `entrada: (internal-only mesh)` partition on the typed
6553    /// Aplicacao view) — four open-coded outer-field accesses that
6554    /// expressed no compile-time link back to the typed slot at the
6555    /// [`AplicacaoSpec`] altitude. A future extension of the
6556    /// `:entrada` outer axis to a richer author surface (a
6557    /// multi-`:entrada` list the M4 CR materializer resolves per-CR
6558    /// at admission time so an Aplicacao can expose a public-web +
6559    /// admin-web pair, a per-cluster `:entrada-overrides` slot the
6560    /// MESH-COMPOSITION §V federation roadmap acknowledges so an
6561    /// operator can pin a per-cluster hostname override without
6562    /// re-authoring the `caixa.lisp`, a promotion of the plain
6563    /// `Option<Entrada>` to a richer `{single, multi}` partition once
6564    /// the multi-`:entrada` roadmap lands) would have had to be
6565    /// threaded through all four open-coded copies in lockstep or one
6566    /// consumer would silently disagree with the peers on which
6567    /// entrada composite a given Aplicacao resolves to — the
6568    /// validator's per-axis bracket-dispatch seed reading the raw
6569    /// slot while the peer `gateway_routes` emitter read an
6570    /// operator-resolved slot would silently split the build-time
6571    /// gateway-shape gate from the runtime Gateway + HTTPRoute
6572    /// emission gate, a four-consumer split at the validator, the
6573    /// `port_for_destination` L4-port resolver, the `gateway_routes`
6574    /// emitter, and the `feira app graph` printer far from the
6575    /// source `caixa.lisp` with no field naming the entrada-drift
6576    /// root cause. Lifting the resolution rule to a typed method on
6577    /// the substrate primitive means every downstream consumer of
6578    /// the Aplicacao's per-`:entrada` external-gateway composite
6579    /// surface reaches for exactly one typed dispatch — the
6580    /// resolver's accept-set migrates as a unit on any future axis
6581    /// addition.
6582    ///
6583    /// Third and final `&Composite`-return accessor on the top-level
6584    /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
6585    /// unlifted outer-composite axis on the outer typed composition
6586    /// view, sibling to the seed [`AplicacaoSpec::politicas`]
6587    /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
6588    /// accessor on the per-`:politicas` outer-composite axis and to
6589    /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
6590    /// distribution-composite composite-reference accessor on the
6591    /// per-`:placement` outer-composite axis; extends the outer-
6592    /// composite reference-return discipline the two peers already
6593    /// route through onto the last unlifted per-`AplicacaoSpec`
6594    /// outer-composite axis. The `:entrada` outer-composite axis is
6595    /// the natural pair to the two peer outer-composite axes on the
6596    /// three operationally-symmetric M3 mesh-slot outer composites
6597    /// (`:politicas` carries the how-to-run policy overlay,
6598    /// `:placement` carries the where-to-run distribution composite,
6599    /// `:entrada` carries the who-can-reach-it external-gateway
6600    /// composite — every whole-Aplicacao mesh-artifact emitter reads
6601    /// all three as one unit). Same "one typed dispatch on the
6602    /// substrate primitive, thin projections at each consumer"
6603    /// discipline the peer outer-composite axes already route through.
6604    /// Named `entrada()` to match the storage field's name verbatim
6605    /// and the tatara-lisp author-surface term (`:entrada`) the
6606    /// field's own docstring already carries; the accessor's
6607    /// identity maps onto the canonical MESH-COMPOSITION §III.4
6608    /// vocabulary the slot's docstring already reaches for. Returns
6609    /// `Option<&Entrada>` (not the owning composite by copy or
6610    /// clone) because every downstream consumer of the entrada
6611    /// composite treats it as a read-only per-axis dispatch source
6612    /// — the reference-view is the narrowest borrow that supports
6613    /// every present + roadmapped consumer (per-axis accessor
6614    /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
6615    /// port-fallback projection, early-return partition on the
6616    /// `None` arm) without cloning the composite through every
6617    /// consumer's fast path. The `Option` half of the return-type
6618    /// preserves the load-bearing "author-omitted `:entrada` ⇒
6619    /// internal-only mesh" partition (not a default composite the
6620    /// downstream must reject on emptiness) — the accessor projects
6621    /// the raw `Option<Entrada>` slot's presence bit through the
6622    /// reference-return unchanged.
6623    #[must_use]
6624    pub fn entrada(&self) -> Option<&Entrada> {
6625        self.entrada.as_ref()
6626    }
6627
6628    /// Validate the typed shape:
6629    ///   - `:membros` is non-empty; every entry has a non-empty `:caixa`
6630    ///     and a non-empty `:versao`; no two entries share the same
6631    ///     `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
6632    ///     not a multiset)
6633    ///   - every `:contratos` :de + :para must be in `:membros`
6634    ///   - no `:contratos` edge is a self-edge (`:de == :para`) — a
6635    ///     contract is an inter-Servico edge, so a Servico contracting
6636    ///     with itself is a build error under every WIT shape
6637    ///     (MESH-COMPOSITION §III.1)
6638    ///   - no two `:contratos` entries agree on
6639    ///     `(de, para, wit, endpoint, subject, slot)` — the typed-graph
6640    ///     edges are a set, not a multiset (peer of the `:membros` /
6641    ///     `:placement :clusters` / `:entrada :paths` duplicate gates)
6642    ///   - `:entrada :para` must be in `:membros`
6643    ///   - `:placement Sharded` must declare `:shard-key` (non-empty);
6644    ///     `:placement Replicated`/`SingleNode` must NOT declare
6645    ///     `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
6646    ///     consumes it (MESH-COMPOSITION §II.4), and the typed partition
6647    ///     between strategy and shard-key is symmetric: every validated
6648    ///     `Placement` has `shard_key.is_some()` iff `estrategia ==
6649    ///     Sharded`
6650    ///   - every `:placement` strategy must declare ≥1 `:clusters` entry —
6651    ///     `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
6652    ///     the shard pool (MESH-COMPOSITION §III.1)
6653    ///   - every `:clusters` entry is non-empty and unique
6654    ///   - `:placement :affinity`, when set, is non-empty
6655    ///   - the synchronous-`:contratos` subgraph is acyclic
6656    ///     (MESH-COMPOSITION §III.3)
6657    ///   - every declared `:politicas` value is operationally meaningful
6658    ///     (zero timeout, zero retries, zero breaker thresholds, zero rate
6659    ///     limit are all build errors — MESH-COMPOSITION §V CSE invariants;
6660    ///     omit the field instead to express "no policy on this axis")
6661    pub fn validate(&self) -> Result<(), AplicacaoError> {
6662        self.validate_membros()?;
6663        let names: std::collections::HashSet<&str> =
6664            self.membros().iter().map(Membro::nome).collect();
6665
6666        // Identity key for the typed-edge duplicate gate below: every
6667        // field that distinguishes one contract from another. Two
6668        // entries that agree on all six are *the same edge declared
6669        // twice*, the typed-graph analogue of duplicate `:membros` /
6670        // `:placement :clusters` / `:entrada :paths` entries (which
6671        // are already build errors at this layer). Rejecting it at the
6672        // validate gate closes a renderer-side footgun: caixa-mesh's
6673        // `cilium_network_policies` keys each emitted policy by
6674        // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
6675        // (de, para) and identical payload would land as two K8s
6676        // objects with colliding `metadata.name`, rejected at apply
6677        // time far from the source caixa.lisp.
6678        let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
6679            std::collections::HashSet::new();
6680        for c in self.contratos() {
6681            // Per-axis value-shape gate on every `:contratos` name
6682            // reference, before any graph-membership lookup. Empty +
6683            // DNS-1123-malformed `:de`/`:para` values silently fell
6684            // through to `ContratoMemberMissing` at the lookup arm
6685            // because every `:membros :caixa` is shape-validated
6686            // (3f9d7a0), so the `names` set structurally cannot contain
6687            // an empty / malformed string and the membership-lookup
6688            // diagnostic always misframed the root cause as
6689            // "this caixa is not in `:membros`". The shape gate runs
6690            // ahead of the lookup so structurally-impossible-to-match
6691            // inputs route through the narrower self-locating
6692            // diagnostic, preserving the legitimate "well-shaped
6693            // phantom reference" arm. `:de` runs before `:para` per
6694            // the canonical edge-direction order the existing
6695            // membership lookup, self-edge check, target dispatch,
6696            // and diagnostic strings already use.
6697            // Route the per-`:contratos` per-arm DNS-1123 shape-gate arg
6698            // + the paired [`AplicacaoError::ContratoMemberMissing`]
6699            // diagnostic's `caixa:` carrier through the lifted
6700            // [`WitContract::source`] / [`WitContract::destination`]
6701            // scalar accessors rather than the raw `&c.de` / `&c.para`
6702            // `&String`-borrow arg site + the raw `c.de.clone()` /
6703            // `c.para.clone()` field-access `String`-carry sites — the
6704            // last unlifted per-`:contratos` raw-field-access sites in
6705            // the M3 mesh-slot validator's per-edge per-arm shape-gate
6706            // arg + phantom-name diagnostic wrap-envelope emit surface.
6707            // `c.source()` is byte-identical to `&c.de` (pinned by the
6708            // sibling `wit_contract_source_returns_de_byte_equal_across_permutations`
6709            // + `wit_contract_source_borrows_from_de_storage` accessor
6710            // tests) and `c.destination()` is byte-identical to `&c.para`
6711            // (pinned by the sibling
6712            // `wit_contract_destination_returns_para_byte_equal_across_permutations`
6713            // + `wit_contract_destination_borrows_from_para_storage`
6714            // accessor tests) — so a future rebrand of either underlying
6715            // storage flows through the accessor's one body without a
6716            // coordinated per-consumer rewrite across the M3 mesh
6717            // validator's per-edge shape-gate + phantom-name refusal
6718            // arms. Peer of the sibling per-`:contratos` self-loop
6719            // arm's `.source().to_string()` / `.world_ref().to_string()`
6720            // `String`-carry sites the earlier convergence lifted onto
6721            // the same accessor pair.
6722            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
6723            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
6724            if !names.contains(c.source()) {
6725                return Err(AplicacaoError::ContratoMemberMissing {
6726                    caixa: c.source().to_string(),
6727                });
6728            }
6729            if !names.contains(c.destination()) {
6730                return Err(AplicacaoError::ContratoMemberMissing {
6731                    caixa: c.destination().to_string(),
6732                });
6733            }
6734            // A `:contratos` entry is an *inter*-Servico contract
6735            // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
6736            // typed edge between two distinct graph nodes. An edge whose
6737            // `:de` equals its `:para` is a Servico contracting with
6738            // itself — a degenerate edge under every WIT shape. The
6739            // synchronous shapes were caught only incidentally, and with
6740            // a misleading diagnostic: `detect_sync_cycles` reported
6741            // `cart → cart` as a `ContratoCycle` whose path is
6742            // `["cart", "cart"]` — framing a self-edge as a multi-node
6743            // deadlock. The pub-sub shape slipped through entirely
6744            // (`detect_sync_cycles` excludes `WitTarget::PubSub`, so a
6745            // `nats:pub-sub` edge from a member to itself silently
6746            // validated, then rendered a `CiliumNetworkPolicy` whose
6747            // endpointSelector and fromEndpoints both name the same
6748            // program — a self-allow rule that is a no-op, since
6749            // intra-pod traffic never traverses the mesh). A self-edge's
6750            // runtime meaning is an in-process call, which doesn't go
6751            // through the mesh at all, so no `:contratos` edge can carry
6752            // it. Firing the gate before the `:wit`/`target()` shape
6753            // checks means the structural "this edge can't exist" error
6754            // precedes the narrower payload-shape diagnostics, and shape-
6755            // agnostically covers all four `WitTarget` arms (HTTP / Store
6756            // / Capability / PubSub) at one point — closing the pub-sub
6757            // hole and replacing the misleading cycle diagnostic in one
6758            // gate. Peer of the duplicate-`:contratos` / duplicate-
6759            // `:membros` set gates: both reject a structurally
6760            // ill-formed graph at the typed surface, before the renderer
6761            // emits a K8s object that fails or no-ops far from the source
6762            // caixa.lisp.
6763            // Route the per-`:contratos` structural self-edge probe
6764            // through the lifted [`WitContract::is_self_loop`] typed
6765            // predicate rather than the raw `c.de == c.para` field-
6766            // equality check — the one production consumer of the per-
6767            // `:contratos` caller-equals-callee endpoint-equality axis
6768            // now keys off exactly one typed dispatch on the substrate
6769            // primitive, so any future rebrand of the axis (an M4-typed-
6770            // caller enum whose identity comparison rule the predicate
6771            // could route through, a per-cluster caller/callee-alias
6772            // table the M4 CR materializer resolves per-CR before the
6773            // equality probe) migrates as a single caixa-core edit
6774            // rather than a coordinated rewrite of the gate + every
6775            // downstream self-edge consumer. Peer of the sibling
6776            // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
6777            // [`WitContract::is_store`] shape-predicate routing on the
6778            // `:wit` world-ref axis, extended onto the per-edge
6779            // endpoint-equality axis.
6780            //
6781            // Route the paired [`AplicacaoError::ContratoSelfLoop`]
6782            // diagnostic's `caixa:` / `wit:` carriers through the
6783            // lifted [`WitContract::source`] / [`WitContract::world_ref`]
6784            // scalar accessors rather than the raw `c.de.clone()` /
6785            // `c.wit.clone()` field-access `String`-carry sites — the
6786            // last unlifted per-`:contratos` raw-field-access
6787            // `.clone()` sites in the M3 mesh-slot validator's self-
6788            // edge refusal arm. `.source().to_string()` is byte-
6789            // identical to `.de.clone()` (pinned by the sibling
6790            // `source_returns_de_byte_equal_across_permutations` accessor
6791            // test), and `.world_ref().to_string()` is byte-identical
6792            // to `.wit.clone()` (pinned by the sibling
6793            // `world_ref_returns_wit_byte_equal_across_permutations`
6794            // accessor test) — so a future rebrand of either underlying
6795            // storage flows through the accessor's one body without a
6796            // coordinated per-consumer rewrite across the M3 mesh
6797            // validator.
6798            if c.is_self_loop() {
6799                return Err(AplicacaoError::ContratoSelfLoop {
6800                    caixa: c.source().to_string(),
6801                    wit: c.world_ref().to_string(),
6802                });
6803            }
6804            if c.world_ref().is_empty() {
6805                let (de, para) = c.edge_pair();
6806                return Err(AplicacaoError::EmptyWit { de, para });
6807            }
6808            // Shape ↔ target consistency — surfaces "HTTP wit without
6809            // :endpoint", "NATS wit with :endpoint set", etc. as named
6810            // build errors instead of silent renderer drops. Threaded
6811            // through the duplicate-edge diagnostic below (via
6812            // [`WitTarget::label`]) so the "which typed target arm did
6813            // the duplicate carry" question is answered by the typed
6814            // enum's variant discriminator, not by re-probing the raw
6815            // `Option<String>` payload fields.
6816            let target_view = c.target()?;
6817            // Contract identity: (de, para, wit, endpoint, subject, slot).
6818            // Two contracts that match on all six are the same typed edge
6819            // declared twice — author error, not a legitimate variant of
6820            // "same caller-callee pair, different payload" (e.g.
6821            // cart→catalog at /products vs /search), which keeps distinct
6822            // identity keys via the differing endpoint payloads.
6823            //
6824            // Route the six-axis dedup key through the lifted
6825            // [`WitContract::identity`] composite-projection accessor
6826            // rather than the inline six-tuple builder — the two
6827            // substrate primitives on the per-`:contratos` identity axis
6828            // (the [`ContratoIdentity`] type alias's six axes, this
6829            // dedup-key's six tuple arms) now migrate as a unit on any
6830            // future axis addition. Peer of the sibling per-`:contratos`
6831            // composite-projection [`WitContract::edge_pair`] /
6832            // [`WitContract::edge_triple`] accessors on the
6833            // caller-callee / caller-callee-wit prefix axes; extends
6834            // the discipline onto the full-identity axis that carries
6835            // the three payload-shape arms too.
6836            let key = c.identity();
6837            crate::render::insert_first_seen(&mut seen_contracts, key, || {
6838                // Route the per-`:contratos` duplicate-gate diagnostic's
6839                // `(de, para, wit)` triple through the lifted
6840                // [`WitContract::edge_triple`] typed accessor rather
6841                // than pairing `edge_pair()` for the `(de, para)` prefix
6842                // with a raw `c.wit.clone()` for the `wit:` tail — the
6843                // paired-with-raw-field-access shape was the last
6844                // per-`:contratos` diagnostic constructor bypassing the
6845                // substrate-primitive composite projection, sibling to
6846                // the eight [`AplicacaoError::Contrato*`] triple-
6847                // carrying constructors [`WitContract::target`]'s edge
6848                // closure feeds through the same accessor.
6849                let (de, para, wit) = c.edge_triple();
6850                AplicacaoError::ContratoDuplicate {
6851                    de,
6852                    para,
6853                    wit,
6854                    target: target_view.label(),
6855                }
6856            })?;
6857        }
6858
6859        // Cycles in the synchronous-edge subgraph are build errors
6860        // (MESH-COMPOSITION §III.3). Pub-sub edges are excluded — they
6861        // are "acyclic by construction" because the publisher fires
6862        // and forgets, so no caller blocks on a downstream that loops
6863        // back to it.
6864        self.detect_sync_cycles()?;
6865
6866        if let Some(e) = self.entrada() {
6867            // Route the per-`:entrada` composite-reference read
6868            // through the lifted [`AplicacaoSpec::entrada`] accessor
6869            // rather than the raw `&self.entrada` field access — the
6870            // shape-and-membership gate's traversal head is now the
6871            // canonical read-side surface every per-Aplicacao entrada
6872            // consumer routes through, closing the fourth of four
6873            // open-coded outer-field accesses on the per-`:entrada`
6874            // outer-composite axis.
6875            //
6876            // Shape gate on `:entrada :para` runs ahead of the
6877            // membership lookup. Every `:membros :caixa` past
6878            // `validate_membro_caixa` is a valid DNS-1123 label
6879            // (3f9d7a0), so the `names` set structurally cannot
6880            // contain an empty / malformed string and the membership-
6881            // lookup diagnostic always misframed the root cause as
6882            // "this caixa is not in `:membros`". The shape gate
6883            // routes structurally-impossible-to-match inputs through
6884            // the narrower self-locating diagnostic, preserving the
6885            // legitimate "well-shaped phantom reference" arm — the
6886            // same trajectory the peer `:membros :caixa` (3f9d7a0),
6887            // `:placement :clusters` (6c8c00b), and `:contratos :de`
6888            // / `:para` (8d5af6b) axes already follow. This closes
6889            // the fourth and last Aplicacao-level Servico-name
6890            // reference axis on the canonical DNS-1123 floor.
6891            // Route the per-`:entrada :para` byte-string reads through
6892            // the lifted [`Entrada::destination`] accessor rather than
6893            // the raw `e.para` field access — the three
6894            // per-`AplicacaoSpec::validate` `:entrada :para` consumers
6895            // (shape-gate `validate_entrada_para` arg, membership
6896            // lookup, `EntradaMemberMissing` diagnostic carry) now key
6897            // off exactly one typed dispatch on the substrate
6898            // primitive, closing the last unlifted per-`:entrada :para`
6899            // raw-field-access axis on the M3 mesh-slot validator.
6900            // The `.destination().to_string()` at the diagnostic site
6901            // is byte-identical to `.para.clone()` — pinned by the
6902            // sibling `destination_returns_entrada_para_byte_equal` +
6903            // `destination_borrows_from_entrada_para_storage` accessor
6904            // tests — so a future rebrand of the underlying `:para`
6905            // storage (a lift from `String` to a typed
6906            // `ServicoName(String)` newtype, a per-Aplicacao interning
6907            // arena the M4 CR materializer authors, a
6908            // `smol_str::SmolStr` inline-buffer swap) flows through
6909            // the accessor's one body without a coordinated
6910            // per-consumer rewrite across the M3 mesh validator.
6911            validate_entrada_para(e.destination())?;
6912            if !names.contains(e.destination()) {
6913                return Err(AplicacaoError::EntradaMemberMissing {
6914                    para: e.destination().to_string(),
6915                });
6916            }
6917            // Route the per-`:entrada :host` byte-string reads through
6918            // the lifted [`Entrada::hostname`] accessor rather than
6919            // the raw `e.host` field access — the emptiness gate and
6920            // the shape-gate `validate_entrada_host` arg now key off
6921            // exactly one typed dispatch on the substrate primitive,
6922            // closing the last unlifted per-`:entrada :host` raw-
6923            // field-access axis on the M3 mesh-slot validator. Peer
6924            // of the sibling per-`:entrada :para` convergence above
6925            // and pinned by the existing
6926            // `hostname_returns_entrada_host_byte_equal` +
6927            // `hostnames_returns_singleton_of_hostname_accessor`
6928            // accessor tests, so any future
6929            // Gateway-API-shaped host renormalization (a wildcard-
6930            // label lift, a trailing-`.` FQDN substitution, an IDNA
6931            // Punycode round-trip the SNI fan-out overlay authors)
6932            // flows through the accessor's one body without a
6933            // coordinated per-consumer rewrite across the M3 mesh
6934            // validator.
6935            if e.hostname().is_empty() {
6936                return Err(AplicacaoError::EmptyEntradaHost);
6937            }
6938            // The `:host` lands verbatim as a K8s Gateway API v1
6939            // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
6940            // both apiserver-validated against the same restrictive
6941            // pattern: lowercase RFC 1123 DNS subdomain, optional
6942            // single leading wildcard label (`*.`), max length 253,
6943            // per-label max length 63, no IP literals, no scheme,
6944            // no port. Until this gate landed `validate()` only
6945            // refused the empty string (`EmptyEntradaHost`); a
6946            // structurally invalid hostname (`"https://example.com"`,
6947            // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
6948            // `"_underscored.example.com"`, `"FOO.example.com"`,
6949            // `"checkout.quero.cloud."`) silently passed validate
6950            // and the apiserver `field is invalid` error surfaced at
6951            // `kubectl apply` time, far from the source caixa.lisp.
6952            // Lifting the gate to caixa-build time mirrors the
6953            // `:entrada :paths` value-shape trajectory (eb3456d) and
6954            // closes the last unstructured `:entrada` axis.
6955            validate_entrada_host(e.hostname())?;
6956            // Structural-floor gate on `:entrada :port`: every
6957            // validated `Entrada::port` past this gate lies in
6958            // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
6959            // type-inferred ceiling closes the top edge, so no companion
6960            // upper-cap arm is needed here — unlike the peer capped-
6961            // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
6962            // `require_positive_bounded_u32` bracket covers both edges).
6963            // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
6964            // accept-set-floor const rather than the prior inline
6965            // `if e.port == 0` byte-check so a future rebrand of the
6966            // accept-set floor (a hypothetical unprivileged-only
6967            // migration lifting the floor to `1024`, a per-cluster
6968            // scoping the operator pins through a future
6969            // `:placement :port-floor` slot as the M4 typed-slot
6970            // trajectory adds it, the future
6971            // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6972            // per-Aplicacao gateway resolver reaching for the same
6973            // floor) is a one-line edit on the canonical
6974            // [`SERVICO_PORT_MIN`] declaration, not a coordinated
6975            // rewrite across the emit site + the pin test + every
6976            // future per-target renderer the substrate adds.
6977            if e.port() < SERVICO_PORT_MIN {
6978                return Err(AplicacaoError::EntradaPortZero);
6979            }
6980            // Each `:entrada :paths` entry becomes a K8s Gateway API
6981            // HTTPRoute `matches[].path.value`. The Gateway API rejects
6982            // values that don't start with `/` for `type: PathPrefix`,
6983            // and an empty value is meaningless. Surface those as build
6984            // errors (MESH-COMPOSITION §III.3) rather than apply-time
6985            // failures. Empty `:paths` itself is fine — caixa-mesh
6986            // falls back to a single `/` catch-all.
6987            let mut seen = std::collections::HashSet::new();
6988            // Route the per-entry value-shape gate's traversal head
6989            // through the lifted [`Entrada::paths`] slice accessor
6990            // rather than the raw `&e.paths` field access — the
6991            // per-Aplicacao `:entrada :paths` validate loop now keys
6992            // off the canonical raw-slot surface every downstream
6993            // per-`:entrada` path-list consumer (the sibling
6994            // [`Entrada::resolved_paths`] fallback-applying resolver
6995            // internal reads, `feira app graph`'s per-Aplicacao entrada
6996            // summary line's `{:?}` Debug print) routes through, so any
6997            // future rebrand on the typed slot's raw-slot reader lands
6998            // at exactly one place. Same convergence discipline as the
6999            // sibling [`Placement::clusters`] (a6e18d7) reader-site
7000            // convergences on the peer M3 mesh-slot `Vec<String>`-carry
7001            // axis.
7002            for p in e.paths() {
7003                if p.is_empty() {
7004                    return Err(AplicacaoError::EntradaPathEmpty);
7005                }
7006                if !p.starts_with('/') {
7007                    return Err(AplicacaoError::EntradaPathNotAbsolute { path: p.clone() });
7008                }
7009                // Per-entry value-shape gate: the path lands verbatim
7010                // as a K8s Gateway API HTTPRoute `matches[].path.value`
7011                // (caixa-mesh/src/lib.rs:498), apiserver-validated
7012                // against `maxLength: 1024` + the Gateway API webhook's
7013                // path-grammar rules (no `//`, no `/./`, no `/../`, no
7014                // query/fragment separators, no whitespace, no control
7015                // characters, no non-ASCII bytes). Until this gate
7016                // landed `validate` only refused the empty string and
7017                // missing-leading-slash (eb3456d); a structurally
7018                // invalid path (`"/api?q=1"`, `"/api#frag"`,
7019                // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
7020                // 1025-byte URL-shaped slug) silently passed validate
7021                // and the failure surfaced at `kubectl apply` time as
7022                // a Gateway API webhook rejection, far from the source
7023                // caixa.lisp, with no field naming the offending
7024                // `:paths` entry. Lifting the gate to caixa-build time
7025                // mirrors the `:entrada :host` value-shape trajectory
7026                // (c7d05ec) on the sibling axis — every author surface
7027                // that emits a Gateway API field now matches the
7028                // apiserver's accepted set at validate time.
7029                validate_entrada_path(p)?;
7030                crate::render::insert_first_seen(&mut seen, p.as_str(), || {
7031                    AplicacaoError::EntradaPathDuplicate { path: p.clone() }
7032                })?;
7033            }
7034        }
7035
7036        self.validate_placement()?;
7037
7038        self.validate_politicas()?;
7039
7040        Ok(())
7041    }
7042
7043    /// Reject `:membros` values that are operationally meaningless. The
7044    /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
7045    /// every entry names a Servico that participates in the Aplicacao,
7046    /// and the rendered programs.yaml fan-out emits one entry per
7047    /// `:membros`. Three authoring footguns are closed here:
7048    ///
7049    ///   - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
7050    ///     a `programs:` entry whose `name:` is the empty string, which
7051    ///     downstream `lareira-fleet-programs` rejects at template time
7052    ///     with a non-localized error;
7053    ///   - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
7054    ///     an empty semver constraint, so the failure surfaces far from
7055    ///     the source caixa.lisp;
7056    ///   - duplicate `:caixa` names — two entries with the same name
7057    ///     produce duplicate programs.yaml entries (one silently
7058    ///     overwrites the other in the cluster's HelmRelease values), and
7059    ///     contract membership lookups against `:contratos` collapse the
7060    ///     two onto one node, masking authoring mistakes.
7061    ///
7062    /// Same value-shape discipline as `:placement :clusters` (where empty
7063    /// + duplicate cluster names are rejected) and `:entrada :paths`
7064    /// (where empty + duplicate path entries are rejected). Lifting these
7065    /// invariants to the typed surface mirrors the MESH-COMPOSITION
7066    /// §III.3 promise that the `:membros` set — the load-bearing identity
7067    /// of the application graph — is well-formed by construction.
7068    fn validate_membros(&self) -> Result<(), AplicacaoError> {
7069        if self.membros().is_empty() {
7070            return Err(AplicacaoError::NoMembros);
7071        }
7072        let mut seen = std::collections::HashSet::new();
7073        for m in self.membros() {
7074            // Route the `MembroCaixaEmpty` refusal-arm's per-member
7075            // empty-`:caixa` shape-gate through the typed
7076            // [`Membro::nome`] accessor rather than the raw `.caixa`
7077            // field access — the last un-lifted `.caixa` production-
7078            // code read site on the per-`:membros` member-caixa `:nome`
7079            // axis, sibling to the six caixa-core validator read sites
7080            // (member-set collector, per-member value-shape gate,
7081            // duplicate dedup key, cycle-detector adjacency-map seed,
7082            // self-loop gate) the 4a32abf lift already routed through
7083            // the accessor and the peer 54bf2f3 caixa-mesh emit-side
7084            // per-`programs[]` entry-`name:` `String`-carry converge.
7085            // Prior to this converge the `MembroCaixaEmpty` refusal
7086            // arm was the solitary consumer bypassing the typed
7087            // dispatch — the same-loop iteration's very next call
7088            // `validate_membro_caixa(m.nome())` already routed through
7089            // the accessor, so an author landing an empty-`:caixa`
7090            // entry hit the accessor on the shape-gate line but
7091            // bypassed it on the emptiness line one line above. A
7092            // future extension of the `:membros :caixa` axis to a
7093            // richer author surface (a per-cluster alias table pinned
7094            // through a future `:placement`-scoped slot, a namespace-
7095            // qualified rewrite the M4 CR materializer applies per-CR,
7096            // a per-member overlay from the future `:membros
7097            // :nome-suffix` slot MESH-COMPOSITION §III.2 acknowledges)
7098            // that lands on the accessor would silently disagree
7099            // between the emptiness gate and every peer consumer —
7100            // an author-declared `:caixa "checkout"` value the
7101            // accessor rewrote to `""` under a future alias arm would
7102            // pass the raw `.is_empty()` gate here while the peer
7103            // `validate_membro_caixa(m.nome())` call one line below
7104            // (and every downstream emit-side consumer routing through
7105            // the accessor) tripped on the empty-value shape far from
7106            // this diagnostic. Pinned by the drift-detection test
7107            // [`validate_membros_empty_gate_routes_through_nome_accessor`]
7108            // below.
7109            if m.nome().is_empty() {
7110                return Err(AplicacaoError::MembroCaixaEmpty);
7111            }
7112            // Every emitted cluster artifact's `metadata.name` derives
7113            // from a `:membros :caixa` value verbatim — the rendered
7114            // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
7115            // the [`crate::LABEL_PROGRAM`] label value on every CNP
7116            // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
7117            // 272), the composed `CiliumNetworkPolicy` `metadata.name`
7118            // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
7119            // `metadata.name` when the member is the `:entrada :para`
7120            // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
7121            // schema enforces the DNS-1123 label rule on admission;
7122            // a structurally invalid member name (`"Cart"`, `"my_cart"`,
7123            // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
7124            // mistaken-identity slug) silently passes the prior empty-/
7125            // duplicate-only gate and the failure surfaces at `kubectl
7126            // apply` time as a `metadata.name: Invalid value` rejection,
7127            // far from the source caixa.lisp, with no field naming the
7128            // offending `:membros` entry. Lifting the gate to caixa-build
7129            // time mirrors the `:entrada :host` value-shape trajectory
7130            // (c7d05ec) on the peer axis — every author surface that
7131            // emits a K8s name now matches the apiserver's accepted set
7132            // at validate time.
7133            validate_membro_caixa(m.nome())?;
7134            // The author surface for `:versao` is the same Cargo-shaped
7135            // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
7136            // `"*"`) every `:deps` entry carries — and the lacre pipeline
7137            // resolves both axes through the same
7138            // [`crate::version::parse_requirement`] entry-point. The
7139            // shared [`crate::render::require_valid_versao_requirement`]
7140            // helper brackets the empty-first + parse cascade both peer
7141            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
7142            // [`crate::SupervisorSpec::validate`] on `:children :versao`)
7143            // route through, so drift between the three axes' accepted
7144            // requirement sets is structurally impossible and the parse-
7145            // side no-op the empty-first arm closes (semver's empty
7146            // parse yields an implicit `*`) lives in exactly one
7147            // predicate.
7148            crate::render::require_valid_versao_requirement(
7149                m.versao_requirement(),
7150                || AplicacaoError::MembroVersaoEmpty {
7151                    caixa: m.nome().to_string(),
7152                },
7153                |reason| AplicacaoError::MembroVersaoInvalid {
7154                    caixa: m.nome().to_string(),
7155                    versao: m.versao_requirement().to_string(),
7156                    reason,
7157                },
7158            )?;
7159            crate::render::insert_first_seen(&mut seen, m.nome(), || {
7160                AplicacaoError::MembroDuplicate {
7161                    caixa: m.nome().to_string(),
7162                }
7163            })?;
7164        }
7165        Ok(())
7166    }
7167
7168    /// Reject `:placement` values that are operationally meaningless or
7169    /// internally contradictory. Each strategy variant has the same
7170    /// invariants on `:clusters` (non-empty list, non-empty unique
7171    /// entries) — the §III.1 author surface is uniform on this axis,
7172    /// even though the *meaning* of the list differs by strategy
7173    /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
7174    /// shard pool).
7175    ///
7176    /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
7177    /// are the same authoring footgun closed for `:politicas` zero
7178    /// values and `:entrada` empty paths: the field is *declared* but
7179    /// carries no meaning, so downstream renderers either skip it
7180    /// silently (cluster-fanout drops the empty entry, no diagnostic)
7181    /// or apply it literally and fail at admission time. Lifting both
7182    /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
7183    /// violation is a build error" promise.
7184    ///
7185    /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
7186    /// is required exactly when `:estrategia Sharded` (hash-keyed
7187    /// distribution, Akka cluster-sharding convention, §II.4) and
7188    /// refused on `:estrategia Replicated`/`SingleNode` (where no
7189    /// hash-keyed routing axis consumes it). The partition closes the
7190    /// "I think I configured sharding" footgun where an author writes
7191    /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
7192    /// the typed slot's value silently vanishes at the renderer layer
7193    /// — every validated `Placement` past this call satisfies
7194    /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
7195    fn validate_placement(&self) -> Result<(), AplicacaoError> {
7196        // Every strategy needs at least one named cluster: `Replicated`
7197        // and `SingleNode` use the list as hosting/takeover candidates
7198        // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
7199        // §II.1), while `Sharded` uses it as the shard pool
7200        // (Akka cluster-sharding convention — §II.4). An empty list is
7201        // meaningless under any of the three.
7202        //
7203        // Route the paired pre-flight `.is_empty()` refusal probe and
7204        // the per-cluster validate loop's traversal head through the
7205        // lifted [`Placement::clusters`] slice-return accessor rather
7206        // than the raw `self.placement.clusters` field access — the
7207        // two production consumers of the per-`:placement` cluster-
7208        // pool `Vec`-carry now key off exactly one typed dispatch on
7209        // the substrate primitive, so any future rebrand on the axis
7210        // (a per-tenant cluster-pool overlay the operator pins through
7211        // a future `:placement :clusters-overrides` slot, a per-
7212        // Aplicacao dynamic cluster-pool derivation the future M5
7213        // adaptive-placement engine computes from `:affinity` weights)
7214        // migrates as a single caixa-core edit rather than a
7215        // coordinated rewrite of the paired arms — sibling of the
7216        // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
7217        // arm migration on the per-`:supervisor` static-child-list
7218        // `Vec`-carry axis.
7219        //
7220        // Route the per-`:placement` outer-composite reference read
7221        // through the lifted [`AplicacaoSpec::placement`] outer accessor
7222        // rather than the raw `&self.placement` field access — the
7223        // per-axis bracket-dispatch fan-out below (`p.clusters()`,
7224        // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
7225        // axis-level lifted accessor family) now routes through the
7226        // substrate-primitive typed dispatch at the outer composition
7227        // altitude, the same shape the peer caixa-mesh
7228        // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
7229        // and the sibling `feira app graph` per-Aplicacao print line
7230        // now key off after this accessor lift.
7231        let p = self.placement();
7232        if p.clusters().is_empty() {
7233            return Err(AplicacaoError::PlacementWithoutClusters {
7234                estrategia: p.estrategia(),
7235            });
7236        }
7237        let mut seen = std::collections::HashSet::new();
7238        for c in p.clusters() {
7239            // Per-entry value-shape gate: the cluster name lands in
7240            // every K8s context / `lareira-fleet-programs` aggregator
7241            // filter / future M4 CR materializer's per-cluster axis
7242            // a validated `:clusters` entry passes through, each
7243            // enforcing the DNS-1123 label rule on admission. Same
7244            // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
7245            // on the peer name axis — both axes' validated values
7246            // are guaranteed-accepted by the apiserver without
7247            // re-validation at any downstream renderer or admission
7248            // layer.
7249            validate_placement_cluster(c)?;
7250            crate::render::insert_first_seen(&mut seen, c.as_str(), || {
7251                AplicacaoError::PlacementClusterDuplicate { cluster: c.clone() }
7252            })?;
7253        }
7254        // Route the per-`:placement :affinity` per-hint value-shape
7255        // gate through the typed [`Placement::affinity`] accessor rather
7256        // than the raw `&self.placement.affinity` field access — the
7257        // sole open-coded field-access site on the per-`:placement`
7258        // M3-Adaptive-compression-hint axis the accessor lift now owns.
7259        // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
7260        // the accessor's `Option<&str>` return type;
7261        // [`validate_placement_affinity`]'s `&str` parameter accepts
7262        // the narrower borrow without a re-allocation, so the routing
7263        // change is byte-for-byte in the pass arm and remains
7264        // byte-for-byte in every failure diagnostic
7265        // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
7266        // String` field is populated inside
7267        // [`validate_placement_affinity`] via the peer `.to_string()`
7268        // path on the same borrowed slice). Peer of the sibling
7269        // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
7270        // routing through [`Placement::shard_key`] at the caixa-core
7271        // site above — extends the "read `:placement` optional-scalars
7272        // through the typed accessor" discipline to the second
7273        // `Option<String>`-shape slot on the M3 mesh-slot family.
7274        //
7275        // Per-hint value-shape gate: the `:affinity` value lands
7276        // verbatim in the M3 Adaptive compression overlay
7277        // (caixa-mesh's `placement.affinity` emission) and every
7278        // future M4 placement-engine routing axis keying off the
7279        // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
7280        // selector — each enforces the DNS-1123 label rule on
7281        // admission. Same typed-shape trajectory as `:placement
7282        // :clusters` (6c8c00b) on the sibling slot and the four
7283        // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
7284        // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
7285        // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
7286        // on the Aplicacao surface to land on the canonical
7287        // [`crate::render::is_dns_1123_label`] floor.
7288        if let Some(a) = p.affinity() {
7289            validate_placement_affinity(a)?;
7290        }
7291        match p.estrategia() {
7292            // Route the `Sharded`-arm shape-gate cascade through the
7293            // typed [`Placement::shard_key`] accessor rather than the
7294            // raw `&self.placement.shard_key` field access — one of the
7295            // two open-coded field-access sites on the per-`:placement`
7296            // Akka-cluster-sharding-key axis the accessor lift now
7297            // owns. The `Some(k)`-bound `k` narrows from `&String` to
7298            // `&str` under the accessor's `Option<&str>` return type;
7299            // `str::is_empty` and [`validate_placement_shard_key`]'s
7300            // `&str` parameter both accept the narrower borrow without
7301            // a re-allocation.
7302            PlacementStrategy::Sharded => match p.shard_key() {
7303                None => return Err(AplicacaoError::ShardedWithoutKey),
7304                Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
7305                // Per-axis value-shape gate on the Akka-cluster-sharding
7306                // `:shard-key` extractor expression. The shape gate runs
7307                // after the more self-locating `ShardedKeyEmpty` arm so
7308                // a `:shard-key ""` surfaces the narrower empty
7309                // diagnostic first; every non-empty `:shard-key` past
7310                // this call is guaranteed to be a printable-ASCII
7311                // single-token reference the future M4 Akka-style
7312                // cluster-sharding reconciler can hash without
7313                // re-validating at the runtime layer. Mirrors the
7314                // payload-axis shape gates on the peer `:contratos`
7315                // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
7316                // 63e18a0 / c4213a4) — each lifts the runtime parser's
7317                // intersection-floor to a caixa-build-time gate.
7318                Some(k) => validate_placement_shard_key(k)?,
7319            },
7320            // `:shard-key` is the Akka-cluster-sharding axis
7321            // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
7322            // across the cluster pool. `Replicated` (active-active across
7323            // every named cluster) and `SingleNode` (Erlang/OTP
7324            // distributed-app takeover/failover, §II.1) have no hash-keyed
7325            // routing axis to consume the slot; downstream renderers
7326            // (caixa-mesh's `placement.shardKey` overlay at
7327            // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
7328            // sharding reconciler) ignore `:shard-key` outside the
7329            // `Sharded` arm by construction. Until this gate landed an
7330            // author who wrote `:placement (:estrategia Replicated
7331            // :shard-key "tenantId")` (an off-by-one strategy typo, a
7332            // copy-paste from a Sharded sibling caixa, the "I think I
7333            // configured sharding" footgun) silently passed validate and
7334            // the typed slot's value vanished at the renderer layer with
7335            // no diagnostic — the canonical "declared-but-inert" footgun
7336            // the empty-:affinity / empty-shard-key / zero-:politicas /
7337            // empty-:contratos-target gates already close on every other
7338            // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
7339            // Lifting the rejection to a build-time gate closes the
7340            // Sharded ↔ non-Sharded partition over the typed
7341            // `:placement` slot: every validated `Placement` past this
7342            // call has `shard_key.is_some()` iff `estrategia ==
7343            // Sharded`, structurally — the future Akka reconciler can
7344            // reach for `placement.shard_key` knowing it's `Some` exactly
7345            // when the strategy consumes it, without re-deriving the
7346            // partition from inline strategy probes.
7347            PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
7348                // Route the non-`Sharded`-arm declared-but-inert refusal
7349                // through the typed [`Placement::shard_key`] accessor —
7350                // the second of the two open-coded field-access sites the
7351                // accessor lift now owns. The `Some(k)`-bound `k` narrows
7352                // from `&String` to `&str`; the `AplicacaoError::
7353                // ShardKeyOnNonSharded { shard_key: String }` diagnostic
7354                // materializes the owned `String` via `k.to_string()`
7355                // (peer to the sibling per-Membro `String`-carry sites
7356                // 4127bb6 routed through `m.nome().to_string()` /
7357                // `m.versao_requirement().to_string()`), so the whole
7358                // `Sharded` ↔ non-`Sharded` partition on the
7359                // `:shard-key` axis now flows through the same typed
7360                // dispatch as the sibling `Sharded`-arm shape gate.
7361                if let Some(k) = p.shard_key() {
7362                    return Err(AplicacaoError::ShardKeyOnNonSharded {
7363                        estrategia: p.estrategia(),
7364                        shard_key: k.to_string(),
7365                    });
7366                }
7367            }
7368        }
7369        Ok(())
7370    }
7371
7372    /// Reject `:politicas` values that are operationally meaningless.
7373    /// Each axis is optional — omitting it expresses "no policy on this
7374    /// axis". Carrying a *zero* value for a declared axis is the bug
7375    /// this function rejects: zero is either
7376    ///
7377    ///   - re-interpreted as "infinite" by downstream proxies (Envoy's
7378    ///     `RouteAction.timeout = 0s` disables the timeout entirely),
7379    ///     directly contradicting MESH-COMPOSITION §V CSE invariant
7380    ///     "every Aplicacao declares :politicas :timeout (no infinite
7381    ///     blocking)", or
7382    ///   - a renderer footgun (a 0-failure circuit breaker trips on the
7383    ///     first call; a 0-rate rate-limit denies every request).
7384    ///
7385    /// Lifting these "0 means the opposite of what you think" idioms to
7386    /// the typed Aplicacao surface as build errors mirrors the §III.3
7387    /// promise that contract drift, capability leaks, and cycles are all
7388    /// build errors — not runtime surprises.
7389    fn validate_politicas(&self) -> Result<(), AplicacaoError> {
7390        // Route the per-`:politicas` composite-reference read through
7391        // the lifted [`AplicacaoSpec::politicas`] outer accessor rather
7392        // than the raw `&self.politicas` field access — the per-axis
7393        // bracket-dispatch fan-out below (`p.timeout()`, `p.retries()`,
7394        // `p.circuit_breaker()`, `p.rate_limit()`) now routes through
7395        // the substrate-primitive typed dispatch at the outer
7396        // composition altitude AND at every per-axis altitude, matching
7397        // the peer caixa-mesh CNP mTLS-overlay + HTTPRoute
7398        // timeout/retry-overlay emitters that already key off the same
7399        // per-axis accessor family. The four-axis fan-out is now
7400        // uniformly `p.<axis>()` — the last two raw `p.timeout` /
7401        // `p.retries` field-access sites (co-resident with the peer
7402        // `p.circuit_breaker()` / `p.rate_limit()` accessor sites that
7403        // b0e741a / 21a6c3b already lifted) now route through
7404        // [`MeshPolicy::timeout`] / [`MeshPolicy::retries`], closing
7405        // the per-`:politicas` bracket-dispatch fan-out's raw-field-
7406        // access axis on the M3 mesh-slot family.
7407        let p = self.politicas();
7408        if let Some(t) = p.timeout() {
7409            // Zero-floor + integer-millisecond canonical-form +
7410            // upper-cap bracket on the typed `:timeout` axis. See
7411            // [`crate::render::require_positive_canonical_bounded_duration`]
7412            // for the full three-arm ordering discipline (zero-floor
7413            // strictly precedes the canonical-form arm so
7414            // `Duration::ZERO` surfaces the self-locating
7415            // `PolicyTimeoutZero` diagnostic naming the omit-axis
7416            // remediation; canonical-form strictly precedes the cap
7417            // arm so a sub-millisecond above-cap `Duration` surfaces
7418            // the more fundamental round-trip-shape diagnostic first)
7419            // and the four peer typed-`Duration` sites that now share
7420            // this canonical bracket. Every validated value lies in
7421            // `1ms..=POLICY_TIMEOUT_MAX` (1ms..=1h), integer-millisecond
7422            // granularity — the same top-and-bottom-edge discipline
7423            // [`POLICY_RETRIES_MAX`] and
7424            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] apply on the sibling
7425            // capped-`u32` `:politicas` axes.
7426            crate::render::require_positive_canonical_bounded_duration(
7427                t,
7428                POLICY_TIMEOUT_MAX,
7429                || AplicacaoError::PolicyTimeoutZero,
7430                |timeout| AplicacaoError::PolicyTimeoutNotCanonical { timeout },
7431                |timeout| AplicacaoError::PolicyTimeoutExceedsCap { timeout },
7432            )?;
7433        }
7434        if let Some(r) = p.retries() {
7435            // Zero-floor + upper-cap bracket on the typed `:retries`
7436            // axis. See [`crate::render::require_positive_bounded_u32`]
7437            // for the ordering discipline (zero-floor arm strictly
7438            // precedes cap arm so `Some(0)` surfaces the self-locating
7439            // `PolicyRetriesZero` diagnostic with its omit-axis
7440            // remediation directly named, not the misleading
7441            // `0 > POLICY_RETRIES_MAX == false` cap-arm miss). Until
7442            // this bracket landed the top edge ran all the way to
7443            // `u32::MAX` and a struct-literal `MeshPolicy { retries:
7444            // Some(100_000), .. }` (or the equivalent author-surface
7445            // `(:retries 100000)` / `(:retries 4294967295)` typo
7446            // landing in the slot) silently passed validate. The
7447            // runtime substrate consuming the value (Envoy's
7448            // `retry_policy.num_retries`, the future
7449            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7450            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7451            // policy into a thundering-herd amplification vector —
7452            // the caller's one request fans out to `retries`
7453            // server-side calls per edge per traversal, multiplying
7454            // load by `(retries+1)^depth` across the
7455            // synchronous-`:contratos` subgraph at the precise moment
7456            // the substrate is already failing (transient failure is
7457            // the trigger), exactly the failure mode AWS App Mesh's
7458            // explicit `maxRetries ≤ 10` schema cap exists to prevent.
7459            // The bracket set is `1..=POLICY_RETRIES_MAX`. Peer with
7460            // the sibling capped-`u32` `:politicas` axes
7461            // (`max_failures`, `rate_limit.rate`) and the peer capped-
7462            // `u32` axes in `:supervisor :max-restarts` +
7463            // `:limits :cpu`; all five now route through the same
7464            // canonical bracket helper.
7465            crate::render::require_positive_bounded_u32(
7466                r,
7467                POLICY_RETRIES_MAX,
7468                || AplicacaoError::PolicyRetriesZero,
7469                |retries| AplicacaoError::PolicyRetriesExceedsCap { retries },
7470            )?;
7471        }
7472        if let Some(cb) = p.circuit_breaker() {
7473            // Zero-floor + upper-cap bracket on the typed
7474            // `:max-failures` axis. See
7475            // [`crate::render::require_positive_bounded_u32`] for the
7476            // ordering discipline (zero-floor arm strictly precedes
7477            // cap arm so `max_failures == 0` surfaces the
7478            // self-locating `PolicyBreakerZeroFailures` diagnostic
7479            // with its omit-axis remediation directly named, not the
7480            // misleading `0 > POLICY_BREAKER_MAX_FAILURES_MAX ==
7481            // false` cap-arm miss). Until this bracket landed the top
7482            // edge ran all the way to `u32::MAX` and a struct-literal
7483            // `CircuitBreaker { max_failures: 100_000, .. }` (or the
7484            // equivalent author-surface `(:max-failures 100000)` /
7485            // `(:max-failures 4294967295)` typo landing in the slot)
7486            // silently passed validate. The runtime substrate
7487            // consuming the value (Envoy's
7488            // `outlier_detection.consecutive_5xx`, the future
7489            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7490            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7491            // breaker policy into a no-op — the trip threshold is
7492            // structurally so high that no realistic
7493            // failures-per-`:window` traffic shape can reach it, the
7494            // breaker never trips, and every typed-slot consumer
7495            // emits an Envoy / Cilium L7 overlay carrying a
7496            // protection that is structurally never enforced. The
7497            // bracket set is `1..=POLICY_BREAKER_MAX_FAILURES_MAX`;
7498            // peer with `retries` and `rate_limit.rate` on the same
7499            // helper.
7500            crate::render::require_positive_bounded_u32(
7501                cb.max_failures(),
7502                POLICY_BREAKER_MAX_FAILURES_MAX,
7503                || AplicacaoError::PolicyBreakerZeroFailures,
7504                |max_failures| AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
7505            )?;
7506            // Zero-floor + integer-millisecond canonical-form +
7507            // upper-cap bracket on the typed `:window` axis. See
7508            // [`crate::render::require_positive_canonical_bounded_duration`]
7509            // for the full three-arm ordering discipline (peer to the
7510            // `:timeout` site immediately above); every validated
7511            // value lies in `1ms..=POLICY_BREAKER_WINDOW_MAX`
7512            // (1ms..=1h), integer-millisecond granularity — the same
7513            // top-and-bottom-edge discipline
7514            // [`POLICY_TIMEOUT_MAX`] applies on the sibling
7515            // duration-typed `:politicas :timeout` axis.
7516            crate::render::require_positive_canonical_bounded_duration(
7517                cb.window(),
7518                POLICY_BREAKER_WINDOW_MAX,
7519                || AplicacaoError::PolicyBreakerZeroWindow,
7520                |window| AplicacaoError::PolicyBreakerWindowNotCanonical { window },
7521                |window| AplicacaoError::PolicyBreakerWindowExceedsCap { window },
7522            )?;
7523        }
7524        if let Some(rl) = p.rate_limit() {
7525            // Zero-floor + upper-cap bracket on the typed
7526            // `:rate-limit` rate axis. See
7527            // [`crate::render::require_positive_bounded_u32`] for the
7528            // ordering discipline (zero-floor arm strictly precedes
7529            // cap arm so `rl.rate == 0` surfaces the self-locating
7530            // `PolicyRateLimitZero` diagnostic with its omit-axis
7531            // remediation directly named, not the misleading
7532            // `0 > POLICY_RATE_LIMIT_MAX == false` cap-arm miss).
7533            // Until this bracket landed the top edge ran all the way
7534            // to `u32::MAX` and a struct-literal
7535            // `RateLimit { rate: u32::MAX, .. }` (or the equivalent
7536            // author-surface `(:rate-limit "4294967295/s")` /
7537            // `(:rate-limit "100000000/m")` typo landing in the slot)
7538            // silently passed validate. The runtime substrate
7539            // consuming the value (Envoy's
7540            // `local_rate_limit.token_bucket.max_tokens`, the future
7541            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7542            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7543            // rate-limit policy into a no-op limiter: the bucket
7544            // capacity is structurally so high that no realistic
7545            // per-edge traffic shape can drain it, the limiter never
7546            // trips, and every typed-slot consumer emits a "rate
7547            // declared" L7 overlay carrying enforcement that is
7548            // structurally never reached — the canonical
7549            // declared-but-inert footgun the sibling
7550            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap arm closes on
7551            // the peer no-op-breaker shape. The bracket set is
7552            // `1..=POLICY_RATE_LIMIT_MAX`; peer with `retries` and
7553            // `max_failures` on the same helper. The rate bracket
7554            // strictly precedes the window-canonical gate so a
7555            // structurally absurd rate magnitude surfaces the more
7556            // fundamental amplification-shape diagnostic before the
7557            // narrower codec-round-trip-shape diagnostic on `:window`.
7558            crate::render::require_positive_bounded_u32(
7559                rl.rate(),
7560                POLICY_RATE_LIMIT_MAX,
7561                || AplicacaoError::PolicyRateLimitZero,
7562                |rate| AplicacaoError::PolicyRateLimitExceedsCap { rate },
7563            )?;
7564            // The `:rate-limit` author surface is the canonical
7565            // `"<n>/<s|m|h>"` form, and the [`rate_limit_codec`] parser
7566            // accepts exactly the three-unit set (1s/60s/3600s) the
7567            // [`rate_limit_codec::render`] formatter emits the canonical
7568            // unit suffix for. A `RateLimit` whose `:window` is anything
7569            // else (zero, 30s, 45s, 120s, 86400s, …) is constructible
7570            // programmatically (struct literals in Rust + the typed
7571            // `Duration` field) but renders to a `<n>/<k>s` fragment
7572            // (the codec's fall-through) the parser then rejects on
7573            // round-trip — silently breaking the THEORY.md §V.2.7
7574            // render-determinism contract for any consumer that
7575            // serializes-then-deserializes the typed slot. Lifting the
7576            // canonical-window invariant to a build-time gate at
7577            // `validate_politicas` makes the codec's round-trip property
7578            // a structural property of the validated typed value:
7579            // every `RateLimit` past `AplicacaoSpec::validate` has a
7580            // window the codec round-trips losslessly, so the next
7581            // typed-slot wiring (the future `CiliumClusterwideEnvoyConfig`
7582            // emitter for `:politicas :rate-limit`, MESH-COMPOSITION
7583            // §III.2 #3) reaches for `rate_limit.window` knowing the
7584            // value is in the codec's accepted set without re-validating
7585            // at the renderer layer. Same trajectory as c4213a4 (typed
7586            // WitContract endpoint/subject/slot value-shape gates) and
7587            // the b0c8389 :behavior + :upgrade-from script-path lifts:
7588            // the typed slot's valid set matches its codec's accepted
7589            // set, structurally.
7590            // Route the canonical-window shape-gate through the substrate
7591            // primitive [`RateLimit::canonical_unit`] rather than the free
7592            // module-private [`is_canonical_rate_limit_window`] predicate:
7593            // both projections resolve `Duration → Option<RateLimitUnit>`
7594            // through [`RateLimitUnit::from_window`] (the sole `Duration → Self`
7595            // arm on the closed-set typed enum), but the accessor is the
7596            // typed method every downstream consumer of the validated slot
7597            // ([`rate_limit_codec::render`]'s canonical arm above, the
7598            // future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7599            // per-`:politicas :rate-limit` admission webhook, the future
7600            // per-`:contratos`-edge rate-limit-override overlay
7601            // MESH-COMPOSITION §III.2 #3 acknowledges) already reads. Two
7602            // production consumers of the canonical-unit axis (the codec
7603            // render and this validate gate) now key off exactly one typed
7604            // dispatch on the substrate primitive, so any future extension
7605            // to `canonical_unit` (a per-cluster canonical-window overlay
7606            // the operator pins through a future `:contratos :rate-limit
7607            // -unit-overrides` slot, a per-tenant unit-alias table the M4
7608            // CR materializer resolves per-CR) reaches both consumers by
7609            // construction rather than a coordinated rewrite of every
7610            // free-helper call site.
7611            if rl.canonical_unit().is_none() {
7612                return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical {
7613                    window: rl.window(),
7614                });
7615            }
7616        }
7617        Ok(())
7618    }
7619
7620    /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
7621    /// A synchronous edge is any contract whose typed [`WitTarget`] is
7622    /// `Http`, `Store`, or `Capability` — the caller blocks on the
7623    /// callee, so a cycle would deadlock at runtime. Pub-sub edges
7624    /// (`WitTarget::PubSub`) are skipped: an event publisher does not
7625    /// block on its subscribers, so they can never close a sync loop.
7626    ///
7627    /// Iterative DFS with three-coloring; the reported cycle is the
7628    /// path of caixa names traversed from the back-edge target around
7629    /// to itself, in declaration order. Adjacency lists and DFS roots
7630    /// are visited in `BTreeMap` key order so the diagnostic is
7631    /// deterministic across runs.
7632    fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
7633        use std::collections::{BTreeMap, BTreeSet};
7634
7635        #[derive(Clone, Copy, PartialEq, Eq)]
7636        enum Mark {
7637            White,
7638            Gray,
7639            Black,
7640        }
7641
7642        let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
7643        for m in self.membros() {
7644            adj.entry(m.nome()).or_default();
7645        }
7646        for c in self.contratos() {
7647            // target() was already called by validate(); re-running here
7648            // keeps detect_sync_cycles self-contained for callers that
7649            // reuse it (M4 per-edge policy resolver) without revalidating.
7650            //
7651            // The pub-sub-arm check routes through the lifted
7652            // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
7653            // arm-discriminator predicate rather than a raw `matches!(…,
7654            // WitTarget::PubSub { .. })` on the variant so a future
7655            // rebrand on the axis (an M4 per-edge WIT registry split of
7656            // [`WitTarget::PubSub`] into shape-specific peers, a
7657            // per-consumer rename that the accept-set already carries)
7658            // reaches this call site through the derive rather than a
7659            // scattered per-arm `matches!` rewrite — same
7660            // `IsVariant`-derived-arm-discriminator discipline the
7661            // peer closed-set typed enums ([`crate::CaixaKind`] via
7662            // f5bba80, [`PlacementStrategy`] via 766ec63,
7663            // [`crate::supervisor::RestartStrategy`] +
7664            // [`crate::supervisor::RestartPolicy`],
7665            // [`crate::upgrade::UpgradeInstruction`] via 915a934)
7666            // already route through on the substrate's other typed-enum
7667            // arm-discriminator axes.
7668            if c.target()?.is_pubsub() {
7669                continue;
7670            }
7671            adj.entry(c.source()).or_default().insert(c.destination());
7672        }
7673
7674        let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
7675        let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
7676
7677        // Stable DFS root order — BTreeMap iteration is sorted by key.
7678        let roots: Vec<&str> = adj.keys().copied().collect();
7679
7680        // Frame: (node, sorted-neighbours snapshot, next-edge index).
7681        for root in roots {
7682            if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
7683                continue;
7684            }
7685            let root_neighbors: Vec<&str> = adj
7686                .get(root)
7687                .map(|s| s.iter().copied().collect())
7688                .unwrap_or_default();
7689            let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
7690            color.insert(root, Mark::Gray);
7691
7692            loop {
7693                // Read+advance the top frame in one borrow scope so we
7694                // can later mutate the stack (push/pop) without holding
7695                // a borrow across.
7696                let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
7697                    let node = top.0;
7698                    if top.2 >= top.1.len() {
7699                        (node, None)
7700                    } else {
7701                        let nxt = top.1[top.2];
7702                        top.2 += 1;
7703                        (node, Some(nxt))
7704                    }
7705                });
7706                let Some((node, nxt_opt)) = step else { break };
7707                let Some(nxt) = nxt_opt else {
7708                    color.insert(node, Mark::Black);
7709                    stack.pop();
7710                    continue;
7711                };
7712                let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
7713                match nxt_color {
7714                    Mark::Gray => {
7715                        // Reconstruct the cycle from `node` back through
7716                        // the parent chain to `nxt`, then close.
7717                        let mut cycle = Vec::new();
7718                        let mut cur = node;
7719                        cycle.push(cur.to_string());
7720                        while cur != nxt {
7721                            match parent.get(cur).copied() {
7722                                Some(p) => {
7723                                    cur = p;
7724                                    cycle.push(cur.to_string());
7725                                }
7726                                None => break,
7727                            }
7728                        }
7729                        cycle.reverse();
7730                        cycle.push(nxt.to_string());
7731                        return Err(AplicacaoError::ContratoCycle { cycle });
7732                    }
7733                    Mark::White => {
7734                        parent.insert(nxt, node);
7735                        color.insert(nxt, Mark::Gray);
7736                        let nxt_neighbors: Vec<&str> = adj
7737                            .get(nxt)
7738                            .map(|s| s.iter().copied().collect())
7739                            .unwrap_or_default();
7740                        stack.push((nxt, nxt_neighbors, 0));
7741                    }
7742                    Mark::Black => {}
7743                }
7744            }
7745        }
7746        Ok(())
7747    }
7748
7749    /// Substrate-canonical destination-facing TCP port every emitted
7750    /// per-Aplicacao artifact must key `destination`-shaped port axes
7751    /// off. Returns the typed `:entrada :port` scalar when this
7752    /// Aplicacao's `:entrada` block names `destination` under its
7753    /// `:para` axis (the destination Servico *is* the ingress apex, so
7754    /// the substrate honors the author-declared listener port
7755    /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
7756    /// fallback otherwise (every non-apex destination — the internal
7757    /// mesh Servicos `:contratos` reach across, the future per-edge
7758    /// policy resolver's per-destination probe targets, the
7759    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
7760    /// L4 port resolver — reads the same substrate-canonical port floor
7761    /// by construction).
7762    ///
7763    /// Prior to this lift the "if :entrada matches this destination use
7764    /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
7765    /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
7766    /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
7767    /// prior to this lift), with no typed method on the substrate primitive
7768    /// that named the rule. A future per-destination port axis addition
7769    /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
7770    /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
7771    /// per-Servico listener ports land, a per-cluster override the operator
7772    /// pins through a future `:placement :default-port` slot — would have
7773    /// to be threaded through every renderer's inline cascade in lockstep
7774    /// or one consumer would silently disagree on which port a given
7775    /// destination Servico's ingress lands at. Lifting the rule to a
7776    /// typed method on the substrate primitive means the M4 CR
7777    /// materializer, the future per-edge policy resolver, and every
7778    /// downstream test-fixture navigator reach for exactly one typed
7779    /// dispatch — the resolver's accept-set moves as a unit on any
7780    /// future axis addition.
7781    ///
7782    /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
7783    /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
7784    /// the typed primitive, thin projections at each consumer"
7785    /// discipline lifts on the sibling `:contratos` payload / `:politicas
7786    /// :rate-limit` unit-suffix axes; extends the discipline onto the
7787    /// destination-facing port-resolution axis every per-Aplicacao
7788    /// L4-fallback renderer consumes.
7789    #[must_use]
7790    pub fn port_for_destination(&self, destination: &str) -> u16 {
7791        // Route the per-`:entrada` composite-reference read through
7792        // the lifted [`AplicacaoSpec::entrada`] accessor rather than
7793        // the raw `self.entrada.as_ref()` field access — the
7794        // per-destination L4-port fallback resolver's composite-
7795        // projection seed is now the canonical read-side surface
7796        // every per-Aplicacao entrada consumer routes through, peer
7797        // of the sibling `validate` per-`:entrada` shape-and-
7798        // membership gate migration on the same outer-composite
7799        // axis.
7800        // Route the per-`:entrada` apex-destination membership probe
7801        // through the lifted [`Entrada::destination`] accessor rather
7802        // than the raw `e.para == destination` field access — the last
7803        // un-lifted `.para` production-code read site on the per-
7804        // `:entrada` `:para` axis, sibling to the four caixa-core
7805        // consumer sites the peer 15ddd8c converge already routed
7806        // through the accessor (the three
7807        // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
7808        // membership gate sites: the `validate_entrada_para` DNS-1123
7809        // shape gate, the per-`:membros` membership lookup, and the
7810        // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
7811        // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
7812        // `entrada.para`-projection converge at
7813        // caixa-core/src/render.rs (the `gateway_api_http_route_name`
7814        // route-name projection site). Prior to this converge the
7815        // `port_for_destination` resolver was the solitary consumer
7816        // bypassing the typed dispatch on the `.para` axis — the two
7817        // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
7818        // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
7819        // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
7820        // reach through the same accessor family compose with this
7821        // resolver at the emit boundary via the apex-identity
7822        // invariant `spec.port_for_destination(entrada.destination())
7823        // == entrada.port` the sibling
7824        // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
7825        // pin pins across four permutations. A future extension of the
7826        // `:entrada :para` axis to a richer author surface (a per-
7827        // cluster alias overlay the operator pins through a future
7828        // `:placement`-scoped slot, a namespace-qualified rewrite the
7829        // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
7830        // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
7831        // §III.2 acknowledges) that lands on the accessor would silently
7832        // disagree between this resolver and the two `caixa-mesh` emit
7833        // sites — an author-declared `:para "cart"` value the accessor
7834        // rewrote to `"cart-v2"` under a future canary arm would leave
7835        // the resolver's membership arm falling through to
7836        // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
7837        // `.para`) while the peer emit-site consumers landed on the
7838        // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
7839        // silently disagreed on which destination port a given typed
7840        // `:entrada` resolves to at cluster-apply time. Pinned by the
7841        // drift-detection test
7842        // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
7843        // below.
7844        self.entrada()
7845            .filter(|e| e.destination() == destination)
7846            .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
7847    }
7848}
7849
7850/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
7851/// entry may name the Aplicacao's own `:nome`.
7852///
7853/// An Aplicacao that lists itself as a member is a degenerate self-edge in
7854/// the typed graph — the application graph is a DAG rooted at the Aplicacao
7855/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
7856/// Servicos that compose the app; an Aplicacao is never its own constituent),
7857/// and the lacre pipeline's closure-resolution would otherwise be handed a
7858/// node that is its own parent: a one-node cycle it either rejects far from
7859/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
7860/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
7861/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
7862/// label + lacre closure root), a member whose `:caixa` equals the
7863/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
7864/// peer.
7865///
7866/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
7867/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
7868/// gate `validate_upgrade_from_against_versao` and the supervision-tree
7869/// self-parent gate `crate::supervisor::validate_no_self_supervision`
7870/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
7871/// not a tree/mesh edge" discipline, here on the second typed-graph axis
7872/// (the Aplicacao :membros set; the supervision-tree :children list was the
7873/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
7874/// every validated Supervisor's children are distinct from its `:nome`,
7875/// every validated Aplicacao's membros are distinct from its `:nome`. The
7876/// transitive consequence is that `:entrada :para` and `:contratos`
7877/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
7878/// name the Aplicacao itself, without re-deriving the partition.
7879pub fn validate_no_self_membership(
7880    membros: &[Membro],
7881    parent_nome: &str,
7882) -> Result<(), AplicacaoError> {
7883    for m in membros {
7884        if m.nome() == parent_nome {
7885            return Err(AplicacaoError::MembroIsSelfAplicacao {
7886                caixa: parent_nome.to_string(),
7887            });
7888        }
7889    }
7890    Ok(())
7891}
7892
7893#[derive(Debug, Error, PartialEq, Eq)]
7894pub enum AplicacaoError {
7895    #[error("Aplicacao must declare at least one :membros entry")]
7896    NoMembros,
7897    #[error(
7898        ":membros entry has empty :caixa (every member must name a Servico; \
7899         omit the entry instead of carrying an empty name)"
7900    )]
7901    MembroCaixaEmpty,
7902    #[error(
7903        ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
7904         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
7905         name / label value the member name lands in; use a lowercase \
7906         alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
7907    )]
7908    MembroCaixaInvalid { caixa: String, reason: String },
7909    #[error(
7910        ":membros entry {caixa:?} has empty :versao (every member must pin a \
7911         semver constraint that resolves through the lacre pipeline)"
7912    )]
7913    MembroVersaoEmpty { caixa: String },
7914    #[error(
7915        ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
7916         requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
7917         `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
7918         carries; the lacre pipeline resolves both through the same parser)"
7919    )]
7920    MembroVersaoInvalid {
7921        caixa: String,
7922        versao: String,
7923        reason: String,
7924    },
7925    #[error(
7926        ":membros entry {caixa:?} appears more than once (the graph node set \
7927         is a set, not a multiset; duplicate members produce duplicate \
7928         programs.yaml entries and ambiguous :contratos membership lookups)"
7929    )]
7930    MembroDuplicate { caixa: String },
7931    #[error(
7932        "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
7933         never its own constituent Servico (the application graph is a DAG rooted \
7934         at the Aplicacao; :membros names the *other* caixas that compose the \
7935         app, not the app itself). Since every :nome is a globally-unique \
7936         substrate identity, a member naming the Aplicacao's own :nome is a \
7937         one-node lacre-closure recursion, not a coincidentally-named peer; \
7938         drop the self-referential :membros entry or rename it to the actual \
7939         constituent caixa."
7940    )]
7941    MembroIsSelfAplicacao { caixa: String },
7942    #[error(
7943        "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
7944         caixa declared in :membros; omit the contract or fill the {slot} field with a \
7945         member name)"
7946    )]
7947    ContratoCaixaEmpty { slot: &'static str },
7948    #[error(
7949        "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
7950         :contratos {slot} value names a member of :membros, which is itself a \
7951         DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
7952         object the member name lands in — Service, Pod, identity-based Cilium \
7953         selector; use a lowercase alphanumeric + hyphen identifier like \
7954         `\"checkout\"` or `\"cart-v2\"`)"
7955    )]
7956    ContratoCaixaInvalid {
7957        slot: &'static str,
7958        caixa: String,
7959        reason: String,
7960    },
7961    #[error("contrato references caixa {caixa:?} not declared in :membros")]
7962    ContratoMemberMissing { caixa: String },
7963    #[error(
7964        "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
7965         entry is an inter-Servico contract whose :de and :para must name distinct \
7966         :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
7967         the contract, or point :para at the member it actually calls)"
7968    )]
7969    ContratoSelfLoop { caixa: String, wit: String },
7970    #[error("contrato {de:?} → {para:?} has empty :wit")]
7971    EmptyWit { de: String, para: String },
7972    #[error(
7973        "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
7974         {reason} (the substrate dispatches `:wit` values on the canonical \
7975         lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
7976         `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
7977         demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
7978         kebab-case identifier per segment)"
7979    )]
7980    ContratoWitInvalid {
7981        de: String,
7982        para: String,
7983        wit: String,
7984        reason: String,
7985    },
7986    #[error(
7987        ":entrada :para is empty (every :entrada must route to a caixa declared in \
7988         :membros; fill the :para field with a member name)"
7989    )]
7990    EntradaParaEmpty,
7991    #[error(
7992        ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
7993         :entrada :para value names a member of :membros, which is itself a DNS-1123 \
7994         label per the K8s apiserver's `metadata.name` rule on every object the \
7995         member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
7996         Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
7997         `\"checkout\"` or `\"cart-v2\"`)"
7998    )]
7999    EntradaParaInvalid { para: String, reason: String },
8000    #[error(":entrada routes to caixa {para:?} not declared in :membros")]
8001    EntradaMemberMissing { para: String },
8002    #[error(":entrada must declare a non-empty :host")]
8003    EmptyEntradaHost,
8004    #[error(
8005        ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
8006         (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
8007         `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
8008         like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
8009    )]
8010    EntradaHostInvalid { host: String, reason: String },
8011    #[error(":entrada :port must be in 1..=65535, got 0")]
8012    EntradaPortZero,
8013    #[error(":entrada :paths entry is empty (use the empty list to match all)")]
8014    EntradaPathEmpty,
8015    #[error(
8016        ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
8017    )]
8018    EntradaPathNotAbsolute { path: String },
8019    #[error(
8020        ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
8021         value: {reason} (the K8s apiserver enforces the same shape on \
8022         `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
8023         single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
8024         requires percent-encoding `%XX` for non-ASCII and whitespace)"
8025    )]
8026    EntradaPathInvalid { path: String, reason: String },
8027    #[error(":entrada :paths entry {path:?} appears more than once")]
8028    EntradaPathDuplicate { path: String },
8029    #[error(
8030        ":placement {estrategia} requires at least one :clusters entry \
8031         (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
8032    )]
8033    PlacementWithoutClusters { estrategia: PlacementStrategy },
8034    #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
8035    PlacementClusterEmpty,
8036    #[error(
8037        ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
8038         (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
8039         in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
8040         future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
8041         — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
8042         identifier like `\"rio\"` or `\"mar-east\"`)"
8043    )]
8044    PlacementClusterInvalid { cluster: String, reason: String },
8045    #[error(":placement :clusters entry {cluster:?} appears more than once")]
8046    PlacementClusterDuplicate { cluster: String },
8047    #[error(
8048        ":placement :affinity must be non-empty when set (omit :affinity to express \
8049         `no placement hint`)"
8050    )]
8051    PlacementAffinityEmpty,
8052    #[error(
8053        ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
8054         (placement hints land verbatim in the M3 Adaptive compression overlay's \
8055         `placement.affinity` field and in every future M4 placement-engine routing \
8056         axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
8057         selector — both enforce the DNS-1123 label rule on admission; use a \
8058         lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
8059         `\"low-latency\"`, or `\"anti-affinity\"`)"
8060    )]
8061    PlacementAffinityInvalid { affinity: String, reason: String },
8062    #[error(":placement Sharded requires :shard-key")]
8063    ShardedWithoutKey,
8064    #[error(
8065        ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
8066         hashes every entity onto the same shard, defeating sharding entirely)"
8067    )]
8068    ShardedKeyEmpty,
8069    #[error(
8070        ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
8071         entity-id extractor expression: {reason} (the future M4 Akka-style \
8072         cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
8073         as a single-token property reference and hashes the extracted entity ID \
8074         to compute shard placement; use a printable-ASCII extractor expression \
8075         like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
8076         `\"${{tenant}}\"`)"
8077    )]
8078    ShardKeyInvalid { shard_key: String, reason: String },
8079    #[error(
8080        ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
8081         Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
8082         convention); :estrategia Replicated runs every cluster active-active and \
8083         :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
8084         distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
8085         to :estrategia Sharded if hash-keyed routing is the intent"
8086    )]
8087    ShardKeyOnNonSharded {
8088        estrategia: PlacementStrategy,
8089        shard_key: String,
8090    },
8091    #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
8092    ContratoMissingTarget {
8093        de: String,
8094        para: String,
8095        wit: String,
8096        expected: &'static str,
8097    },
8098    #[error(
8099        "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
8100         expected `:{expected}` only"
8101    )]
8102    ContratoWrongTarget {
8103        de: String,
8104        para: String,
8105        wit: String,
8106        expected: &'static str,
8107    },
8108    #[error(
8109        "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
8110         like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
8111         that matches no traffic and silently drops every request)"
8112    )]
8113    ContratoEndpointEmpty { de: String, para: String },
8114    #[error(
8115        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
8116         (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
8117         :entrada :paths)"
8118    )]
8119    ContratoEndpointNotAbsolute {
8120        de: String,
8121        para: String,
8122        endpoint: String,
8123    },
8124    #[error(
8125        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
8126         Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
8127         emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
8128         caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
8129         shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
8130         like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
8131         and whitespace)"
8132    )]
8133    ContratoEndpointInvalid {
8134        de: String,
8135        para: String,
8136        endpoint: String,
8137        reason: String,
8138    },
8139    #[error(
8140        "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
8141         subject is a no-op subscribe; omit :subject only if the WIT world is not \
8142         pub-sub-shaped)"
8143    )]
8144    ContratoSubjectEmpty { de: String, para: String },
8145    #[error(
8146        "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
8147         NATS subject: {reason} (the NATS server's subject parser enforces the \
8148         same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
8149         single-token and `>` multi-token wildcards — at publish/subscribe time; \
8150         use a token-by-token form like `\"checkout.events.charge.failed\"` or \
8151         `\"orders.*.completed\"` — a malformed subject silently drops every \
8152         message at runtime far from the source caixa.lisp)"
8153    )]
8154    ContratoSubjectInvalid {
8155        de: String,
8156        para: String,
8157        subject: String,
8158        reason: String,
8159    },
8160    #[error(
8161        "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
8162         addresses the bucket root, defeating the per-key isolation the slot exists \
8163         for; omit :slot only if the WIT world is not store-shaped)"
8164    )]
8165    ContratoSlotEmpty { de: String, para: String },
8166    #[error(
8167        "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
8168         WASI keyvalue store slot template: {reason} (the substrate enforces \
8169         the printable-ASCII intersection-floor every kv backend admits — \
8170         use a single-token path / template expression like `\"checkout/$orderId\"`, \
8171         `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
8172         percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
8173         slot either gets rejected on write by strict backends or silently \
8174         corrupts the next read on permissive ones, far from the source caixa.lisp)"
8175    )]
8176    ContratoSlotInvalid {
8177        de: String,
8178        para: String,
8179        slot: String,
8180        reason: String,
8181    },
8182    #[error(
8183        "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
8184         or an event-sourced indirection (MESH-COMPOSITION §III.3)",
8185        cycle.join(" → ")
8186    )]
8187    ContratoCycle { cycle: Vec<String> },
8188    #[error(
8189        ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
8190         than once (the typed graph edges are a set, not a multiset; duplicate \
8191         contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
8192         values that K8s admission rejects far from the source caixa.lisp)"
8193    )]
8194    ContratoDuplicate {
8195        de: String,
8196        para: String,
8197        wit: String,
8198        target: String,
8199    },
8200    #[error(
8201        ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
8202         contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
8203         express `no per-call deadline on this axis`"
8204    )]
8205    PolicyTimeoutZero,
8206    #[error(
8207        ":politicas :retries must be > 0 when set; omit :retries to express \
8208         `no retries on transient failure`"
8209    )]
8210    PolicyRetriesZero,
8211    #[error(
8212        ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
8213         (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
8214         retry policy into a thundering-herd amplification vector on transient \
8215         failure (one caller request fans out to `(retries+1)^depth` server-side \
8216         calls across the synchronous-:contratos subgraph), exactly the failure \
8217         mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
8218         Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
8219         or omit :retries to disable retries entirely"
8220    )]
8221    PolicyRetriesExceedsCap { retries: u32 },
8222    #[error(
8223        ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
8224         breaker trips on the first call); omit :circuit-breaker to disable it"
8225    )]
8226    PolicyBreakerZeroFailures,
8227    #[error(
8228        ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
8229         mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
8230         above this cap turns the typed breaker policy into a no-op: the trip \
8231         threshold is structurally so high that no realistic failures-per-:window \
8232         traffic shape can reach it, so the breaker never trips and every typed-slot \
8233         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
8234         Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
8235         structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
8236         Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
8237         omit :circuit-breaker to disable the breaker entirely"
8238    )]
8239    PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
8240    #[error(
8241        ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
8242         tracks no failures); omit :circuit-breaker to disable it"
8243    )]
8244    PolicyBreakerZeroWindow,
8245    #[error(
8246        ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
8247         request); omit :rate-limit to disable rate limiting"
8248    )]
8249    PolicyRateLimitZero,
8250    #[error(
8251        ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
8252         (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
8253         rate-limit policy into a no-op limiter: the token-bucket capacity is \
8254         structurally so high that no realistic per-edge traffic shape can drain it, \
8255         so the limiter never trips and every typed-slot consumer (the future \
8256         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
8257         local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
8258         that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
8259         Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
8260         Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
8261         Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
8262         to disable rate limiting entirely"
8263    )]
8264    PolicyRateLimitExceedsCap { rate: u32 },
8265    #[error(
8266        ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
8267         the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
8268         rate-limit codec round-trips losslessly; got {window:?} which renders to a \
8269         non-round-trippable form (omit :rate-limit to disable, or pick one of the \
8270         three canonical windows)"
8271    )]
8272    PolicyRateLimitWindowNotCanonical { window: Duration },
8273    #[error(
8274        ":politicas :timeout must be an integer number of milliseconds — the canonical \
8275         authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
8276         duration codec round-trips losslessly; got {timeout:?} which carries a \
8277         sub-millisecond residue that either truncates to a different `Duration` on \
8278         re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
8279         to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
8280         zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
8281         (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
8282    )]
8283    PolicyTimeoutNotCanonical { timeout: Duration },
8284    #[error(
8285        ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
8286         (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
8287         per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
8288         overlays carry a deadline so long no realistic synchronous-:contratos \
8289         traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
8290         CSE invariant degenerates to enforcement only at the per-Servico \
8291         `:limits :wall-clock` layer — far above the per-edge granularity the typed \
8292         `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
8293         (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
8294         ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
8295         maxes out at the same `3600s` ceiling) or omit :timeout to express \
8296         `no per-call deadline on this axis` (the synchronous-call deadline then \
8297         relies entirely on the per-Servico `:limits :wall-clock` axis)"
8298    )]
8299    PolicyTimeoutExceedsCap { timeout: Duration },
8300    #[error(
8301        ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
8302         the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
8303         the shared duration codec round-trips losslessly; got {window:?} which carries a \
8304         sub-millisecond residue that either truncates to a different `Duration` on \
8305         re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
8306         Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
8307    )]
8308    PolicyBreakerWindowNotCanonical { window: Duration },
8309    #[error(
8310        ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
8311         (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
8312         rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
8313         is structurally so long that transient failures are never forgotten, the breaker \
8314         trips once and stays tripped for the lifetime of the component, and every typed-slot \
8315         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
8316         outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
8317         Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
8318         default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
8319         the breaker entirely"
8320    )]
8321    PolicyBreakerWindowExceedsCap { window: Duration },
8322}
8323
8324#[cfg(test)]
8325mod tests {
8326    use super::*;
8327
8328    fn membro(name: &str, ver: &str) -> Membro {
8329        Membro {
8330            caixa: name.into(),
8331            versao: ver.into(),
8332        }
8333    }
8334
8335    fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
8336        WitContract {
8337            de: de.into(),
8338            para: para.into(),
8339            wit: "wasi:http/proxy".into(),
8340            endpoint: Some(ep.into()),
8341            subject: None,
8342            slot: None,
8343        }
8344    }
8345
8346    fn three_member_spec() -> AplicacaoSpec {
8347        AplicacaoSpec {
8348            membros: vec![
8349                membro("catalog", "^0.1"),
8350                membro("cart", "^0.1"),
8351                membro("payment", "^0.2"),
8352            ],
8353            contratos: vec![
8354                contract_http("cart", "catalog", "/products/:id"),
8355                contract_http("cart", "payment", "/charge"),
8356            ],
8357            politicas: MeshPolicy {
8358                timeout: Some(Duration::from_secs(30)),
8359                retries: Some(3),
8360                mtls_required: Some(true),
8361                ..Default::default()
8362            },
8363            placement: Placement {
8364                estrategia: PlacementStrategy::Replicated,
8365                clusters: vec!["rio".into(), "mar".into()],
8366                affinity: Some("data-locality".into()),
8367                shard_key: None,
8368            },
8369            entrada: Some(Entrada {
8370                host: "checkout.quero.cloud".into(),
8371                para: "cart".into(),
8372                paths: vec!["/api/cart".into(), "/api/products".into()],
8373                port: 8080,
8374            }),
8375        }
8376    }
8377
8378    #[test]
8379    fn happy_path_validates() {
8380        three_member_spec().validate().unwrap();
8381    }
8382
8383    #[test]
8384    fn rejects_empty_membros() {
8385        let mut s = three_member_spec();
8386        s.membros = vec![];
8387        assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
8388    }
8389
8390    #[test]
8391    fn rejects_empty_membro_caixa() {
8392        // A `:caixa ""` entry has no name to render into programs.yaml
8393        // and no caixa.lisp to resolve at lacre time.
8394        let mut s = three_member_spec();
8395        s.membros[1].caixa = String::new();
8396        assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
8397    }
8398
8399    #[test]
8400    fn rejects_empty_membro_versao() {
8401        // A `:versao ""` entry can't pin a semver constraint, so the
8402        // lacre pipeline fails far from the source.
8403        let mut s = three_member_spec();
8404        s.membros[2].versao = String::new();
8405        let err = s.validate().unwrap_err();
8406        assert!(
8407            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
8408            "got {err:?}"
8409        );
8410    }
8411
8412    #[test]
8413    fn rejects_duplicate_membro_caixa() {
8414        // Two `:membros` entries with the same `:caixa` collapse to one
8415        // node in the membership HashSet, which masks `:contratos`
8416        // membership errors and produces duplicate programs.yaml entries.
8417        let mut s = three_member_spec();
8418        s.membros.push(membro("cart", "^0.2"));
8419        let err = s.validate().unwrap_err();
8420        assert!(
8421            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
8422            "got {err:?}"
8423        );
8424    }
8425
8426    #[test]
8427    fn rejects_invalid_membro_versao_requirement() {
8428        // The fail-before-pass-after pin: a non-empty but malformed
8429        // semver requirement (`"^bad-version"`) silently passed
8430        // `validate()` on every pre-gate codebase because the prior
8431        // shape only refused the empty string. The parse failure
8432        // surfaced far downstream at lacre-resolve time with a
8433        // `semver::Error` that didn't name which `:membros` entry
8434        // carried the typo. The new gate moves the check to caixa-build
8435        // time at the source caixa.lisp.
8436        let mut s = three_member_spec();
8437        s.membros[2].versao = "^bad-version".into();
8438        let err = s.validate().unwrap_err();
8439        assert!(
8440            matches!(
8441                err,
8442                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8443                    if caixa == "payment" && versao == "^bad-version"
8444            ),
8445            "got {err:?}"
8446        );
8447    }
8448
8449    #[test]
8450    fn rejects_membro_versao_with_double_caret_typo() {
8451        // `"^^0.1"` is the canonical doubled-caret typo — looks like a
8452        // Cargo-shaped requirement on first glance but fails the parser
8453        // because semver doesn't accept stacked operators. Pin this
8454        // adjacent-shape footgun explicitly so a future relaxation that
8455        // accepts "looks-canonical-but-isn't" forms surfaces here.
8456        let mut s = three_member_spec();
8457        s.membros[0].versao = "^^0.1".into();
8458        let err = s.validate().unwrap_err();
8459        assert!(
8460            matches!(
8461                err,
8462                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8463                    if caixa == "catalog" && versao == "^^0.1"
8464            ),
8465            "got {err:?}"
8466        );
8467    }
8468
8469    #[test]
8470    fn rejects_membro_versao_with_v_prefixed_tag() {
8471        // `"v0.1"` is the canonical "git-tag-shape leaking into the
8472        // semver requirement slot" typo — an author copies the
8473        // publish-side git-tag string verbatim into `:versao`, but
8474        // Cargo's semver parser rejects the leading `v` (only digits +
8475        // canonical operators are valid in the major-version
8476        // position). The gate's diagnostic names which member entry
8477        // carried the v-prefix so the fix is one edit, not a grep
8478        // through every member's `:versao`. (Note: bare `x`-glob
8479        // shorthands like `^0.1.x` are *accepted* by the semver crate
8480        // as an `*` wildcard on the patch axis — they're a Cargo-side
8481        // valid shape, not a typo, so the gate intentionally lets them
8482        // through.)
8483        let mut s = three_member_spec();
8484        s.membros[1].versao = "v0.1".into();
8485        let err = s.validate().unwrap_err();
8486        assert!(
8487            matches!(
8488                err,
8489                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8490                    if caixa == "cart" && versao == "v0.1"
8491            ),
8492            "got {err:?}"
8493        );
8494    }
8495
8496    #[test]
8497    fn accepts_canonical_membro_versao_forms() {
8498        // The four Cargo-shaped requirement forms `:deps :versao`
8499        // already accepts via `crate::parse_requirement` must pass the
8500        // membros gate without re-validating at the resolver layer.
8501        // Pin every leg so a future tightening of the canonical set
8502        // surfaces here as a test failure.
8503        for form in [
8504            "^0.1",      // caret — minor-range pin (the most common shape)
8505            "~0.1.2",    // tilde — patch-range pin
8506            "0.1.0",     // exact — single-version pin
8507            "*",         // wildcard — explicitly any-version (semver::VersionReq::STAR)
8508            ">=0.1, <2", // multi-range — comma-separated comparators
8509        ] {
8510            let mut s = three_member_spec();
8511            for m in &mut s.membros {
8512                m.versao = form.into();
8513            }
8514            s.validate()
8515                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
8516        }
8517    }
8518
8519    #[test]
8520    fn membro_versao_empty_takes_precedence_over_invalid() {
8521        // Order pin: the existing `MembroVersaoEmpty` diagnostic
8522        // (which doesn't try to parse) fires before the new
8523        // `MembroVersaoInvalid` parse-side diagnostic, so an empty
8524        // `:versao` keeps its narrower error message — `parse_requirement`
8525        // would also reject `""`, but the empty-string arm is the more
8526        // self-locating diagnostic for the author.
8527        let mut s = three_member_spec();
8528        s.membros[1].versao = String::new();
8529        let err = s.validate().unwrap_err();
8530        assert!(
8531            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
8532            "got {err:?}"
8533        );
8534    }
8535
8536    #[test]
8537    fn membro_versao_invalid_fires_before_duplicate_check() {
8538        // Order pin: a malformed requirement on a non-duplicate entry
8539        // surfaces *its own* diagnostic (which names the offending
8540        // `:versao` string), even when a later entry would otherwise
8541        // collapse onto an earlier name. The per-entry shape gate runs
8542        // inline before the duplicate-key insert, parallel to
8543        // `membros_validation_runs_before_contratos_membership_check`
8544        // and `duplicate_contrato_gate_runs_after_target_shape_check`.
8545        let mut s = three_member_spec();
8546        s.membros[0].versao = "^bad".into();
8547        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
8548        let err = s.validate().unwrap_err();
8549        assert!(
8550            matches!(
8551                err,
8552                AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
8553            ),
8554            "got {err:?}"
8555        );
8556    }
8557
8558    #[test]
8559    fn membro_versao_invalid_diagnostic_carries_offending_versao() {
8560        // The diagnostic-shape pin: the error names the offending
8561        // `:versao` value verbatim so the author can grep their
8562        // caixa.lisp without re-running the build, and carries a
8563        // non-empty `reason` from `semver::VersionReq::parse` so the
8564        // parser's own wording flows through to the diagnostic.
8565        let mut s = three_member_spec();
8566        s.membros[2].versao = "not-a-req".into();
8567        let err = s.validate().unwrap_err();
8568        let AplicacaoError::MembroVersaoInvalid {
8569            caixa,
8570            versao,
8571            reason,
8572        } = err
8573        else {
8574            panic!("expected MembroVersaoInvalid, got other variant");
8575        };
8576        assert_eq!(caixa, "payment");
8577        assert_eq!(versao, "not-a-req");
8578        assert!(
8579            !reason.is_empty(),
8580            "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
8581        );
8582    }
8583
8584    #[test]
8585    fn membro_versao_invalid_runs_before_contratos_check() {
8586        // A malformed `:versao` on any member must surface its own
8587        // diagnostic (which names *which* member to fix) before any
8588        // `:contratos` membership lookup raises `ContratoMemberMissing`.
8589        // The `:contratos` gate runs after `validate_membros`, so this
8590        // is structurally guaranteed — pin it explicitly so a future
8591        // refactor that reorders the gates surfaces here.
8592        let mut s = three_member_spec();
8593        s.membros[1].versao = "^^0.1".into();
8594        // Add a contrato whose `:para` doesn't exist — would normally
8595        // raise ContratoMemberMissing at the membership lookup, but
8596        // the membros gate must fire first.
8597        s.contratos
8598            .push(contract_http("cart", "phantom", "/never-reached"));
8599        let err = s.validate().unwrap_err();
8600        assert!(
8601            matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
8602            "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
8603        );
8604    }
8605
8606    #[test]
8607    fn membros_validation_runs_before_contratos_membership_check() {
8608        // If `:membros` carries a duplicate, the membership-collapse
8609        // would silently accept a `:contratos :para "phantom"` so long
8610        // as some entry hashes to "phantom". Pinning order: the
8611        // duplicate-membros error fires first, regardless of whether
8612        // contratos reference real members.
8613        let mut s = three_member_spec();
8614        s.membros = vec![
8615            membro("cart", "^0.1"),
8616            membro("cart", "^0.2"),
8617            membro("catalog", "^0.1"),
8618            membro("payment", "^0.1"),
8619        ];
8620        let err = s.validate().unwrap_err();
8621        assert!(
8622            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
8623            "got {err:?}"
8624        );
8625    }
8626
8627    #[test]
8628    fn distinct_membros_validate() {
8629        // Pin the happy-path: every `:membros` entry has a non-empty
8630        // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
8631        // The fixture already satisfies this; this test makes the
8632        // invariant explicit so a future refactor of the fixture can't
8633        // silently break the guarantee.
8634        three_member_spec().validate().unwrap();
8635    }
8636
8637    // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
8638
8639    #[test]
8640    fn rejects_membro_caixa_with_uppercase() {
8641        // The canonical "I copied the Servico's display name verbatim"
8642        // typo — caixa names are lowercase per K8s DNS-1123 label rule,
8643        // but author tools often round-trip a TitleCase or CamelCase
8644        // identifier from an ADR or a sketch. Pin the diagnostic names
8645        // the offending name and suggests the lower-cased fix in one
8646        // edit, mirroring the `rejects_entrada_host_with_uppercase`
8647        // gate's shape (c7d05ec).
8648        let mut s = three_member_spec();
8649        s.membros[1].caixa = "Cart".into();
8650        let err = s.validate().unwrap_err();
8651        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
8652            panic!("expected MembroCaixaInvalid, got other variant");
8653        };
8654        assert_eq!(caixa, "Cart");
8655        assert!(
8656            reason.contains("uppercase"),
8657            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
8658        );
8659        assert!(
8660            reason.contains("\"cart\""),
8661            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
8662        );
8663    }
8664
8665    #[test]
8666    fn rejects_membro_caixa_with_underscore() {
8667        // The canonical "I'm thinking of a Python module / Postgres
8668        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
8669        // label schema. K8s rejects `metadata.name: my_cart` at admission
8670        // time with an opaque `field is invalid` (no source-citing
8671        // diagnostic). The gate moves it to caixa-build time.
8672        let mut s = three_member_spec();
8673        s.membros[0].caixa = "my_cart".into();
8674        let err = s.validate().unwrap_err();
8675        assert!(
8676            matches!(
8677                err,
8678                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
8679                    if caixa == "my_cart" && reason.contains('_')
8680            ),
8681            "got {err:?}"
8682        );
8683    }
8684
8685    #[test]
8686    fn rejects_membro_caixa_with_dot() {
8687        // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
8688        // subdomain — even though K8s `metadata.name` itself accepts
8689        // dots (DNS-1123 subdomain rule), this string also lands as a
8690        // K8s Service name (DNS-1035 label — no dots) and as a label
8691        // value on identity-based Cilium selectors. The strictest floor
8692        // among the use sites wins. The "I want to namespace my member
8693        // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
8694        let mut s = three_member_spec();
8695        s.membros[2].caixa = "team.cart".into();
8696        let err = s.validate().unwrap_err();
8697        assert!(
8698            matches!(
8699                err,
8700                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
8701                    if caixa == "team.cart" && reason.contains('.')
8702            ),
8703            "got {err:?}"
8704        );
8705    }
8706
8707    #[test]
8708    fn rejects_membro_caixa_with_leading_hyphen() {
8709        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
8710        // with an alphanumeric. The K8s apiserver rejects `-cart`
8711        // outright; the renderer would emit a `metadata.name: "-cart"`
8712        // that fails admission far from the source caixa.lisp.
8713        let mut s = three_member_spec();
8714        s.membros[0].caixa = "-cart".into();
8715        let err = s.validate().unwrap_err();
8716        assert!(
8717            matches!(
8718                err,
8719                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
8720                    if caixa == "-cart" && reason.contains("start and end")
8721            ),
8722            "got {err:?}"
8723        );
8724    }
8725
8726    #[test]
8727    fn rejects_membro_caixa_with_trailing_hyphen() {
8728        // The symmetric arm of the boundary rule. Pin separately so
8729        // both ends of the label are covered against a future relaxation
8730        // that only checks one boundary.
8731        let mut s = three_member_spec();
8732        s.membros[1].caixa = "cart-".into();
8733        let err = s.validate().unwrap_err();
8734        assert!(
8735            matches!(
8736                err,
8737                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
8738                    if caixa == "cart-"
8739            ),
8740            "got {err:?}"
8741        );
8742    }
8743
8744    #[test]
8745    fn rejects_membro_caixa_with_unicode() {
8746        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
8747        // (`xn--…`) by the author before it reaches K8s. The byte-by-
8748        // byte ASCII validity check rejects multi-byte UTF-8 sequences
8749        // by the first byte that fails the `[a-z0-9-]` predicate.
8750        let mut s = three_member_spec();
8751        s.membros[2].caixa = "café".into();
8752        let err = s.validate().unwrap_err();
8753        assert!(
8754            matches!(
8755                err,
8756                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
8757                    if caixa == "café"
8758            ),
8759            "got {err:?}"
8760        );
8761    }
8762
8763    #[test]
8764    fn rejects_membro_caixa_with_whitespace() {
8765        // Whitespace is the canonical "I pasted from a sketch / doc"
8766        // footgun. The apiserver rejects every `metadata.name` value
8767        // carrying whitespace; pin the gate fires at the right boundary.
8768        let mut s = three_member_spec();
8769        s.membros[0].caixa = "my cart".into();
8770        let err = s.validate().unwrap_err();
8771        assert!(
8772            matches!(
8773                err,
8774                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
8775                    if caixa == "my cart"
8776            ),
8777            "got {err:?}"
8778        );
8779    }
8780
8781    #[test]
8782    fn rejects_membro_caixa_too_long() {
8783        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
8784        // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
8785        // exactly. The gate's reason names both the cap and the actual
8786        // length so the author can shorten in one edit.
8787        let mut s = three_member_spec();
8788        let too_long = "a".repeat(64);
8789        s.membros[1].caixa = too_long.clone();
8790        let err = s.validate().unwrap_err();
8791        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
8792            panic!("expected MembroCaixaInvalid");
8793        };
8794        assert_eq!(caixa, too_long);
8795        assert!(
8796            reason.contains("63") && reason.contains("64"),
8797            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
8798        );
8799    }
8800
8801    #[test]
8802    fn membro_caixa_max_length_validates() {
8803        // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
8804        // so a future tightening (e.g. dropping to 62) surfaces here as
8805        // a regression, mirroring `entrada_host_max_length_validates`
8806        // (c7d05ec).
8807        let mut s = three_member_spec();
8808        s.membros[2].caixa = "a".repeat(63);
8809        s.entrada.as_mut().unwrap().para = "a".repeat(63);
8810        // remove contratos referencing the renamed member; they'd
8811        // raise ContratoMemberMissing otherwise
8812        s.contratos
8813            .retain(|c| c.de != "payment" && c.para != "payment");
8814        s.validate().unwrap();
8815    }
8816
8817    #[test]
8818    fn accepts_canonical_membro_caixa_forms() {
8819        // The DNS-1123 label shapes a caixa author is realistically
8820        // going to write: single-word lowercase, hyphen-joined, ending
8821        // in a digit-suffixed version (`cart-v2`), starting with a
8822        // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
8823        // DNS-1035 which requires a letter at position 0), single-
8824        // character (`a` — boundary). Pin every leg so a future
8825        // tightening that bans (e.g.) digit-start identifiers surfaces
8826        // here.
8827        for form in [
8828            "checkout",
8829            "cart",
8830            "cart-v2",
8831            "a",
8832            "c0",
8833            "3rd-party-shim",
8834            "x-1-2-3-4",
8835        ] {
8836            let mut s = three_member_spec();
8837            // Renaming a member also requires updating downstream refs;
8838            // drop everything else and rebuild a minimal spec around
8839            // just the one renamed member.
8840            s.membros = vec![membro(form, "^0.1")];
8841            s.contratos = vec![];
8842            s.entrada = None;
8843            s.validate()
8844                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
8845        }
8846    }
8847
8848    #[test]
8849    fn membro_caixa_empty_takes_precedence_over_invalid() {
8850        // Order pin: the existing `MembroCaixaEmpty` diagnostic
8851        // (which doesn't try to parse) fires before the new
8852        // `MembroCaixaInvalid` parse-side diagnostic, so an empty
8853        // `:caixa` keeps its narrower error message — the new gate
8854        // would also reject `""`, but the empty-string arm is the more
8855        // self-locating diagnostic for the author. Mirrors the
8856        // `entrada_host_empty_takes_precedence_over_invalid` pin
8857        // (c7d05ec).
8858        let mut s = three_member_spec();
8859        s.membros[1].caixa = String::new();
8860        let err = s.validate().unwrap_err();
8861        assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
8862    }
8863
8864    #[test]
8865    fn membro_caixa_invalid_fires_before_versao_check() {
8866        // Order pin: an invalid-shape `:caixa` surfaces *its own*
8867        // diagnostic (which names the offending caixa name), even when
8868        // the same entry's `:versao` is also empty/invalid. The shape
8869        // gate runs first because the diagnostic is more self-locating —
8870        // an empty/invalid `:versao` on an invalid-shape caixa name is
8871        // a downstream-fix-after-the-caixa-rename concern.
8872        let mut s = three_member_spec();
8873        s.membros[1].caixa = "Cart".into();
8874        s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
8875        let err = s.validate().unwrap_err();
8876        assert!(
8877            matches!(
8878                err,
8879                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
8880            ),
8881            "got {err:?}"
8882        );
8883    }
8884
8885    #[test]
8886    fn membro_caixa_invalid_fires_before_duplicate_check() {
8887        // Order pin: a malformed-shape `:caixa` on an earlier entry
8888        // surfaces *its own* diagnostic, even when a later entry would
8889        // otherwise collapse onto a duplicate name. The per-entry shape
8890        // gate runs inline before the duplicate-key insert, parallel
8891        // to `membro_versao_invalid_fires_before_duplicate_check`.
8892        let mut s = three_member_spec();
8893        s.membros[0].caixa = "Catalog".into();
8894        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
8895        let err = s.validate().unwrap_err();
8896        assert!(
8897            matches!(
8898                err,
8899                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
8900            ),
8901            "got {err:?}"
8902        );
8903    }
8904
8905    #[test]
8906    fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
8907        // The diagnostic-shape pin: the error names the offending
8908        // `:caixa` value verbatim so the author can grep their
8909        // caixa.lisp without re-running the build, and carries a
8910        // non-empty `reason` naming the specific violation. Same
8911        // shape every typed-shape gate enshrines (c7d05ec's
8912        // `entrada_host_diagnostic_carries_offending_host`,
8913        // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
8914        let mut s = three_member_spec();
8915        s.membros[2].caixa = "BAD_NAME".into();
8916        let err = s.validate().unwrap_err();
8917        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
8918            panic!("expected MembroCaixaInvalid");
8919        };
8920        assert_eq!(caixa, "BAD_NAME");
8921        assert!(
8922            !reason.is_empty(),
8923            "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
8924        );
8925    }
8926
8927    #[test]
8928    fn rejects_contrato_with_unknown_de() {
8929        let mut s = three_member_spec();
8930        s.contratos.push(contract_http("phantom", "catalog", "/x"));
8931        let err = s.validate().unwrap_err();
8932        assert!(
8933            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
8934        );
8935    }
8936
8937    #[test]
8938    fn rejects_contrato_with_unknown_para() {
8939        let mut s = three_member_spec();
8940        s.contratos.push(contract_http("cart", "phantom", "/x"));
8941        let err = s.validate().unwrap_err();
8942        assert!(
8943            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
8944        );
8945    }
8946
8947    #[test]
8948    fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
8949        // The read-path pin: the phantom-`:de` refusal arm's
8950        // `ContratoMemberMissing.caixa` carrier must be observed through
8951        // the lifted [`WitContract::source`] accessor, not the raw
8952        // `.de.clone()` field-access `String`-carry. Peer of the sibling
8953        // per-`:contratos` self-loop arm's `.source().to_string()` /
8954        // `.world_ref().to_string()` `String`-carry sites the earlier
8955        // convergence lifted onto the same accessor pair. A future
8956        // silent detour that reintroduced the raw `.de.clone()` at the
8957        // wrap envelope while the shape-gate and membership lookup
8958        // routed through the accessor would surface here as a byte-equal
8959        // miss between the fired diagnostic's `caixa:` field and the
8960        // offending edge's `.source()` — pinning the accessor as the
8961        // sole read path across the phantom-name refusal arm's arg +
8962        // wrap-envelope emit surface.
8963        let mut s = three_member_spec();
8964        let phantom = contract_http("phantom", "catalog", "/x");
8965        s.contratos.push(phantom.clone());
8966        let err = s.validate().unwrap_err();
8967        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
8968            panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
8969        };
8970        assert_eq!(
8971            caixa,
8972            phantom.source(),
8973            "ContratoMemberMissing.caixa on the phantom-:de arm must \
8974             byte-equal WitContract::source — the wrap envelope must \
8975             route through the lifted accessor rather than the raw \
8976             .de.clone() field-access String-carry"
8977        );
8978    }
8979
8980    #[test]
8981    fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
8982        // The symmetric read-path pin on the `:para` phantom-name
8983        // refusal arm — same shape as the sibling `:de` pin above but
8984        // on the callee-Servico axis. Pins the wrap envelope's
8985        // `caixa:` field is observed through the lifted
8986        // [`WitContract::destination`] accessor, not the raw
8987        // `.para.clone()` field-access `String`-carry.
8988        let mut s = three_member_spec();
8989        let phantom = contract_http("cart", "phantom", "/x");
8990        s.contratos.push(phantom.clone());
8991        let err = s.validate().unwrap_err();
8992        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
8993            panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
8994        };
8995        assert_eq!(
8996            caixa,
8997            phantom.destination(),
8998            "ContratoMemberMissing.caixa on the phantom-:para arm must \
8999             byte-equal WitContract::destination — the wrap envelope \
9000             must route through the lifted accessor rather than the raw \
9001             .para.clone() field-access String-carry"
9002        );
9003    }
9004
9005    #[test]
9006    fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
9007        // The read-path pin on the `:de` DNS-1123-malformed shape-gate
9008        // refusal arm — the `validate_contrato_caixa` arg must be
9009        // observed through the lifted [`WitContract::source`] accessor,
9010        // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
9011        // value routes through the shared
9012        // [`crate::render::require_valid_dns_1123_label`] floor with the
9013        // accessor-projected value; the fired
9014        // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
9015        // the offending edge's `.source()`, pinning that the arg + the
9016        // downstream `caixa: caixa.to_string()` wrap route through the
9017        // same accessor's read path.
9018        let mut s = three_member_spec();
9019        let malformed = contract_http("BAD_NAME", "catalog", "/x");
9020        s.contratos.push(malformed.clone());
9021        let err = s.validate().unwrap_err();
9022        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
9023            panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
9024        };
9025        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
9026        assert_eq!(
9027            caixa,
9028            malformed.source(),
9029            "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
9030             byte-equal WitContract::source — the shape-gate arg + wrap \
9031             envelope must route through the lifted accessor rather \
9032             than the raw &c.de &String-borrow"
9033        );
9034    }
9035
9036    #[test]
9037    fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
9038        // Symmetric arm to the sibling `:de` malformed-shape pin above,
9039        // on the `:para` axis. Pins the shape-gate arg + wrap envelope
9040        // route through the lifted [`WitContract::destination`]
9041        // accessor. `:para` runs after the `:de` shape gate in the
9042        // canonical edge-direction order, so the `:de` value must be
9043        // well-shaped for the `:para` gate to fire — the `cart` :de is
9044        // canonical.
9045        let mut s = three_member_spec();
9046        let malformed = contract_http("cart", "BAD_NAME", "/x");
9047        s.contratos.push(malformed.clone());
9048        let err = s.validate().unwrap_err();
9049        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
9050            panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
9051        };
9052        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
9053        assert_eq!(
9054            caixa,
9055            malformed.destination(),
9056            "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
9057             byte-equal WitContract::destination — the shape-gate arg + \
9058             wrap envelope must route through the lifted accessor \
9059             rather than the raw &c.para &String-borrow"
9060        );
9061    }
9062
9063    // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
9064
9065    #[test]
9066    fn rejects_contrato_de_empty() {
9067        // `:de ""` previously fell through to `ContratoMemberMissing`
9068        // (with `caixa: ""`) because the validated `:membros :caixa`
9069        // set never contains the empty string. The narrower
9070        // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
9071        // the offending slot.
9072        let mut s = three_member_spec();
9073        s.contratos.push(contract_http("", "catalog", "/x"));
9074        let err = s.validate().unwrap_err();
9075        assert_eq!(
9076            err,
9077            AplicacaoError::ContratoCaixaEmpty {
9078                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9079            },
9080            "got {err:?}"
9081        );
9082    }
9083
9084    #[test]
9085    fn rejects_contrato_para_empty() {
9086        // Symmetric arm to `:de ""` — `:para ""` previously fell
9087        // through to `ContratoMemberMissing { caixa: "" }`.
9088        let mut s = three_member_spec();
9089        s.contratos.push(contract_http("cart", "", "/x"));
9090        let err = s.validate().unwrap_err();
9091        assert_eq!(
9092            err,
9093            AplicacaoError::ContratoCaixaEmpty {
9094                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
9095            },
9096            "got {err:?}"
9097        );
9098    }
9099
9100    #[test]
9101    fn rejects_contrato_de_with_uppercase() {
9102        // The canonical "I copied the Servico's TitleCase display
9103        // name from an ADR" typo. Until this gate landed `:de "Cart"`
9104        // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
9105        // as "this caixa isn't in `:membros`" when the root cause is
9106        // "this `:de` value's shape can never legitimately match a
9107        // validated member (DNS-1123 labels are lowercase)". The
9108        // narrower diagnostic names the offending slot, the value
9109        // verbatim, and the parser-shaped reason.
9110        let mut s = three_member_spec();
9111        s.contratos.push(contract_http("Cart", "catalog", "/x"));
9112        let err = s.validate().unwrap_err();
9113        let AplicacaoError::ContratoCaixaInvalid {
9114            slot,
9115            caixa,
9116            reason,
9117        } = err
9118        else {
9119            panic!("expected ContratoCaixaInvalid, got other variant");
9120        };
9121        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
9122        assert_eq!(caixa, "Cart");
9123        assert!(
9124            reason.contains("uppercase"),
9125            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9126        );
9127    }
9128
9129    #[test]
9130    fn rejects_contrato_para_with_underscore() {
9131        // The canonical "I'm thinking of a Python module" leak —
9132        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
9133        // Pin the `:para` axis surfaces the same diagnostic shape as
9134        // the `:de` axis on the underscore violation.
9135        let mut s = three_member_spec();
9136        s.contratos.push(contract_http("cart", "my_catalog", "/x"));
9137        let err = s.validate().unwrap_err();
9138        assert!(
9139            matches!(
9140                err,
9141                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9142                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
9143            ),
9144            "got {err:?}"
9145        );
9146    }
9147
9148    #[test]
9149    fn rejects_contrato_de_with_dot() {
9150        // A `:contratos :de` value is a single DNS-1123 *label*, not
9151        // a subdomain — mirroring the `:membros :caixa` floor. The
9152        // strictest floor among the use sites wins.
9153        let mut s = three_member_spec();
9154        s.contratos
9155            .push(contract_http("team.cart", "catalog", "/x"));
9156        let err = s.validate().unwrap_err();
9157        assert!(
9158            matches!(
9159                err,
9160                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9161                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
9162            ),
9163            "got {err:?}"
9164        );
9165    }
9166
9167    #[test]
9168    fn rejects_contrato_para_with_unicode() {
9169        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9170        // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
9171        // validity check rejects multi-byte UTF-8 by the first
9172        // non-`[a-z0-9-]` byte.
9173        let mut s = three_member_spec();
9174        s.contratos.push(contract_http("cart", "café", "/x"));
9175        let err = s.validate().unwrap_err();
9176        assert!(
9177            matches!(
9178                err,
9179                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9180                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
9181            ),
9182            "got {err:?}"
9183        );
9184    }
9185
9186    #[test]
9187    fn rejects_contrato_de_with_leading_hyphen() {
9188        // DNS-1123 boundary rule: labels must start and end with an
9189        // alphanumeric. K8s rejects `-cart` outright; the narrower
9190        // shape diagnostic now names the violation at caixa-build
9191        // time rather than the misframed membership-lookup arm.
9192        let mut s = three_member_spec();
9193        s.contratos.push(contract_http("-cart", "catalog", "/x"));
9194        let err = s.validate().unwrap_err();
9195        assert!(
9196            matches!(
9197                err,
9198                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9199                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
9200            ),
9201            "got {err:?}"
9202        );
9203    }
9204
9205    #[test]
9206    fn contrato_de_empty_takes_precedence_over_invalid() {
9207        // Order pin: the `ContratoCaixaEmpty` arm fires before the
9208        // `ContratoCaixaInvalid` parse-side arm — same empty-first
9209        // cascade `validate_membro_caixa` / `validate_placement_cluster`
9210        // / `validate_entrada_host` already establish on their peer
9211        // name axes. The empty string is a structurally distinct
9212        // authoring footgun (the author left the field blank, vs.
9213        // typed a malformed value), so it gets its own diagnostic.
9214        let mut s = three_member_spec();
9215        s.contratos.push(contract_http("", "catalog", "/x"));
9216        let err = s.validate().unwrap_err();
9217        assert_eq!(
9218            err,
9219            AplicacaoError::ContratoCaixaEmpty {
9220                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9221            }
9222        );
9223    }
9224
9225    #[test]
9226    fn contrato_de_shape_fires_before_para_shape() {
9227        // Per-axis order pin: within one `:contratos` entry, the `:de`
9228        // shape gate fires before the `:para` shape gate — same
9229        // edge-direction order the existing `ContratoMemberMissing` /
9230        // `ContratoSelfLoop` / target-dispatch checks use, so the
9231        // diagnostic for a contract with both `:de` and `:para`
9232        // malformed is stable. Authors fixing the surfaced `:de`
9233        // first will see `:para`'s diagnostic on re-run.
9234        let mut s = three_member_spec();
9235        s.contratos.push(contract_http("Cart", "Catalog", "/x"));
9236        let err = s.validate().unwrap_err();
9237        assert!(
9238            matches!(
9239                err,
9240                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9241                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
9242            ),
9243            "got {err:?}"
9244        );
9245    }
9246
9247    #[test]
9248    fn contrato_shape_fires_before_membership_lookup() {
9249        // The load-bearing pin: an invalid-shape `:de` surfaces its
9250        // *own* diagnostic, not the misframed `ContratoMemberMissing`.
9251        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
9252        // an invalid-shape `:de` could never legitimately match any
9253        // member — the prior `ContratoMemberMissing` diagnostic was
9254        // a structural impossibility framed as a graph-membership
9255        // failure. The shape gate now routes every such input through
9256        // the narrower self-locating diagnostic.
9257        let mut s = three_member_spec();
9258        s.contratos.push(contract_http("Cart", "catalog", "/x"));
9259        let err = s.validate().unwrap_err();
9260        assert!(
9261            matches!(
9262                err,
9263                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
9264            ),
9265            "got {err:?}"
9266        );
9267        // And the symmetric case: an invalid-shape `:para` surfaces
9268        // its own diagnostic too, even when `:de` is well-shaped.
9269        let mut s = three_member_spec();
9270        s.contratos.push(contract_http("cart", "Catalog", "/x"));
9271        let err = s.validate().unwrap_err();
9272        assert!(
9273            matches!(
9274                err,
9275                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
9276            ),
9277            "got {err:?}"
9278        );
9279    }
9280
9281    #[test]
9282    fn contrato_shape_fires_before_self_edge_check() {
9283        // A `:de "Cart" :para "Cart"` entry is two distinct authoring
9284        // bugs: the shape violation (uppercase) and the self-edge
9285        // violation. The narrower per-axis shape diagnostic surfaces
9286        // first because fixing the shape may reveal that the author
9287        // also meant to point `:para` at a different member — the
9288        // self-edge framing is only useful once both endpoints have
9289        // valid shape.
9290        let mut s = three_member_spec();
9291        s.contratos.push(contract_http("Cart", "Cart", "/x"));
9292        let err = s.validate().unwrap_err();
9293        assert!(
9294            matches!(
9295                err,
9296                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9297                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
9298            ),
9299            "got {err:?}"
9300        );
9301    }
9302
9303    #[test]
9304    fn contrato_well_shaped_phantom_still_raises_member_missing() {
9305        // Strict-improvement pin: a well-shaped `:de` that simply
9306        // isn't in `:membros` (a phantom reference — author meant
9307        // to add the member but didn't, or renamed and missed an
9308        // update) still surfaces `ContratoMemberMissing`, unchanged.
9309        // The shape gate only intercepts inputs that could never
9310        // legitimately match a validated member; legitimately-shaped
9311        // phantom references remain on the graph-membership axis.
9312        let mut s = three_member_spec();
9313        s.contratos
9314            .push(contract_http("phantom-shim", "catalog", "/x"));
9315        let err = s.validate().unwrap_err();
9316        assert!(
9317            matches!(
9318                err,
9319                AplicacaoError::ContratoMemberMissing { ref caixa }
9320                    if caixa == "phantom-shim"
9321            ),
9322            "got {err:?}"
9323        );
9324    }
9325
9326    #[test]
9327    fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
9328        // The diagnostic-shape pin: the error names the offending
9329        // slot (`:de` or `:para`) verbatim and the offending value
9330        // verbatim plus a non-empty parser-shaped reason, so the
9331        // author can grep their caixa.lisp for `:de "<name>"` /
9332        // `:para "<name>"` and fix it in one edit. Same diagnostic
9333        // shape as `MembroCaixaInvalid` (3f9d7a0) and
9334        // `PlacementClusterInvalid` (6c8c00b).
9335        let mut s = three_member_spec();
9336        s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
9337        let err = s.validate().unwrap_err();
9338        let AplicacaoError::ContratoCaixaInvalid {
9339            slot,
9340            caixa,
9341            reason,
9342        } = err
9343        else {
9344            panic!("expected ContratoCaixaInvalid, got {err:?}");
9345        };
9346        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
9347        assert_eq!(caixa, "BAD_NAME");
9348        assert!(
9349            !reason.is_empty(),
9350            "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
9351        );
9352    }
9353
9354    #[test]
9355    fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
9356        // Scalar-value pin: the two author-facing kebab-case labels the
9357        // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
9358        // admits on the `:contratos` per-entry endpoint-shape axis,
9359        // one arm per typed sub-slot. Mirrors the peer scalar-value
9360        // pin the sibling top-level M2 / M3 / Supervisor
9361        // author-facing-label consts carry
9362        // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
9363        // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
9364        // slot itself), so every altitude of the typed-slot algebra
9365        // shares the same "one canonical byte-string per arm"
9366        // discipline. A future rebrand (`:de` → `:from` matching the
9367        // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
9368        // sibling, `:para` → `:to` matching the same, or
9369        // `:de`/`:para` → `:source`/`:target` matching the WIT
9370        // world's `import`/`export` half-vocabulary) lands as an
9371        // edit to exactly one const, and every consumer that reaches
9372        // for the label picks it up at build time rather than at
9373        // runtime as a downstream `ContratoCaixaEmpty` /
9374        // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
9375        // diagnostic mismatch far from the rename's commit.
9376        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
9377        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
9378    }
9379
9380    #[test]
9381    fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
9382        // Production-through-const pin: the two per-axis labels the
9383        // per-`:contratos` entry endpoint-shape gate at
9384        // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
9385        // argument to [`validate_contrato_caixa`] route through the
9386        // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
9387        // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
9388        // future rebrand that reaches the const but not the gate (or
9389        // vice versa) surfaces here at build time rather than at
9390        // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
9391        // `slot: <stale-kebab-case>` diagnostic far from the rename's
9392        // commit. Mirror of the peer
9393        // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
9394        // pin (882f498) on the sibling M3 top-level slot axis.
9395        let mut s = three_member_spec();
9396        s.contratos.push(contract_http("", "catalog", "/x"));
9397        assert_eq!(
9398            s.validate().unwrap_err(),
9399            AplicacaoError::ContratoCaixaEmpty {
9400                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9401            }
9402        );
9403        let mut s = three_member_spec();
9404        s.contratos.push(contract_http("cart", "", "/x"));
9405        assert_eq!(
9406            s.validate().unwrap_err(),
9407            AplicacaoError::ContratoCaixaEmpty {
9408                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
9409            }
9410        );
9411    }
9412
9413    #[test]
9414    fn accepts_canonical_contrato_caixa_forms() {
9415        // The DNS-1123 label shapes a caixa author is realistically
9416        // going to write on a `:contratos :de` / `:para`. Pin every
9417        // leg so a future tightening that bans (e.g.) digit-start
9418        // identifiers surfaces here, mirroring
9419        // `accepts_canonical_membro_caixa_forms` on the peer name
9420        // axis.
9421        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
9422            let mut s = three_member_spec();
9423            s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
9424            s.contratos = vec![contract_http("checkout", form, "/x")];
9425            s.entrada = None;
9426            s.validate().unwrap_or_else(|e| {
9427                panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
9428            });
9429
9430            let mut s = three_member_spec();
9431            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
9432            s.contratos = vec![contract_http(form, "catalog", "/x")];
9433            s.entrada = None;
9434            s.validate().unwrap_or_else(|e| {
9435                panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
9436            });
9437        }
9438    }
9439
9440    #[test]
9441    fn rejects_empty_wit() {
9442        let mut s = three_member_spec();
9443        s.contratos.push(WitContract {
9444            de: "cart".into(),
9445            para: "catalog".into(),
9446            wit: "".into(),
9447            endpoint: None,
9448            subject: None,
9449            slot: None,
9450        });
9451        let err = s.validate().unwrap_err();
9452        assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
9453    }
9454
9455    #[test]
9456    fn rejects_entrada_to_unknown_member() {
9457        let mut s = three_member_spec();
9458        s.entrada.as_mut().unwrap().para = "phantom".into();
9459        assert!(matches!(
9460            s.validate().unwrap_err(),
9461            AplicacaoError::EntradaMemberMissing { .. }
9462        ));
9463    }
9464
9465    // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
9466
9467    #[test]
9468    fn rejects_entrada_para_empty() {
9469        // `:para ""` previously fell through to
9470        // `EntradaMemberMissing { para: "" }` because the validated
9471        // `:membros :caixa` set never contains the empty string. The
9472        // narrower `EntradaParaEmpty` diagnostic now names the
9473        // offending slot directly — same empty-first cascade
9474        // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
9475        // `ContratoCaixaEmpty` establish on the peer name axes.
9476        let mut s = three_member_spec();
9477        s.entrada.as_mut().unwrap().para = String::new();
9478        let err = s.validate().unwrap_err();
9479        assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
9480    }
9481
9482    #[test]
9483    fn rejects_entrada_para_with_uppercase() {
9484        // The canonical "I copied the Servico's TitleCase display
9485        // name from an ADR" typo. Until this gate landed `:para "Cart"`
9486        // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
9487        // as "this caixa isn't in `:membros`" when the root cause is
9488        // "this `:para` value's shape can never legitimately match a
9489        // validated member (DNS-1123 labels are lowercase)". The
9490        // narrower diagnostic names the value verbatim plus the
9491        // parser-shaped reason.
9492        let mut s = three_member_spec();
9493        s.entrada.as_mut().unwrap().para = "Cart".into();
9494        let err = s.validate().unwrap_err();
9495        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
9496            panic!("expected EntradaParaInvalid, got other variant");
9497        };
9498        assert_eq!(para, "Cart");
9499        assert!(
9500            reason.contains("uppercase"),
9501            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9502        );
9503    }
9504
9505    #[test]
9506    fn rejects_entrada_para_with_underscore() {
9507        // The canonical "I'm thinking of a Python module" leak —
9508        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
9509        let mut s = three_member_spec();
9510        s.entrada.as_mut().unwrap().para = "my_cart".into();
9511        let err = s.validate().unwrap_err();
9512        assert!(
9513            matches!(
9514                err,
9515                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9516                    if para == "my_cart" && reason.contains('_')
9517            ),
9518            "got {err:?}"
9519        );
9520    }
9521
9522    #[test]
9523    fn rejects_entrada_para_with_dot() {
9524        // An `:entrada :para` value is a single DNS-1123 *label*, not
9525        // a subdomain — mirroring the `:membros :caixa` floor. The
9526        // strictest floor among the use sites wins.
9527        let mut s = three_member_spec();
9528        s.entrada.as_mut().unwrap().para = "team.cart".into();
9529        let err = s.validate().unwrap_err();
9530        assert!(
9531            matches!(
9532                err,
9533                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9534                    if para == "team.cart" && reason.contains('.')
9535            ),
9536            "got {err:?}"
9537        );
9538    }
9539
9540    #[test]
9541    fn rejects_entrada_para_with_unicode() {
9542        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9543        // (`xn--…`) before it reaches K8s.
9544        let mut s = three_member_spec();
9545        s.entrada.as_mut().unwrap().para = "café".into();
9546        let err = s.validate().unwrap_err();
9547        assert!(
9548            matches!(
9549                err,
9550                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
9551            ),
9552            "got {err:?}"
9553        );
9554    }
9555
9556    #[test]
9557    fn rejects_entrada_para_with_leading_hyphen() {
9558        // DNS-1123 boundary rule: labels must start and end with an
9559        // alphanumeric. K8s rejects `-cart` outright.
9560        let mut s = three_member_spec();
9561        s.entrada.as_mut().unwrap().para = "-cart".into();
9562        let err = s.validate().unwrap_err();
9563        assert!(
9564            matches!(
9565                err,
9566                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9567                    if para == "-cart" && reason.contains("start and end")
9568            ),
9569            "got {err:?}"
9570        );
9571    }
9572
9573    #[test]
9574    fn rejects_entrada_para_with_trailing_hyphen() {
9575        // Symmetric boundary arm.
9576        let mut s = three_member_spec();
9577        s.entrada.as_mut().unwrap().para = "cart-".into();
9578        let err = s.validate().unwrap_err();
9579        assert!(
9580            matches!(
9581                err,
9582                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9583                    if para == "cart-" && reason.contains("start and end")
9584            ),
9585            "got {err:?}"
9586        );
9587    }
9588
9589    #[test]
9590    fn rejects_entrada_para_too_long() {
9591        // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
9592        // bytes per label. K8s rejects longer names at admission on
9593        // every `metadata.name` axis.
9594        let mut s = three_member_spec();
9595        s.entrada.as_mut().unwrap().para = "a".repeat(64);
9596        let err = s.validate().unwrap_err();
9597        assert!(
9598            matches!(
9599                err,
9600                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9601                    if para.len() == 64 && reason.contains("max length")
9602            ),
9603            "got {err:?}"
9604        );
9605    }
9606
9607    #[test]
9608    fn entrada_para_empty_takes_precedence_over_invalid() {
9609        // Order pin: the `EntradaParaEmpty` arm fires before the
9610        // `EntradaParaInvalid` parse-side arm — same empty-first
9611        // cascade `validate_membro_caixa` / `validate_placement_cluster`
9612        // / `validate_contrato_caixa` already establish.
9613        let mut s = three_member_spec();
9614        s.entrada.as_mut().unwrap().para = String::new();
9615        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
9616    }
9617
9618    #[test]
9619    fn entrada_para_shape_fires_before_membership_lookup() {
9620        // The load-bearing pin: an invalid-shape `:para` surfaces its
9621        // *own* diagnostic, not the misframed `EntradaMemberMissing`.
9622        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
9623        // an invalid-shape `:para` could never legitimately match any
9624        // member — the prior `EntradaMemberMissing` diagnostic framed
9625        // a structural impossibility as a graph-membership failure.
9626        let mut s = three_member_spec();
9627        s.entrada.as_mut().unwrap().para = "Cart".into();
9628        let err = s.validate().unwrap_err();
9629        assert!(
9630            matches!(
9631                err,
9632                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
9633            ),
9634            "got {err:?}"
9635        );
9636    }
9637
9638    #[test]
9639    fn entrada_para_shape_fires_before_host_gate() {
9640        // Per-`:entrada` order pin: the `:para` shape gate fires
9641        // before the `:host` gate, mirroring the existing
9642        // `entrada_host_member_missing_takes_precedence_over_host_invalid`
9643        // ordering where the member-lookup arm preceded the host gate.
9644        // The shape gate slots ahead of that, so a malformed `:para`
9645        // surfaces its own diagnostic even when `:host` is also wrong.
9646        let mut s = three_member_spec();
9647        let e = s.entrada.as_mut().unwrap();
9648        e.para = "Cart".into();
9649        e.host = "BAD HOST".into();
9650        let err = s.validate().unwrap_err();
9651        assert!(
9652            matches!(
9653                err,
9654                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
9655            ),
9656            "got {err:?}"
9657        );
9658    }
9659
9660    #[test]
9661    fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
9662        // Strict-improvement pin: a well-shaped `:para` that simply
9663        // isn't in `:membros` (a phantom reference — author meant to
9664        // add the member but didn't, or renamed and missed an
9665        // update) still surfaces `EntradaMemberMissing`, unchanged.
9666        // The shape gate only intercepts inputs that could never
9667        // legitimately match a validated member.
9668        let mut s = three_member_spec();
9669        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
9670        let err = s.validate().unwrap_err();
9671        assert!(
9672            matches!(
9673                err,
9674                AplicacaoError::EntradaMemberMissing { ref para }
9675                    if para == "phantom-shim"
9676            ),
9677            "got {err:?}"
9678        );
9679    }
9680
9681    #[test]
9682    fn entrada_para_invalid_diagnostic_carries_offending_para() {
9683        // The diagnostic-shape pin: the error names the offending
9684        // `:para` value verbatim plus a non-empty parser-shaped
9685        // reason, so the author can grep their caixa.lisp for
9686        // `:para "<name>"` and fix it in one edit. Same diagnostic
9687        // shape as `MembroCaixaInvalid` (3f9d7a0),
9688        // `PlacementClusterInvalid` (6c8c00b), and
9689        // `ContratoCaixaInvalid` (8d5af6b).
9690        let mut s = three_member_spec();
9691        s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
9692        let err = s.validate().unwrap_err();
9693        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
9694            panic!("expected EntradaParaInvalid, got {err:?}");
9695        };
9696        assert_eq!(para, "BAD_NAME");
9697        assert!(
9698            !reason.is_empty(),
9699            "EntradaParaInvalid `reason` must carry a parser-shaped wording"
9700        );
9701    }
9702
9703    #[test]
9704    fn accepts_canonical_entrada_para_forms() {
9705        // Positive-control sweep covering the DNS-1123 label shapes a
9706        // caixa author is realistically going to write on `:entrada
9707        // :para`. Pin every leg so a future tightening that bans
9708        // (e.g.) digit-start identifiers surfaces here, mirroring
9709        // `accepts_canonical_membro_caixa_forms` and
9710        // `accepts_canonical_contrato_caixa_forms` on the peer name
9711        // axes.
9712        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
9713            let mut s = three_member_spec();
9714            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
9715            s.contratos = vec![contract_http(form, "catalog", "/x")];
9716            s.entrada = Some(Entrada {
9717                host: "checkout.quero.cloud".into(),
9718                para: form.into(),
9719                paths: vec!["/api".into()],
9720                port: 8080,
9721            });
9722            s.validate().unwrap_or_else(|e| {
9723                panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
9724            });
9725        }
9726    }
9727
9728    #[test]
9729    fn rejects_replicated_without_clusters() {
9730        let mut s = three_member_spec();
9731        s.placement.clusters = vec![];
9732        assert!(matches!(
9733            s.validate().unwrap_err(),
9734            AplicacaoError::PlacementWithoutClusters { .. }
9735        ));
9736    }
9737
9738    #[test]
9739    fn rejects_sharded_without_key() {
9740        let mut s = three_member_spec();
9741        s.placement.estrategia = PlacementStrategy::Sharded;
9742        s.placement.shard_key = None;
9743        s.placement.clusters = vec!["rio".into()];
9744        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
9745    }
9746
9747    #[test]
9748    fn sharded_with_key_validates() {
9749        let mut s = three_member_spec();
9750        s.placement.estrategia = PlacementStrategy::Sharded;
9751        s.placement.shard_key = Some("$tenantId".into());
9752        s.validate().unwrap();
9753    }
9754
9755    #[test]
9756    fn round_trip_via_json_preserves_shape() {
9757        let s = three_member_spec();
9758        let json = serde_json::to_string(&s.membros).unwrap();
9759        let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
9760        assert_eq!(back, s.membros);
9761
9762        let json = serde_json::to_string(&s.contratos).unwrap();
9763        let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
9764        assert_eq!(back, s.contratos);
9765
9766        let json = serde_json::to_string(&s.placement).unwrap();
9767        let back: Placement = serde_json::from_str(&json).unwrap();
9768        assert_eq!(back, s.placement);
9769
9770        let json = serde_json::to_string(&s.entrada).unwrap();
9771        let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
9772        assert_eq!(back, s.entrada);
9773    }
9774
9775    #[test]
9776    fn rate_limit_round_trip_seconds() {
9777        let policy = MeshPolicy {
9778            rate_limit: Some(RateLimit {
9779                rate: 100,
9780                window: Duration::from_secs(1),
9781            }),
9782            ..Default::default()
9783        };
9784        let json = serde_json::to_string(&policy).unwrap();
9785        assert!(json.contains("\"100/s\""));
9786        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
9787        assert_eq!(back.rate_limit.unwrap().rate, 100);
9788        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
9789    }
9790
9791    #[test]
9792    fn rate_limit_round_trip_minutes() {
9793        let policy = MeshPolicy {
9794            rate_limit: Some(RateLimit {
9795                rate: 5000,
9796                window: Duration::from_secs(60),
9797            }),
9798            ..Default::default()
9799        };
9800        let json = serde_json::to_string(&policy).unwrap();
9801        assert!(json.contains("\"5000/m\""));
9802    }
9803
9804    #[test]
9805    fn circuit_breaker_round_trip() {
9806        let policy = MeshPolicy {
9807            circuit_breaker: Some(CircuitBreaker {
9808                max_failures: 5,
9809                window: Duration::from_secs(60),
9810            }),
9811            ..Default::default()
9812        };
9813        let json = serde_json::to_string(&policy).unwrap();
9814        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
9815        assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
9816        assert_eq!(
9817            back.circuit_breaker.unwrap().window,
9818            Duration::from_secs(60)
9819        );
9820    }
9821
9822    #[test]
9823    fn rejects_http_contrato_without_endpoint() {
9824        let mut s = three_member_spec();
9825        s.contratos.push(WitContract {
9826            de: "cart".into(),
9827            para: "catalog".into(),
9828            wit: "wasi:http/proxy".into(),
9829            endpoint: None,
9830            subject: None,
9831            slot: None,
9832        });
9833        let err = s.validate().unwrap_err();
9834        assert!(matches!(
9835            err,
9836            AplicacaoError::ContratoMissingTarget {
9837                expected: WitTarget::HTTP_FIELD_NAME,
9838                ..
9839            }
9840        ));
9841    }
9842
9843    #[test]
9844    fn rejects_http_contrato_with_subject() {
9845        let mut s = three_member_spec();
9846        s.contratos.push(WitContract {
9847            de: "cart".into(),
9848            para: "catalog".into(),
9849            wit: "wasi:http/proxy".into(),
9850            endpoint: Some("/x".into()),
9851            subject: Some("not.allowed.here".into()),
9852            slot: None,
9853        });
9854        let err = s.validate().unwrap_err();
9855        assert!(matches!(
9856            err,
9857            AplicacaoError::ContratoWrongTarget {
9858                expected: WitTarget::HTTP_FIELD_NAME,
9859                ..
9860            }
9861        ));
9862    }
9863
9864    #[test]
9865    fn rejects_pubsub_contrato_without_subject() {
9866        let mut s = three_member_spec();
9867        s.contratos.push(WitContract {
9868            de: "cart".into(),
9869            para: "catalog".into(),
9870            wit: "nats:pub-sub".into(),
9871            endpoint: None,
9872            subject: None,
9873            slot: None,
9874        });
9875        let err = s.validate().unwrap_err();
9876        assert!(matches!(
9877            err,
9878            AplicacaoError::ContratoMissingTarget {
9879                expected: WitTarget::PUBSUB_FIELD_NAME,
9880                ..
9881            }
9882        ));
9883    }
9884
9885    #[test]
9886    fn rejects_pubsub_contrato_with_endpoint() {
9887        let mut s = three_member_spec();
9888        s.contratos.push(WitContract {
9889            de: "cart".into(),
9890            para: "catalog".into(),
9891            wit: "kafka:topic".into(),
9892            endpoint: Some("/wrong".into()),
9893            subject: Some("topic.x".into()),
9894            slot: None,
9895        });
9896        let err = s.validate().unwrap_err();
9897        assert!(matches!(
9898            err,
9899            AplicacaoError::ContratoWrongTarget {
9900                expected: WitTarget::PUBSUB_FIELD_NAME,
9901                ..
9902            }
9903        ));
9904    }
9905
9906    #[test]
9907    fn rejects_store_contrato_without_slot() {
9908        let mut s = three_member_spec();
9909        s.contratos.push(WitContract {
9910            de: "cart".into(),
9911            para: "catalog".into(),
9912            wit: "wasi:keyvalue/store".into(),
9913            endpoint: None,
9914            subject: None,
9915            slot: None,
9916        });
9917        let err = s.validate().unwrap_err();
9918        assert!(matches!(
9919            err,
9920            AplicacaoError::ContratoMissingTarget {
9921                expected: WitTarget::STORE_FIELD_NAME,
9922                ..
9923            }
9924        ));
9925    }
9926
9927    // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
9928
9929    #[test]
9930    fn rejects_http_contrato_with_empty_endpoint() {
9931        // `Some("")` for an HTTP endpoint passes the presence check
9932        // (target() previously returned WitTarget::Http { endpoint: "" })
9933        // but renders as a `path: ""` Cilium L7 rule that matches no
9934        // traffic. Same value-shape footgun closed for :entrada :paths
9935        // entries (eb3456d).
9936        let mut s = three_member_spec();
9937        s.contratos.push(WitContract {
9938            de: "cart".into(),
9939            para: "catalog".into(),
9940            wit: "wasi:http/proxy".into(),
9941            endpoint: Some(String::new()),
9942            subject: None,
9943            slot: None,
9944        });
9945        let err = s.validate().unwrap_err();
9946        assert!(
9947            matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
9948                if de == "cart" && para == "catalog"),
9949            "got {err:?}"
9950        );
9951    }
9952
9953    #[test]
9954    fn rejects_http_contrato_with_relative_endpoint() {
9955        // Cilium L7 :path + Gateway API PathPrefix both require a
9956        // leading `/`. Same shape required of :entrada :paths
9957        // (eb3456d). Lifted into target() so every consumer of the
9958        // typed WitTarget view inherits the guarantee.
9959        let mut s = three_member_spec();
9960        s.contratos.push(WitContract {
9961            de: "cart".into(),
9962            para: "catalog".into(),
9963            wit: "wasi:http/proxy".into(),
9964            endpoint: Some("products/:id".into()),
9965            subject: None,
9966            slot: None,
9967        });
9968        let err = s.validate().unwrap_err();
9969        assert!(
9970            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
9971                if endpoint == "products/:id"),
9972            "got {err:?}"
9973        );
9974    }
9975
9976    #[test]
9977    fn rejects_pubsub_contrato_with_empty_subject() {
9978        // NATS / Kafka publish without a subject is a no-op subscribe;
9979        // never the author's intent. Same empty-string rejection as
9980        // :membros :caixa, :placement :clusters entries, :entrada
9981        // :paths entries — every value carried by every typed slot is
9982        // value-shape-checked at validate().
9983        let mut s = three_member_spec();
9984        s.contratos.push(WitContract {
9985            de: "cart".into(),
9986            para: "catalog".into(),
9987            wit: "nats:pub-sub".into(),
9988            endpoint: None,
9989            subject: Some(String::new()),
9990            slot: None,
9991        });
9992        let err = s.validate().unwrap_err();
9993        assert!(
9994            matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
9995                if de == "cart" && para == "catalog"),
9996            "got {err:?}"
9997        );
9998    }
9999
10000    #[test]
10001    fn rejects_store_contrato_with_empty_slot() {
10002        // An empty slot template addresses the bucket root, defeating
10003        // the per-key isolation the slot exists for — a footgun on
10004        // `wasi:keyvalue/store` whose closest analog is the empty
10005        // shard-key rejected on :placement Sharded (c7c7799).
10006        let mut s = three_member_spec();
10007        s.contratos.push(WitContract {
10008            de: "cart".into(),
10009            para: "catalog".into(),
10010            wit: "wasi:keyvalue/store".into(),
10011            endpoint: None,
10012            subject: None,
10013            slot: Some(String::new()),
10014        });
10015        let err = s.validate().unwrap_err();
10016        assert!(
10017            matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
10018                if de == "cart" && para == "catalog"),
10019            "got {err:?}"
10020        );
10021    }
10022
10023    #[test]
10024    fn http_contrato_root_endpoint_validates() {
10025        // Pin the boundary case: a single-`/` endpoint is the catch-all
10026        // form the Gateway HTTPRoute renderer falls back to when
10027        // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
10028        // must remain a valid contrato endpoint too.
10029        let mut s = three_member_spec();
10030        s.contratos.push(contract_http("cart", "catalog", "/"));
10031        s.validate().unwrap();
10032    }
10033
10034    // ── :contratos :endpoint value-shape gate ────────────────────────────
10035    //
10036    // Mirrors the `:entrada :paths` value-shape suite on the peer
10037    // HTTP-path axis. Until this gate landed `WitContract::target()`
10038    // only refused the empty string + the missing-leading-`/` form
10039    // (c4213a4); a structurally invalid endpoint passed validate and
10040    // landed verbatim as a Cilium L7 `path:` rule
10041    // (caixa-mesh/src/lib.rs:311) that either silently dropped all
10042    // traffic or was rejected at apply time by Cilium policy admission.
10043    // Every authoring footgun the K8s Gateway API webhook / Cilium
10044    // policy validator would catch on admission now becomes a caixa-
10045    // build-time `ContratoEndpointInvalid` with the offending
10046    // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
10047    // shape as `EntradaPathInvalid` on the sibling axis; same shared
10048    // predicate (`crate::render::is_gateway_api_http_path`) ensures
10049    // drift between the two axes' rule enforcement is a build error
10050    // at the predicate.
10051
10052    fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
10053        // Fresh spec per call so the would-be-duplicate edge
10054        // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
10055        // `three_member_spec`'s pre-existing
10056        // `(cart, catalog, …, /products/:id)` entry — only the
10057        // endpoint payload differs.
10058        let mut s = three_member_spec();
10059        s.contratos.push(contract_http("cart", "catalog", ep));
10060        s.validate().unwrap_err()
10061    }
10062
10063    #[test]
10064    fn rejects_http_contrato_endpoint_with_query() {
10065        // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
10066        // silently rendered as a Cilium L7 `path: "/charge?token=X"`
10067        // rule the L7 matcher would never satisfy.
10068        let err = contrato_endpoint_err("/charge?token=X");
10069        assert!(
10070            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10071                if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
10072            "got {err:?}"
10073        );
10074    }
10075
10076    #[test]
10077    fn rejects_http_contrato_endpoint_with_fragment() {
10078        let err = contrato_endpoint_err("/charge#frag");
10079        assert!(
10080            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10081                if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
10082            "got {err:?}"
10083        );
10084    }
10085
10086    #[test]
10087    fn rejects_http_contrato_endpoint_with_whitespace() {
10088        let err = contrato_endpoint_err("/foo bar");
10089        assert!(
10090            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10091                if endpoint == "/foo bar" && reason.contains("whitespace")),
10092            "got {err:?}"
10093        );
10094    }
10095
10096    #[test]
10097    fn rejects_http_contrato_endpoint_with_control_char() {
10098        let err = contrato_endpoint_err("/api/\x01bar");
10099        assert!(
10100            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10101                if endpoint == "/api/\x01bar" && reason.contains("control character")),
10102            "got {err:?}"
10103        );
10104    }
10105
10106    #[test]
10107    fn rejects_http_contrato_endpoint_with_non_ascii() {
10108        let err = contrato_endpoint_err("/api/café");
10109        assert!(
10110            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10111                if endpoint == "/api/café" && reason.contains("non-ASCII")),
10112            "got {err:?}"
10113        );
10114    }
10115
10116    #[test]
10117    fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
10118        let err = contrato_endpoint_err("/api//cart");
10119        assert!(
10120            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10121                if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
10122            "got {err:?}"
10123        );
10124    }
10125
10126    #[test]
10127    fn rejects_http_contrato_endpoint_with_dot_segment() {
10128        let err = contrato_endpoint_err("/api/./cart");
10129        assert!(
10130            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10131                if endpoint == "/api/./cart" && reason.contains("`.` segment")),
10132            "got {err:?}"
10133        );
10134    }
10135
10136    #[test]
10137    fn rejects_http_contrato_endpoint_with_parent_segment() {
10138        // Path-traversal in a contrato endpoint is the canonical
10139        // "L7 rule that the workload's HTTP server's path-resolution
10140        // logic interprets differently than the policy enforcer"
10141        // footgun. Rejected outright at validate time.
10142        let err = contrato_endpoint_err("/api/../etc");
10143        assert!(
10144            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10145                if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
10146            "got {err:?}"
10147        );
10148    }
10149
10150    #[test]
10151    fn rejects_http_contrato_endpoint_too_long() {
10152        // 1025-byte endpoint — one over the Gateway API
10153        // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
10154        // path matcher has no inherent length limit but the policy
10155        // CR itself rides through the K8s apiserver, which enforces
10156        // ConfigMap-shaped limits; sharing the Gateway API cap is the
10157        // conservative floor.
10158        let big = format!("/api/{}", "a".repeat(1020));
10159        assert_eq!(big.len(), 1025);
10160        let err = contrato_endpoint_err(&big);
10161        assert!(
10162            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10163                if endpoint == &big && reason.contains("max length of 1024")),
10164            "got {err:?}"
10165        );
10166    }
10167
10168    #[test]
10169    fn http_contrato_endpoint_max_length_validates() {
10170        // 1024-byte endpoint — exactly the cap. Boundary pin: drift
10171        // in the cap surfaces here and at
10172        // `rejects_http_contrato_endpoint_too_long` simultaneously,
10173        // mirroring `entrada_path_max_length_validates` on the peer
10174        // axis.
10175        let big = format!("/api/{}", "a".repeat(1019));
10176        assert_eq!(big.len(), 1024);
10177        let mut s = three_member_spec();
10178        s.contratos.push(contract_http("cart", "catalog", &big));
10179        s.validate().unwrap();
10180    }
10181
10182    #[test]
10183    fn http_contrato_endpoint_accepts_canonical_forms() {
10184        // Positive-set sweep: every canonical HTTP-path shape the
10185        // sibling `:entrada :paths` axis accepts (the bare-root `/`,
10186        // plain paths, hidden-file-style `.config` segments distinct
10187        // from the `.` segment, digit-bearing segments, the canonical
10188        // route-template `:param` form, trailing-slash form,
10189        // percent-encoded segments, the `/foo..bar` interior-`..`-
10190        // substring forms that are NOT `..` segments) must remain a
10191        // valid contrato endpoint too. Drift between this list and
10192        // the entrada path positive sweep surfaces at the shared
10193        // `is_gateway_api_http_path` substrate-side suite — one
10194        // source of truth. Uses a fresh `(payment, catalog)` edge so
10195        // none of the swept endpoints collide with the pre-existing
10196        // `(cart, catalog, /products/:id)` / `(cart, payment,
10197        // /charge)` entries in `three_member_spec`.
10198        for ep in [
10199            "/",
10200            "/charge",
10201            "/v1/charge",
10202            "/api/.config",
10203            "/products/:id",
10204            "/api/cart/",
10205            "/api/caf%C3%A9",
10206            "/foo..bar",
10207            "/...",
10208        ] {
10209            let mut s = three_member_spec();
10210            s.contratos.push(contract_http("payment", "catalog", ep));
10211            s.validate()
10212                .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
10213        }
10214    }
10215
10216    #[test]
10217    fn contrato_endpoint_empty_takes_precedence_over_invalid() {
10218        // Ordering pin: `ContratoEndpointEmpty` is the more self-
10219        // locating diagnostic on `""` and must lead — the value-
10220        // shape gate is only reached after the empty-check fires.
10221        // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
10222        // on the peer axis.
10223        let mut s = three_member_spec();
10224        s.contratos.push(WitContract {
10225            de: "cart".into(),
10226            para: "catalog".into(),
10227            wit: "wasi:http/proxy".into(),
10228            endpoint: Some(String::new()),
10229            subject: None,
10230            slot: None,
10231        });
10232        let err = s.validate().unwrap_err();
10233        assert!(
10234            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
10235            "got {err:?}"
10236        );
10237    }
10238
10239    #[test]
10240    fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
10241        // Ordering pin: an endpoint without a leading `/` surfaces the
10242        // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
10243        // value-shape gate is only consulted on endpoints that already
10244        // satisfy the absolute-prefix invariant. Mirrors
10245        // `entrada_path_not_absolute_takes_precedence_over_invalid`.
10246        let err = contrato_endpoint_err("bad path");
10247        assert!(
10248            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
10249                if endpoint == "bad path"),
10250            "got {err:?}"
10251        );
10252    }
10253
10254    #[test]
10255    fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
10256        // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
10257        // `:para` + a non-empty reason flow through verbatim so the
10258        // author can grep their caixa.lisp for the offending contrato
10259        // block and fix it in one edit. Same shape as
10260        // `entrada_path_diagnostic_carries_offending_path`.
10261        let err = contrato_endpoint_err("/api?q=1");
10262        match err {
10263            AplicacaoError::ContratoEndpointInvalid {
10264                de,
10265                para,
10266                endpoint,
10267                reason,
10268            } => {
10269                assert_eq!(de, "cart");
10270                assert_eq!(para, "catalog");
10271                assert_eq!(endpoint, "/api?q=1");
10272                assert!(!reason.is_empty(), "reason field must be non-empty");
10273            }
10274            other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
10275        }
10276    }
10277
10278    #[test]
10279    fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
10280        // The compounding theorem: every &str inside a WitTarget
10281        // returned by target() is non-empty (and absolute, for Http).
10282        // Renderers downstream of typed_view() can rely on this
10283        // without re-checking — the type system carries the proof.
10284        let http = contract_http("cart", "catalog", "/x");
10285        match http.target().unwrap() {
10286            WitTarget::Http { endpoint } => {
10287                assert!(!endpoint.is_empty());
10288                assert!(endpoint.starts_with('/'));
10289            }
10290            other => panic!("expected Http, got {other:?}"),
10291        }
10292        let nats = WitContract {
10293            de: "a".into(),
10294            para: "b".into(),
10295            wit: "nats:pub-sub".into(),
10296            endpoint: None,
10297            subject: Some("topic.x".into()),
10298            slot: None,
10299        };
10300        match nats.target().unwrap() {
10301            WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
10302            other => panic!("expected PubSub, got {other:?}"),
10303        }
10304        let kv = WitContract {
10305            de: "a".into(),
10306            para: "b".into(),
10307            wit: "wasi:keyvalue/store".into(),
10308            endpoint: None,
10309            subject: None,
10310            slot: Some("checkout/$orderId".into()),
10311        };
10312        match kv.target().unwrap() {
10313            WitTarget::Store { slot } => assert!(!slot.is_empty()),
10314            other => panic!("expected Store, got {other:?}"),
10315        }
10316    }
10317
10318    #[test]
10319    fn target_diagnostic_names_offending_endpoint_value() {
10320        // When the malformed endpoint string is non-trivial, the
10321        // diagnostic carries the actual value back to the author —
10322        // not a generic "endpoint malformed" error.
10323        let bad = WitContract {
10324            de: "src".into(),
10325            para: "dst".into(),
10326            wit: "wasi:http/proxy".into(),
10327            endpoint: Some("api/v1/charge".into()),
10328            subject: None,
10329            slot: None,
10330        };
10331        match bad.target().unwrap_err() {
10332            AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
10333                assert_eq!(de, "src");
10334                assert_eq!(para, "dst");
10335                assert_eq!(endpoint, "api/v1/charge");
10336            }
10337            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
10338        }
10339    }
10340
10341    #[test]
10342    fn rejects_unknown_wit_with_target_set() {
10343        let mut s = three_member_spec();
10344        s.contratos.push(WitContract {
10345            de: "cart".into(),
10346            para: "catalog".into(),
10347            wit: "custom:exchange".into(),
10348            endpoint: Some("/leaked".into()),
10349            subject: None,
10350            slot: None,
10351        });
10352        let err = s.validate().unwrap_err();
10353        assert!(matches!(
10354            err,
10355            AplicacaoError::ContratoWrongTarget {
10356                expected: WitTarget::CAPABILITY_EXPECTED,
10357                ..
10358            }
10359        ));
10360    }
10361
10362    #[test]
10363    fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
10364        // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
10365        // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
10366        // fourth arm of the same "which payload field name goes in the
10367        // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
10368        // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
10369        // consts cover on the peer HTTP / PubSub / Store arms
10370        // (`wit_target_field_name_pins_per_variant`). Until this lift
10371        // landed the byte-string sat twice — once inline in the
10372        // [`WitContract::target`] Capability-arm rejection at the
10373        // production dispatch, once in `rejects_unknown_wit_with_target_set`
10374        // pinning against the same literal — with no compile-time link
10375        // between them. Same "one canonical declaration, next to the
10376        // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
10377        // lift established for the payload-less arm's human-readable
10378        // label axis; this test is the shape peer of
10379        // `wit_target_label_pins_per_variant`'s Capability-arm assertion
10380        // pair (routes-through-const + scalar-value pin) on the
10381        // wrong-target diagnostic-scalar axis.
10382        //
10383        // Fail-before-pass-after was verified locally by mutating the
10384        // const declaration to `"capability"` — the scalar-value pin
10385        // below fires (`"capability" != "none"`) and the routes-through
10386        // assertion below still holds (production and const walk in
10387        // lockstep), which is the correct behavior: a rename on the
10388        // const drifts here first, not at a downstream consumer.
10389        assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
10390
10391        let mut s = three_member_spec();
10392        s.contratos.push(WitContract {
10393            de: "cart".into(),
10394            para: "catalog".into(),
10395            wit: "custom:exchange".into(),
10396            endpoint: Some("/leaked".into()),
10397            subject: None,
10398            slot: None,
10399        });
10400        match s.validate().unwrap_err() {
10401            AplicacaoError::ContratoWrongTarget { expected, .. } => {
10402                assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
10403            }
10404            other => panic!("expected ContratoWrongTarget, got {other:?}"),
10405        }
10406    }
10407
10408    #[test]
10409    fn unknown_wit_capability_only_validates() {
10410        let mut s = three_member_spec();
10411        s.contratos.push(WitContract {
10412            de: "cart".into(),
10413            para: "catalog".into(),
10414            // A WIT world we haven't yet shaped — accept it as a typed
10415            // capability edge so authors aren't blocked while the WIT
10416            // registry catches up. No payload field may be carried.
10417            wit: "custom:exchange".into(),
10418            endpoint: None,
10419            subject: None,
10420            slot: None,
10421        });
10422        s.validate().unwrap();
10423        let added = s.contratos.last().unwrap();
10424        assert_eq!(added.target().unwrap(), WitTarget::Capability);
10425    }
10426
10427    #[test]
10428    fn target_typed_view_round_trips_each_shape() {
10429        let http = contract_http("cart", "catalog", "/products/:id");
10430        assert_eq!(
10431            http.target().unwrap(),
10432            WitTarget::Http {
10433                endpoint: "/products/:id"
10434            }
10435        );
10436        let nats = WitContract {
10437            de: "a".into(),
10438            para: "b".into(),
10439            wit: "nats:pub-sub".into(),
10440            endpoint: None,
10441            subject: Some("topic.x".into()),
10442            slot: None,
10443        };
10444        assert_eq!(
10445            nats.target().unwrap(),
10446            WitTarget::PubSub { subject: "topic.x" }
10447        );
10448        let kv = WitContract {
10449            de: "a".into(),
10450            para: "b".into(),
10451            wit: "wasi:keyvalue/store".into(),
10452            endpoint: None,
10453            subject: None,
10454            slot: Some("checkout/$orderId".into()),
10455        };
10456        assert_eq!(
10457            kv.target().unwrap(),
10458            WitTarget::Store {
10459                slot: "checkout/$orderId"
10460            }
10461        );
10462    }
10463
10464    #[test]
10465    fn wit_contract_kind_predicates() {
10466        let http = contract_http("a", "b", "/x");
10467        assert!(http.is_http());
10468        assert!(!http.is_pubsub());
10469        assert!(!http.is_store());
10470        assert!(!http.is_capability());
10471
10472        let nats = WitContract {
10473            de: "a".into(),
10474            para: "b".into(),
10475            wit: "nats:pub-sub".into(),
10476            endpoint: None,
10477            subject: Some("topic.x".into()),
10478            slot: None,
10479        };
10480        assert!(nats.is_pubsub());
10481        assert!(!nats.is_http());
10482        assert!(!nats.is_capability());
10483
10484        let kv = WitContract {
10485            de: "a".into(),
10486            para: "b".into(),
10487            wit: "wasi:keyvalue/store".into(),
10488            endpoint: None,
10489            subject: None,
10490            slot: Some("checkout/$orderId".into()),
10491        };
10492        assert!(kv.is_store());
10493        assert!(!kv.is_http());
10494        assert!(!kv.is_capability());
10495
10496        // Fourth arm on the paired closed-set predicate family: the
10497        // payload-less capability edge that projects to the payload-
10498        // less [`WitTarget::Capability`] arm under [`WitContract::target`].
10499        // Extends the 3-arm predicate sweep this test opened to cover
10500        // the closed 4-way partition [`WitContract::is_capability`]
10501        // closes on the pre-projection WIT-shape axis, matched with the
10502        // sibling post-projection [`WitTarget`]-side `IsVariant`-derived
10503        // 4-arm predicate set.
10504        let cap = WitContract {
10505            de: "a".into(),
10506            para: "b".into(),
10507            wit: "custom:capability-only".into(),
10508            endpoint: None,
10509            subject: None,
10510            slot: None,
10511        };
10512        assert!(cap.is_capability());
10513        assert!(!cap.is_http());
10514        assert!(!cap.is_pubsub());
10515        assert!(!cap.is_store());
10516    }
10517
10518    // ── :contratos :wit value-shape gate ─────────────────────────────────
10519    //
10520    // Mirrors the `:contratos :endpoint` value-shape suite on the peer
10521    // dispatch-discriminator axis. Until this gate landed
10522    // `WitContract::target()` accepted any non-empty string and
10523    // silently demoted unrecognized shapes to a capability-only L4
10524    // edge — the canonical "I thought I had L7 HTTP routing, got
10525    // L4-only" footgun. Every authoring footgun the WIT registry's
10526    // own grammar rejects (uppercase, hyphen-for-colon typo,
10527    // whitespace, empty package, doubled `@`, …) now becomes a
10528    // caixa-build-time `ContratoWitInvalid` with the offending
10529    // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
10530    // as `ContratoEndpointInvalid` on the sibling axis; same shared
10531    // predicate (`crate::render::is_wit_world_ref`) ensures drift
10532    // between any two axes' rule enforcement is a build error at the
10533    // predicate, not piecemeal across renderers.
10534
10535    fn contrato_wit_err(wit: &str) -> AplicacaoError {
10536        // Fresh spec per call so the new contract doesn't collide on
10537        // identity with `three_member_spec`'s pre-existing entries.
10538        // The new edge uses `(payment, catalog)` — a pair the fixture
10539        // doesn't already declare — with no payload field set, so the
10540        // wit-shape gate fires before any payload-shape arm.
10541        let mut s = three_member_spec();
10542        s.contratos.push(WitContract {
10543            de: "payment".into(),
10544            para: "catalog".into(),
10545            wit: wit.into(),
10546            endpoint: None,
10547            subject: None,
10548            slot: None,
10549        });
10550        s.validate().unwrap_err()
10551    }
10552
10553    #[test]
10554    fn rejects_wit_with_uppercase_namespace() {
10555        // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
10556        // didn't match the lowercase `wasi:http/` prefix is_http() keys
10557        // off, so the dispatch fell through to the capability arm and
10558        // the contract silently rendered as an L4-only Cilium edge.
10559        // The new gate surfaces the uppercase typo at validate time
10560        // with the offending `:wit` named.
10561        let err = contrato_wit_err("WASI:http/proxy");
10562        assert!(
10563            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10564                if wit == "WASI:http/proxy" && reason.contains("lowercase")),
10565            "got {err:?}"
10566        );
10567    }
10568
10569    #[test]
10570    fn rejects_wit_with_hyphen_for_colon_typo() {
10571        // The canonical "I forgot the `:` separator" typo — pre-gate
10572        // this passed as Capability silently, so the renderer emitted
10573        // an L4-only policy where the author expected L7 HTTP rules.
10574        let err = contrato_wit_err("wasi-http/proxy");
10575        assert!(
10576            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10577                if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
10578            "got {err:?}"
10579        );
10580    }
10581
10582    #[test]
10583    fn rejects_wit_with_multiple_colons() {
10584        // Doubled `:` — the namespace/package split has nowhere to
10585        // anchor, so the dispatch silently demotes to Capability.
10586        let err = contrato_wit_err("wasi:http:proxy");
10587        assert!(
10588            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10589                if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
10590            "got {err:?}"
10591        );
10592    }
10593
10594    #[test]
10595    fn rejects_wit_with_empty_package() {
10596        // `wasi:` — namespace alone with no package. Pre-gate this
10597        // failed neither the is_http nor is_pubsub nor is_store
10598        // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
10599        // a bare `wasi:`), so it silently demoted to Capability.
10600        let err = contrato_wit_err("wasi:");
10601        assert!(
10602            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10603                if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
10604            "got {err:?}"
10605        );
10606    }
10607
10608    #[test]
10609    fn rejects_wit_with_underscore() {
10610        // Underscore — WIT identifiers are kebab-case, same rule
10611        // DNS-1123 enforces on its peer axes. The diagnostic carries
10612        // the explicit "use `-` instead" remediation.
10613        let err = contrato_wit_err("wasi:http_proxy");
10614        assert!(
10615            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10616                if wit == "wasi:http_proxy" && reason.contains('_')),
10617            "got {err:?}"
10618        );
10619    }
10620
10621    #[test]
10622    fn rejects_wit_with_whitespace() {
10623        // Whitespace mid-token — the prefix check matches but the
10624        // package-and-onward parse silently demoted to Capability.
10625        let err = contrato_wit_err("wasi:http proxy");
10626        assert!(
10627            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10628                if wit == "wasi:http proxy" && reason.contains("whitespace")),
10629            "got {err:?}"
10630        );
10631    }
10632
10633    #[test]
10634    fn rejects_wit_with_non_ascii() {
10635        // Un-percent-encoded non-ASCII byte — the canonical "I copied
10636        // the package name from a doc with smart quotes / accented
10637        // characters" footgun.
10638        let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
10639        assert!(
10640            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10641                if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
10642            "got {err:?}"
10643        );
10644    }
10645
10646    #[test]
10647    fn rejects_wit_with_consecutive_hyphens() {
10648        // `pub--sub` — WIT identifiers join words with single hyphens.
10649        let err = contrato_wit_err("nats:pub--sub");
10650        assert!(
10651            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10652                if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
10653            "got {err:?}"
10654        );
10655    }
10656
10657    #[test]
10658    fn rejects_wit_with_trailing_at_no_version() {
10659        // `wasi:http/proxy@` — the version-suffix author started to
10660        // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
10661        // parser would reject this; surface it at validate time.
10662        let err = contrato_wit_err("wasi:http/proxy@");
10663        assert!(
10664            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10665                if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
10666            "got {err:?}"
10667        );
10668    }
10669
10670    #[test]
10671    fn rejects_wit_too_long() {
10672        // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
10673        // The legitimate-shape arms all pass (lowercase, single `:`,
10674        // kebab-case identifiers); only the cap arm fires. Surfaces
10675        // the paste-from-binary / accidental-multi-line-blob landing
10676        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
10677        // on the peer axis.
10678        let big = format!("wasi:{}", "a".repeat(124));
10679        assert_eq!(big.len(), 129);
10680        let err = contrato_wit_err(&big);
10681        assert!(
10682            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10683                if wit == &big && reason.contains("max length of 128")),
10684            "got {err:?}"
10685        );
10686    }
10687
10688    #[test]
10689    fn wit_max_length_validates() {
10690        // 128-byte WIT reference — exactly the cap. Boundary pin:
10691        // drift in the cap surfaces here and at `rejects_wit_too_long`
10692        // simultaneously, mirroring
10693        // `http_contrato_endpoint_max_length_validates` on the peer
10694        // axis.
10695        let big = format!("wasi:{}", "a".repeat(123));
10696        assert_eq!(big.len(), 128);
10697        let mut s = three_member_spec();
10698        s.contratos.push(WitContract {
10699            de: "payment".into(),
10700            para: "catalog".into(),
10701            wit: big,
10702            endpoint: None,
10703            subject: None,
10704            slot: None,
10705        });
10706        s.validate().unwrap();
10707    }
10708
10709    #[test]
10710    fn wit_accepts_canonical_forms_at_aplicacao_layer() {
10711        // Positive-set sweep through the AplicacaoSpec::validate
10712        // surface (rather than the substrate-side predicate directly)
10713        // — pins every shape the existing test fixtures + the
10714        // checkout-aplicacao example carry, so the gate's accept-set
10715        // matches the substrate's emit-set. Drift between this list
10716        // and `render::tests::wit_world_ref_accepts_canonical_forms`
10717        // surfaces at the substrate layer's positive sweep — one
10718        // source of truth for the rule.
10719        for wit in [
10720            "wasi:http/proxy",
10721            "wasi:keyvalue/store",
10722            "nats:pub-sub",
10723            "kafka:topic",
10724            "custom:exchange",
10725            "pleme:cap/audit",
10726            "wasi:http/proxy@0.2.0",
10727        ] {
10728            // Payload field paired to the dispatched WIT shape so the
10729            // shape-↔-target arm doesn't fire instead of the wit-shape
10730            // arm we're exercising. Routes off the same
10731            // `wit_shape_is_http` / `wit_shape_is_pubsub` /
10732            // `wit_shape_is_store` free functions the production
10733            // `WitContract::is_http` / `is_pubsub` / `is_store`
10734            // methods delegate to (both consult the lifted
10735            // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
10736            // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
10737            // future prefix addition to the routing accept-set
10738            // reaches this test's payload-dispatch arm by
10739            // construction — no per-test-site drift can hide a
10740            // shape-→-target-slot mismatch that would silently
10741            // demote a canonical `:wit` value to the
10742            // `(None, None, None)` capability-only arm and let the
10743            // `AplicacaoSpec::validate` positive sweep pass on a
10744            // shape it should exercise as HTTP / pub-sub / store.
10745            let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
10746                (Some("/x".into()), None, None)
10747            } else if wit_shape_is_pubsub(wit) {
10748                (None, Some("topic.x".into()), None)
10749            } else if wit_shape_is_store(wit) {
10750                (None, None, Some("bucket/$key".into()))
10751            } else {
10752                (None, None, None)
10753            };
10754            let mut s = three_member_spec();
10755            s.contratos.push(WitContract {
10756                de: "payment".into(),
10757                para: "catalog".into(),
10758                wit: wit.into(),
10759                endpoint,
10760                subject,
10761                slot,
10762            });
10763            s.validate()
10764                .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
10765        }
10766    }
10767
10768    #[test]
10769    fn wit_shape_predicates_accept_canonical_prefix_set() {
10770        // Positive-set sweep pinning every prefix in
10771        // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
10772        // WIT_STORE_SHAPE_PREFIXES against the three free-function
10773        // dispatch predicates. The six prefixes are the load-bearing
10774        // routing keys the substrate's WIT-shape dispatch consults
10775        // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
10776        // key/value-store-slot admission); any drift between the
10777        // free-function accept-set and this list surfaces here
10778        // rather than at apply time as a silent
10779        // shape-→-capability-only demotion.
10780        assert!(wit_shape_is_http("wasi:http/proxy"));
10781        assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
10782        assert!(wit_shape_is_http("http:incoming"));
10783
10784        assert!(wit_shape_is_pubsub("nats:pub-sub"));
10785        assert!(wit_shape_is_pubsub("kafka:topic"));
10786
10787        assert!(wit_shape_is_store("wasi:keyvalue/store"));
10788        assert!(wit_shape_is_store("kv:cache/session"));
10789    }
10790
10791    #[test]
10792    fn wit_shape_predicates_reject_uncanonical_forms() {
10793        // Negative-set pin: the six canonical prefixes are
10794        // lowercase-only (mirrors the `is_wit_world_ref` substrate
10795        // predicate's lowercase invariant — see its docstring on the
10796        // "I thought I had L7 HTTP routing, got L4-only" footgun).
10797        // The empty string, an uppercase-prefixed form, a hyphen-
10798        // instead-of-colon typo, and a bare kebab identifier all miss
10799        // every shape arm — reachable-by-construction only via the
10800        // `is_wit_world_ref` gate that admission-checks the `:wit`
10801        // value first, but pinned here so any future
10802        // free-function change (e.g. a case-insensitive
10803        // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
10804        // this unit level.
10805        for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
10806            assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
10807            assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
10808            assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
10809        }
10810    }
10811
10812    #[test]
10813    fn wit_shape_predicates_partition_canonical_set() {
10814        // Every canonical prefix routes to exactly one shape arm —
10815        // the three prefix sets are pairwise disjoint. Pins the
10816        // routing property [`WitContract::target`] relies on: an
10817        // `is_http()` return of `true` guarantees `is_pubsub()` and
10818        // `is_store()` return `false`, so the shape-→-target-slot
10819        // dispatch (endpoint vs subject vs slot) is unambiguous.
10820        // Drift (e.g. a future `"kv:"` moved into the HTTP set
10821        // without removal from the store set) would silently route
10822        // one prefix to two arms and the first-matching-arm order
10823        // becomes load-bearing — this pin surfaces it as a build
10824        // error instead.
10825        for prefix in WIT_HTTP_SHAPE_PREFIXES {
10826            let sample = format!("{prefix}x");
10827            assert!(wit_shape_is_http(&sample));
10828            assert!(!wit_shape_is_pubsub(&sample));
10829            assert!(!wit_shape_is_store(&sample));
10830        }
10831        for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
10832            let sample = format!("{prefix}x");
10833            assert!(!wit_shape_is_http(&sample));
10834            assert!(wit_shape_is_pubsub(&sample));
10835            assert!(!wit_shape_is_store(&sample));
10836        }
10837        for prefix in WIT_STORE_SHAPE_PREFIXES {
10838            let sample = format!("{prefix}x");
10839            assert!(!wit_shape_is_http(&sample));
10840            assert!(!wit_shape_is_pubsub(&sample));
10841            assert!(wit_shape_is_store(&sample));
10842        }
10843    }
10844
10845    #[test]
10846    fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
10847        // Positive pin: [`wit_shape_matches`] is exactly the
10848        // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
10849        // parameterized on the accept-set. Two-prefix accept-set,
10850        // one-prefix accept-set, and empty accept-set (which must
10851        // reject everything, including the empty string — an empty
10852        // `any()` fold returns `false`) all pinned so a future
10853        // reimplementation that swaps `starts_with` for `contains`,
10854        // `==`, or a case-folded comparator surfaces at unit-test
10855        // time.
10856        let two = &["wasi:http/", "http:"];
10857        assert!(wit_shape_matches("wasi:http/proxy", two));
10858        assert!(wit_shape_matches("http:incoming", two));
10859        assert!(!wit_shape_matches("wasi:keyvalue/store", two));
10860
10861        let one = &["nats:"];
10862        assert!(wit_shape_matches("nats:pub-sub", one));
10863        assert!(!wit_shape_matches("kafka:topic", one));
10864
10865        // Empty accept-set matches nothing — the identity element
10866        // for the disjunctive `any()` fold across the prefix set.
10867        // Reachable via a future `wit_shape_is_<name>` const paired
10868        // to a still-empty prefix table on a nascent shape-arm draft.
10869        let empty: &[&str] = &[];
10870        assert!(!wit_shape_matches("wasi:http/proxy", empty));
10871        assert!(!wit_shape_matches("", empty));
10872
10873        // starts_with, not contains: a prefix embedded mid-string
10874        // never matches. Pins the routing invariant [`WitContract::target`]
10875        // relies on (an authored `:wit "custom:wasi:http/"` string
10876        // does not silently route through the HTTP arm just because
10877        // it happens to contain the canonical HTTP prefix).
10878        assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
10879    }
10880
10881    #[test]
10882    fn wit_shape_predicates_delegate_to_wit_shape_matches() {
10883        // Equivalence pin: each per-shape predicate is exactly
10884        // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
10885        // every canonical prefix + the empty string + one negative
10886        // sample against every peer so a future predicate that grew
10887        // its own inline `iter().any(starts_with)` (rather than
10888        // delegating through the lifted combinator) drifts loudly here
10889        // — the peer-const table's contents must agree with the
10890        // predicate's accept-set by construction.
10891        let samples = [
10892            String::new(),
10893            "wasi:http/proxy".to_string(),
10894            "http:incoming".to_string(),
10895            "nats:pub-sub".to_string(),
10896            "kafka:topic".to_string(),
10897            "wasi:keyvalue/store".to_string(),
10898            "kv:cache/session".to_string(),
10899            "custom-shape".to_string(),
10900            "WASI:HTTP/proxy".to_string(),
10901        ];
10902        for wit in &samples {
10903            assert_eq!(
10904                wit_shape_is_http(wit),
10905                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
10906                "wit_shape_is_http drifted from combinator on {wit:?}",
10907            );
10908            assert_eq!(
10909                wit_shape_is_pubsub(wit),
10910                wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
10911                "wit_shape_is_pubsub drifted from combinator on {wit:?}",
10912            );
10913            assert_eq!(
10914                wit_shape_is_store(wit),
10915                wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
10916                "wit_shape_is_store drifted from combinator on {wit:?}",
10917            );
10918        }
10919    }
10920
10921    #[test]
10922    fn wit_contract_shape_methods_delegate_to_free_functions() {
10923        // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
10924        // `is_store` are `&self` conveniences on top of the free
10925        // functions — for every canonical prefix the method's return
10926        // matches its free-function peer. Sweeps the union of the
10927        // three prefix sets so a future method that grew its own
10928        // inline prefix logic (rather than delegating) drifts loudly
10929        // here on the first prefix the free function accepts and the
10930        // method doesn't.
10931        for shape_set in [
10932            WIT_HTTP_SHAPE_PREFIXES,
10933            WIT_PUBSUB_SHAPE_PREFIXES,
10934            WIT_STORE_SHAPE_PREFIXES,
10935        ] {
10936            for prefix in shape_set {
10937                let c = WitContract {
10938                    de: "cart".into(),
10939                    para: "catalog".into(),
10940                    wit: format!("{prefix}x"),
10941                    endpoint: None,
10942                    subject: None,
10943                    slot: None,
10944                };
10945                assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
10946                assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
10947                assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
10948                assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
10949            }
10950        }
10951        // Capability-arm delegation sweep: two representative
10952        // Capability-shaped `:wit` values (a bare non-prefix-matching
10953        // WIT world, the deliberately-shaped empty string
10954        // [`WitContract::is_capability`]'s docstring calls out as
10955        // syntactically Capability). Extends the free-function
10956        // delegation pin onto the fourth arm so a future
10957        // [`WitContract::is_capability`] rewrite that grew an inline
10958        // prefix-set scan (rather than delegating through
10959        // [`wit_shape_is_capability`]) drifts loudly here on the first
10960        // Capability-shaped sample.
10961        for wit in ["custom:capability-only", ""] {
10962            let c = WitContract {
10963                de: "cart".into(),
10964                para: "catalog".into(),
10965                wit: wit.into(),
10966                endpoint: None,
10967                subject: None,
10968                slot: None,
10969            };
10970            assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
10971        }
10972    }
10973
10974    #[test]
10975    fn wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis() {
10976        // 4-way partition-witness pin on the raw `&str` axis: for every
10977        // canonical prefix in the three payload-arm accept-sets,
10978        // exactly one of the four [`wit_shape_is_http`] /
10979        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
10980        // [`wit_shape_is_capability`] free functions returns `true` and
10981        // the other three return `false` — the four-arm partition
10982        // witness that locks the free-function WIT-shape-classifier
10983        // family into a partition of the `:contratos :wit` axis
10984        // load-bearing. Peer of the sibling [`WitContract`]-surface
10985        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
10986        // partition pin — extends the discipline onto the raw `&str`
10987        // axis so any future arm addition (a hypothetical
10988        // `wasi:sockets/*` transport-layer shape, an `oci:*`
10989        // capability-import carrier per the sibling
10990        // [`wit_shape_matches`] docstring's trajectory bullet) that
10991        // landed on one of the payload-arm free functions without
10992        // shrinking [`wit_shape_is_capability`]'s accept-set surfaces
10993        // here as two arms returning `true` simultaneously at
10994        // caixa-core build time rather than a silent per-consumer
10995        // misclassification at renderer emit time.
10996        for shape_set in [
10997            WIT_HTTP_SHAPE_PREFIXES,
10998            WIT_PUBSUB_SHAPE_PREFIXES,
10999            WIT_STORE_SHAPE_PREFIXES,
11000        ] {
11001            for prefix in shape_set {
11002                let wit = format!("{prefix}x");
11003                let hits = [
11004                    wit_shape_is_http(&wit),
11005                    wit_shape_is_pubsub(&wit),
11006                    wit_shape_is_store(&wit),
11007                    wit_shape_is_capability(&wit),
11008                ]
11009                .iter()
11010                .filter(|&&b| b)
11011                .count();
11012                assert_eq!(
11013                    hits,
11014                    1,
11015                    "raw-&str WIT-shape 4-way predicate partition must \
11016                     admit exactly one arm per canonical prefix; got {hits} \
11017                     hits at wit={wit:?} (is_http={}, is_pubsub={}, is_store={}, \
11018                     is_capability={})",
11019                    wit_shape_is_http(&wit),
11020                    wit_shape_is_pubsub(&wit),
11021                    wit_shape_is_store(&wit),
11022                    wit_shape_is_capability(&wit),
11023                );
11024            }
11025        }
11026        // Capability-arm sweep on the raw `&str` axis: two
11027        // representative Capability-shaped `:wit` values (a bare non-
11028        // prefix-matching WIT world, the deliberately-shaped empty
11029        // string the pure classifier still admits per
11030        // [`wit_shape_is_capability`]'s docstring). Both must land on
11031        // the fourth arm exclusively so the partition witness holds
11032        // across the full 4-arm closure on the raw `&str` axis.
11033        for wit in ["custom:capability-only", ""] {
11034            let hits = [
11035                wit_shape_is_http(wit),
11036                wit_shape_is_pubsub(wit),
11037                wit_shape_is_store(wit),
11038                wit_shape_is_capability(wit),
11039            ]
11040            .iter()
11041            .filter(|&&b| b)
11042            .count();
11043            assert_eq!(
11044                hits, 1,
11045                "raw-&str WIT-shape 4-way predicate partition must \
11046                 admit exactly one arm on Capability-shaped wit={wit:?}"
11047            );
11048            assert!(
11049                wit_shape_is_capability(wit),
11050                "wit={wit:?} must project onto the Capability arm on the raw-&str axis"
11051            );
11052        }
11053    }
11054
11055    #[test]
11056    fn wit_shape_is_capability_composes_through_payload_arm_predicate_negation() {
11057        // Composition-witness pin: [`wit_shape_is_capability`] is the
11058        // exact-inverse disjunction of the sibling payload-arm free-
11059        // function trio [`wit_shape_is_http`] / [`wit_shape_is_pubsub`]
11060        // / [`wit_shape_is_store`]. A future reimplementation that
11061        // grew its own prefix-set scan (e.g. inlining a fourth
11062        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does
11063        // not own today) rather than delegating to the sibling trio
11064        // would drift loudly here — the composition contract binds the
11065        // fourth-arm free-function predicate to the exact-inverse of
11066        // the three payload-arm free-function predicates, so any
11067        // rebrand of any prefix-set const flows through
11068        // [`wit_shape_is_capability`] by construction without a
11069        // coordinated per-consumer rewrite. Peer of the sibling
11070        // [`WitContract`]-surface
11071        // [`wit_contract_is_capability_composes_through_shape_predicate_negation`]
11072        // composition pin — extends the discipline onto the raw
11073        // `&str` axis.
11074        let mut cases: Vec<String> = Vec::new();
11075        for shape_set in [
11076            WIT_HTTP_SHAPE_PREFIXES,
11077            WIT_PUBSUB_SHAPE_PREFIXES,
11078            WIT_STORE_SHAPE_PREFIXES,
11079        ] {
11080            for prefix in shape_set {
11081                cases.push(format!("{prefix}x"));
11082            }
11083        }
11084        cases.push("custom:capability-only".to_string());
11085        cases.push(String::new());
11086        for wit in cases {
11087            assert_eq!(
11088                wit_shape_is_capability(&wit),
11089                !wit_shape_is_http(&wit) && !wit_shape_is_pubsub(&wit) && !wit_shape_is_store(&wit),
11090                "wit_shape_is_capability must equal \
11091                 !wit_shape_is_http() && !wit_shape_is_pubsub() && !wit_shape_is_store() \
11092                 at wit={wit:?}"
11093            );
11094        }
11095    }
11096
11097    #[test]
11098    fn wit_contract_is_capability_partitions_the_wit_shape_space() {
11099        // 4-way partition-witness pin: for every canonical prefix in
11100        // the payload-arm accept-sets, exactly one of the four
11101        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
11102        // [`WitContract::is_store`] / [`WitContract::is_capability`]
11103        // predicates returns `true` and the other three return `false`
11104        // — the four-arm partition witness that locks the substrate's
11105        // WIT-shape-space closure on the pre-projection axis load-
11106        // bearing. A future arm addition (a hypothetical fourth
11107        // payload-shape prefix set, a `wasi:sockets/*` transport-layer
11108        // shape) that landed on one of the payload-arm predicates
11109        // without shrinking [`WitContract::is_capability`]'s accept-set
11110        // would surface here as two arms returning `true` simultaneously
11111        // — a partition-witness break the pin catches at caixa-core
11112        // build time rather than a silent per-consumer misclassification
11113        // at renderer emit time. Peer of the sibling `WitTarget`-side
11114        // [`tests::wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`]
11115        // partition-witness pin on the post-projection payload-scalar
11116        // arm-set — extends the discipline onto the pre-projection
11117        // 4-arm shape-space.
11118        for shape_set in [
11119            WIT_HTTP_SHAPE_PREFIXES,
11120            WIT_PUBSUB_SHAPE_PREFIXES,
11121            WIT_STORE_SHAPE_PREFIXES,
11122        ] {
11123            for prefix in shape_set {
11124                let c = WitContract {
11125                    de: "cart".into(),
11126                    para: "catalog".into(),
11127                    wit: format!("{prefix}x"),
11128                    endpoint: None,
11129                    subject: None,
11130                    slot: None,
11131                };
11132                let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
11133                    .iter()
11134                    .filter(|&&b| b)
11135                    .count();
11136                assert_eq!(
11137                    hits,
11138                    1,
11139                    "WitContract WIT-shape 4-way predicate partition must \
11140                     admit exactly one arm per canonical prefix; got {hits} \
11141                     hits at wit={:?} (is_http={}, is_pubsub={}, is_store={}, \
11142                     is_capability={})",
11143                    c.wit,
11144                    c.is_http(),
11145                    c.is_pubsub(),
11146                    c.is_store(),
11147                    c.is_capability(),
11148                );
11149            }
11150        }
11151        // Capability-arm sweep: two representative capability shapes
11152        // (a bare WIT world outside the three payload-arm prefix sets,
11153        // and the deliberately-shaped empty string that
11154        // [`crate::render::is_wit_world_ref`] rejects at
11155        // [`WitContract::target`] time but which the pure classifier
11156        // still admits — see the method docstring's "purely syntactic
11157        // classification" note). Both must land on the fourth arm
11158        // exclusively, so the partition witness holds across the full
11159        // 4-arm closure.
11160        for wit in ["custom:capability-only", ""] {
11161            let c = WitContract {
11162                de: "cart".into(),
11163                para: "catalog".into(),
11164                wit: wit.into(),
11165                endpoint: None,
11166                subject: None,
11167                slot: None,
11168            };
11169            let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
11170                .iter()
11171                .filter(|&&b| b)
11172                .count();
11173            assert_eq!(
11174                hits, 1,
11175                "WitContract WIT-shape 4-way predicate partition must \
11176                 admit exactly one arm on Capability-shaped wit={wit:?}"
11177            );
11178            assert!(
11179                c.is_capability(),
11180                "wit={wit:?} must project onto the Capability arm"
11181            );
11182        }
11183    }
11184
11185    #[test]
11186    fn wit_contract_is_capability_composes_through_shape_predicate_negation() {
11187        // Composition-witness pin: [`WitContract::is_capability`] is the
11188        // exact-inverse disjunction of the sibling payload-arm predicate
11189        // trio [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
11190        // [`WitContract::is_store`]. A future reimplementation that
11191        // grew its own prefix-set scan (e.g. inlining a fourth
11192        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does not
11193        // own today) rather than delegating to the sibling trio would
11194        // drift loudly here — the composition contract binds the
11195        // fourth-arm predicate to the exact-inverse of the three
11196        // payload-arm predicates, so any rebrand of any prefix-set const
11197        // flows through this method by construction without a
11198        // coordinated per-consumer rewrite. Sweeps the union of the
11199        // three payload-arm prefix sets plus two Capability-shaped
11200        // shapes (a bare non-prefix-matching WIT world, the deliberately-
11201        // empty string the pure classifier still admits per the method
11202        // docstring's "purely syntactic classification" note).
11203        let mut cases: Vec<String> = Vec::new();
11204        for shape_set in [
11205            WIT_HTTP_SHAPE_PREFIXES,
11206            WIT_PUBSUB_SHAPE_PREFIXES,
11207            WIT_STORE_SHAPE_PREFIXES,
11208        ] {
11209            for prefix in shape_set {
11210                cases.push(format!("{prefix}x"));
11211            }
11212        }
11213        cases.push("custom:capability-only".to_string());
11214        cases.push(String::new());
11215        for wit in cases {
11216            let c = WitContract {
11217                de: "cart".into(),
11218                para: "catalog".into(),
11219                wit: wit.clone(),
11220                endpoint: None,
11221                subject: None,
11222                slot: None,
11223            };
11224            assert_eq!(
11225                c.is_capability(),
11226                !c.is_http() && !c.is_pubsub() && !c.is_store(),
11227                "WitContract::is_capability must equal \
11228                 !is_http() && !is_pubsub() && !is_store() at wit={wit:?}"
11229            );
11230        }
11231    }
11232
11233    #[test]
11234    fn wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant() {
11235        // Cross-projection-witness pin: whenever [`WitContract::target`]
11236        // succeeds, the pre-projection [`WitContract::is_capability`]
11237        // classification agrees with the post-projection
11238        // [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
11239        // predicate — the 4-arm typed partition on the substrate's
11240        // typed-view surface (7f6aa98 IsVariant lift) and the peer 4-arm
11241        // partition on the pre-projection axis line up by construction.
11242        // A future divergence between the two axes (a peer
11243        // [`WitTarget`] variant addition that landed on the typed-view
11244        // surface without a peer prefix-set + [`WitContract`] predicate
11245        // extension, or vice versa) would surface here at caixa-core
11246        // build time rather than a silent per-consumer split at renderer
11247        // emit time. Peer of the sibling pre-/post-projection
11248        // agreement pins the payload-carrier trio
11249        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
11250        // [`WitContract::slot`] on pre-projection; [`WitTarget::http_endpoint`]
11251        // / [`WitTarget::pubsub_subject`] / [`WitTarget::store_slot`] on
11252        // post-projection — b11bb49 trio lift) already carry across the
11253        // three payload arms — this pin closes the pair on the fourth
11254        // payload-less arm.
11255        let http = WitContract {
11256            de: "cart".into(),
11257            para: "catalog".into(),
11258            wit: "wasi:http/proxy".into(),
11259            endpoint: Some("/x".into()),
11260            subject: None,
11261            slot: None,
11262        };
11263        assert!(!http.is_capability());
11264        assert!(!http.target().unwrap().is_capability());
11265
11266        let nats = WitContract {
11267            de: "cart".into(),
11268            para: "catalog".into(),
11269            wit: "nats:pub-sub".into(),
11270            endpoint: None,
11271            subject: Some("events.x".into()),
11272            slot: None,
11273        };
11274        assert!(!nats.is_capability());
11275        assert!(!nats.target().unwrap().is_capability());
11276
11277        let kv = WitContract {
11278            de: "cart".into(),
11279            para: "catalog".into(),
11280            wit: "wasi:keyvalue/store".into(),
11281            endpoint: None,
11282            subject: None,
11283            slot: Some("checkout/$orderId".into()),
11284        };
11285        assert!(!kv.is_capability());
11286        assert!(!kv.target().unwrap().is_capability());
11287
11288        let cap = WitContract {
11289            de: "cart".into(),
11290            para: "catalog".into(),
11291            wit: "custom:capability-only".into(),
11292            endpoint: None,
11293            subject: None,
11294            slot: None,
11295        };
11296        assert!(cap.is_capability());
11297        assert!(cap.target().unwrap().is_capability());
11298    }
11299
11300    #[test]
11301    fn empty_wit_takes_precedence_over_invalid() {
11302        // Ordering pin: `EmptyWit` is the more self-locating
11303        // diagnostic on `""` and must lead — the value-shape gate is
11304        // only reached after the empty-check fires. Mirrors
11305        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
11306        // the peer payload axis.
11307        let mut s = three_member_spec();
11308        s.contratos.push(WitContract {
11309            de: "payment".into(),
11310            para: "catalog".into(),
11311            wit: String::new(),
11312            endpoint: None,
11313            subject: None,
11314            slot: None,
11315        });
11316        let err = s.validate().unwrap_err();
11317        assert!(
11318            matches!(err, AplicacaoError::EmptyWit { .. }),
11319            "got {err:?}"
11320        );
11321    }
11322
11323    #[test]
11324    fn wit_invalid_fires_before_payload_shape_arm() {
11325        // Ordering pin: a malformed `:wit` surfaces *its own*
11326        // diagnostic (which names the offending wit verbatim) before
11327        // any payload-field check — a contrato whose wit is
11328        // structurally invalid AND carries a wrong target field
11329        // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
11330        // because the dispatch on the wit is what decides which
11331        // payload field is "right" in the first place. Without this
11332        // ordering, the author would see "wrong target field" for a
11333        // wit that hasn't even been parsed, which doesn't name the
11334        // root cause.
11335        let mut s = three_member_spec();
11336        s.contratos.push(WitContract {
11337            de: "payment".into(),
11338            para: "catalog".into(),
11339            // Hyphen-for-colon typo + endpoint set: pre-gate this
11340            // raised `ContratoWrongTarget { expected: "none" }` (the
11341            // Capability arm rejecting the endpoint), masking the
11342            // real authoring mistake (the wit isn't `wasi:http/proxy`).
11343            wit: "wasi-http/proxy".into(),
11344            endpoint: Some("/x".into()),
11345            subject: None,
11346            slot: None,
11347        });
11348        let err = s.validate().unwrap_err();
11349        assert!(
11350            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
11351                if wit == "wasi-http/proxy"),
11352            "got {err:?}"
11353        );
11354    }
11355
11356    #[test]
11357    fn wit_invalid_diagnostic_carries_offending_wit() {
11358        // Diagnostic-shape pin — the offending `:wit` + `:de` +
11359        // `:para` + a non-empty reason flow through verbatim so the
11360        // author can grep their caixa.lisp for the offending contrato
11361        // block and fix it in one edit. Same shape as
11362        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
11363        let err = contrato_wit_err("WASI:HTTP/proxy");
11364        match err {
11365            AplicacaoError::ContratoWitInvalid {
11366                de,
11367                para,
11368                wit,
11369                reason,
11370            } => {
11371                assert_eq!(de, "payment");
11372                assert_eq!(para, "catalog");
11373                assert_eq!(wit, "WASI:HTTP/proxy");
11374                assert!(!reason.is_empty(), "reason field must be non-empty");
11375            }
11376            other => panic!("expected ContratoWitInvalid, got {other:?}"),
11377        }
11378    }
11379
11380    // ── :contratos :subject value-shape gate ─────────────────────────────
11381    //
11382    // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
11383    // suites on the peer payload axes. Until this gate landed
11384    // `WitContract::target()` only refused the empty string; a
11385    // structurally invalid subject silently passed validate and the
11386    // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
11387    // Subject'` on publish / subscribe, or as a silent message drop,
11388    // far from the source caixa.lisp. Every authoring footgun the
11389    // NATS server's subject parser would catch on admission now
11390    // becomes a caixa-build-time `ContratoSubjectInvalid` with the
11391    // offending `:subject` + `:de` + `:para` named verbatim. Same
11392    // diagnostic shape as `ContratoEndpointInvalid` /
11393    // `ContratoWitInvalid` on the peer payload axes; same shared
11394    // predicate (`crate::render::is_nats_subject`) ensures drift
11395    // between any two axes' rule enforcement is a build error at the
11396    // predicate, not piecemeal across renderers.
11397
11398    fn contrato_subject_err(subject: &str) -> AplicacaoError {
11399        // Fresh spec per call so the new contract doesn't collide on
11400        // identity with `three_member_spec`'s pre-existing entries.
11401        // The new edge uses `(payment, catalog)` — a pair the fixture
11402        // doesn't already declare — with `:wit "nats:pub-sub"` and the
11403        // varying `:subject`, so the subject-shape gate fires cleanly
11404        // after the wit-shape gate (which `"nats:pub-sub"` passes).
11405        let mut s = three_member_spec();
11406        s.contratos.push(WitContract {
11407            de: "payment".into(),
11408            para: "catalog".into(),
11409            wit: "nats:pub-sub".into(),
11410            endpoint: None,
11411            subject: Some(subject.into()),
11412            slot: None,
11413        });
11414        s.validate().unwrap_err()
11415    }
11416
11417    #[test]
11418    fn rejects_pubsub_contrato_subject_with_whitespace() {
11419        // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
11420        // landed at the NATS server as a malformed subject the parser
11421        // rejects with `-ERR 'Invalid Subject'`. Now caught at the
11422        // source caixa.lisp.
11423        let err = contrato_subject_err("foo bar");
11424        assert!(
11425            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11426                if subject == "foo bar" && reason.contains("whitespace")),
11427            "got {err:?}"
11428        );
11429    }
11430
11431    #[test]
11432    fn rejects_pubsub_contrato_subject_with_control_char() {
11433        let err = contrato_subject_err("foo\x01bar");
11434        assert!(
11435            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11436                if subject == "foo\x01bar" && reason.contains("control character")),
11437            "got {err:?}"
11438        );
11439    }
11440
11441    #[test]
11442    fn rejects_pubsub_contrato_subject_with_non_ascii() {
11443        // Un-percent-encoded non-ASCII byte — the canonical "I copied
11444        // the subject from a doc with smart quotes / accented
11445        // characters" footgun.
11446        let err = contrato_subject_err("foo.caf\u{e9}");
11447        assert!(
11448            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11449                if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
11450            "got {err:?}"
11451        );
11452    }
11453
11454    #[test]
11455    fn rejects_pubsub_contrato_subject_with_leading_dot() {
11456        // Empty leading token — NATS rejects.
11457        let err = contrato_subject_err(".foo");
11458        assert!(
11459            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11460                if subject == ".foo" && reason.contains("must not start with `.`")),
11461            "got {err:?}"
11462        );
11463    }
11464
11465    #[test]
11466    fn rejects_pubsub_contrato_subject_with_trailing_dot() {
11467        // Empty trailing token — NATS rejects. The remediation
11468        // (use `>` instead) is in the reason string.
11469        let err = contrato_subject_err("foo.");
11470        assert!(
11471            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11472                if subject == "foo." && reason.contains("must not end with `.`")),
11473            "got {err:?}"
11474        );
11475    }
11476
11477    #[test]
11478    fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
11479        // The canonical "I forgot to fill in the middle segment"
11480        // typo — `"foo..bar"`. NATS rejects empty tokens.
11481        let err = contrato_subject_err("foo..bar");
11482        assert!(
11483            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11484                if subject == "foo..bar" && reason.contains("consecutive `.`")),
11485            "got {err:?}"
11486        );
11487    }
11488
11489    #[test]
11490    fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
11491        // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
11492        // as the final segment. Pre-gate this passed as a typed edge
11493        // and surfaced at runtime as a NATS subscribe rejection.
11494        let err = contrato_subject_err("foo.>.bar");
11495        assert!(
11496            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11497                if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
11498            "got {err:?}"
11499        );
11500    }
11501
11502    #[test]
11503    fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
11504        // `foo*.bar` — NATS wildcards are standalone tokens. The
11505        // remediation is in the reason string.
11506        let err = contrato_subject_err("foo*.bar");
11507        assert!(
11508            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11509                if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
11510            "got {err:?}"
11511        );
11512    }
11513
11514    #[test]
11515    fn rejects_pubsub_contrato_subject_with_invalid_char() {
11516        // `foo,bar` — comma is not a valid NATS subject character.
11517        // Pinned separately from the wildcard arms so the invalid-
11518        // character diagnostic is in force.
11519        let err = contrato_subject_err("foo,bar");
11520        assert!(
11521            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11522                if subject == "foo,bar" && reason.contains("invalid character")),
11523            "got {err:?}"
11524        );
11525    }
11526
11527    #[test]
11528    fn rejects_pubsub_contrato_subject_too_long() {
11529        // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
11530        // The legitimate-shape arms all pass (one all-`a` token, no
11531        // `.`, no wildcards); only the cap arm fires. Surfaces the
11532        // paste-from-binary / accidental-multi-line-blob landing
11533        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
11534        // on the peer axis.
11535        let big = "a".repeat(257);
11536        assert_eq!(big.len(), 257);
11537        let err = contrato_subject_err(&big);
11538        assert!(
11539            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11540                if subject == &big && reason.contains("max length of 256")),
11541            "got {err:?}"
11542        );
11543    }
11544
11545    #[test]
11546    fn pubsub_contrato_subject_max_length_validates() {
11547        // 256-byte subject — exactly the cap. Boundary pin: drift in
11548        // the cap surfaces here and at
11549        // `rejects_pubsub_contrato_subject_too_long` simultaneously,
11550        // mirroring `http_contrato_endpoint_max_length_validates` and
11551        // `wit_max_length_validates` on the peer axes.
11552        let big = "a".repeat(256);
11553        assert_eq!(big.len(), 256);
11554        let mut s = three_member_spec();
11555        s.contratos.push(WitContract {
11556            de: "payment".into(),
11557            para: "catalog".into(),
11558            wit: "nats:pub-sub".into(),
11559            endpoint: None,
11560            subject: Some(big),
11561            slot: None,
11562        });
11563        s.validate().unwrap();
11564    }
11565
11566    #[test]
11567    fn pubsub_contrato_subject_accepts_canonical_forms() {
11568        // Positive-set sweep: every canonical NATS subject shape the
11569        // substrate-side `is_nats_subject` predicate accepts (the
11570        // multi-dot `events.order.charged`, the snake_case / kebab-
11571        // case / mixed-case tokens, the digit-bearing tokens, the
11572        // single-token wildcard `*` at every segment position, and
11573        // the trailing `>` multi-token wildcard) must remain a valid
11574        // contrato subject too. Drift between this list and the
11575        // substrate-side `nats_subject_accepts_canonical_forms` sweep
11576        // surfaces at the shared predicate — one source of truth.
11577        // Uses a fresh `(payment, catalog)` edge so none of the swept
11578        // subjects collide with the pre-existing entries in
11579        // `three_member_spec`.
11580        for subject in [
11581            "checkout.events.charge.failed",
11582            "rio.events.order.charged",
11583            "orders",
11584            "orders.123",
11585            "snake_case.token",
11586            "kebab-case.token",
11587            "MixedCase.Token",
11588            "orders.*.charged",
11589            "*.events.*",
11590            "orders.>",
11591        ] {
11592            let mut s = three_member_spec();
11593            s.contratos.push(WitContract {
11594                de: "payment".into(),
11595                para: "catalog".into(),
11596                wit: "nats:pub-sub".into(),
11597                endpoint: None,
11598                subject: Some(subject.into()),
11599                slot: None,
11600            });
11601            s.validate()
11602                .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
11603        }
11604    }
11605
11606    #[test]
11607    fn contrato_subject_empty_takes_precedence_over_invalid() {
11608        // Ordering pin: `ContratoSubjectEmpty` is the more self-
11609        // locating diagnostic on `""` and must lead — the value-shape
11610        // gate is only reached after the empty-check fires. Mirrors
11611        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
11612        // the peer payload axis.
11613        let mut s = three_member_spec();
11614        s.contratos.push(WitContract {
11615            de: "payment".into(),
11616            para: "catalog".into(),
11617            wit: "nats:pub-sub".into(),
11618            endpoint: None,
11619            subject: Some(String::new()),
11620            slot: None,
11621        });
11622        let err = s.validate().unwrap_err();
11623        assert!(
11624            matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
11625            "got {err:?}"
11626        );
11627    }
11628
11629    #[test]
11630    fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
11631        // Diagnostic-shape pin — the offending `:subject` + `:de` +
11632        // `:para` + a non-empty reason flow through verbatim so the
11633        // author can grep their caixa.lisp for the offending contrato
11634        // block and fix it in one edit. Same shape as
11635        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
11636        // and `wit_invalid_diagnostic_carries_offending_wit`.
11637        let err = contrato_subject_err("foo..bar");
11638        match err {
11639            AplicacaoError::ContratoSubjectInvalid {
11640                de,
11641                para,
11642                subject,
11643                reason,
11644            } => {
11645                assert_eq!(de, "payment");
11646                assert_eq!(para, "catalog");
11647                assert_eq!(subject, "foo..bar");
11648                assert!(!reason.is_empty(), "reason field must be non-empty");
11649            }
11650            other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
11651        }
11652    }
11653
11654    #[test]
11655    fn target_view_pubsub_subject_passes_through_to_typed_view() {
11656        // The compounding theorem on the pub-sub axis: every
11657        // `WitTarget::PubSub { subject }` returned by `target()` carries
11658        // a NATS-server-accepted subject. Renderers downstream of
11659        // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
11660        // NATS Stream/Consumer CR emitter, the future `feira app graph`
11661        // view's subject labeller) can rely on this without re-checking
11662        // — the type system carries the proof. Mirrors
11663        // `target_view_payload_is_guaranteed_nonempty_after_target_call`
11664        // on the peer axes.
11665        let nats = WitContract {
11666            de: "a".into(),
11667            para: "b".into(),
11668            wit: "nats:pub-sub".into(),
11669            endpoint: None,
11670            subject: Some("orders.events.*.charged".into()),
11671            slot: None,
11672        };
11673        match nats.target().unwrap() {
11674            WitTarget::PubSub { subject } => {
11675                assert_eq!(subject, "orders.events.*.charged");
11676            }
11677            other => panic!("expected PubSub, got {other:?}"),
11678        }
11679    }
11680
11681    // ── :contratos :slot value-shape gate ────────────────────────────────
11682    //
11683    // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
11684    // (63e18a0) value-shape suites on the peer payload axes. Until this
11685    // gate landed `WitContract::target()` only refused the empty string
11686    // for the Store arm; a structurally invalid slot (raw whitespace,
11687    // control character, non-ASCII byte, paste-from-binary multi-line
11688    // blob) silently passed validate and surfaced at runtime as a
11689    // per-backend kv write rejection or a silent next-read corruption,
11690    // far from the source caixa.lisp with no field naming which
11691    // `:contratos` edge carried the typo. Every authoring footgun the
11692    // kv backend intersection-floor would catch on write now becomes a
11693    // caixa-build-time `ContratoSlotInvalid` with the offending
11694    // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
11695    // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
11696    // peer payload axes; same shared predicate
11697    // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
11698    // any two axes' rule enforcement is a build error at the
11699    // predicate, not piecemeal across renderers. Closes the typed
11700    // payload-axis value-shape trajectory across all three legs of the
11701    // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
11702
11703    fn contrato_slot_err(slot: &str) -> AplicacaoError {
11704        // Fresh spec per call so the new contract doesn't collide on
11705        // identity with `three_member_spec`'s pre-existing entries
11706        // and doesn't close a synchronous cycle the cycle detector
11707        // would reject before the slot-shape gate fires. The new edge
11708        // uses `(payment, catalog)` — a pair the fixture doesn't
11709        // already declare in either direction (the fixture carries
11710        // `cart -> catalog` and `cart -> payment`, so `payment ->
11711        // catalog` doesn't form a cycle on the sync subgraph) — with
11712        // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
11713        // slot-shape gate fires cleanly after the wit-shape gate
11714        // (which `"wasi:keyvalue/store"` passes). Same edge pair the
11715        // peer `contrato_subject_err` helper uses (63e18a0).
11716        let mut s = three_member_spec();
11717        s.contratos.push(WitContract {
11718            de: "payment".into(),
11719            para: "catalog".into(),
11720            wit: "wasi:keyvalue/store".into(),
11721            endpoint: None,
11722            subject: None,
11723            slot: Some(slot.into()),
11724        });
11725        s.validate().unwrap_err()
11726    }
11727
11728    #[test]
11729    fn rejects_store_contrato_slot_with_whitespace() {
11730        // Fail-before-pass-after pin — pre-gate `"check out/$order"`
11731        // silently landed at the kv backend with whitespace whose
11732        // runtime behavior varies unpredictably across backends (etcd
11733        // accepts, Redis accepts then breaks on next CLI op, DynamoDB
11734        // rejects on write). Now caught at the source caixa.lisp.
11735        let err = contrato_slot_err("check out/$order");
11736        assert!(
11737            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11738                if slot == "check out/$order" && reason.contains("whitespace")),
11739            "got {err:?}"
11740        );
11741    }
11742
11743    #[test]
11744    fn rejects_store_contrato_slot_with_tab() {
11745        // Tab byte arm-pinned separately from the space arm so a
11746        // future relaxation that admits one but not the other surfaces
11747        // here.
11748        let err = contrato_slot_err("check\tout");
11749        assert!(
11750            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11751                if slot == "check\tout" && reason.contains("whitespace")),
11752            "got {err:?}"
11753        );
11754    }
11755
11756    #[test]
11757    fn rejects_store_contrato_slot_with_control_char() {
11758        // SOH (0x01) — distinct from the whitespace arm. Redis admits
11759        // and corrupts on RESP protocol framing; DynamoDB rejects on
11760        // write.
11761        let err = contrato_slot_err("checkout/\x01order");
11762        assert!(
11763            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11764                if slot == "checkout/\x01order" && reason.contains("control character")),
11765            "got {err:?}"
11766        );
11767    }
11768
11769    #[test]
11770    fn rejects_store_contrato_slot_with_newline() {
11771        // Embedded newline — the canonical "the paste-from-binary slug
11772        // spans multiple lines" footgun. Distinct from the whitespace
11773        // arm because `\n` is a control character (0x0A).
11774        let err = contrato_slot_err("checkout\norder");
11775        assert!(
11776            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11777                if slot == "checkout\norder" && reason.contains("control character")),
11778            "got {err:?}"
11779        );
11780    }
11781
11782    #[test]
11783    fn rejects_store_contrato_slot_with_non_ascii() {
11784        // Un-percent-encoded non-ASCII byte — the canonical "I copied
11785        // the slot from a doc with accented characters" footgun. Each
11786        // kv backend re-encodes non-ASCII differently (etcd preserves
11787        // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
11788        // rejects), so the typed slot's value set is the intersection-
11789        // floor every backend admits identically (printable ASCII).
11790        let err = contrato_slot_err("ch\u{e9}ckout/$order");
11791        assert!(
11792            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11793                if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
11794            "got {err:?}"
11795        );
11796    }
11797
11798    #[test]
11799    fn rejects_store_contrato_slot_too_long() {
11800        // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
11801        // legitimate-shape arms all pass (a single all-`a` token, no
11802        // separators); only the cap arm fires. Surfaces the paste-
11803        // from-binary / accidental-multi-line-blob landing footgun.
11804        // Mirrors `rejects_pubsub_contrato_subject_too_long` and
11805        // `rejects_http_contrato_endpoint_too_long` on the peer
11806        // payload axes.
11807        let big = "a".repeat(513);
11808        assert_eq!(big.len(), 513);
11809        let err = contrato_slot_err(&big);
11810        assert!(
11811            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11812                if slot == &big && reason.contains("max length of 512")),
11813            "got {err:?}"
11814        );
11815    }
11816
11817    #[test]
11818    fn store_contrato_slot_max_length_validates() {
11819        // 512-byte slot — exactly the cap. Boundary pin: drift in the
11820        // cap surfaces here and at `rejects_store_contrato_slot_too_long`
11821        // simultaneously, mirroring
11822        // `pubsub_contrato_subject_max_length_validates` and
11823        // `http_contrato_endpoint_max_length_validates` on the peer
11824        // payload axes.
11825        let big = "a".repeat(512);
11826        assert_eq!(big.len(), 512);
11827        let mut s = three_member_spec();
11828        s.contratos.push(WitContract {
11829            de: "payment".into(),
11830            para: "catalog".into(),
11831            wit: "wasi:keyvalue/store".into(),
11832            endpoint: None,
11833            subject: None,
11834            slot: Some(big),
11835        });
11836        s.validate().unwrap();
11837    }
11838
11839    #[test]
11840    fn store_contrato_slot_accepts_canonical_forms() {
11841        // Positive-set sweep: every canonical kv slot template the
11842        // substrate-side `is_wasi_keyvalue_slot` predicate accepts
11843        // (single-token identifiers, path-namespaced `$`-templates,
11844        // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
11845        // snake_case / kebab-case / MixedCase tokens, digit-bearing
11846        // tokens, percent-encoded fragments) must remain valid
11847        // contrato slots too. Drift between this list and the
11848        // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
11849        // surfaces at the shared predicate — one source of truth.
11850        // Uses a fresh `(payment, catalog)` edge so none of the swept
11851        // slots collide with the pre-existing entries in
11852        // `three_member_spec`.
11853        for slot in [
11854            "checkout",
11855            "checkout/$orderId",
11856            "users:{tenant}/{id}",
11857            "session.<sid>",
11858            "session.tokens.<sid>",
11859            "snake_case_key",
11860            "kebab-case-key",
11861            "MixedCase",
11862            "shard0",
11863            "v2/key",
11864            "users/caf%C3%A9",
11865        ] {
11866            let mut s = three_member_spec();
11867            s.contratos.push(WitContract {
11868                de: "payment".into(),
11869                para: "catalog".into(),
11870                wit: "wasi:keyvalue/store".into(),
11871                endpoint: None,
11872                subject: None,
11873                slot: Some(slot.into()),
11874            });
11875            s.validate()
11876                .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
11877        }
11878    }
11879
11880    #[test]
11881    fn contrato_slot_empty_takes_precedence_over_invalid() {
11882        // Ordering pin: `ContratoSlotEmpty` is the more self-locating
11883        // diagnostic on `""` and must lead — the value-shape gate is
11884        // only reached after the empty-check fires. Mirrors
11885        // `contrato_subject_empty_takes_precedence_over_invalid` and
11886        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
11887        // the peer payload axes.
11888        let mut s = three_member_spec();
11889        s.contratos.push(WitContract {
11890            de: "payment".into(),
11891            para: "catalog".into(),
11892            wit: "wasi:keyvalue/store".into(),
11893            endpoint: None,
11894            subject: None,
11895            slot: Some(String::new()),
11896        });
11897        let err = s.validate().unwrap_err();
11898        assert!(
11899            matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
11900            "got {err:?}"
11901        );
11902    }
11903
11904    #[test]
11905    fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
11906        // Diagnostic-shape pin — the offending `:slot` + `:de` +
11907        // `:para` + a non-empty reason flow through verbatim so the
11908        // author can grep their caixa.lisp for the offending contrato
11909        // block and fix it in one edit. Same shape as
11910        // `contrato_subject_invalid_diagnostic_carries_offending_subject`
11911        // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
11912        // on the peer payload axes.
11913        let err = contrato_slot_err("check out/$order");
11914        match err {
11915            AplicacaoError::ContratoSlotInvalid {
11916                de,
11917                para,
11918                slot,
11919                reason,
11920            } => {
11921                assert_eq!(de, "payment");
11922                assert_eq!(para, "catalog");
11923                assert_eq!(slot, "check out/$order");
11924                assert!(!reason.is_empty(), "reason field must be non-empty");
11925            }
11926            other => panic!("expected ContratoSlotInvalid, got {other:?}"),
11927        }
11928    }
11929
11930    #[test]
11931    fn target_view_store_slot_passes_through_to_typed_view() {
11932        // The compounding theorem on the store axis: every
11933        // `WitTarget::Store { slot }` returned by `target()` carries a
11934        // kv-backend-accepted slot template. Renderers downstream of
11935        // `typed_view()` (the future per-Servico `:capabilities
11936        // wasi:keyvalue/store` axis emitter, the future `feira app
11937        // graph` view's slot labeller, the future kv-provider CR
11938        // materializer) can rely on this without re-checking — the
11939        // type system carries the proof. Mirrors
11940        // `target_view_pubsub_subject_passes_through_to_typed_view` on
11941        // the peer payload axis.
11942        let store = WitContract {
11943            de: "a".into(),
11944            para: "b".into(),
11945            wit: "wasi:keyvalue/store".into(),
11946            endpoint: None,
11947            subject: None,
11948            slot: Some("checkout/$orderId".into()),
11949        };
11950        match store.target().unwrap() {
11951            WitTarget::Store { slot } => {
11952                assert_eq!(slot, "checkout/$orderId");
11953            }
11954            other => panic!("expected Store, got {other:?}"),
11955        }
11956    }
11957
11958    #[test]
11959    fn rejects_self_loop_in_synchronous_contratos() {
11960        // A synchronous self-edge (`cart → cart` over HTTP) is now
11961        // rejected by the dedicated `ContratoSelfLoop` gate — a precise
11962        // "this edge is degenerate" diagnostic — rather than incidentally
11963        // by the cycle detector framing it as a `["cart", "cart"]`
11964        // multi-node deadlock.
11965        let mut s = three_member_spec();
11966        s.contratos.push(contract_http("cart", "cart", "/loop"));
11967        let err = s.validate().unwrap_err();
11968        match err {
11969            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
11970                assert_eq!(caixa, "cart");
11971                assert_eq!(wit, "wasi:http/proxy");
11972            }
11973            other => panic!("expected ContratoSelfLoop, got {other:?}"),
11974        }
11975    }
11976
11977    #[test]
11978    fn rejects_self_loop_in_pubsub_contratos() {
11979        // The cycle detector excludes pub-sub edges (acyclic by
11980        // construction), so before the explicit gate a `nats:pub-sub`
11981        // self-edge silently validated and rendered a self-allow CNP.
11982        // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
11983        let mut s = three_member_spec();
11984        s.contratos.push(WitContract {
11985            de: "payment".into(),
11986            para: "payment".into(),
11987            wit: "nats:pub-sub".into(),
11988            endpoint: None,
11989            subject: Some("rio.events.payment".into()),
11990            slot: None,
11991        });
11992        let err = s.validate().unwrap_err();
11993        match err {
11994            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
11995                assert_eq!(caixa, "payment");
11996                assert_eq!(wit, "nats:pub-sub");
11997            }
11998            other => panic!("expected ContratoSelfLoop, got {other:?}"),
11999        }
12000    }
12001
12002    #[test]
12003    fn self_loop_fires_before_payload_shape_check() {
12004        // The structural "this edge can't exist" error precedes the
12005        // narrower payload-shape diagnostics: a self-edge carrying an
12006        // otherwise-malformed endpoint still reports ContratoSelfLoop,
12007        // not ContratoEndpointInvalid.
12008        let mut s = three_member_spec();
12009        s.contratos.push(WitContract {
12010            de: "cart".into(),
12011            para: "cart".into(),
12012            wit: "wasi:http/proxy".into(),
12013            endpoint: Some("not-absolute".into()),
12014            subject: None,
12015            slot: None,
12016        });
12017        match s.validate().unwrap_err() {
12018            AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
12019            other => panic!("expected ContratoSelfLoop, got {other:?}"),
12020        }
12021    }
12022
12023    #[test]
12024    fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
12025        // A self-edge naming a non-member reports the more fundamental
12026        // ContratoMemberMissing first (the member doesn't exist), so the
12027        // self-loop gate is reached only once both endpoints resolve.
12028        let mut s = three_member_spec();
12029        s.contratos.push(contract_http("ghost", "ghost", "/loop"));
12030        match s.validate().unwrap_err() {
12031            AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
12032            other => panic!("expected ContratoMemberMissing, got {other:?}"),
12033        }
12034    }
12035
12036    #[test]
12037    fn rejects_two_node_synchronous_cycle() {
12038        let mut s = three_member_spec();
12039        // existing edges: cart → catalog, cart → payment
12040        // adding catalog → cart closes a 2-cycle on the HTTP subgraph
12041        s.contratos
12042            .push(contract_http("catalog", "cart", "/refresh"));
12043        let err = s.validate().unwrap_err();
12044        match err {
12045            AplicacaoError::ContratoCycle { cycle } => {
12046                // Cycle traversal should mention both endpoints, with
12047                // the back-edge target appearing as both first and last
12048                // element to close the loop.
12049                assert!(cycle.len() >= 3);
12050                assert_eq!(cycle.first(), cycle.last());
12051                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
12052                assert!(body.contains("cart"));
12053                assert!(body.contains("catalog"));
12054            }
12055            other => panic!("expected ContratoCycle, got {other:?}"),
12056        }
12057    }
12058
12059    #[test]
12060    fn rejects_three_node_synchronous_cycle() {
12061        let mut s = three_member_spec();
12062        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
12063        s.contratos = vec![
12064            contract_http("catalog", "cart", "/x"),
12065            contract_http("cart", "payment", "/y"),
12066            contract_http("payment", "catalog", "/z"),
12067        ];
12068        let err = s.validate().unwrap_err();
12069        match err {
12070            AplicacaoError::ContratoCycle { cycle } => {
12071                assert_eq!(cycle.first(), cycle.last());
12072                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
12073                assert_eq!(body.len(), 3);
12074                assert!(body.contains("cart"));
12075                assert!(body.contains("catalog"));
12076                assert!(body.contains("payment"));
12077            }
12078            other => panic!("expected ContratoCycle, got {other:?}"),
12079        }
12080    }
12081
12082    #[test]
12083    fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
12084        // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
12085        // "acyclic by construction" — so a cycle whose closing edge
12086        // is pub-sub should NOT raise ContratoCycle.
12087        let mut s = three_member_spec();
12088        s.contratos = vec![
12089            contract_http("catalog", "cart", "/x"),
12090            contract_http("cart", "payment", "/y"),
12091            // Closing edge is pub-sub — async; not a sync deadlock.
12092            WitContract {
12093                de: "payment".into(),
12094                para: "catalog".into(),
12095                wit: "nats:pub-sub".into(),
12096                endpoint: None,
12097                subject: Some("checkout.events.charge.completed".into()),
12098                slot: None,
12099            },
12100        ];
12101        s.validate().expect("pub-sub edge breaks the sync cycle");
12102    }
12103
12104    #[test]
12105    fn store_edge_counts_as_synchronous_for_cycle_detection() {
12106        // wasi:keyvalue/store is request/response; a cycle through one
12107        // *is* a sync deadlock, just like HTTP.
12108        let mut s = three_member_spec();
12109        s.contratos = vec![
12110            contract_http("catalog", "cart", "/x"),
12111            WitContract {
12112                de: "cart".into(),
12113                para: "catalog".into(),
12114                wit: "wasi:keyvalue/store".into(),
12115                endpoint: None,
12116                subject: None,
12117                slot: Some("session/$id".into()),
12118            },
12119        ];
12120        let err = s.validate().unwrap_err();
12121        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
12122    }
12123
12124    #[test]
12125    fn capability_edge_counts_as_synchronous_for_cycle_detection() {
12126        // Capability-only edges (unknown WIT shape, no payload) default
12127        // to synchronous — safer; authors with truly async capability
12128        // semantics can model them as pub-sub explicitly.
12129        let mut s = three_member_spec();
12130        s.contratos = vec![
12131            contract_http("catalog", "cart", "/x"),
12132            WitContract {
12133                de: "cart".into(),
12134                para: "catalog".into(),
12135                wit: "custom:exchange".into(),
12136                endpoint: None,
12137                subject: None,
12138                slot: None,
12139            },
12140        ];
12141        let err = s.validate().unwrap_err();
12142        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
12143    }
12144
12145    #[test]
12146    fn long_acyclic_chain_validates() {
12147        // A long sync chain (no back-edges) must validate even when
12148        // every node is reachable from the first.
12149        let mut s = three_member_spec();
12150        s.membros = vec![
12151            membro("a", "^0.1"),
12152            membro("b", "^0.1"),
12153            membro("c", "^0.1"),
12154            membro("d", "^0.1"),
12155            membro("e", "^0.1"),
12156        ];
12157        s.contratos = vec![
12158            contract_http("a", "b", "/1"),
12159            contract_http("b", "c", "/2"),
12160            contract_http("c", "d", "/3"),
12161            contract_http("d", "e", "/4"),
12162        ];
12163        s.entrada.as_mut().unwrap().para = "a".into();
12164        s.validate().unwrap();
12165    }
12166
12167    #[test]
12168    fn diamond_acyclic_validates() {
12169        // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
12170        let mut s = three_member_spec();
12171        s.membros = vec![
12172            membro("a", "^0.1"),
12173            membro("b", "^0.1"),
12174            membro("c", "^0.1"),
12175            membro("d", "^0.1"),
12176        ];
12177        s.contratos = vec![
12178            contract_http("a", "b", "/1"),
12179            contract_http("a", "c", "/2"),
12180            contract_http("b", "d", "/3"),
12181            contract_http("c", "d", "/4"),
12182        ];
12183        s.entrada.as_mut().unwrap().para = "a".into();
12184        s.validate().unwrap();
12185    }
12186
12187    // ── duplicate-`:contratos` build-error gate ──────────────────────────
12188
12189    #[test]
12190    fn rejects_duplicate_http_contrato() {
12191        // Fail-before-pass-after pin: the fixture's `cart → catalog`
12192        // HTTP edge appears once. Push an identical entry — same
12193        // (de, para, wit, endpoint) — and validate() must reject it.
12194        // Until this gate landed the typed surface accepted the
12195        // duplicate silently and caixa-mesh's `cilium_network_policies`
12196        // emitted two ``CiliumNetworkPolicy`` objects with identical
12197        // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
12198        // admission rejects on `kubectl apply` far from the source.
12199        let mut s = three_member_spec();
12200        s.contratos
12201            .push(contract_http("cart", "catalog", "/products/:id"));
12202        let err = s.validate().unwrap_err();
12203        assert!(
12204            matches!(
12205                err,
12206                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
12207                    if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
12208            ),
12209            "got {err:?}"
12210        );
12211    }
12212
12213    #[test]
12214    fn rejects_duplicate_pubsub_contrato() {
12215        // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
12216        // edges with identical (de, para, subject) are degenerate;
12217        // pin that the typed surface refuses both at validate time.
12218        let mut s = three_member_spec();
12219        let pubsub = WitContract {
12220            de: "payment".into(),
12221            para: "cart".into(),
12222            wit: "nats:pub-sub".into(),
12223            endpoint: None,
12224            subject: Some("checkout.events.charge.failed".into()),
12225            slot: None,
12226        };
12227        s.contratos.push(pubsub.clone());
12228        s.contratos.push(pubsub);
12229        let err = s.validate().unwrap_err();
12230        assert!(
12231            matches!(
12232                err,
12233                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
12234                    if de == "payment" && para == "cart" && wit == "nats:pub-sub"
12235            ),
12236            "got {err:?}"
12237        );
12238    }
12239
12240    #[test]
12241    fn rejects_duplicate_store_contrato() {
12242        // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
12243        // edges with identical (de, para, slot) collapse to one mesh-
12244        // policy edge; pin the build error.
12245        let mut s = three_member_spec();
12246        let store = WitContract {
12247            de: "cart".into(),
12248            para: "payment".into(),
12249            wit: "wasi:keyvalue/store".into(),
12250            endpoint: None,
12251            subject: None,
12252            slot: Some("checkout/$orderId".into()),
12253        };
12254        // Drop the conflicting HTTP `cart → payment` edge from the
12255        // fixture so the duplicate-store pair is the only one
12256        // distinguishable on this pair.
12257        s.contratos
12258            .retain(|c| !(c.de == "cart" && c.para == "payment"));
12259        s.contratos.push(store.clone());
12260        s.contratos.push(store);
12261        let err = s.validate().unwrap_err();
12262        assert!(
12263            matches!(
12264                err,
12265                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
12266                    if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
12267            ),
12268            "got {err:?}"
12269        );
12270    }
12271
12272    #[test]
12273    fn rejects_duplicate_capability_contrato() {
12274        // Same gate on the pure-capability axis (no payload selector).
12275        // Two contracts with identical (de, para, wit) and no
12276        // endpoint/subject/slot are duplicate edges; pin so a future
12277        // `target_label` change can't accidentally collapse the
12278        // capability arm into a None-shaped key that compares equal
12279        // to a populated one.
12280        let mut s = three_member_spec();
12281        let capability = WitContract {
12282            de: "cart".into(),
12283            para: "catalog".into(),
12284            wit: "pleme:cap/audit".into(),
12285            endpoint: None,
12286            subject: None,
12287            slot: None,
12288        };
12289        s.contratos.push(capability.clone());
12290        s.contratos.push(capability);
12291        let err = s.validate().unwrap_err();
12292        match err {
12293            AplicacaoError::ContratoDuplicate {
12294                de,
12295                para,
12296                wit,
12297                target,
12298            } => {
12299                assert_eq!(de, "cart");
12300                assert_eq!(para, "catalog");
12301                assert_eq!(wit, "pleme:cap/audit");
12302                assert!(
12303                    target.contains("capability"),
12304                    "capability-edge duplicate diagnostic must surface the \
12305                     no-payload shape (got target = {target:?})"
12306                );
12307            }
12308            other => panic!("expected ContratoDuplicate, got {other:?}"),
12309        }
12310    }
12311
12312    #[test]
12313    fn accepts_distinct_http_paths_between_same_pair() {
12314        // Negative pin: two HTTP contracts cart → catalog at distinct
12315        // endpoints (`/products/:id` and `/search`) are *not*
12316        // duplicates — they're distinct typed edges differing on the
12317        // payload axis. The duplicate-gate must not over-match here,
12318        // since the cart-calls-catalog-on-multiple-paths shape is the
12319        // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
12320        // example: cart calls catalog at /products/:id, payment at
12321        // /charge — same shape extends to two paths on one para).
12322        let mut s = three_member_spec();
12323        s.contratos
12324            .push(contract_http("cart", "catalog", "/search"));
12325        s.validate()
12326            .expect("distinct endpoints between same (de, para) must validate");
12327    }
12328
12329    #[test]
12330    fn accepts_same_endpoint_on_different_pairs() {
12331        // Negative pin: the same `/charge` endpoint reused on two
12332        // different (de, para) pairs is two distinct edges, not a
12333        // duplicate. Pinning this shape so the gate's identity key
12334        // includes both `de` and `para` (not just `(wit, endpoint)`).
12335        let mut s = three_member_spec();
12336        s.contratos
12337            .push(contract_http("payment", "catalog", "/charge"));
12338        s.validate()
12339            .expect("same endpoint reused on distinct (de, para) must validate");
12340    }
12341
12342    #[test]
12343    fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
12344        // Pin the diagnostic shape: the duplicate-edge error names
12345        // *which* target field carried the conflict, so the author
12346        // doesn't have to re-grep the source caixa.lisp to find it.
12347        // Same self-locating diagnostic discipline as
12348        // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
12349        let mut s = three_member_spec();
12350        s.contratos
12351            .push(contract_http("cart", "catalog", "/products/:id"));
12352        let err = s.validate().unwrap_err();
12353        let msg = format!("{err}");
12354        assert!(
12355            msg.contains("\"/products/:id\""),
12356            "duplicate-contrato diagnostic must name the offending \
12357             :endpoint payload (got: {msg:?})"
12358        );
12359        assert!(
12360            msg.contains("cart") && msg.contains("catalog"),
12361            "diagnostic must name both endpoints of the duplicate edge \
12362             (got: {msg:?})"
12363        );
12364    }
12365
12366    #[test]
12367    fn duplicate_contrato_gate_runs_after_membership_check() {
12368        // Order pin: a duplicate contract whose `:de` is *also* not in
12369        // `:membros` surfaces the membership error first — the
12370        // missing-member diagnostic is more locating than the
12371        // duplicate-edge one (the author has to fix the membership
12372        // before the duplicate is meaningful). Same ordering
12373        // discipline as `membros_validation_runs_before_contratos_membership_check`.
12374        let mut s = three_member_spec();
12375        s.contratos.push(contract_http("phantom", "catalog", "/x"));
12376        s.contratos.push(contract_http("phantom", "catalog", "/x"));
12377        let err = s.validate().unwrap_err();
12378        assert!(
12379            matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
12380            "membership-missing must fire before duplicate-edge (got {err:?})"
12381        );
12382    }
12383
12384    #[test]
12385    fn duplicate_contrato_gate_runs_after_target_shape_check() {
12386        // Order pin: a contract with a malformed target (e.g. an HTTP
12387        // wit world with an empty :endpoint) surfaces the target-shape
12388        // error first, not the duplicate one. Even when two such
12389        // malformed entries are identical, the per-contract `target()`
12390        // check fires inside the loop *before* the duplicate-key
12391        // insert, so the diagnostic remains the most-locating one.
12392        let mut s = three_member_spec();
12393        let malformed = WitContract {
12394            de: "cart".into(),
12395            para: "catalog".into(),
12396            wit: "wasi:http/proxy".into(),
12397            endpoint: Some(String::new()),
12398            subject: None,
12399            slot: None,
12400        };
12401        s.contratos.push(malformed.clone());
12402        s.contratos.push(malformed);
12403        let err = s.validate().unwrap_err();
12404        assert!(
12405            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
12406            "endpoint-empty must fire before duplicate-edge (got {err:?})"
12407        );
12408    }
12409
12410    #[test]
12411    fn wit_target_label_pins_per_variant_format() {
12412        // Label format is the single source of truth every duplicate-
12413        // `:contratos` diagnostic + every future `feira app graph`
12414        // consumer routes through. Pin the shape per variant so a
12415        // future edit to `WitTarget::label` (e.g. a JSON emitter that
12416        // strips the leading `:`, or a rename from `endpoint` →
12417        // `path`) surfaces as a red-red test rather than as a silent
12418        // downstream diagnostic drift. Together with the exhaustive
12419        // `match` on `WitTarget` inside `label()`, adding a future
12420        // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
12421        // peer, per-edge WIT registry variants) is a compile error at
12422        // the label site — not a fall-through into the `Capability`
12423        // "no payload" default the prior raw-field-probe helper
12424        // silently landed on.
12425        assert_eq!(
12426            WitTarget::Http {
12427                endpoint: "/charge",
12428            }
12429            .label(),
12430            "\
12431:endpoint \"/charge\""
12432        );
12433        assert_eq!(
12434            WitTarget::PubSub {
12435                subject: "events.checkout.paid",
12436            }
12437            .label(),
12438            "\
12439:subject \"events.checkout.paid\""
12440        );
12441        assert_eq!(
12442            WitTarget::Store {
12443                slot: "checkout/$order",
12444            }
12445            .label(),
12446            "\
12447:slot \"checkout/$order\""
12448        );
12449        assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
12450        // Capability-arm label routes through the lifted
12451        // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
12452        // declaration per arm, next to the variant" discipline the
12453        // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
12454        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
12455        // consts already carry extends to the payload-less arm; the
12456        // byte-string equality pin below plus this label-routes-
12457        // through-the-const pin make a future rebrand on either the
12458        // const declaration or the `label()` template a build error
12459        // here rather than a downstream consumer surprise.
12460        assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
12461        assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
12462    }
12463
12464    #[test]
12465    fn wit_target_display_routes_through_label_helper() {
12466        // Fail-before-pass-after pin on the fourth (and only remaining)
12467        // typed-shape-discriminator axis to converge onto the
12468        // three-path-convergence discipline the sibling M3
12469        // [`PlacementStrategy`] (0a2f653) and M2
12470        // [`crate::supervisor::RestartStrategy`] /
12471        // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
12472        // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
12473        // through [`WitTarget::label`], so every consumer reaching for
12474        // `format!("{v}")` on a typed payload target lands on the same
12475        // stable author-facing byte-string [`WitTarget::label`] returns
12476        // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
12477        // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
12478        // `:contratos` gate seeds via [`WitTarget::label`] at
12479        // aplicacao.rs:5491 already threads through.
12480        //
12481        // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
12482        // through to the `Debug` derive's structural output
12483        // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
12484        // rather than the [`WitTarget::label`] helper's stable byte-
12485        // string (`:endpoint "/charge"` — the author-facing `:contratos`
12486        // keyword form). Every future consumer that reaches for
12487        // `format!("{target}")` — the canonical shape every user-facing
12488        // pretty-print site on the sibling typed-enum axes
12489        // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
12490        // [`crate::supervisor::RestartPolicy`]) already uses — would
12491        // silently land under a different byte-string than the
12492        // [`WitTarget::label`] callers that the duplicate-`:contratos`
12493        // diagnostic already threads through, with the mismatch
12494        // surfacing as a downstream diagnostic / graph / audit line
12495        // reading one spelling while the substrate's own gate emitted
12496        // another.
12497        //
12498        // Pin the routing here so a future
12499        // `impl std::fmt::Display for WitTarget<'_>` reimplementation
12500        // that hand-rolls the per-arm formatting instead of delegating
12501        // to [`WitTarget::label`] fails at caixa-core build time.
12502        for variant in [
12503            WitTarget::Http {
12504                endpoint: "/charge",
12505            },
12506            WitTarget::PubSub {
12507                subject: "events.checkout.paid",
12508            },
12509            WitTarget::Store {
12510                slot: "checkout/$order",
12511            },
12512            WitTarget::Capability,
12513        ] {
12514            assert_eq!(
12515                variant.to_string(),
12516                variant.label(),
12517                "WitTarget::{variant:?} Display must route through \
12518                 WitTarget::label (single source of truth: the lifted \
12519                 payload_pair 4-arm dispatch the label helper already \
12520                 threads through)"
12521            );
12522        }
12523    }
12524
12525    #[test]
12526    fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
12527        // Consumer-side pin on the three-path convergence:
12528        // [`std::fmt::Display`] agrees byte-for-byte with the
12529        // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
12530        // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
12531        // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
12532        // Pre-lift the two paths were structurally independent — the
12533        // substrate-side gate reached for `target_view.label()` while a
12534        // future downstream diagnostic / graph / audit line reaching
12535        // for `format!("{target}")` would silently land on the `Debug`
12536        // derive's structural output. Pin the two paths byte-for-byte
12537        // here so any future variant addition (M4 `Rest`/`Grpc` split
12538        // of [`WitTarget::Http`], `Queue`-shaped peer of
12539        // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
12540        // match error at [`WitTarget::payload_pair`] rather than a
12541        // silent per-consumer dispatch miss.
12542        for variant in [
12543            WitTarget::Http {
12544                endpoint: "/charge",
12545            },
12546            WitTarget::PubSub {
12547                subject: "events.checkout.paid",
12548            },
12549            WitTarget::Store {
12550                slot: "checkout/$order",
12551            },
12552            WitTarget::Capability,
12553        ] {
12554            assert_eq!(
12555                format!("{variant}"),
12556                variant.label(),
12557                "WitTarget::{variant:?} Display byte-string must match \
12558                 the AplicacaoError::ContratoDuplicate `target:` carrier \
12559                 the AplicacaoSpec::validate duplicate-`:contratos` gate \
12560                 seeds via WitTarget::label — three-path convergence: \
12561                 Display + label + payload_pair all resolve to the same \
12562                 per-arm byte-string"
12563            );
12564        }
12565    }
12566
12567    #[test]
12568    fn wit_target_payload_pair_pins_per_variant() {
12569        // Pin the per-arm `(field-name, payload)` pair single-sourced
12570        // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
12571        // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
12572        // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
12573        // and [`WitTarget::field_name`] (returns the first component)
12574        // route through. Until this lift landed [`WitTarget::label`]
12575        // dispatched on the same three arms with a per-arm
12576        // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
12577        // paired [`WitTarget::HTTP_FIELD_NAME`] /
12578        // [`WitTarget::PUBSUB_FIELD_NAME`] /
12579        // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
12580        // canonical "same shape, written N times" duplication
12581        // THEORY.md §I.3.5 promotes to a build-time concern. A future
12582        // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
12583        // [`WitTarget::Http`], `Queue`-shaped peer of
12584        // [`WitTarget::Store`]) is one match-arm edit at
12585        // [`WitTarget::payload_pair`], visible here as a compile-time
12586        // exhaustiveness error on both this pin and the label-format
12587        // pin above.
12588        assert_eq!(
12589            WitTarget::Http {
12590                endpoint: "/charge"
12591            }
12592            .payload_pair(),
12593            Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
12594        );
12595        assert_eq!(
12596            WitTarget::PubSub {
12597                subject: "events.x",
12598            }
12599            .payload_pair(),
12600            Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
12601        );
12602        assert_eq!(
12603            WitTarget::Store {
12604                slot: "checkout/$order",
12605            }
12606            .payload_pair(),
12607            Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
12608        );
12609        assert_eq!(WitTarget::Capability.payload_pair(), None);
12610    }
12611
12612    #[test]
12613    fn wit_target_field_name_pins_per_variant() {
12614        // Pin the per-arm author-facing `:contratos` payload field
12615        // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
12616        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
12617        // + returned by [`WitTarget::field_name`]. Every downstream
12618        // consumer (the [`WitContract::target`] gate's `expected:`
12619        // scalar, the [`WitTarget::label`] template's keyword prefix,
12620        // the `feira app graph` verb's `endpoint=…` prefix) routes
12621        // through the same three peer consts, so a rename on the
12622        // author-surface `(defcaixa … :contratos ((:de … :para …
12623        // :wit … :endpoint …)))` field lands in exactly one place.
12624        assert_eq!(
12625            WitTarget::Http {
12626                endpoint: "/charge"
12627            }
12628            .field_name(),
12629            Some(WitTarget::HTTP_FIELD_NAME),
12630        );
12631        assert_eq!(
12632            WitTarget::PubSub {
12633                subject: "events.x",
12634            }
12635            .field_name(),
12636            Some(WitTarget::PUBSUB_FIELD_NAME),
12637        );
12638        assert_eq!(
12639            WitTarget::Store {
12640                slot: "checkout/$order",
12641            }
12642            .field_name(),
12643            Some(WitTarget::STORE_FIELD_NAME),
12644        );
12645        // Capability arm carries no payload field — the diagnostic
12646        // never reports `expected: "capability"` because the gate's
12647        // Capability arm accepts no payload at all (it fires the
12648        // "expected: none" WrongTarget error instead), so the field-
12649        // name method returns None here rather than a placeholder.
12650        assert_eq!(WitTarget::Capability.field_name(), None);
12651
12652        // Peer const scalar values pinned so a rename on either side
12653        // (author-surface field name in the `(defcaixa …)` DSL, or
12654        // the diagnostic's `expected:` scalar) can't drift without
12655        // failing here first.
12656        assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
12657        assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
12658        assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
12659    }
12660
12661    #[test]
12662    fn wit_target_payload_pins_per_variant() {
12663        // Pin the per-arm payload scalar single-sourced onto the
12664        // [`WitTarget::payload_pair`] 4-arm dispatch and surfaced through
12665        // [`WitTarget::payload`] — the peer per-half projection to
12666        // [`WitTarget::field_name`] on the paired sub-selector axis. The
12667        // three payload-carrying arms round-trip their author-declared
12668        // scalar verbatim (`Http` → `Some("/charge")`, `PubSub` →
12669        // `Some("events.x")`, `Store` → `Some("checkout/$order")`) and
12670        // the payload-less [`WitTarget::Capability`] arm returns `None`.
12671        // Same shape as the sibling `wit_target_field_name_pins_per_variant`
12672        // (c6ec2af) pin on the Component-0 projection axis, extended
12673        // onto the Component-1 projection axis so both per-half readers
12674        // on the paired dispatch carry their own byte-shape pin.
12675        assert_eq!(
12676            WitTarget::Http {
12677                endpoint: "/charge",
12678            }
12679            .payload(),
12680            Some("/charge"),
12681        );
12682        assert_eq!(
12683            WitTarget::PubSub {
12684                subject: "events.x",
12685            }
12686            .payload(),
12687            Some("events.x"),
12688        );
12689        assert_eq!(
12690            WitTarget::Store {
12691                slot: "checkout/$order",
12692            }
12693            .payload(),
12694            Some("checkout/$order"),
12695        );
12696        assert_eq!(WitTarget::Capability.payload(), None);
12697    }
12698
12699    #[test]
12700    fn wit_target_payload_matches_payload_pair_second_component_per_variant() {
12701        // Per-variant equivalence pin: for every arm of [`WitTarget`],
12702        // `.payload()` equals `.payload_pair().map(|(_, p)| p)`
12703        // byte-for-byte. Guards the drift surface where a future refactor
12704        // that split one accessor off the shared match onto its own
12705        // dispatch — a well-meaning "inline the pair back into per-half
12706        // fields for one crate-internal caller who only wanted one half"
12707        // or a scratch `impl` shadowing the derived projection — would
12708        // silently desynchronize [`WitTarget::payload`] from the
12709        // authoritative [`WitTarget::payload_pair`] dispatch, and every
12710        // downstream consumer that thinks "the payload half of the pair"
12711        // would drift from the diagnostic / graph consumers reading the
12712        // same match through [`WitTarget::label`] / [`WitTarget::graph_label`].
12713        // Sibling to the peer [`caixa_flux::GitRefSpec`] `ref_value`
12714        // per-half projection pin (`gitrefspec_ref_pair_projects_
12715        // ref_field_name_and_ref_value_per_variant`, 655a1c0) on the
12716        // FluxCD source-controller `spec.ref.<field>` axis — same "one
12717        // paired dispatch, both per-half projections agree byte-for-
12718        // byte" discipline extended onto the M3 `:contratos` payload-
12719        // arm surface.
12720        for variant in [
12721            WitTarget::Http {
12722                endpoint: "/charge",
12723            },
12724            WitTarget::PubSub {
12725                subject: "events.checkout.paid",
12726            },
12727            WitTarget::Store {
12728                slot: "checkout/$order",
12729            },
12730            WitTarget::Capability,
12731        ] {
12732            let via_projection = variant.payload();
12733            let via_pair = variant.payload_pair().map(|(_, p)| p);
12734            assert_eq!(
12735                via_projection, via_pair,
12736                "WitTarget::{variant:?} payload() must equal \
12737                 payload_pair().map(|(_, p)| p) byte-for-byte — a \
12738                 regression that splits the two per-half projections off \
12739                 their shared match would silently desynchronize the \
12740                 payload accessor from the paired dispatch every \
12741                 diagnostic / graph consumer reads through",
12742            );
12743        }
12744    }
12745
12746    #[test]
12747    fn wit_target_http_endpoint_pins_per_variant() {
12748        // Pin the per-arm HTTP-endpoint scalar single-sourced onto the
12749        // [`WitTarget::http_endpoint`] 2-arm dispatch — the
12750        // substrate-primitive per-arm post-projection accessor every
12751        // L7-HTTP-facing consumer routes through, sibling to the peer
12752        // WitContract pre-projection [`WitContract::endpoint`] (7020470)
12753        // scalar accessor on the raw-field axis. The [`WitTarget::Http`]
12754        // arm round-trips its author-declared endpoint verbatim as
12755        // `Some("/charge")`; the three sibling arms
12756        // ([`WitTarget::PubSub`] / [`WitTarget::Store`] /
12757        // [`WitTarget::Capability`]) each return `None` because they
12758        // carry no HTTP endpoint by definition. Same fail-before-pass-
12759        // after per-variant discipline as the sibling
12760        // `wit_target_payload_pins_per_variant` (5d6dc92) /
12761        // `wit_target_field_name_pins_per_variant` (c6ec2af) /
12762        // `wit_target_payload_pair_pins_per_variant` (6788ed6) pins on
12763        // the peer pan-arm / per-half projection axes — extended onto
12764        // the per-arm HTTP-shape post-projection axis so a future
12765        // [`WitTarget`] variant addition (a `Rest`/`Grpc` split of
12766        // [`WitTarget::Http`], a `Queue`-shaped peer of
12767        // [`WitTarget::Store`]) trips a compile-time exhaustiveness
12768        // error on the sibling [`WitTarget::http_endpoint`] match arms
12769        // whose payload the L7-HTTP-shape accept-set is meant to bound.
12770        assert_eq!(
12771            WitTarget::Http {
12772                endpoint: "/charge",
12773            }
12774            .http_endpoint(),
12775            Some("/charge"),
12776        );
12777        assert_eq!(
12778            WitTarget::PubSub {
12779                subject: "events.checkout.paid",
12780            }
12781            .http_endpoint(),
12782            None,
12783        );
12784        assert_eq!(
12785            WitTarget::Store {
12786                slot: "checkout/$order",
12787            }
12788            .http_endpoint(),
12789            None,
12790        );
12791        assert_eq!(WitTarget::Capability.http_endpoint(), None);
12792    }
12793
12794    #[test]
12795    fn wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere() {
12796        // Per-variant coherence pin: for every arm of [`WitTarget`],
12797        // `.http_endpoint()` equals `.payload()` on the [`WitTarget::Http`]
12798        // arm (both project the same author-declared request-path
12799        // scalar), and returns `None` on every sibling arm regardless of
12800        // whether [`WitTarget::payload`] itself returns `Some` (PubSub /
12801        // Store carry their own payload the pan-arm accessor surfaces,
12802        // but that payload is not an HTTP endpoint — the per-arm
12803        // accessor must not leak it through the HTTP-shape channel).
12804        // Guards the drift surface where a future refactor that
12805        // conflated the per-arm HTTP projection with the pan-arm
12806        // [`WitTarget::payload`] projection — a well-meaning "one
12807        // accessor for the L7 branch, one for the graph" collapse that
12808        // routes both through the same 4-arm dispatch — would silently
12809        // widen the L7-HTTP-shape accept-set onto pub-sub / store
12810        // payloads at the caixa-mesh L7 emit branch, admitting a
12811        // `nats:pub-sub` edge's `:subject` as a Cilium L7 HTTP `path:`
12812        // rule with the operator-side apply-time symptom (Cilium's
12813        // eBPF data-plane rejects every ingress edge whose L7 filter
12814        // doesn't match the wire-format HTTP request line) far from
12815        // the source refactor. Sibling to the peer
12816        // `wit_target_payload_matches_payload_pair_second_component_
12817        // per_variant` (5d6dc92) coherence pin on the pan-arm axis —
12818        // extended onto the per-arm HTTP specialization axis so both
12819        // the pan-arm and the per-arm projections carry their own
12820        // byte-shape coherence witness against the substrate's typed
12821        // arm-family accept-set.
12822        for variant in [
12823            WitTarget::Http {
12824                endpoint: "/charge",
12825            },
12826            WitTarget::PubSub {
12827                subject: "events.checkout.paid",
12828            },
12829            WitTarget::Store {
12830                slot: "checkout/$order",
12831            },
12832            WitTarget::Capability,
12833        ] {
12834            let per_arm = variant.http_endpoint();
12835            let pan_arm = variant.payload();
12836            if variant.is_http() {
12837                assert_eq!(
12838                    per_arm, pan_arm,
12839                    "WitTarget::{variant:?} http_endpoint() must equal \
12840                     payload() on the Http arm — a per-arm-vs-pan-arm \
12841                     split would silently drift the L7 emit branch's \
12842                     path-scalar source from the graph verb's payload \
12843                     scalar source",
12844                );
12845            } else {
12846                assert_eq!(
12847                    per_arm, None,
12848                    "WitTarget::{variant:?} http_endpoint() must return \
12849                     None on non-Http arms — a leak that surfaced a \
12850                     pub-sub :subject or a key/value :slot through the \
12851                     HTTP-endpoint accessor would silently widen the \
12852                     Cilium L7 HTTP `path:` rule accept-set onto \
12853                     protocol shapes Cilium's eBPF data-plane can't \
12854                     introspect",
12855                );
12856            }
12857        }
12858    }
12859
12860    #[test]
12861    fn wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant() {
12862        // Per-variant coherence pin: for every arm of [`WitTarget`],
12863        // `.http_endpoint().is_some()` iff `.is_http()`. Guards the
12864        // drift surface where a future extension of the
12865        // [`WitTarget::http_endpoint`] accessor's accept-set (e.g. a
12866        // `Rest`/`Grpc` split of [`WitTarget::Http`] that widened the
12867        // accessor to cover both peers) landed without a paired
12868        // extension of the [`gen_platform::IsVariant`]-derived
12869        // `is_http()` predicate's accept-set, or vice versa — a
12870        // regression that split the "which arms count as HTTP-shaped
12871        // for L7-path emission?" answer between two dispatch surfaces
12872        // the substrate ships. Sibling to the peer
12873        // `wit_target_field_name_pins_per_variant` (c6ec2af) discipline
12874        // on the paired dispatch axis — extended onto the per-arm
12875        // predicate-vs-accessor coherence axis so the gen-platform
12876        // IsVariant predicate and the substrate-lifted per-arm
12877        // accessor carry one shared answer to "is this the HTTP arm?".
12878        for variant in [
12879            WitTarget::Http {
12880                endpoint: "/charge",
12881            },
12882            WitTarget::PubSub {
12883                subject: "events.checkout.paid",
12884            },
12885            WitTarget::Store {
12886                slot: "checkout/$order",
12887            },
12888            WitTarget::Capability,
12889        ] {
12890            assert_eq!(
12891                variant.http_endpoint().is_some(),
12892                variant.is_http(),
12893                "WitTarget::{variant:?} http_endpoint().is_some() must \
12894                 equal is_http() — a drift would split the L7 emit \
12895                 branch's arm-set gate from the substrate-derived \
12896                 shape-discrimination predicate on the same axis",
12897            );
12898        }
12899    }
12900
12901    #[test]
12902    fn wit_target_pubsub_subject_pins_per_variant() {
12903        // Fail-before-pass-after pin: the substrate-canonical per-arm
12904        // pub-sub-subject scalar accessor [`WitTarget::pubsub_subject`]
12905        // is the single dispatch every future pub-sub-facing consumer
12906        // routes through, sibling to the peer [`WitContract::subject`]
12907        // (63e18a0) pre-projection scalar accessor on the raw-field
12908        // axis and to the peer [`WitTarget::http_endpoint`] (5d6dc92)
12909        // post-projection per-arm accessor on the sibling HTTP-shape
12910        // axis. The [`WitTarget::PubSub`] arm round-trips its
12911        // author-declared subject verbatim as
12912        // `Some("events.checkout.paid")`; the three sibling arms each
12913        // return `None` because they carry no NATS-shaped subject by
12914        // definition. Same fail-before-pass-after per-variant discipline
12915        // as the sibling `wit_target_http_endpoint_pins_per_variant`
12916        // pin on the peer per-arm axis — extended onto the per-arm
12917        // pub-sub-shape post-projection axis so a future [`WitTarget`]
12918        // variant addition (a `Rest`/`Grpc` split of [`WitTarget::Http`],
12919        // a `Queue`-shaped peer of [`WitTarget::Store`]) trips a
12920        // compile-time exhaustiveness error on the sibling
12921        // [`WitTarget::pubsub_subject`] match arms whose payload the
12922        // pub-sub-shape accept-set is meant to bound.
12923        assert_eq!(
12924            WitTarget::PubSub {
12925                subject: "events.checkout.paid",
12926            }
12927            .pubsub_subject(),
12928            Some("events.checkout.paid"),
12929        );
12930        assert_eq!(
12931            WitTarget::Http {
12932                endpoint: "/charge",
12933            }
12934            .pubsub_subject(),
12935            None,
12936        );
12937        assert_eq!(
12938            WitTarget::Store {
12939                slot: "checkout/$order",
12940            }
12941            .pubsub_subject(),
12942            None,
12943        );
12944        assert_eq!(WitTarget::Capability.pubsub_subject(), None);
12945    }
12946
12947    #[test]
12948    fn wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere() {
12949        // Per-variant coherence pin: for every arm of [`WitTarget`],
12950        // `.pubsub_subject()` equals `.payload()` on the
12951        // [`WitTarget::PubSub`] arm (both project the same
12952        // author-declared subject scalar), and returns `None` on every
12953        // sibling arm regardless of whether [`WitTarget::payload`]
12954        // itself returns `Some` (Http / Store carry their own payload
12955        // the pan-arm accessor surfaces, but that payload is not a
12956        // pub-sub subject — the per-arm accessor must not leak it
12957        // through the pub-sub-shape channel). Sibling to the peer
12958        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
12959        // coherence pin on the per-arm HTTP-shape axis — extended onto
12960        // the per-arm pub-sub specialization axis so both per-arm
12961        // projections carry their own byte-shape coherence witness
12962        // against the substrate's typed arm-family accept-set.
12963        for variant in [
12964            WitTarget::Http {
12965                endpoint: "/charge",
12966            },
12967            WitTarget::PubSub {
12968                subject: "events.checkout.paid",
12969            },
12970            WitTarget::Store {
12971                slot: "checkout/$order",
12972            },
12973            WitTarget::Capability,
12974        ] {
12975            let per_arm = variant.pubsub_subject();
12976            let pan_arm = variant.payload();
12977            if variant.is_pubsub() {
12978                assert_eq!(
12979                    per_arm, pan_arm,
12980                    "WitTarget::{variant:?} pubsub_subject() must equal \
12981                     payload() on the PubSub arm — a per-arm-vs-pan-arm \
12982                     split would silently drift the pub-sub-shape emit \
12983                     branch's subject-scalar source from the graph verb's \
12984                     payload scalar source",
12985                );
12986            } else {
12987                assert_eq!(
12988                    per_arm, None,
12989                    "WitTarget::{variant:?} pubsub_subject() must return \
12990                     None on non-PubSub arms — a leak that surfaced an \
12991                     HTTP :endpoint or a key/value :slot through the \
12992                     pub-sub-subject accessor would silently widen the \
12993                     downstream NATS-shape accept-set onto protocol \
12994                     shapes NATS servers can't route",
12995                );
12996            }
12997        }
12998    }
12999
13000    #[test]
13001    fn wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant() {
13002        // Per-variant coherence pin: for every arm of [`WitTarget`],
13003        // `.pubsub_subject().is_some()` iff `.is_pubsub()`. Guards the
13004        // drift surface where a future extension of the
13005        // [`WitTarget::pubsub_subject`] accessor's accept-set landed
13006        // without a paired extension of the [`gen_platform::IsVariant`]-
13007        // derived `is_pubsub()` predicate's accept-set, or vice versa
13008        // — a regression that split the "which arms count as pub-sub-
13009        // shaped for subject emission?" answer between two dispatch
13010        // surfaces the substrate ships. Sibling to the peer
13011        // `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
13012        // pin on the per-arm HTTP-shape axis — extended onto the
13013        // per-arm pub-sub predicate-vs-accessor coherence axis so the
13014        // gen-platform IsVariant predicate and the substrate-lifted
13015        // per-arm accessor carry one shared answer to "is this the
13016        // PubSub arm?".
13017        for variant in [
13018            WitTarget::Http {
13019                endpoint: "/charge",
13020            },
13021            WitTarget::PubSub {
13022                subject: "events.checkout.paid",
13023            },
13024            WitTarget::Store {
13025                slot: "checkout/$order",
13026            },
13027            WitTarget::Capability,
13028        ] {
13029            assert_eq!(
13030                variant.pubsub_subject().is_some(),
13031                variant.is_pubsub(),
13032                "WitTarget::{variant:?} pubsub_subject().is_some() must \
13033                 equal is_pubsub() — a drift would split the pub-sub \
13034                 emit branch's arm-set gate from the substrate-derived \
13035                 shape-discrimination predicate on the same axis",
13036            );
13037        }
13038    }
13039
13040    #[test]
13041    fn wit_target_store_slot_pins_per_variant() {
13042        // Fail-before-pass-after pin: the substrate-canonical per-arm
13043        // key/value-store-slot scalar accessor [`WitTarget::store_slot`]
13044        // is the single dispatch every future store-facing consumer
13045        // routes through, sibling to the peer [`WitContract::slot`]
13046        // pre-projection scalar accessor on the raw-field axis and to
13047        // the peer [`WitTarget::http_endpoint`] (5d6dc92) +
13048        // [`WitTarget::pubsub_subject`] post-projection per-arm
13049        // accessors on the sibling per-payload-arm axes. The
13050        // [`WitTarget::Store`] arm round-trips its author-declared
13051        // slot verbatim as `Some("checkout/$order")`; the three
13052        // sibling arms each return `None` because they carry no
13053        // WASI-key/value slot by definition. Same fail-before-pass-
13054        // after per-variant discipline as the sibling
13055        // `wit_target_http_endpoint_pins_per_variant` +
13056        // `wit_target_pubsub_subject_pins_per_variant` pins on the
13057        // peer per-arm axes — extended onto the per-arm store-shape
13058        // post-projection axis so a future [`WitTarget`] variant
13059        // addition trips a compile-time exhaustiveness error on the
13060        // sibling [`WitTarget::store_slot`] match arms whose payload
13061        // the store-shape accept-set is meant to bound.
13062        assert_eq!(
13063            WitTarget::Store {
13064                slot: "checkout/$order",
13065            }
13066            .store_slot(),
13067            Some("checkout/$order"),
13068        );
13069        assert_eq!(
13070            WitTarget::Http {
13071                endpoint: "/charge",
13072            }
13073            .store_slot(),
13074            None,
13075        );
13076        assert_eq!(
13077            WitTarget::PubSub {
13078                subject: "events.checkout.paid",
13079            }
13080            .store_slot(),
13081            None,
13082        );
13083        assert_eq!(WitTarget::Capability.store_slot(), None);
13084    }
13085
13086    #[test]
13087    fn wit_target_store_slot_matches_payload_on_store_arm_and_is_none_elsewhere() {
13088        // Per-variant coherence pin: for every arm of [`WitTarget`],
13089        // `.store_slot()` equals `.payload()` on the
13090        // [`WitTarget::Store`] arm (both project the same
13091        // author-declared slot scalar), and returns `None` on every
13092        // sibling arm regardless of whether [`WitTarget::payload`]
13093        // itself returns `Some`. Sibling to the peer
13094        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
13095        // and `wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere`
13096        // pins on the per-arm HTTP and PubSub axes — closes the
13097        // per-arm-vs-pan-arm byte-shape coherence trio across all
13098        // three payload arms.
13099        for variant in [
13100            WitTarget::Http {
13101                endpoint: "/charge",
13102            },
13103            WitTarget::PubSub {
13104                subject: "events.checkout.paid",
13105            },
13106            WitTarget::Store {
13107                slot: "checkout/$order",
13108            },
13109            WitTarget::Capability,
13110        ] {
13111            let per_arm = variant.store_slot();
13112            let pan_arm = variant.payload();
13113            if variant.is_store() {
13114                assert_eq!(
13115                    per_arm, pan_arm,
13116                    "WitTarget::{variant:?} store_slot() must equal \
13117                     payload() on the Store arm — a per-arm-vs-pan-arm \
13118                     split would silently drift the store-shape emit \
13119                     branch's slot-scalar source from the graph verb's \
13120                     payload scalar source",
13121                );
13122            } else {
13123                assert_eq!(
13124                    per_arm, None,
13125                    "WitTarget::{variant:?} store_slot() must return \
13126                     None on non-Store arms — a leak that surfaced an \
13127                     HTTP :endpoint or a NATS :subject through the \
13128                     key/value-slot accessor would silently widen the \
13129                     downstream WASI-key/value slot accept-set onto \
13130                     protocol shapes the kv backends can't route",
13131                );
13132            }
13133        }
13134    }
13135
13136    #[test]
13137    fn wit_target_store_slot_agrees_with_is_store_predicate_per_variant() {
13138        // Per-variant coherence pin: for every arm of [`WitTarget`],
13139        // `.store_slot().is_some()` iff `.is_store()`. Guards the
13140        // drift surface where a future extension of the
13141        // [`WitTarget::store_slot`] accessor's accept-set landed
13142        // without a paired extension of the [`gen_platform::IsVariant`]-
13143        // derived `is_store()` predicate's accept-set. Sibling to the
13144        // peer `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
13145        // and `wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant`
13146        // pins — closes the per-arm predicate-vs-accessor coherence
13147        // trio across all three payload arms so the gen-platform
13148        // IsVariant predicate and the substrate-lifted per-arm
13149        // accessor carry one shared answer to "is this the Store arm?".
13150        for variant in [
13151            WitTarget::Http {
13152                endpoint: "/charge",
13153            },
13154            WitTarget::PubSub {
13155                subject: "events.checkout.paid",
13156            },
13157            WitTarget::Store {
13158                slot: "checkout/$order",
13159            },
13160            WitTarget::Capability,
13161        ] {
13162            assert_eq!(
13163                variant.store_slot().is_some(),
13164                variant.is_store(),
13165                "WitTarget::{variant:?} store_slot().is_some() must \
13166                 equal is_store() — a drift would split the store-shape \
13167                 emit branch's arm-set gate from the substrate-derived \
13168                 shape-discrimination predicate on the same axis",
13169            );
13170        }
13171    }
13172
13173    #[test]
13174    fn wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set() {
13175        // Fail-before-pass-after cross-axis pin on the trio
13176        // (`http_endpoint`, `pubsub_subject`, `store_slot`): on every
13177        // payload-carrying arm of [`WitTarget`], exactly one per-arm
13178        // accessor returns `Some(payload)` and the two peers return
13179        // `None`; and on the payload-less [`WitTarget::Capability`]
13180        // arm, all three return `None`. Guards the drift surface where
13181        // a future extension of one per-arm accessor's accept-set (e.g.
13182        // a hypothetical `Rest`/`Grpc` split of [`WitTarget::Http`]
13183        // that widened `http_endpoint` to cover both peers without
13184        // narrowing the peer `pubsub_subject` / `store_slot` accept-
13185        // sets to keep the partition mutually exclusive) landed without
13186        // threading through the peer per-arm accessors — the resulting
13187        // silent overlap would land the same edge's payload on two
13188        // downstream per-shape emit branches at once, or leak a
13189        // pub-sub subject through the store-slot channel, at renderer
13190        // emit time far from the substrate primitive's arm-widening
13191        // commit. Peer of the sibling `wit_target_field_names_are_pairwise_distinct`
13192        // 3-way pin on the payload-field-name axis — extended onto the
13193        // per-arm-accessor payload-projection axis so the substrate-
13194        // owned partition invariant is load-bearing at every per-arm
13195        // consumer's read site.
13196        let payload_variants = [
13197            (
13198                WitTarget::Http {
13199                    endpoint: "/charge",
13200                },
13201                "http",
13202            ),
13203            (
13204                WitTarget::PubSub {
13205                    subject: "events.checkout.paid",
13206                },
13207                "pubsub",
13208            ),
13209            (
13210                WitTarget::Store {
13211                    slot: "checkout/$order",
13212                },
13213                "store",
13214            ),
13215        ];
13216        for (variant, own_arm_label) in payload_variants {
13217            let own_arm_hit = match own_arm_label {
13218                "http" => variant.is_http(),
13219                "pubsub" => variant.is_pubsub(),
13220                "store" => variant.is_store(),
13221                other => panic!("unknown own-arm label {other:?}"),
13222            };
13223            let per_arm_results = [
13224                ("http_endpoint", variant.http_endpoint()),
13225                ("pubsub_subject", variant.pubsub_subject()),
13226                ("store_slot", variant.store_slot()),
13227            ];
13228            let some_count = per_arm_results.iter().filter(|(_, v)| v.is_some()).count();
13229            assert_eq!(
13230                some_count, 1,
13231                "WitTarget::{variant:?} must land exactly one per-arm \
13232                 post-projection accessor's Some result — the trio \
13233                 (http_endpoint, pubsub_subject, store_slot) must \
13234                 partition the payload arm-set; got {per_arm_results:?}",
13235            );
13236            assert!(
13237                own_arm_hit,
13238                "WitTarget::{variant:?} own-arm gen-platform predicate \
13239                 must return true on its own arm — a partition failure \
13240                 upstream of this pin",
13241            );
13242            assert!(
13243                variant.payload().is_some(),
13244                "WitTarget::{variant:?} pan-arm payload() must return \
13245                 Some on every payload-carrying arm the trio partitions",
13246            );
13247        }
13248        // The payload-less Capability arm must return None on every
13249        // per-arm accessor — the partition's terminal-fallback shape.
13250        let cap = WitTarget::Capability;
13251        assert_eq!(cap.http_endpoint(), None);
13252        assert_eq!(cap.pubsub_subject(), None);
13253        assert_eq!(cap.store_slot(), None);
13254        assert_eq!(
13255            cap.payload(),
13256            None,
13257            "WitTarget::Capability pan-arm payload() must return None — \
13258             the trio's payload-less-arm coherence witness",
13259        );
13260    }
13261
13262    #[test]
13263    fn wit_target_field_names_are_pairwise_distinct() {
13264        // Distinctness pin: if any two of the three payload-field-name
13265        // scalars ever collapse (e.g. an accidental `endpoint` copy-
13266        // paste over the `subject` const), the [`WitContract::target`]
13267        // gate's diagnostic would point authors at the wrong field —
13268        // an "expected `:endpoint`" error on a pub-sub edge would
13269        // silently misroute the fix. Same cross-axis-distinctness
13270        // discipline as the peer M3 `:placement :estrategia` variant-
13271        // discriminator scalar-value pins (cc8f749) applied to the
13272        // payload-field-name axis.
13273        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
13274        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
13275        assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
13276    }
13277
13278    #[test]
13279    fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
13280        // Fail-before-pass-after pin: the graph-verb payload column's
13281        // per-arm `{field}={payload}` byte-string is derived through the
13282        // single [`WitTarget::payload_pair`] 4-arm dispatch on the three
13283        // payload-carrying arms, not through a hand-rolled per-arm match
13284        // that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
13285        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13286        // inline. A future variant addition — the M4-and-later per-edge
13287        // WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
13288        // peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
13289        // peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
13290        // and both [`WitTarget::label`] (duplicate-`:contratos`
13291        // diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
13292        // payload column) pick up the new arm from the same dispatch.
13293        // Prior to this lift the graph verb open-coded the 4-arm match
13294        // in caixa-feira, so a variant addition would have to be threaded
13295        // through both projections in lockstep or the graph verb would
13296        // silently drop the new arm to `(capability-only)`.
13297        for variant in [
13298            WitTarget::Http {
13299                endpoint: "/charge",
13300            },
13301            WitTarget::PubSub {
13302                subject: "events.checkout.paid",
13303            },
13304            WitTarget::Store {
13305                slot: "checkout/$order",
13306            },
13307        ] {
13308            let (field, payload) = variant
13309                .payload_pair()
13310                .expect("payload arm must expose (field, payload)");
13311            assert_eq!(
13312                variant.graph_label(),
13313                format!("{field}={payload}"),
13314                "WitTarget::{variant:?} graph_label must route the \
13315                 `{{field}}={{payload}}` template through payload_pair — \
13316                 a regression to a hand-rolled per-arm match at the graph \
13317                 verb would silently disagree with a future variant \
13318                 addition landed only at payload_pair"
13319            );
13320        }
13321    }
13322
13323    #[test]
13324    fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
13325        // Fail-before-pass-after pin on the payload-less arm: the graph
13326        // verb's `(capability-only)` byte-string routes through the
13327        // lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
13328        // [`WitTarget::Capability`] arm, not through an inline
13329        // `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
13330        // per-`:contratos` payload column. Peer of the sibling
13331        // [`wit_target_label_pins_per_variant_format`] Capability-arm
13332        // assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
13333        // extended here onto the third payload-less-arm consumer axis
13334        // (graph verb, sibling to the duplicate-`:contratos` diagnostic
13335        // axis and the wrong-target diagnostic axis).
13336        assert_eq!(
13337            WitTarget::Capability.graph_label(),
13338            WitTarget::CAPABILITY_GRAPH_LABEL,
13339        );
13340        assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
13341    }
13342
13343    #[test]
13344    fn wit_target_capability_graph_label_distinct_from_capability_label() {
13345        // Cross-consumer-axis distinctness pin: the graph-verb
13346        // payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
13347        // (`(capability-only)`) and the duplicate-`:contratos` diagnostic
13348        // label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
13349        // payload)`) surface the payload-less arm on two distinct
13350        // consumer axes; a collapse (an accidental rebrand that lands
13351        // one spelling on both consts, a copy-paste that unifies them
13352        // "for consistency") would silently merge the two byte-strings
13353        // and lose the vocabulary distinction the graph verb's
13354        // compact-column form and the diagnostic's descriptive-clause
13355        // form each carry on purpose. Peer of the sibling 4-way
13356        // [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
13357        // pin on the `ContratoWrongTarget::expected` scalar-value axis —
13358        // extended here onto the cross-consumer-axis distinctness of the
13359        // two payload-less-arm consts.
13360        assert_ne!(
13361            WitTarget::CAPABILITY_GRAPH_LABEL,
13362            WitTarget::CAPABILITY_LABEL,
13363            "WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
13364             and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
13365             diagnostic) must remain distinct — a collapse would silently \
13366             merge two consumer axes onto one spelling"
13367        );
13368    }
13369
13370    #[test]
13371    fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
13372        // 4-way distinctness pin extending the sibling
13373        // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
13374        // (which covers only the HTTP / PubSub / Store payload arms)
13375        // onto the fourth scalar the shared
13376        // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
13377        // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
13378        // (`"none"`), the payload-less Capability-arm rejection scalar.
13379        //
13380        // All four [`WitTarget::HTTP_FIELD_NAME`] /
13381        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13382        // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
13383        // dispatch surface [`WitContract::target`] writes onto the
13384        // `ContratoWrongTarget::expected` field — the same `&'static
13385        // str` axis authors read as "this WIT world's shape admits
13386        // (only|not) `:<field>`". Pairwise-distinctness is the invariant
13387        // downstream consumers rely on: an `expected: "endpoint"`
13388        // diagnostic on a Capability-shaped edge tells the author to
13389        // add a `:endpoint "…"` slot to a WIT world that admits none,
13390        // silently misrouting the fix. Until this pin landed the three
13391        // payload-arm consts were distinctness-guarded by the sibling
13392        // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
13393        // scalar (d4f54f2) sat unguarded — a rebrand collision (the
13394        // author-facing vocabulary shift from `"none"` to `"endpoint"`
13395        // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
13396        // into per-shape peers) would have silently landed one
13397        // Capability-arm rejection on a payload-arm's `expected:` byte-
13398        // string and desynchronized the diagnostic from the author's
13399        // typed shape.
13400        //
13401        // Same 4-way pairwise-distinctness pin discipline as the peer
13402        // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
13403        // (cc8f749) applies on the sibling M3 closed-set typed-enum
13404        // scalar-value dispatch axis; extends the pin trajectory the
13405        // sibling `wit_target_field_names_are_pairwise_distinct`
13406        // 3-way pin opened to cover the last unguarded corner on the
13407        // `ContratoWrongTarget::expected` scalar-value axis.
13408        //
13409        // Fail-before-pass-after locally verified by mutating
13410        // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
13411        // — this pin fires as expected; restoring passes.
13412        let all = [
13413            WitTarget::HTTP_FIELD_NAME,
13414            WitTarget::PUBSUB_FIELD_NAME,
13415            WitTarget::STORE_FIELD_NAME,
13416            WitTarget::CAPABILITY_EXPECTED,
13417        ];
13418        for (i, a) in all.iter().enumerate() {
13419            for (j, b) in all.iter().enumerate() {
13420                if i != j {
13421                    assert_ne!(
13422                        a, b,
13423                        "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
13424                         STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
13425                         pairwise distinct — got duplicate {a:?} at indices \
13426                         {i} and {j}; all four scalars thread through the \
13427                         shared `AplicacaoError::ContratoWrongTarget::expected` \
13428                         &'static str axis, so a collapse silently misdirects \
13429                         the diagnostic on which typed shape the WIT world admits",
13430                    );
13431                }
13432            }
13433        }
13434    }
13435
13436    #[test]
13437    fn wit_target_is_variant_predicates_partition_the_arm_set() {
13438        // Fail-before-pass-after pin on the
13439        // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
13440        // each of the four variants exactly one of the generated
13441        // `is_http` / `is_pubsub` / `is_store` / `is_capability`
13442        // predicates returns `true` and the other three return
13443        // `false`. Prior to this derive the only production
13444        // arm-discriminator on [`WitTarget`] — the sync-cycle
13445        // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
13446        // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
13447        // the variant that expressed no compile-time link back to
13448        // the closed-set typed dispatch a future fifth
13449        // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
13450        // split of [`WitTarget::PubSub`] into shape-specific peers,
13451        // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
13452        // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
13453        // to thread through in lockstep or the DFS exclusion would
13454        // silently disagree with the peer diagnostic templates on
13455        // which arms carry sync-versus-async semantics. Peer of the
13456        // sibling [`crate::CaixaKind`] (f5bba80),
13457        // [`PlacementStrategy`] (766ec63),
13458        // [`crate::supervisor::RestartStrategy`],
13459        // [`crate::supervisor::RestartPolicy`], and
13460        // [`crate::upgrade::UpgradeInstruction`] (915a934)
13461        // `IsVariant` derives on the sibling closed-set typed-enum
13462        // discriminator axes — extends the same one-typed-dispatch-
13463        // per-variant discipline onto the last unlifted closed-set
13464        // typed-enum discriminator on the caixa surface (the M3
13465        // mesh-slot per-`:contratos` target-arm axis), closing the
13466        // arm-discriminator convergence trajectory across every
13467        // closed-set typed enum in caixa-core.
13468        let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
13469            (
13470                WitTarget::Http { endpoint: "/x" },
13471                [true, false, false, false],
13472            ),
13473            (
13474                WitTarget::PubSub {
13475                    subject: "events.x",
13476                },
13477                [false, true, false, false],
13478            ),
13479            (
13480                WitTarget::Store { slot: "kv/x" },
13481                [false, false, true, false],
13482            ),
13483            (WitTarget::Capability, [false, false, false, true]),
13484        ];
13485        for (variant, expected) in rows {
13486            let observed = [
13487                variant.is_http(),
13488                variant.is_pubsub(),
13489                variant.is_store(),
13490                variant.is_capability(),
13491            ];
13492            assert_eq!(
13493                observed, expected,
13494                "WitTarget::{variant:?} is_* predicates must partition \
13495                 the arm set (http, pubsub, store, capability); got {observed:?}"
13496            );
13497        }
13498    }
13499
13500    #[test]
13501    fn wit_target_is_variant_predicates_are_const_fn() {
13502        // The [`gen_platform::IsVariant`] derive emits `const fn`
13503        // predicates on the peer [`crate::CaixaKind`] +
13504        // [`crate::upgrade::UpgradeInstruction`] +
13505        // [`crate::supervisor::RestartStrategy`] +
13506        // [`crate::supervisor::RestartPolicy`] +
13507        // [`PlacementStrategy`] closed-set typed enums — pin the
13508        // same posture on [`WitTarget`] so a future accidental
13509        // downgrade to non-`const` (an added runtime helper reachable
13510        // only from a non-`const` context, a manual hand-rolled
13511        // `impl` that shadows the derive-generated method) trips at
13512        // caixa-core build time rather than surfacing as a downstream
13513        // `const`-context regression far from the derive declaration.
13514        //
13515        // Unlike the peer unit-variant enums (`CaixaKind` /
13516        // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
13517        // whose `const` constructors need no arguments, the three
13518        // payload-carrying [`WitTarget`] arms are const-constructed
13519        // through `&'static str` payloads — the same `'static`
13520        // lifetime the closed-set typed enum's four-arm partition
13521        // pin above already threads through.
13522        const HTTP: WitTarget<'static> = WitTarget::Http { endpoint: "/x" };
13523        const PUBSUB: WitTarget<'static> = WitTarget::PubSub { subject: "e" };
13524        const STORE: WitTarget<'static> = WitTarget::Store { slot: "kv/x" };
13525        const CAPABILITY: WitTarget<'static> = WitTarget::Capability;
13526        const IS_HTTP: bool = HTTP.is_http();
13527        const IS_PUBSUB: bool = PUBSUB.is_pubsub();
13528        const IS_STORE: bool = STORE.is_store();
13529        const IS_CAPABILITY: bool = CAPABILITY.is_capability();
13530        assert!(IS_HTTP);
13531        assert!(IS_PUBSUB);
13532        assert!(IS_STORE);
13533        assert!(IS_CAPABILITY);
13534    }
13535
13536    #[test]
13537    fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
13538        // Consumer-side pin on the sole production converge site:
13539        // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
13540        // edges from the synchronous-subgraph DFS via the lifted
13541        // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
13542        // predicate (rebound from the prior raw
13543        // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
13544        // variant). Byte-equivalent today (`is_pubsub` is the
13545        // derive-generated `matches!(self, Self::PubSub { .. })` by
13546        // construction, the `#[is_variant(name = "pubsub")]` override
13547        // aliasing the auto-derived `is_pub_sub` back to the sibling
13548        // [`WitContract::is_pubsub`] name); pin the behavior so a
13549        // future accidental drift (a rebind onto a peer arm
13550        // predicate, a manual hand-rolled `impl` that shadows the
13551        // derive-generated method with different semantics, a peer
13552        // arm rename that shifts which variant carries sync-versus-
13553        // async semantics) trips at caixa-core test time rather than
13554        // at some downstream operator's runtime dispatch far from the
13555        // rebind commit.
13556        //
13557        // The fixture constructs a two-Servico Aplicacao with one
13558        // pub-sub edge that would close a sync-cycle if the DFS did
13559        // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
13560        // pub-sub exclusion means the DFS sees only the `b → a` HTTP
13561        // edge, which is not a cycle. A regression in the converge
13562        // (a rebind that reads the pub-sub arm as sync) would report
13563        // `AplicacaoError::ContratoCycle`.
13564        let s = AplicacaoSpec {
13565            membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
13566            contratos: vec![
13567                // Pub-sub edge: DFS must skip via is_pubsub().
13568                WitContract {
13569                    de: "a".into(),
13570                    para: "b".into(),
13571                    wit: "nats:pub-sub".into(),
13572                    endpoint: None,
13573                    subject: Some("events.x".into()),
13574                    slot: None,
13575                },
13576                // HTTP edge: DFS must include.
13577                WitContract {
13578                    de: "b".into(),
13579                    para: "a".into(),
13580                    wit: "wasi:http/proxy".into(),
13581                    endpoint: Some("/x".into()),
13582                    subject: None,
13583                    slot: None,
13584                },
13585            ],
13586            politicas: MeshPolicy::default(),
13587            placement: Placement {
13588                estrategia: PlacementStrategy::Replicated,
13589                clusters: vec!["rio".into()],
13590                affinity: None,
13591                shard_key: None,
13592            },
13593            entrada: None,
13594        };
13595        s.validate()
13596            .expect("pub-sub edge must be excluded from sync-cycle DFS");
13597    }
13598
13599    #[test]
13600    fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
13601        // Consumer-side pin: the same three peer consts thread through
13602        // both the [`WitTarget::label`] template (leading-`:` keyword
13603        // prefix in the duplicate-`:contratos` diagnostic) and the
13604        // [`WitContract::target`] gate's [`AplicacaoError::
13605        // ContratoMissingTarget`] `expected:` scalar (the field the
13606        // author needs to add). Pin both routes at once so a future
13607        // refactor can't accidentally split them onto separate string
13608        // literals — the "one place, everywhere reaches for it"
13609        // invariant the peer const set carries.
13610        let http_label = WitTarget::Http { endpoint: "/x" }.label();
13611        assert!(
13612            http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
13613            "label must lead with :{} keyword (got {http_label:?})",
13614            WitTarget::HTTP_FIELD_NAME,
13615        );
13616
13617        let mut s = three_member_spec();
13618        s.contratos.push(WitContract {
13619            de: "cart".into(),
13620            para: "catalog".into(),
13621            wit: "kafka:topic".into(),
13622            endpoint: None,
13623            subject: None,
13624            slot: None,
13625        });
13626        match s.validate().unwrap_err() {
13627            AplicacaoError::ContratoMissingTarget { expected, .. } => {
13628                assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
13629            }
13630            other => panic!("expected ContratoMissingTarget, got {other:?}"),
13631        }
13632    }
13633
13634    #[test]
13635    fn duplicate_pubsub_diagnostic_names_offending_subject() {
13636        // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
13637        // on the pub-sub target axis: the duplicate-edge diagnostic
13638        // must name the `:subject` payload verbatim (not just the
13639        // `(de, para, wit)` triple). Prior to lifting the label onto
13640        // [`WitTarget::label`] the diagnostic derived the label from
13641        // raw [`WitContract`] `Option<String>` probes — a future
13642        // `WitTarget` variant addition (M4 per-edge WIT registry)
13643        // would silently fall through to the `Capability` "no
13644        // payload" default without a compiler warning. Pinning the
13645        // pub-sub arm's format closes the second of three
13646        // payload-carrying `WitTarget` arms this diagnostic threads
13647        // through.
13648        let mut s = three_member_spec();
13649        let pubsub = WitContract {
13650            de: "payment".into(),
13651            para: "cart".into(),
13652            wit: "nats:pub-sub".into(),
13653            endpoint: None,
13654            subject: Some("events.checkout.paid".into()),
13655            slot: None,
13656        };
13657        s.contratos.push(pubsub.clone());
13658        s.contratos.push(pubsub);
13659        let err = s.validate().unwrap_err();
13660        let msg = format!("{err}");
13661        assert!(
13662            msg.contains(":subject \"events.checkout.paid\""),
13663            "duplicate-pubsub diagnostic must name the offending \
13664             :subject payload (got: {msg:?})"
13665        );
13666    }
13667
13668    #[test]
13669    fn duplicate_store_diagnostic_names_offending_slot() {
13670        // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
13671        // key-value target axis: the diagnostic must name the `:slot`
13672        // payload verbatim. Third of three payload-carrying
13673        // `WitTarget` arms this diagnostic threads through, closing
13674        // the per-arm label pin trilogy (`Http` — 6841,
13675        // `PubSub` + `Store` — this test + peer above).
13676        let mut s = three_member_spec();
13677        let store = WitContract {
13678            de: "cart".into(),
13679            para: "payment".into(),
13680            wit: "wasi:keyvalue/store".into(),
13681            endpoint: None,
13682            subject: None,
13683            slot: Some("checkout/$orderId".into()),
13684        };
13685        s.contratos
13686            .retain(|c| !(c.de == "cart" && c.para == "payment"));
13687        s.contratos.push(store.clone());
13688        s.contratos.push(store);
13689        let err = s.validate().unwrap_err();
13690        let msg = format!("{err}");
13691        assert!(
13692            msg.contains(":slot \"checkout/$orderId\""),
13693            "duplicate-store diagnostic must name the offending :slot \
13694             payload (got: {msg:?})"
13695        );
13696    }
13697
13698    #[test]
13699    fn rejects_entrada_path_without_leading_slash() {
13700        let mut s = three_member_spec();
13701        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
13702        let err = s.validate().unwrap_err();
13703        assert!(
13704            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
13705            "got {err:?}"
13706        );
13707    }
13708
13709    #[test]
13710    fn rejects_empty_entrada_path() {
13711        let mut s = three_member_spec();
13712        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "".into()];
13713        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
13714    }
13715
13716    #[test]
13717    fn rejects_duplicate_entrada_paths() {
13718        let mut s = three_member_spec();
13719        s.entrada.as_mut().unwrap().paths = vec![
13720            "/api/cart".into(),
13721            "/api/products".into(),
13722            "/api/cart".into(),
13723        ];
13724        let err = s.validate().unwrap_err();
13725        assert!(
13726            matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
13727            "got {err:?}"
13728        );
13729    }
13730
13731    #[test]
13732    fn rejects_zero_entrada_port() {
13733        let mut s = three_member_spec();
13734        s.entrada.as_mut().unwrap().port = 0;
13735        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
13736    }
13737
13738    // ── :entrada :paths value-shape gate ─────────────────────────────
13739    //
13740    // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
13741    // sibling `:paths` axis. Every authoring footgun the K8s Gateway
13742    // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
13743    // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
13744    // time now becomes a caixa-build-time `EntradaPathInvalid` with
13745    // the offending `:paths` entry named verbatim.
13746
13747    #[test]
13748    fn rejects_entrada_path_with_query() {
13749        // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
13750        // silently passed validate and the Gateway API webhook
13751        // rejected it at apply time with no source citation.
13752        let mut s = three_member_spec();
13753        s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
13754        let err = s.validate().unwrap_err();
13755        assert!(
13756            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13757                if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
13758            "got {err:?}"
13759        );
13760    }
13761
13762    #[test]
13763    fn rejects_entrada_path_with_fragment() {
13764        let mut s = three_member_spec();
13765        s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
13766        let err = s.validate().unwrap_err();
13767        assert!(
13768            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13769                if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
13770            "got {err:?}"
13771        );
13772    }
13773
13774    #[test]
13775    fn rejects_entrada_path_with_space() {
13776        let mut s = three_member_spec();
13777        s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
13778        let err = s.validate().unwrap_err();
13779        assert!(
13780            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13781                if path == "/api/my cart" && reason.contains("whitespace")),
13782            "got {err:?}"
13783        );
13784    }
13785
13786    #[test]
13787    fn rejects_entrada_path_with_tab() {
13788        let mut s = three_member_spec();
13789        s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
13790        let err = s.validate().unwrap_err();
13791        assert!(
13792            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13793                if path == "/api/\tcart" && reason.contains("whitespace")),
13794            "got {err:?}"
13795        );
13796    }
13797
13798    #[test]
13799    fn rejects_entrada_path_with_control_char() {
13800        // 0x01 (SOH) — a non-whitespace control char surfaces the
13801        // distinct "control character" reason arm, separate from
13802        // the whitespace arm. Pinned so a future refactor that
13803        // collapses the two arms can't accidentally drop the more
13804        // self-locating diagnostic.
13805        let mut s = three_member_spec();
13806        s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
13807        let err = s.validate().unwrap_err();
13808        assert!(
13809            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13810                if path == "/api/\x01cart" && reason.contains("control character")),
13811            "got {err:?}"
13812        );
13813    }
13814
13815    #[test]
13816    fn rejects_entrada_path_with_non_ascii() {
13817        // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
13818        // unreserved-set rule rejects. The Gateway API webhook
13819        // rejects literal non-ASCII bytes; percent-encoding is the
13820        // only way to author non-ASCII in a path.
13821        let mut s = three_member_spec();
13822        s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
13823        let err = s.validate().unwrap_err();
13824        assert!(
13825            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13826                if path == "/api/café" && reason.contains("non-ASCII")),
13827            "got {err:?}"
13828        );
13829    }
13830
13831    #[test]
13832    fn rejects_entrada_path_with_consecutive_slashes() {
13833        let mut s = three_member_spec();
13834        s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
13835        let err = s.validate().unwrap_err();
13836        assert!(
13837            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13838                if path == "/api//cart" && reason.contains("consecutive `/`")),
13839            "got {err:?}"
13840        );
13841    }
13842
13843    #[test]
13844    fn rejects_entrada_path_with_dot_segment() {
13845        let mut s = three_member_spec();
13846        s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
13847        let err = s.validate().unwrap_err();
13848        assert!(
13849            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13850                if path == "/api/./cart" && reason.contains("`.` segment")),
13851            "got {err:?}"
13852        );
13853    }
13854
13855    #[test]
13856    fn rejects_entrada_path_with_trailing_dot_segment() {
13857        // The bare `/.` and the trailing `/foo/.` are both rejected
13858        // by the Gateway API webhook; pinned separately so a future
13859        // narrowing that catches only the inner form surfaces here.
13860        let mut s = three_member_spec();
13861        s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
13862        let err = s.validate().unwrap_err();
13863        assert!(
13864            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13865                if path == "/api/." && reason.contains("`.` segment")),
13866            "got {err:?}"
13867        );
13868    }
13869
13870    #[test]
13871    fn rejects_entrada_path_with_parent_segment() {
13872        let mut s = three_member_spec();
13873        s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
13874        let err = s.validate().unwrap_err();
13875        assert!(
13876            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13877                if path == "/api/../etc" && reason.contains("`..` parent-segment")),
13878            "got {err:?}"
13879        );
13880    }
13881
13882    #[test]
13883    fn rejects_entrada_path_with_trailing_parent_segment() {
13884        // Trailing `/..` — symmetric arm of the parent-segment rule,
13885        // pinned separately so a future relaxation that only checks
13886        // the inner form (`/../`) surfaces here.
13887        let mut s = three_member_spec();
13888        s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
13889        let err = s.validate().unwrap_err();
13890        assert!(
13891            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13892                if path == "/api/.." && reason.contains("`..` parent-segment")),
13893            "got {err:?}"
13894        );
13895    }
13896
13897    #[test]
13898    fn rejects_entrada_path_too_long() {
13899        // 1025-byte path — one over the Gateway API HTTPPathMatch.value
13900        // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
13901        // ASCII-alphanumeric body so only the length rule fires.
13902        let mut s = three_member_spec();
13903        let big = format!("/api/{}", "a".repeat(1020));
13904        assert_eq!(big.len(), 1025);
13905        s.entrada.as_mut().unwrap().paths = vec![big.clone()];
13906        let err = s.validate().unwrap_err();
13907        assert!(
13908            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13909                if path == &big && reason.contains("max length of 1024")),
13910            "got {err:?}"
13911        );
13912    }
13913
13914    #[test]
13915    fn entrada_path_max_length_validates() {
13916        // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
13917        // maxLength cap. Boundary pin: drift in the cap surfaces here
13918        // and at `rejects_entrada_path_too_long` simultaneously.
13919        let mut s = three_member_spec();
13920        let big = format!("/api/{}", "a".repeat(1019));
13921        assert_eq!(big.len(), 1024);
13922        s.entrada.as_mut().unwrap().paths = vec![big];
13923        s.validate().unwrap();
13924    }
13925
13926    #[test]
13927    fn entrada_accepts_canonical_paths() {
13928        // Positive-control sweep — every form the Gateway API
13929        // apiserver accepts must round-trip through validate. Covers
13930        // the root catch-all, plain paths, dot-prefixed segments
13931        // (hidden-file-style, distinct from `.` and `..` segments
13932        // which are rejected), digit-bearing segments, the canonical
13933        // route-template `:param` form (`:` is RFC 3986 reserved-set
13934        // valid in paths), trailing-slash form, percent-encoded
13935        // segments, and an interior `..` *substring* (`/foo..bar` is
13936        // not the `..` segment and is allowed).
13937        for path in [
13938            "/",
13939            "/api/cart",
13940            "/healthz",
13941            "/api/.config",
13942            "/v1/products",
13943            "/products/:id",
13944            "/api/cart/",
13945            "/api/caf%C3%A9",
13946            "/foo..bar",
13947            "/...",
13948        ] {
13949            let mut s = three_member_spec();
13950            s.entrada.as_mut().unwrap().paths = vec![path.into()];
13951            s.validate()
13952                .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
13953        }
13954    }
13955
13956    #[test]
13957    fn entrada_path_empty_takes_precedence_over_invalid() {
13958        // Ordering pin: `EntradaPathEmpty` is the more self-locating
13959        // diagnostic on `""` and must lead — `validate_entrada_path`
13960        // is only reached after the empty-check fires at the call
13961        // site. (The predicate itself defends against direct
13962        // invocation by returning the same error on `""`.)
13963        let mut s = three_member_spec();
13964        s.entrada.as_mut().unwrap().paths = vec!["".into()];
13965        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
13966    }
13967
13968    #[test]
13969    fn entrada_path_not_absolute_takes_precedence_over_invalid() {
13970        // Ordering pin: a path without a leading `/` surfaces the
13971        // narrower `EntradaPathNotAbsolute` diagnostic first; the
13972        // value-shape gate is only consulted on paths that already
13973        // satisfy the absolute-prefix invariant.
13974        let mut s = three_member_spec();
13975        // `bad path` would fire the whitespace rule under the
13976        // value-shape gate, but missing-leading-`/` is the more
13977        // self-locating diagnostic.
13978        s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
13979        let err = s.validate().unwrap_err();
13980        assert!(
13981            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
13982            "got {err:?}"
13983        );
13984    }
13985
13986    #[test]
13987    fn entrada_path_invalid_fires_before_duplicate_check() {
13988        // Ordering pin: a malformed path on the *first* entry of a
13989        // would-be duplicate pair fires the value-shape gate before
13990        // the duplicate gate, mirroring the
13991        // `placement_cluster_invalid_fires_before_duplicate_check`
13992        // (6cbb900) pattern on the peer axis.
13993        let mut s = three_member_spec();
13994        s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
13995        let err = s.validate().unwrap_err();
13996        assert!(
13997            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
13998            "got {err:?}"
13999        );
14000    }
14001
14002    #[test]
14003    fn entrada_path_diagnostic_carries_offending_path() {
14004        // Diagnostic-shape pin — the offending path + a non-empty
14005        // reason flow through verbatim so the author can grep their
14006        // caixa.lisp for `:paths` and fix it in one edit. Same shape
14007        // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
14008        let mut s = three_member_spec();
14009        s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
14010        let err = s.validate().unwrap_err();
14011        match err {
14012            AplicacaoError::EntradaPathInvalid { path, reason } => {
14013                assert_eq!(path, "/api?q=1");
14014                assert!(!reason.is_empty(), "reason field must be non-empty");
14015            }
14016            other => panic!("expected EntradaPathInvalid, got {other:?}"),
14017        }
14018    }
14019
14020    #[test]
14021    fn rejects_entrada_path_with_curly_brace_template_form() {
14022        // Per-axis pin on the shared `is_gateway_api_http_path`
14023        // reserved-byte arm: the canonical "I wrote an OpenAPI
14024        // path-template `{id}` instead of the Gateway API `:id` form"
14025        // footgun the K8s apiserver would otherwise catch at admission
14026        // time on every `HTTPRoute.spec.rules[].matches[].path.value`
14027        // landing site, far from the caixa.lisp. Surfaces as
14028        // `EntradaPathInvalid` carrying the offending path verbatim
14029        // plus the canonical `%7B`/`%7D` percent-encoding remediation
14030        // — the substrate-side `gateway_api_http_path_rejects_every_
14031        // reserved_printable_ascii_byte` predicate-level sweep pins the
14032        // full eleven-byte set; this per-axis pin confirms the
14033        // diagnostic flows through to the `EntradaPathInvalid` variant.
14034        let mut s = three_member_spec();
14035        s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
14036        let err = s.validate().unwrap_err();
14037        assert!(
14038            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14039                if path == "/api/cart/{id}"
14040                    && reason.contains("reserved character")
14041                    && reason.contains("'{'")
14042                    && reason.contains("%7B")),
14043            "got {err:?}"
14044        );
14045    }
14046
14047    #[test]
14048    fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
14049        // Per-axis peer of `rejects_entrada_path_with_curly_brace_
14050        // template_form` on the sibling `:contratos :endpoint` axis.
14051        // Same shared `is_gateway_api_http_path` reserved-byte arm
14052        // fires through `ContratoEndpointInvalid`, with the offending
14053        // endpoint + `:de` + `:para` + reason flowing through verbatim.
14054        // Pins that the lifted predicate's tightening lands on both
14055        // caller axes simultaneously — one source of truth for the
14056        // Gateway API HTTPPathMatch.value accepted set.
14057        let err = contrato_endpoint_err("/api/cart/{id}");
14058        assert!(
14059            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
14060                if endpoint == "/api/cart/{id}"
14061                    && reason.contains("reserved character")
14062                    && reason.contains("'{'")
14063                    && reason.contains("%7B")),
14064            "got {err:?}"
14065        );
14066    }
14067
14068    // ── :entrada :host value-shape gate ──────────────────────────────
14069    //
14070    // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
14071    // the sibling `:host` axis. Every authoring footgun the K8s
14072    // Gateway API v1 apiserver would catch at admission time becomes
14073    // a caixa-build-time `EntradaHostInvalid` with the offending
14074    // `:host` named verbatim. Same diagnostic shape as
14075    // `MembroVersaoInvalid` (9888b13).
14076
14077    #[test]
14078    fn rejects_entrada_host_with_scheme() {
14079        // Fail-before-pass-after pin — pre-gate codebases silently
14080        // accepted `https://…` and the apiserver rejected it at apply
14081        // time with no source citation.
14082        let mut s = three_member_spec();
14083        s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
14084        let err = s.validate().unwrap_err();
14085        assert!(
14086            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
14087                if host == "https://checkout.quero.cloud"),
14088            "got {err:?}"
14089        );
14090    }
14091
14092    #[test]
14093    fn rejects_entrada_host_with_port() {
14094        // The `:8080` port suffix is the canonical "I forgot the port
14095        // belongs in `:entrada :port`" footgun. The top-level `:` arm
14096        // (introduced after the per-label loop-only impl silently
14097        // surfaced a deep "label \"cloud:8080\" contains invalid
14098        // character ':'" leak) names the canonical fix verbatim — the
14099        // `:entrada :port` slot.
14100        let mut s = three_member_spec();
14101        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
14102        let err = s.validate().unwrap_err();
14103        assert!(
14104            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
14105                if host == "checkout.quero.cloud:8080"
14106                && reason.contains(":entrada :port")),
14107            "got {err:?}"
14108        );
14109    }
14110
14111    #[test]
14112    fn rejects_entrada_host_with_trailing_colon() {
14113        // Trailing `:` (e.g. an in-progress `:host "example.com:"`
14114        // edit) — the per-label loop would land it as a deep
14115        // "label \"com:\" must start and end with an alphanumeric"
14116        // / "contains invalid character ':'" leak. The top-level
14117        // `:` arm pre-empts with the canonical `:port` slot
14118        // diagnostic.
14119        let mut s = three_member_spec();
14120        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
14121        let err = s.validate().unwrap_err();
14122        assert!(
14123            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
14124                if host == "checkout.quero.cloud:"
14125                && reason.contains(":entrada :port")),
14126            "got {err:?}"
14127        );
14128    }
14129
14130    #[test]
14131    fn rejects_entrada_host_unbracketed_ipv6_literal() {
14132        // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
14133        // literals across the board (peer with `rejects_entrada_host_
14134        // ipv4_literal` above for the four-label-all-digit IPv4 arm).
14135        // Before this top-level `:` arm landed the per-label loop
14136        // surfaced a single-label byte-class diagnostic that named the
14137        // `:` byte but not the IP-literal prohibition. The top-level
14138        // `:` arm names both the `:port` slot and the IP-literal
14139        // prohibition verbatim, so an author whose `:host "2001:..."`
14140        // value lands here gets a self-locating fix either way.
14141        let mut s = three_member_spec();
14142        s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
14143        let err = s.validate().unwrap_err();
14144        assert!(
14145            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
14146                if host == "2001:db8::1"
14147                && reason.contains("IPv6")),
14148            "got {err:?}"
14149        );
14150    }
14151
14152    #[test]
14153    fn rejects_entrada_host_wildcard_with_port() {
14154        // Wildcard host with port suffix — the `*.` strip and the
14155        // per-label loop on `["foo", "quero", "cloud:8080"]` would
14156        // surface the deep byte-class leak. The top-level `:` arm sits
14157        // upstream of the `*.` strip, so it names the canonical `:port`
14158        // fix verbatim regardless of whether the host is wildcard-led.
14159        let mut s = three_member_spec();
14160        s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
14161        let err = s.validate().unwrap_err();
14162        assert!(
14163            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
14164                if host == "*.quero.cloud:8080"
14165                && reason.contains(":entrada :port")),
14166            "got {err:?}"
14167        );
14168    }
14169
14170    #[test]
14171    fn rejects_entrada_host_with_path() {
14172        let mut s = three_member_spec();
14173        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
14174        let err = s.validate().unwrap_err();
14175        assert!(
14176            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
14177                if host == "checkout.quero.cloud/api"),
14178            "got {err:?}"
14179        );
14180    }
14181
14182    #[test]
14183    fn rejects_entrada_host_with_uppercase() {
14184        // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
14185        // rejected, not silently lower-cased.
14186        let mut s = three_member_spec();
14187        s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
14188        let err = s.validate().unwrap_err();
14189        assert!(
14190            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14191                if reason.contains("uppercase")),
14192            "got {err:?}"
14193        );
14194    }
14195
14196    #[test]
14197    fn rejects_entrada_host_with_underscore() {
14198        // RFC 1123 allows `[a-z0-9-]` only; underscore is the
14199        // canonical "I'm thinking of HTTP cookies / SRV records" leak.
14200        let mut s = three_member_spec();
14201        s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
14202        let err = s.validate().unwrap_err();
14203        assert!(
14204            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14205                if reason.contains('_')),
14206            "got {err:?}"
14207        );
14208    }
14209
14210    #[test]
14211    fn rejects_entrada_host_ipv4_literal() {
14212        // Gateway API v1 explicitly forbids IP literals as Hostnames.
14213        let mut s = three_member_spec();
14214        s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
14215        let err = s.validate().unwrap_err();
14216        assert!(
14217            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14218                if reason.contains("IPv4")),
14219            "got {err:?}"
14220        );
14221    }
14222
14223    #[test]
14224    fn rejects_entrada_host_with_trailing_dot() {
14225        // The Gateway API regex anchors at end-of-string with no
14226        // trailing `.` allowance — the FQDN root-dot form is rejected.
14227        let mut s = three_member_spec();
14228        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
14229        let err = s.validate().unwrap_err();
14230        assert!(
14231            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
14232                if host == "checkout.quero.cloud."),
14233            "got {err:?}"
14234        );
14235    }
14236
14237    #[test]
14238    fn rejects_entrada_host_with_leading_dot() {
14239        let mut s = three_member_spec();
14240        s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
14241        let err = s.validate().unwrap_err();
14242        assert!(
14243            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14244                if reason.contains("empty label")),
14245            "got {err:?}"
14246        );
14247    }
14248
14249    #[test]
14250    fn rejects_entrada_host_with_consecutive_dots() {
14251        let mut s = three_member_spec();
14252        s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
14253        let err = s.validate().unwrap_err();
14254        assert!(
14255            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14256                if reason.contains("empty label")),
14257            "got {err:?}"
14258        );
14259    }
14260
14261    #[test]
14262    fn rejects_entrada_host_with_leading_hyphen_label() {
14263        let mut s = three_member_spec();
14264        s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
14265        let err = s.validate().unwrap_err();
14266        assert!(
14267            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14268                if reason.contains("alphanumeric")),
14269            "got {err:?}"
14270        );
14271    }
14272
14273    #[test]
14274    fn rejects_entrada_host_with_trailing_hyphen_label() {
14275        let mut s = three_member_spec();
14276        s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
14277        let err = s.validate().unwrap_err();
14278        assert!(
14279            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14280                if reason.contains("alphanumeric")),
14281            "got {err:?}"
14282        );
14283    }
14284
14285    #[test]
14286    fn rejects_entrada_host_with_inner_wildcard() {
14287        // Gateway API allows `*` only as the first label (`*.foo`);
14288        // any inner or trailing `*` is rejected.
14289        let mut s = three_member_spec();
14290        s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
14291        let err = s.validate().unwrap_err();
14292        assert!(
14293            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14294                if reason.contains("wildcard")),
14295            "got {err:?}"
14296        );
14297    }
14298
14299    #[test]
14300    fn rejects_entrada_host_bare_wildcard() {
14301        // `*.` with no domain is meaningless; Gateway API rejects it.
14302        let mut s = three_member_spec();
14303        s.entrada.as_mut().unwrap().host = "*.".into();
14304        let err = s.validate().unwrap_err();
14305        assert!(
14306            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14307                if reason.contains("wildcard")),
14308            "got {err:?}"
14309        );
14310    }
14311
14312    #[test]
14313    fn rejects_entrada_host_with_whitespace() {
14314        let mut s = three_member_spec();
14315        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
14316        let err = s.validate().unwrap_err();
14317        assert!(
14318            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14319                if reason.contains("whitespace")),
14320            "got {err:?}"
14321        );
14322    }
14323
14324    #[test]
14325    fn rejects_entrada_host_space_names_offending_byte() {
14326        // Embedded space in the `:entrada :host` axis surfaces the
14327        // byte-naming diagnostic through the lifted
14328        // `find_ascii_whitespace_byte` predicate. Peer with the
14329        // sibling `parse_rejects_leading_whitespace` pins on
14330        // `supervisor::duration_codec` (a7ae622) — same "the
14331        // diagnostic carries the offending byte's `0x{b:02x}` shape"
14332        // discipline extended from the shared duration codec to the
14333        // Gateway API v1 Hostname axis.
14334        let mut s = three_member_spec();
14335        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
14336        let err = s.validate().unwrap_err();
14337        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14338            panic!("expected EntradaHostInvalid, got {err:?}");
14339        };
14340        assert!(
14341            reason.contains("ASCII whitespace byte"),
14342            "expected byte-naming diagnostic, got {reason:?}"
14343        );
14344        assert!(
14345            reason.contains("0x20"),
14346            "expected offending space byte 0x20, got {reason:?}"
14347        );
14348    }
14349
14350    #[test]
14351    fn rejects_entrada_host_tab_names_offending_byte() {
14352        // Embedded tab byte in the `:entrada :host` axis — the
14353        // canonical paste-from-YAML-block-scalar / paste-from-
14354        // indented-doc footgun. Pins that the lifted predicate covers
14355        // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
14356        // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
14357        // not just the leading-space case the pre-lift `.bytes().any`
14358        // arm's opaque "must not contain whitespace" reason already
14359        // covered. Peer with `parse_rejects_tab_byte` on
14360        // `supervisor::duration_codec` (a7ae622).
14361        let mut s = three_member_spec();
14362        s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
14363        let err = s.validate().unwrap_err();
14364        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14365            panic!("expected EntradaHostInvalid, got {err:?}");
14366        };
14367        assert!(
14368            reason.contains("ASCII whitespace byte"),
14369            "expected byte-naming diagnostic, got {reason:?}"
14370        );
14371        assert!(
14372            reason.contains("0x09"),
14373            "expected offending tab byte 0x09, got {reason:?}"
14374        );
14375    }
14376
14377    #[test]
14378    fn rejects_entrada_host_lf_names_offending_byte() {
14379        // Embedded LF byte in the `:entrada :host` axis — the
14380        // canonical paste-from-shell-heredoc / paste-from-multiline-
14381        // doc footgun the caixa-mesh YAML emitter would silently
14382        // reinterpret at the Gateway API v1 HTTPRoute admission
14383        // layer (an embedded LF byte in a YAML plain scalar either
14384        // truncates the value at the emitter or crashes the parser
14385        // on the k8s-apiserver side). Pins the third representative
14386        // of the full ASCII-whitespace set through the shared
14387        // predicate.
14388        let mut s = three_member_spec();
14389        s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
14390        let err = s.validate().unwrap_err();
14391        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14392            panic!("expected EntradaHostInvalid, got {err:?}");
14393        };
14394        assert!(
14395            reason.contains("ASCII whitespace byte"),
14396            "expected byte-naming diagnostic, got {reason:?}"
14397        );
14398        assert!(
14399            reason.contains("0x0a"),
14400            "expected offending LF byte 0x0a, got {reason:?}"
14401        );
14402    }
14403
14404    #[test]
14405    fn rejects_entrada_host_nbsp_names_offending_codepoint() {
14406        // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
14407        // axis — the canonical paste-from-typography /
14408        // paste-from-word-processor footgun. Before the non-ASCII
14409        // Unicode `White_Space` scan lifted through the shared
14410        // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
14411        // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
14412        // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
14413        // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
14414        // with the far-from-source `label "…" must start and end
14415        // with an alphanumeric` diagnostic — burying the
14416        // paste-from-typography origin under a label-shape leak.
14417        // Peer with the sibling non-ASCII-whitespace pins at
14418        // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
14419        // — 1b75b38), `limits::parse_duration`,
14420        // `limits::parse_millicores`, and the shared duration codec
14421        // — same "the diagnostic carries the offending Unicode
14422        // codepoint's `U+XXXX` shape" discipline extended from every
14423        // typed-magnitude codec to the Gateway API v1 Hostname axis.
14424        let mut s = three_member_spec();
14425        s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
14426        let err = s.validate().unwrap_err();
14427        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14428            panic!("expected EntradaHostInvalid, got {err:?}");
14429        };
14430        assert!(
14431            reason.contains("non-ASCII Unicode whitespace character"),
14432            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
14433        );
14434        assert!(
14435            reason.contains("U+00A0"),
14436            "expected offending NBSP codepoint U+00A0, got {reason:?}"
14437        );
14438    }
14439
14440    #[test]
14441    fn rejects_entrada_host_line_separator_names_offending_codepoint() {
14442        // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
14443        // `:entrada :host` axis — the canonical paste-from-web-doc /
14444        // paste-from-published-HTML footgun. `char::is_whitespace`
14445        // returns true for `U+2028` per the Unicode `White_Space`
14446        // property, so `str::trim` at any downstream site would
14447        // silently strip it — same drift class as NBSP but on a
14448        // different codepoint region. Pins the second representative
14449        // (non-Latin-1 `char::is_whitespace` member) through the
14450        // shared predicate. Peer with
14451        // `parse_byte_size_rejects_internal_line_separator` on
14452        // `limits::parse_byte_size` (1b75b38).
14453        let mut s = three_member_spec();
14454        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
14455        let err = s.validate().unwrap_err();
14456        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14457            panic!("expected EntradaHostInvalid, got {err:?}");
14458        };
14459        assert!(
14460            reason.contains("non-ASCII Unicode whitespace character"),
14461            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
14462        );
14463        assert!(
14464            reason.contains("U+2028"),
14465            "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
14466        );
14467    }
14468
14469    #[test]
14470    fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
14471        // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
14472        // labels in the `:entrada :host` axis — the canonical
14473        // paste-from-CJK-typography footgun (CJK IMEs default to
14474        // full-width whitespace when the space bar is pressed in
14475        // Japanese / Chinese input modes). Pins the third
14476        // representative of the non-ASCII Unicode `White_Space` set
14477        // through the shared predicate: the CJK block, distinct from
14478        // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
14479        // SEPARATOR `U+2028` — covering the same axis breadth the
14480        // sibling `parse_byte_size_rejects_trailing_ideographic_space`
14481        // (1b75b38) pins on `limits::parse_byte_size`.
14482        let mut s = three_member_spec();
14483        s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
14484        let err = s.validate().unwrap_err();
14485        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14486            panic!("expected EntradaHostInvalid, got {err:?}");
14487        };
14488        assert!(
14489            reason.contains("non-ASCII Unicode whitespace character"),
14490            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
14491        );
14492        assert!(
14493            reason.contains("U+3000"),
14494            "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
14495        );
14496    }
14497
14498    #[test]
14499    fn rejects_entrada_host_too_long() {
14500        // Total length cap = 253; build a 254-byte host out of two
14501        // 63-byte labels + one 62-byte label + dots.
14502        let mut s = three_member_spec();
14503        let big = format!(
14504            "{}.{}.{}.{}",
14505            "a".repeat(63),
14506            "b".repeat(63),
14507            "c".repeat(63),
14508            "d".repeat(254 - 63 * 3 - 3)
14509        );
14510        assert_eq!(big.len(), 254);
14511        s.entrada.as_mut().unwrap().host = big;
14512        let err = s.validate().unwrap_err();
14513        assert!(
14514            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14515                if reason.contains("max length of 253")),
14516            "got {err:?}"
14517        );
14518    }
14519
14520    #[test]
14521    fn rejects_entrada_host_label_too_long() {
14522        let mut s = three_member_spec();
14523        // 64-byte label — one over the per-label cap.
14524        s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
14525        let err = s.validate().unwrap_err();
14526        assert!(
14527            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14528                if reason.contains("label max length of 63")),
14529            "got {err:?}"
14530        );
14531    }
14532
14533    #[test]
14534    fn entrada_host_diagnostic_carries_offending_host() {
14535        // Diagnostic-shape pin — the offending host + a non-empty
14536        // reason flow through verbatim so the author can grep their
14537        // caixa.lisp for `:host "<host>"` and fix it in one edit.
14538        let mut s = three_member_spec();
14539        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
14540        let err = s.validate().unwrap_err();
14541        match err {
14542            AplicacaoError::EntradaHostInvalid { host, reason } => {
14543                assert_eq!(host, "checkout.quero.cloud:8080");
14544                assert!(!reason.is_empty(), "reason field must be non-empty");
14545            }
14546            other => panic!("expected EntradaHostInvalid, got {other:?}"),
14547        }
14548    }
14549
14550    #[test]
14551    fn entrada_host_empty_takes_precedence_over_invalid() {
14552        // Ordering pin: `EmptyEntradaHost` is the more self-locating
14553        // diagnostic on `""` and must lead — `validate_entrada_host`
14554        // is only reached after the empty-check fires at the call
14555        // site. (The predicate itself defends against direct
14556        // invocation by returning the same error on `""`.)
14557        let mut s = three_member_spec();
14558        s.entrada.as_mut().unwrap().host = String::new();
14559        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
14560    }
14561
14562    #[test]
14563    fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
14564        // Ordering pin: a missing :para member is the more
14565        // self-locating diagnostic and fires before the host gate.
14566        let mut s = three_member_spec();
14567        let e = s.entrada.as_mut().unwrap();
14568        e.para = "ghost".into();
14569        e.host = "BAD HOST".into();
14570        let err = s.validate().unwrap_err();
14571        assert!(
14572            matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
14573            "got {err:?}"
14574        );
14575    }
14576
14577    #[test]
14578    fn entrada_host_invalid_fires_before_port_zero() {
14579        // Ordering pin: the host gate fires before the port gate so
14580        // a malformed host is named even when the port is also wrong.
14581        let mut s = three_member_spec();
14582        let e = s.entrada.as_mut().unwrap();
14583        e.host = "Checkout.quero.cloud".into();
14584        e.port = 0;
14585        let err = s.validate().unwrap_err();
14586        assert!(
14587            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
14588                if host == "Checkout.quero.cloud"),
14589            "got {err:?}"
14590        );
14591    }
14592
14593    #[test]
14594    fn entrada_accepts_canonical_hosts() {
14595        // Positive-control sweep — every form the Gateway API
14596        // apiserver accepts must round-trip through validate. Covers
14597        // a plain DNS subdomain, a leading wildcard, a single-label
14598        // host (cluster-internal), a max-length-edge label, a
14599        // hyphen-bearing label, and a Punycode IDN label.
14600        for host in [
14601            "checkout.quero.cloud",
14602            "*.quero.cloud",
14603            "checkout",
14604            // 63-byte label — exactly the per-label cap.
14605            "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
14606            "foo-bar.quero.cloud",
14607            // Punycode IDN — valid because the author pre-encoded.
14608            "xn--bcher-kva.example.com",
14609        ] {
14610            let mut s = three_member_spec();
14611            s.entrada.as_mut().unwrap().host = host.into();
14612            s.validate()
14613                .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
14614        }
14615    }
14616
14617    #[test]
14618    fn entrada_host_max_length_validates() {
14619        // 253-byte host is the cap exactly — must validate. Build a
14620        // 253-byte host out of three 63-byte labels + one 61-byte
14621        // label + 3 dots = 252 bytes, then pad one byte to 253.
14622        let mut s = three_member_spec();
14623        let host = format!(
14624            "{}.{}.{}.{}",
14625            "a".repeat(63),
14626            "b".repeat(63),
14627            "c".repeat(63),
14628            "d".repeat(253 - 63 * 3 - 3)
14629        );
14630        assert_eq!(host.len(), 253);
14631        s.entrada.as_mut().unwrap().host = host;
14632        s.validate().unwrap();
14633    }
14634
14635    #[test]
14636    fn entrada_host_total_length_cap_threads_lifted_render_const() {
14637        // Cross-crate-side pin: the aplicacao-side `:entrada :host`
14638        // total-length gate now reads the K8s Gateway API v1 Hostname
14639        // `maxLength: 253` cap from the lifted
14640        // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
14641        // of truth — the same constant every future Gateway-API-Hostname
14642        // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
14643        // materializer's per-host validator, the future per-`Certificate`
14644        // SAN emitter for cert-manager, the multi-`:entrada`
14645        // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
14646        // from. Before the lift, the aplicacao-side reader consumed a
14647        // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
14648        // 253-byte value as the peer render-side canonical bounds
14649        // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
14650        // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
14651        // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
14652        // module boundary — a future 253-byte drift on either side would
14653        // silently split into two axes' worth of admission-schema mismatch
14654        // without a build-time signal. Pin the cap through a fresh 254-
14655        // byte host that hits the total-length arm, then read the reason
14656        // for the exact byte count the shared constant carries: any future
14657        // regression on the lift (a private alias reintroduced, a hard-
14658        // coded literal at the arm, a mismatch between the aplicacao-side
14659        // and render-side canonicals) surfaces as this pin's diagnostic
14660        // failing to match, not as a per-cluster admission rejection far
14661        // from the caixa.lisp source line.
14662        let mut s = three_member_spec();
14663        let over_cap = format!(
14664            "{}.{}.{}.{}",
14665            "a".repeat(63),
14666            "b".repeat(63),
14667            "c".repeat(63),
14668            "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
14669        );
14670        assert_eq!(
14671            over_cap.len(),
14672            crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
14673        );
14674        s.entrada.as_mut().unwrap().host = over_cap;
14675        let err = s.validate().unwrap_err();
14676        match err {
14677            AplicacaoError::EntradaHostInvalid { reason, .. } => {
14678                let needle = format!(
14679                    "max length of {} bytes",
14680                    crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
14681                );
14682                assert!(
14683                    reason.contains(&needle),
14684                    "diagnostic must name the lifted \
14685                     GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
14686                );
14687            }
14688            other => panic!("expected EntradaHostInvalid, got {other:?}"),
14689        }
14690    }
14691
14692    #[test]
14693    fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
14694        // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
14695        // on the per-label-cap axis. Before the lift, the aplicacao-side
14696        // per-label arm consumed a private const alias
14697        // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
14698        // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
14699        // split from it at the module boundary — every `.`-separated
14700        // label in a Gateway API v1 Hostname is a DNS-1123 label under
14701        // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
14702        // so the private alias's 63 and the canonical const's 63 were
14703        // pinning the same underlying rule twice. Pin the cap through a
14704        // 64-byte label that hits the per-label arm, then read the reason
14705        // for the exact byte count the shared constant carries: any
14706        // future drift on either side (a private alias reintroduced, a
14707        // hard-coded literal at the arm, a mismatch between the two
14708        // 63-byte pins) surfaces at this pin's diagnostic rather than at
14709        // a per-cluster admission rejection whose "field is invalid"
14710        // opacity misframes the root cause.
14711        let mut s = three_member_spec();
14712        let over_cap_label = format!(
14713            "{}.quero.cloud",
14714            "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
14715        );
14716        s.entrada.as_mut().unwrap().host = over_cap_label;
14717        let err = s.validate().unwrap_err();
14718        match err {
14719            AplicacaoError::EntradaHostInvalid { reason, .. } => {
14720                let needle = format!(
14721                    "label max length of {} bytes",
14722                    crate::render::DNS_1123_LABEL_MAX_LEN,
14723                );
14724                assert!(
14725                    reason.contains(&needle),
14726                    "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
14727                     cap verbatim on the per-label arm, got: {reason:?}",
14728                );
14729            }
14730            other => panic!("expected EntradaHostInvalid, got {other:?}"),
14731        }
14732    }
14733
14734    #[test]
14735    fn entrada_with_empty_paths_validates() {
14736        // Empty `:paths` is the documented "match every path" form;
14737        // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
14738        let mut s = three_member_spec();
14739        s.entrada.as_mut().unwrap().paths = vec![];
14740        s.validate().unwrap();
14741    }
14742
14743    #[test]
14744    fn entrada_root_path_validates() {
14745        // The author-supplied bare-root `:entrada :paths` entry is the
14746        // same byte-shape the peer emit-side catch-all constant
14747        // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
14748        // the author's `:paths` list is empty — sweeping the test-side
14749        // probe literal onto the lifted const closes the two-axis pin
14750        // (author-side admit + emit-side canonical fallback) around
14751        // one `&'static str`, so a future rebrand of the catch-all
14752        // reaches both consumers by construction. Peer to
14753        // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
14754        // on the canonical-literal pin surface.
14755        let mut s = three_member_spec();
14756        s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
14757        s.validate().unwrap();
14758    }
14759
14760    #[test]
14761    fn placement_strategy_variants_round_trip() {
14762        for s in [
14763            PlacementStrategy::SingleNode,
14764            PlacementStrategy::Replicated,
14765            PlacementStrategy::Sharded,
14766        ] {
14767            let p = Placement {
14768                estrategia: s,
14769                clusters: vec!["rio".into()],
14770                affinity: None,
14771                // Route the paired `:shard-key` fixture-builder through the
14772                // typed cross-slot invariant predicate
14773                // [`PlacementStrategy::requires_shard_key`] rather than the
14774                // [`gen_platform::IsVariant`]-derived [`Self::is_sharded`]
14775                // arm-identity predicate — the two answer the same
14776                // question under today's closed accept-set but a future
14777                // arm addition that consumed `:shard-key` under a
14778                // non-`Sharded` name would silently mis-attach the
14779                // fixture's `:shard-key` if the builder read through the
14780                // arm-identity predicate. The cross-slot-invariant
14781                // predicate migrates through one caixa-core edit on any
14782                // future arm addition; the fixture keeps producing a
14783                // `validate()`-passing round-trip by construction.
14784                shard_key: if s.requires_shard_key() {
14785                    Some("$key".into())
14786                } else {
14787                    None
14788                },
14789            };
14790            let json = serde_json::to_string(&p).unwrap();
14791            let back: Placement = serde_json::from_str(&json).unwrap();
14792            assert_eq!(back, p);
14793        }
14794    }
14795
14796    #[test]
14797    fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
14798        // The fail-before-pass-after pin: pre-lift there was no
14799        // single-source binding between the [`PlacementStrategy`]
14800        // variant name the `Serialize` derive emits and the byte-
14801        // string every downstream cluster-side dispatcher (the
14802        // `lareira-fleet-programs` aggregator's per-entry strategy
14803        // branch, the future `app-operator` reconciler, the M3
14804        // Adaptive compression pass's per-strategy weighting) probes
14805        // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
14806        // future `#[serde(rename_all = "kebab-case")]` attribute on
14807        // the enum — or a variant rename in the source — would
14808        // silently rebrand the emitted scalar under one spelling
14809        // while every downstream dispatcher still probed the other,
14810        // with the failure surfacing at the aggregator's dispatch
14811        // step or the operator's reconcile posture (workloads coming
14812        // up under the `default()` `Replicated` arm rather than the
14813        // typed slot's declared strategy) far from the source
14814        // rebrand commit and with no field naming the drift. Pinning
14815        // the two paths (the `Serialize` derive's serialized string
14816        // AND the [`PlacementStrategy::as_str`] helper) to the same
14817        // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
14818        // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
14819        // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
14820        // makes any future drift on either endpoint fail here at
14821        // caixa-core build time.
14822        for (variant, expected) in [
14823            (
14824                PlacementStrategy::SingleNode,
14825                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
14826            ),
14827            (
14828                PlacementStrategy::Replicated,
14829                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
14830            ),
14831            (
14832                PlacementStrategy::Sharded,
14833                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
14834            ),
14835        ] {
14836            let json = serde_json::to_string(&variant).unwrap();
14837            assert_eq!(
14838                json,
14839                format!("\"{expected}\""),
14840                "PlacementStrategy::{variant:?} must serialize to {expected:?}"
14841            );
14842            assert_eq!(
14843                variant.as_str(),
14844                expected,
14845                "PlacementStrategy::{variant:?}.as_str() must return the lifted \
14846                 M3_PLACEMENT_ESTRATEGIA_* constant"
14847            );
14848        }
14849    }
14850
14851    #[test]
14852    fn m3_placement_estrategia_consts_are_pairwise_distinct() {
14853        // Cross-arm drift-detection pin on the M3
14854        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
14855        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
14856        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
14857        // scalar-value pentad: a future collapse of two canonical
14858        // variant byte-strings onto the same value (an accidental
14859        // copy-paste flip of
14860        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
14861        // read `"SingleNode"`, a per-arm rebrand that lands one const
14862        // without touching its paired peer) would silently reroute
14863        // every downstream operator's per-strategy dispatch onto the
14864        // sibling arm's reconcile branch and pass every
14865        // propagation-probe test that expected only the stale arm's
14866        // value — a `Replicated`-declared Aplicacao would come up
14867        // under the `SingleNode` primary-and-standby reconcile
14868        // posture, so every-cluster active-active workload would
14869        // silently collapse onto one-cluster-runs-at-a-time takeover
14870        // semantics against its declared strategy, with no field
14871        // naming the strategy-value drift root cause. Peer of the
14872        // sibling
14873        // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
14874        // (09ffb2d) /
14875        // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
14876        // (ccdf955) /
14877        // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
14878        // (d739850) distinctness pins on the sibling OTP-shape /
14879        // caixa-kind closed-set typed-enum discriminator axes — the
14880        // fourth (and structurally the M3 mesh-primitive-defining)
14881        // closed-set typed-enum axis to converge on the same
14882        // "pairwise-distinct-by-construction" discipline.
14883        //
14884        // Fail-before-pass-after locally verified by mutating
14885        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
14886        // also read `"SingleNode"` — this pin fires as expected;
14887        // restoring passes.
14888        let all = [
14889            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
14890            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
14891            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
14892        ];
14893        for (i, a) in all.iter().enumerate() {
14894            for (j, b) in all.iter().enumerate() {
14895                if i != j {
14896                    assert_ne!(
14897                        a, b,
14898                        "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
14899                         distinct — got duplicate {a:?} at indices {i} and {j}",
14900                    );
14901                }
14902            }
14903        }
14904    }
14905
14906    #[test]
14907    fn placement_strategy_display_routes_through_as_str_helper() {
14908        // The fail-before-pass-after pin: pre-lift the sibling
14909        // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
14910        // / [`crate::supervisor::RestartPolicy`] both carried a stable
14911        // [`std::fmt::Display`] surface via their
14912        // `#[discriminant(also_display)]` gen-platform derive, but
14913        // [`PlacementStrategy`] did not — every consumer reaching for
14914        // a strategy byte-string past the wire format had to pick
14915        // between three paths ([`PlacementStrategy::as_str`], the
14916        // `Serialize` derive's serialized string, or `format!("{v:?}")`
14917        // on the `Debug` derive), any two of which a future variant
14918        // rename or `#[serde(rename_all = "kebab-case")]` attribute
14919        // would silently desynchronize. Wiring [`std::fmt::Display`]
14920        // through [`PlacementStrategy::as_str`] closes the third path:
14921        // every `format!("{v}")` call reaches the same lifted
14922        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
14923        // and the [`PlacementStrategy::as_str`] helper already route
14924        // through, so a future variant rename lands at exactly one
14925        // place. Pin the routing here so a future
14926        // `impl std::fmt::Display for PlacementStrategy` reimplementation
14927        // that hand-rolls the arms instead of delegating to
14928        // [`PlacementStrategy::as_str`] fails at caixa-core build time.
14929        for variant in [
14930            PlacementStrategy::SingleNode,
14931            PlacementStrategy::Replicated,
14932            PlacementStrategy::Sharded,
14933        ] {
14934            assert_eq!(
14935                variant.to_string(),
14936                variant.as_str(),
14937                "PlacementStrategy::{variant:?} Display must route through \
14938                 PlacementStrategy::as_str (single source of truth: the lifted \
14939                 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
14940            );
14941        }
14942    }
14943
14944    #[test]
14945    fn placement_strategy_display_matches_serialized_wire_byte_string() {
14946        // The fail-before-pass-after pin on the second half of the
14947        // three-path convergence: `Display` (user-facing text) agrees
14948        // byte-for-byte with the `Serialize` derive's wire format
14949        // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
14950        // scalar) on every variant. Pre-lift the two paths were
14951        // structurally independent — a future
14952        // `#[serde(rename_all = "kebab-case")]` attribute on the enum
14953        // would silently rebrand the emitted wire scalar
14954        // (`single-node`, `replicated`, `sharded`) while every consumer
14955        // that pretty-prints the strategy (the M3 diagnostic templates,
14956        // the future `feira app graph` per-Aplicacao strategy line,
14957        // the future M4 CR materializer's admission-webhook rejection
14958        // body) would still emit the TitleCase form the `as_str` /
14959        // `Display` route returns, with the mismatch surfacing at
14960        // consumer parse time / operator dispatch time far from the
14961        // source rebrand commit. Pin the two paths byte-for-byte here
14962        // so any future serde-attribute or variant-rename drift is a
14963        // caixa-core-build-time test failure at this call, not a
14964        // silent per-consumer dispatch miss.
14965        for variant in [
14966            PlacementStrategy::SingleNode,
14967            PlacementStrategy::Replicated,
14968            PlacementStrategy::Sharded,
14969        ] {
14970            let wire = serde_json::to_string(&variant).unwrap();
14971            // Strip the outer `"…"` the JSON string form carries — the
14972            // wire scalar the K8s / YAML apiserver consumes is the
14973            // enclosed byte-string, not the quote wrapper.
14974            let unquoted = wire
14975                .strip_prefix('"')
14976                .and_then(|s| s.strip_suffix('"'))
14977                .expect("serialized PlacementStrategy is a JSON string");
14978            assert_eq!(
14979                variant.to_string(),
14980                unquoted,
14981                "PlacementStrategy::{variant:?} Display byte-string must match the \
14982                 Serialize derive's wire byte-string (three-path convergence: \
14983                 Display + as_str + Serialize all resolve to the same \
14984                 M3_PLACEMENT_ESTRATEGIA_* const)"
14985            );
14986        }
14987    }
14988
14989    #[test]
14990    fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
14991        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
14992        // derive on [`PlacementStrategy`]: for each of the three variants
14993        // exactly one of the generated `is_single_node` / `is_replicated`
14994        // / `is_sharded` predicates returns `true` and the other two
14995        // return `false`. Prior to this derive the three per-arm
14996        // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
14997        // (the `placement_strategy_variants_round_trip` fixture, the
14998        // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
14999        // fixture, and the
15000        // `validate_placement_reads_through_lifted_estrategia_accessor`
15001        // fixture) each open-coded a per-arm PartialEq compare against
15002        // the enum variant — three sites that expressed no compile-time
15003        // link back to the closed-set typed dispatch a future fourth
15004        // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
15005        // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
15006        // would have to thread through in lockstep or one fixture would
15007        // silently disagree with the others on which arms consume the
15008        // `:shard-key` axis. Peer of the sibling
15009        // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
15010        // / [`crate::supervisor::RestartPolicy`] /
15011        // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
15012        // the sibling closed-set typed-enum discriminator axes — extends
15013        // the same one-typed-dispatch-per-variant discipline onto the
15014        // fifth (and only remaining) closed-set typed-enum discriminator
15015        // on the caixa surface, closing the axis on the M3 mesh-slot
15016        // family.
15017        let rows: [(PlacementStrategy, [bool; 3]); 3] = [
15018            (PlacementStrategy::SingleNode, [true, false, false]),
15019            (PlacementStrategy::Replicated, [false, true, false]),
15020            (PlacementStrategy::Sharded, [false, false, true]),
15021        ];
15022        for (variant, expected) in rows {
15023            let observed = [
15024                variant.is_single_node(),
15025                variant.is_replicated(),
15026                variant.is_sharded(),
15027            ];
15028            assert_eq!(
15029                observed, expected,
15030                "PlacementStrategy::{variant:?} is_* predicates must partition \
15031                 the arm set (single_node, replicated, sharded); got {observed:?}"
15032            );
15033        }
15034    }
15035
15036    #[test]
15037    fn placement_strategy_is_variant_predicates_are_const_fn() {
15038        // The [`gen_platform::IsVariant`] derive emits `const fn`
15039        // predicates on the peer [`crate::CaixaKind`] +
15040        // [`crate::upgrade::UpgradeInstruction`] +
15041        // [`crate::supervisor::RestartStrategy`] +
15042        // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
15043        // pin the same posture on [`PlacementStrategy`] so a future
15044        // accidental downgrade to non-`const` (an added runtime helper
15045        // reachable only from a non-`const` context, a manual hand-rolled
15046        // `impl` that shadows the derive-generated method) trips at
15047        // caixa-core build time rather than surfacing as a downstream
15048        // `const`-context regression far from the derive declaration.
15049        const IS_SINGLE_NODE: bool = PlacementStrategy::SingleNode.is_single_node();
15050        const IS_REPLICATED: bool = PlacementStrategy::Replicated.is_replicated();
15051        const IS_SHARDED: bool = PlacementStrategy::Sharded.is_sharded();
15052        assert!(IS_SINGLE_NODE);
15053        assert!(IS_REPLICATED);
15054        assert!(IS_SHARDED);
15055    }
15056
15057    #[test]
15058    fn placement_strategy_requires_shard_key_partitions_the_arm_set() {
15059        // Fail-before-pass-after pin on the substrate-lifted
15060        // [`PlacementStrategy::requires_shard_key`] cross-slot-invariant
15061        // per-arm predicate: for each variant in the closed accept-set the
15062        // predicate returns `true` iff the variant consumes the paired
15063        // [`Placement::shard_key`] axis under
15064        // [`AplicacaoSpec::validate_placement`]'s `Sharded` ↔ non-`Sharded`
15065        // partition. Today the accept-set is the singleton `{Sharded}` —
15066        // `Sharded` is the Akka-style hash-keyed distribution arm
15067        // (MESH-COMPOSITION §II.4), `SingleNode` (Erlang/OTP takeover —
15068        // §II.1) and `Replicated` (active-active) refuse the axis through
15069        // [`AplicacaoError::ShardKeyOnNonSharded`].
15070        //
15071        // Pins the per-arm truth-table so a future arm addition (an
15072        // `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint the
15073        // roadmap names, a `WeightedShard` promotion the future M5
15074        // adaptive-placement engine acknowledges) that landed a variant
15075        // without extending this predicate's arm-set would surface as a
15076        // caixa-core build-time exhaustiveness error at the
15077        // `match self { … }` arm-fan below rather than a silent per-consumer
15078        // mis-classification at renderer emit time. The paired
15079        // [`Self::is_sharded`] `gen_platform::IsVariant`-derived arm-identity
15080        // predicate stays a distinct question — arm-identity (which the
15081        // sibling
15082        // [`placement_strategy_is_variant_predicates_partition_the_arm_set`]
15083        // pin already locks) is not cross-slot-invariant consumption; today
15084        // they trip on the same singleton but the pair migrates through
15085        // one caixa-core edit on any future arm addition.
15086        //
15087        // Peer of the sibling per-arm classifier pins
15088        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
15089        // (7b97d26) on the [`WitContract`] pre-projection WIT-shape axis
15090        // and the [`WitTarget::is_capability`] `gen_platform::IsVariant`-
15091        // derived paired predicate on the post-projection typed-view axis
15092        // — same "per-arm semantic-classification predicate paired with
15093        // the arm-identity predicate the derive already emits" discipline
15094        // extended onto the M3 mesh-slot `:placement :estrategia` ↔
15095        // `:placement :shard-key` cross-slot-invariant axis.
15096        let rows: [(PlacementStrategy, bool); 3] = [
15097            (PlacementStrategy::SingleNode, false),
15098            (PlacementStrategy::Replicated, false),
15099            (PlacementStrategy::Sharded, true),
15100        ];
15101        for (variant, expected) in rows {
15102            assert_eq!(
15103                variant.requires_shard_key(),
15104                expected,
15105                "PlacementStrategy::{variant:?}.requires_shard_key() must \
15106                 be {expected} (the substrate-canonical cross-slot invariant \
15107                 on the :placement :shard-key axis; today `Sharded` is the \
15108                 singleton consuming arm — MESH-COMPOSITION §II.4)",
15109            );
15110        }
15111    }
15112
15113    #[test]
15114    fn placement_strategy_requires_shard_key_is_const_fn() {
15115        // The [`PlacementStrategy::requires_shard_key`] cross-slot-
15116        // invariant per-arm predicate is declared `#[must_use] pub const
15117        // fn` — pin the `const`-eval posture here so a future accidental
15118        // downgrade to non-`const` (an added runtime helper reachable
15119        // only from a non-`const` context, a manual hand-rolled `impl`
15120        // that shadows the current three-arm `match self { … }` dispatch)
15121        // trips at caixa-core build time rather than surfacing as a
15122        // downstream `const`-context regression far from the declaration.
15123        // Same shape as the sibling
15124        // [`placement_strategy_is_variant_predicates_are_const_fn`] pin on
15125        // the peer [`gen_platform::IsVariant`]-derived arm-identity
15126        // predicate axis, but here the load-bearing assertions live in
15127        // module-scope `const _: () = assert!(…)` items so a violation
15128        // fails at compile time (const-eval trip) rather than test time —
15129        // strictly stronger than the runtime `assert!(CONST)` pattern the
15130        // sibling pin uses, and side-steps the
15131        // `clippy::assertions_on_constants` lint the runtime pattern
15132        // otherwise accumulates on the module baseline.
15133        //
15134        // The test body simply witnesses that the module-scope items
15135        // compiled and the runtime dispatch agrees with the const-eval
15136        // dispatch on every arm — the runtime read gives the test a
15137        // failure surface (rather than an empty test body clippy would
15138        // flag as a no-op).
15139        const REQUIRES_SINGLE_NODE: bool = PlacementStrategy::SingleNode.requires_shard_key();
15140        const REQUIRES_REPLICATED: bool = PlacementStrategy::Replicated.requires_shard_key();
15141        const REQUIRES_SHARDED: bool = PlacementStrategy::Sharded.requires_shard_key();
15142        assert_eq!(
15143            [REQUIRES_SINGLE_NODE, REQUIRES_REPLICATED, REQUIRES_SHARDED,],
15144            [
15145                PlacementStrategy::SingleNode.requires_shard_key(),
15146                PlacementStrategy::Replicated.requires_shard_key(),
15147                PlacementStrategy::Sharded.requires_shard_key(),
15148            ],
15149            "runtime and const-eval dispatch on \
15150             PlacementStrategy::requires_shard_key must agree on every arm",
15151        );
15152    }
15153
15154    #[test]
15155    fn placement_estrategia_accessor_is_const_fn() {
15156        // The [`Placement::estrategia`] per-`:placement` distribution-
15157        // strategy `Copy`-return scalar accessor is declared
15158        // `#[must_use] pub const fn` — matching the peer M3 mesh-slot
15159        // `Copy`-return accessor family ([`MeshPolicy::timeout`] /
15160        // [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
15161        // [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`]
15162        // on the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`]
15163        // / [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
15164        // [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
15165        // [`RateLimit`], every one a `pub const fn`). Pin the
15166        // `const`-eval posture here so a future accidental downgrade to
15167        // non-`const` (an added runtime helper reachable only from a
15168        // non-`const` context, a slot promotion to a non-`Copy` return
15169        // that would silently drop the `const` qualifier, a manual
15170        // hand-rolled shadow) trips at caixa-core build time rather
15171        // than surfacing as a downstream `const`-context regression far
15172        // from the declaration.
15173        //
15174        // Same shape as the sibling
15175        // [`placement_strategy_requires_shard_key_is_const_fn`] pin on
15176        // the peer [`PlacementStrategy::requires_shard_key`] `const fn`
15177        // predicate axis — the load-bearing witness lives in the
15178        // module-scope `const fn` wrapper `estrategia_via_const_fn`
15179        // below: a body that calls [`Placement::estrategia`] under a
15180        // `const fn` signature is well-formed only when the callee is
15181        // itself `const fn`, so any future accidental downgrade of
15182        // [`Placement::estrategia`] to non-`const` fails at caixa-core
15183        // build time (const-eval E0015 / E0658 depending on the arm),
15184        // strictly stronger than a runtime `assert!(CONST)` and
15185        // side-stepping the destructor-in-const restriction that
15186        // blocks direct `const _: PlacementStrategy = FIXTURE.estrategia()`
15187        // items on `Placement`'s `Vec<String>` / `Option<String>`
15188        // carriers.
15189        //
15190        // The runtime body witnesses that the const-eval-shaped
15191        // wrapper agrees with a direct call on every closed-set arm.
15192        const fn estrategia_via_const_fn(p: &Placement) -> PlacementStrategy {
15193            p.estrategia()
15194        }
15195        for estrategia in [
15196            PlacementStrategy::SingleNode,
15197            PlacementStrategy::Replicated,
15198            PlacementStrategy::Sharded,
15199        ] {
15200            let placement = Placement {
15201                estrategia,
15202                clusters: Vec::new(),
15203                affinity: None,
15204                shard_key: None,
15205            };
15206            assert_eq!(
15207                estrategia_via_const_fn(&placement),
15208                placement.estrategia(),
15209                "const-fn-wrapped and direct dispatch on \
15210                 Placement::estrategia must agree for {estrategia:?}",
15211            );
15212        }
15213    }
15214
15215    #[test]
15216    fn entrada_port_accessor_is_const_fn() {
15217        // The [`Entrada::port`] per-`:entrada` L4-port `Copy`-return
15218        // scalar accessor is declared `#[must_use] pub const fn` —
15219        // matching the peer M3 mesh-slot `Copy`-return accessor family
15220        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`] /
15221        // [`MeshPolicy::mtls_required`] / [`MeshPolicy::rate_limit`] /
15222        // [`MeshPolicy::circuit_breaker`] on the parent [`MeshPolicy`],
15223        // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
15224        // on the sibling [`CircuitBreaker`], [`RateLimit::rate`] /
15225        // [`RateLimit::window`] on the sibling [`RateLimit`], the
15226        // sibling per-`:placement` [`Placement::estrategia`] pinned by
15227        // [`placement_estrategia_accessor_is_const_fn`] above — every
15228        // one a `pub const fn`). Pin the `const`-eval posture here so
15229        // a future accidental downgrade to non-`const` (an added
15230        // runtime helper reachable only from a non-`const` context, an
15231        // `Option<u16>`-shape migration once the substrate grows
15232        // per-`:membros` heterogeneous listener ports that would
15233        // silently drop the `const` qualifier, a manual hand-rolled
15234        // shadow) trips at caixa-core build time rather than surfacing
15235        // as a downstream `const`-context regression far from the
15236        // declaration.
15237        //
15238        // Same shape as the sibling
15239        // [`placement_estrategia_accessor_is_const_fn`] pin above — the
15240        // load-bearing witness lives in the module-scope `const fn`
15241        // wrapper `port_via_const_fn`: a body that calls
15242        // [`Entrada::port`] under a `const fn` signature is well-formed
15243        // only when the callee is itself `const fn`, side-stepping the
15244        // destructor-in-const restriction that would otherwise block a
15245        // direct `const _: u16 = FIXTURE.port()` item on `Entrada`'s
15246        // `String` / `Vec<String>` carriers.
15247        //
15248        // The runtime body sweeps a representative port set spanning
15249        // the [`SERVICO_PORT_MIN`] floor, the substrate-canonical
15250        // [`DEFAULT_SERVICO_PORT`] default, and the top-edge `u16::MAX`
15251        // ceiling — the const-fn-wrapped call must agree with a direct
15252        // call on every fixture (a violation trips the test) and every
15253        // returned scalar must byte-equal the input `port` (a violation
15254        // means the accessor stopped being a raw field-return copy).
15255        const fn port_via_const_fn(e: &Entrada) -> u16 {
15256            e.port()
15257        }
15258        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, u16::MAX] {
15259            let entrada = Entrada {
15260                host: String::new(),
15261                para: String::new(),
15262                port,
15263                paths: Vec::new(),
15264            };
15265            assert_eq!(
15266                port_via_const_fn(&entrada),
15267                entrada.port(),
15268                "const-fn-wrapped and direct dispatch on Entrada::port \
15269                 must agree for port={port}",
15270            );
15271            assert_eq!(
15272                entrada.port(),
15273                port,
15274                "Entrada::port must return the storage-side u16 verbatim \
15275                 for port={port}",
15276            );
15277        }
15278    }
15279
15280    #[test]
15281    fn validate_placement_admits_paired_shape_iff_strategy_requires_shard_key() {
15282        // Load-bearing cross-slot-partition pin closing the loop between
15283        // the substrate-lifted
15284        // [`PlacementStrategy::requires_shard_key`] per-arm predicate on
15285        // the closed-set typed enum and the actual
15286        // [`AplicacaoSpec::validate_placement`] runtime behavior across
15287        // the paired `:placement :shard-key` axis: every validated
15288        // [`Placement`] past [`AplicacaoSpec::validate_placement`]
15289        // satisfies `placement.shard_key().is_some() ==
15290        // placement.estrategia().requires_shard_key()`. The four-cell
15291        // shape witness sweeps every combination of (variant in the
15292        // closed accept-set, `:shard-key` Some/None) and pins:
15293        //
15294        //   * variant.requires_shard_key() && shard_key.is_some() →
15295        //     validate() passes; the paired shape is the sole
15296        //     `requires_shard_key` arm-family accepted shape.
15297        //   * variant.requires_shard_key() && shard_key.is_none() →
15298        //     validate() fails with [`AplicacaoError::ShardedWithoutKey`];
15299        //     the paired shape is the refused missing-key shape on
15300        //     Sharded-family arms.
15301        //   * !variant.requires_shard_key() && shard_key.is_some() →
15302        //     validate() fails with
15303        //     [`AplicacaoError::ShardKeyOnNonSharded`]; the paired shape
15304        //     is the refused declared-but-inert shape on non-Sharded-
15305        //     family arms.
15306        //   * !variant.requires_shard_key() && shard_key.is_none() →
15307        //     validate() passes; the paired shape is the sole
15308        //     non-`requires_shard_key` arm-family accepted shape.
15309        //
15310        // The compile-time-exhaustive `match p.estrategia()` dispatch at
15311        // [`AplicacaoSpec::validate_placement`] preserves its structural
15312        // arm-fan (a future arm addition still surfaces a build-time
15313        // exhaustiveness error there); this pin closes the semantic loop
15314        // between the arm-fan's shape-gate cascades and the substrate-
15315        // canonical predicate every downstream consumer of the paired
15316        // shape reads through. Fail-before-pass-after locally verified by
15317        // mutating the predicate's `Sharded => true` arm to `false` — the
15318        // truthy `expects_ok` cell for `Sharded` + `Some` trips the
15319        // `validate() must pass` assertion; restoring passes. Same "close
15320        // the loop between the typed predicate and the runtime behavior"
15321        // discipline as the sibling
15322        // [`wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant`]
15323        // (7b97d26) cross-projection pin on the peer [`WitTarget`]
15324        // per-arm classifier axis.
15325        for variant in [
15326            PlacementStrategy::SingleNode,
15327            PlacementStrategy::Replicated,
15328            PlacementStrategy::Sharded,
15329        ] {
15330            for present in [false, true] {
15331                let mut spec = three_member_spec();
15332                spec.placement.estrategia = variant;
15333                spec.placement.shard_key = present.then(|| "tenantId".into());
15334                let expects_ok = variant.requires_shard_key() == present;
15335                let result = spec.validate();
15336                match (expects_ok, &result) {
15337                    (true, Ok(())) => {}
15338                    (false, Err(err)) => {
15339                        // Cross-check the refusal diagnostic names the
15340                        // right cell of the four-cell shape witness — the
15341                        // `requires_shard_key && !present` cell must trip
15342                        // [`AplicacaoError::ShardedWithoutKey`]; the
15343                        // `!requires_shard_key && present` cell must trip
15344                        // [`AplicacaoError::ShardKeyOnNonSharded`].
15345                        match (variant.requires_shard_key(), present, err) {
15346                            (true, false, AplicacaoError::ShardedWithoutKey) => {}
15347                            (
15348                                false,
15349                                true,
15350                                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. },
15351                            ) => {
15352                                assert_eq!(
15353                                    *e, variant,
15354                                    "ShardKeyOnNonSharded.estrategia must byte-equal \
15355                                     the paired PlacementStrategy",
15356                                );
15357                            }
15358                            _ => panic!(
15359                                "unexpected refusal for estrategia={variant:?} \
15360                                 present={present}: {err:?}"
15361                            ),
15362                        }
15363                    }
15364                    (true, Err(err)) => panic!(
15365                        "validate() must pass for estrategia={variant:?} \
15366                         present={present} (requires_shard_key={} == present={present}), \
15367                         got {err:?}",
15368                        variant.requires_shard_key(),
15369                    ),
15370                    (false, Ok(())) => panic!(
15371                        "validate() must fail for estrategia={variant:?} \
15372                         present={present} (requires_shard_key={} != present={present})",
15373                        variant.requires_shard_key(),
15374                    ),
15375                }
15376            }
15377        }
15378    }
15379
15380    #[test]
15381    fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
15382        // Pin the M3 diagnostic template routes through the typed
15383        // [`PlacementStrategy`] Display byte-string (rebound from the
15384        // prior `{estrategia:?}` `Debug` route). Pre-lift the two
15385        // routes emitted identical bytes (the `Debug` derive on a
15386        // unit variant emits the variant name verbatim, exactly what
15387        // `as_str` returns), but the two paths were structurally
15388        // independent — a future `#[serde(rename_all = "…")]`
15389        // attribute or variant rename would coordinate the wire /
15390        // `Display` / `as_str` triple through the lifted const but
15391        // leave the `Debug` route on the compiler-derived variant name,
15392        // silently desynchronizing the diagnostic byte-string from the
15393        // wire byte-string. Rebinding the template onto `Display`
15394        // ties the diagnostic to the same lifted
15395        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
15396        // emits — drift becomes structurally impossible. Pin the
15397        // byte-string here so a future edit that reverts the template
15398        // to `{estrategia:?}` is caught at caixa-core test time, not
15399        // at consumer dispatch time.
15400        for (variant, expected_scalar) in [
15401            (
15402                PlacementStrategy::SingleNode,
15403                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15404            ),
15405            (
15406                PlacementStrategy::Replicated,
15407                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15408            ),
15409            (
15410                PlacementStrategy::Sharded,
15411                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
15412            ),
15413        ] {
15414            let err = AplicacaoError::PlacementWithoutClusters {
15415                estrategia: variant,
15416            };
15417            let msg = err.to_string();
15418            assert!(
15419                msg.starts_with(&format!(":placement {expected_scalar} requires")),
15420                "PlacementWithoutClusters diagnostic for {variant:?} must open \
15421                 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
15422            );
15423        }
15424    }
15425
15426    #[test]
15427    fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
15428        // Peer of
15429        // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
15430        // on the second M3 diagnostic that carries the typed
15431        // [`PlacementStrategy`] in its `#[error(…)]` template. Both
15432        // diagnostics now route the strategy scalar through the same
15433        // [`std::fmt::Display`] surface, tying the diagnostic
15434        // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
15435        // const set the wire format also emits. The two non-Sharded
15436        // arms are exercised here (the diagnostic exists to flag a
15437        // `:shard-key` slot the current strategy will never consume);
15438        // the peer `Sharded` arm never reaches this diagnostic (the
15439        // `Sharded` strategy consumes `:shard-key` — the
15440        // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
15441        // slot instead).
15442        for (variant, expected_scalar) in [
15443            (
15444                PlacementStrategy::SingleNode,
15445                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15446            ),
15447            (
15448                PlacementStrategy::Replicated,
15449                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15450            ),
15451        ] {
15452            let err = AplicacaoError::ShardKeyOnNonSharded {
15453                estrategia: variant,
15454                shard_key: "$tenantId".into(),
15455            };
15456            let msg = err.to_string();
15457            assert!(
15458                msg.starts_with(&format!(":placement {expected_scalar} carries")),
15459                "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
15460                 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
15461            );
15462        }
15463    }
15464
15465    #[test]
15466    fn placement_strategy_all_enumerates_every_variant_once() {
15467        // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
15468        // exhaustive-iteration surface: every variant appears exactly
15469        // once, and the slice length matches the arm count of the
15470        // closed set. Every consumer that walks the accepted-strategy
15471        // set (a future `feira app placement --list` CLI-side surfacing,
15472        // a future M4 admission-webhook's rejection body naming the
15473        // accepted-strategy list, the [`PlacementStrategy::from_wire`]
15474        // reverse-projection consumers that iterate the accept-set for
15475        // a "did you mean" hint) reads through this slice, so a future
15476        // variant addition (an `Anycast` mesh-anycast arm the
15477        // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
15478        // grows the enum but forgets to grow [`Self::ALL`] silently
15479        // truncates every downstream consumer's accept-set at the same
15480        // pre-addition boundary — this pin fails at caixa-core build
15481        // time on the pairwise-distinct + arm-count invariants.
15482        //
15483        // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
15484        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
15485        // pins on the peer closed-set typed-enum axes.
15486        let all: &[PlacementStrategy] = PlacementStrategy::ALL;
15487        assert_eq!(
15488            all.len(),
15489            3,
15490            "PlacementStrategy::ALL must enumerate every variant of the \
15491             three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
15492        );
15493        for (i, a) in all.iter().enumerate() {
15494            for (j, b) in all.iter().enumerate() {
15495                if i != j {
15496                    assert_ne!(
15497                        a, b,
15498                        "PlacementStrategy::ALL must carry every variant exactly \
15499                         once — got duplicate {a:?} at indices {i} and {j}"
15500                    );
15501                }
15502            }
15503        }
15504        for variant in [
15505            PlacementStrategy::SingleNode,
15506            PlacementStrategy::Replicated,
15507            PlacementStrategy::Sharded,
15508        ] {
15509            assert!(
15510                all.contains(&variant),
15511                "PlacementStrategy::ALL must contain {variant:?} — a future variant \
15512                 addition that grows the enum but forgets to grow the ALL slice \
15513                 silently truncates every downstream consumer's accept-set at the \
15514                 pre-addition boundary"
15515            );
15516        }
15517    }
15518
15519    #[test]
15520    fn placement_strategy_from_wire_accepts_every_lifted_constant() {
15521        // Fail-before-pass-after pin on the forward accept-set of the
15522        // [`PlacementStrategy::from_wire`] reverse projection: every
15523        // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
15524        // constant the [`PlacementStrategy::as_str`] emitter walks
15525        // parses back to its paired variant. Any future arm addition
15526        // that grows the emitter's `as_str` match but forgets to grow
15527        // the parser's `from_str` match silently splits the two halves
15528        // of the round-trip — the wire byte-string one non-serde
15529        // consumer parses from the one the emitter wrote — with the
15530        // failure surfacing at parse time far from the rebrand commit.
15531        // Pinning the three-arm accept-set here catches the drift at
15532        // caixa-core build time.
15533        //
15534        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
15535        // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
15536        // closed-set typed-enum `str → Self` axes.
15537        for (wire, expected) in [
15538            (
15539                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15540                PlacementStrategy::SingleNode,
15541            ),
15542            (
15543                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15544                PlacementStrategy::Replicated,
15545            ),
15546            (
15547                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
15548                PlacementStrategy::Sharded,
15549            ),
15550        ] {
15551            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
15552                panic!(
15553                    "PlacementStrategy::from_wire({wire:?}) must accept every \
15554                     M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
15555                     lifted canonical byte-string that PlacementStrategy::{expected:?} \
15556                     serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
15557                )
15558            });
15559            assert_eq!(
15560                parsed, expected,
15561                "PlacementStrategy::from_wire({wire:?}) must return \
15562                 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
15563            );
15564        }
15565    }
15566
15567    #[test]
15568    fn placement_strategy_from_wire_round_trips_through_as_str() {
15569        // Fail-before-pass-after pin on the closed round-trip between
15570        // the forward [`PlacementStrategy::as_str`] emitter and the
15571        // reverse [`PlacementStrategy::from_wire`] parser: for every
15572        // variant in [`PlacementStrategy::ALL`], parsing the emitter's
15573        // output must return exactly the same variant. Any per-arm
15574        // divergence — a future arm added to `as_str` but not
15575        // `from_str`, an accidental copy-paste flip in one but not the
15576        // other — silently splits the emit and parse halves and the
15577        // failure surfaces at consumer parse time far from the drift
15578        // site. The `ALL`-iterating shape means a future variant
15579        // addition picks up the coverage by construction.
15580        //
15581        // Peer of the sibling [`crate::kind::tests`] round-trip pin on
15582        // [`crate::CaixaKind::from_wire`] and the
15583        // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
15584        // sibling round-trip pin on [`RateLimitUnit`].
15585        for &variant in PlacementStrategy::ALL {
15586            let wire = variant.as_str();
15587            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
15588                panic!(
15589                    "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
15590                     must be Some({variant:?}) — the two halves of the round-trip \
15591                     dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
15592                     got None on wire byte-string {wire:?}"
15593                )
15594            });
15595            assert_eq!(
15596                parsed, variant,
15597                "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
15598                 must round-trip to the same variant; got {parsed:?}"
15599            );
15600        }
15601    }
15602
15603    #[test]
15604    fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
15605        // Fail-before-pass-after pin on the closed-set refusal
15606        // discipline of [`PlacementStrategy::from_wire`]: every
15607        // byte-string outside the three-arm accept-set returns `None`
15608        // rather than silently collapsing onto the [`Default`]
15609        // (`Replicated`) arm or an arbitrary neighbor. The refusal set
15610        // exercised here sweeps the load-bearing drift shapes: the
15611        // empty string (a stripped serde-attribute drift), an all-
15612        // whitespace string (the canonical text-editor accidental
15613        // padding shape), the lowercased kebab-case forms a future
15614        // `#[serde(rename_all = "kebab-case")]` attribute would emit
15615        // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
15616        // coincidentally match the accepted canonical scalars, so only
15617        // `"single-node"` fires as a refusal, but pinning the case-
15618        // sensitivity of the accepted arms via the peer [`SingleNode`]
15619        // assertion in the round-trip pin makes the discipline
15620        // structurally clear), the lowercased single-word forms
15621        // (`"singlenode"`), the padded canonical scalar
15622        // (`" Sharded "`), the trailing-comma / trailing-newline shapes
15623        // (`"Sharded\n"`), and a pointer-different `&'static str` that
15624        // happens to alias a canonical byte-string by content but not
15625        // by identity (validated implicitly by the emitter's routing
15626        // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
15627        // identity a paired [`crate::assert_str_reexport_identity`] pin
15628        // in caixa-core's per-const declaration surface would catch).
15629        //
15630        // Peer of the sibling
15631        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
15632        // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
15633        for bad in [
15634            "",
15635            " ",
15636            "\n",
15637            "\t",
15638            "single-node",
15639            "singlenode",
15640            "SingleNodes",
15641            "single_node",
15642            "single node",
15643            "SINGLENODE",
15644            "SingleNode ",
15645            " SingleNode",
15646            " Sharded ",
15647            "Sharded\n",
15648            "replicated ",
15649            "sharded",
15650            "REPLICATED",
15651            "Anycast",
15652            "Global",
15653            "?",
15654        ] {
15655            assert!(
15656                PlacementStrategy::from_wire(bad).is_none(),
15657                "PlacementStrategy::from_wire({bad:?}) must return None — the \
15658                 parser's accept-set is exactly the three PlacementStrategy::as_str \
15659                 outputs (SingleNode, Replicated, Sharded), and this byte-string \
15660                 is outside that closed set"
15661            );
15662        }
15663    }
15664
15665    #[test]
15666    fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
15667        // Fail-before-pass-after pin on the third path of the four-path
15668        // convergence: `from_str` (the reverse projection) inverts the
15669        // `Serialize` derive's wire byte-string on every variant.
15670        // Together with the pre-existing three-path convergence
15671        // (`Display` + `as_str` + `Serialize` all resolve to the same
15672        // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
15673        // the peer
15674        // [`placement_strategy_display_matches_serialized_wire_byte_string`])
15675        // this closes the round-trip: the wire byte-string the
15676        // `Serialize` derive emits parses back to the same variant
15677        // through `from_str`, so any future serde-attribute or variant-
15678        // rename drift on the emit half now surfaces as a matched drift
15679        // on the parse half at caixa-core build time — the two halves
15680        // migrate as a unit through the lifted consts on any future
15681        // rename, and the round-trip cannot silently split.
15682        //
15683        // Peer of the sibling
15684        // [`placement_strategy_display_matches_serialized_wire_byte_string`]
15685        // wire-format pin — extends the three-path convergence
15686        // (`Display` + `as_str` + `Serialize`) onto the fourth path
15687        // (`from_str`), closing the `str ↔ Self` round-trip on the
15688        // M3 `:placement :estrategia` closed-set axis.
15689        for &variant in PlacementStrategy::ALL {
15690            let wire = serde_json::to_string(&variant).unwrap();
15691            let unquoted = wire
15692                .strip_prefix('"')
15693                .and_then(|s| s.strip_suffix('"'))
15694                .expect("serialized PlacementStrategy is a JSON string");
15695            let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
15696                panic!(
15697                    "PlacementStrategy::from_wire({unquoted:?}) must accept the \
15698                     Serialize derive's wire byte-string for \
15699                     PlacementStrategy::{variant:?} — the four-path convergence \
15700                     (Display + as_str + Serialize + from_str) resolves through \
15701                     the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
15702                )
15703            });
15704            assert_eq!(
15705                parsed, variant,
15706                "PlacementStrategy::from_wire of the Serialize derive's wire \
15707                 byte-string for PlacementStrategy::{variant:?} must round-trip \
15708                 to the same variant; got {parsed:?}"
15709            );
15710        }
15711    }
15712
15713    #[test]
15714    fn rejects_zero_policy_timeout() {
15715        let mut s = three_member_spec();
15716        s.politicas.timeout = Some(Duration::ZERO);
15717        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
15718    }
15719
15720    #[test]
15721    fn rejects_zero_policy_retries() {
15722        let mut s = three_member_spec();
15723        s.politicas.retries = Some(0);
15724        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
15725    }
15726
15727    #[test]
15728    fn rejects_policy_retries_above_cap() {
15729        // The fail-before-pass-after pin: `Some(11)` is structurally
15730        // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
15731        // passed validate on every pre-gate codebase because the
15732        // typed slot's only check was the zero-floor arm. The
15733        // thundering-herd amplification vector only surfaced at the
15734        // runtime substrate (Envoy / Cilium L7 retry overlay)
15735        // far from the source caixa.lisp with no field naming the
15736        // offending policy.
15737        let mut s = three_member_spec();
15738        s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
15739        assert_eq!(
15740            s.validate().unwrap_err(),
15741            AplicacaoError::PolicyRetriesExceedsCap {
15742                retries: POLICY_RETRIES_MAX + 1
15743            }
15744        );
15745    }
15746
15747    #[test]
15748    fn rejects_policy_retries_far_above_cap() {
15749        // The `u32::MAX` worst case — the four-billion-retry policy
15750        // a typo (`(:retries 4294967295)`) or struct-literal
15751        // copy-paste lands in the slot. Pin the cap arm's coverage
15752        // explicitly across the full `u32` overflow so a future
15753        // relaxation that drops the upper bound surfaces here.
15754        let mut s = three_member_spec();
15755        s.politicas.retries = Some(u32::MAX);
15756        assert_eq!(
15757            s.validate().unwrap_err(),
15758            AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
15759        );
15760    }
15761
15762    #[test]
15763    fn accepts_policy_retries_at_cap() {
15764        // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
15765        // must validate. The cap is inclusive on the top edge,
15766        // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
15767        // discipline on the sibling [`crate::LimitsSpec::memory`]
15768        // axis. Pin the boundary explicitly so a future off-by-one
15769        // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
15770        // surfaces here as a test failure rather than a silent
15771        // contract narrowing.
15772        let mut s = three_member_spec();
15773        s.politicas.retries = Some(POLICY_RETRIES_MAX);
15774        s.validate()
15775            .expect("retries == POLICY_RETRIES_MAX must validate");
15776    }
15777
15778    #[test]
15779    fn accepts_policy_retries_typical_values() {
15780        // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
15781        // every value in the validated set must pass. The
15782        // Envoy / Istio production-playbook recommendation band
15783        // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
15784        // (`maxRetries ≤ 10`) both lie within this set.
15785        for r in 1..=POLICY_RETRIES_MAX {
15786            let mut s = three_member_spec();
15787            s.politicas.retries = Some(r);
15788            s.validate()
15789                .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
15790        }
15791    }
15792
15793    #[test]
15794    fn policy_retries_zero_takes_precedence_over_cap() {
15795        // The cross-arm ordering pin: `Some(0)` is structurally
15796        // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
15797        // (cap), but the zero-floor diagnostic is the more
15798        // self-locating one (it directly names the omit-axis
15799        // remediation), so the validate gate must fire on zero
15800        // first. Pin the order so a future refactor that reorders
15801        // the arms surfaces here as a test failure rather than a
15802        // silent diagnostic regression. Same shape every other
15803        // zero-then-shape ordering on this surface uses
15804        // ([`AplicacaoError::PolicyTimeoutZero`] then
15805        // [`AplicacaoError::PolicyTimeoutNotCanonical`];
15806        // [`AplicacaoError::PolicyBreakerZeroWindow`] then
15807        // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
15808        let mut s = three_member_spec();
15809        s.politicas.retries = Some(0);
15810        assert_eq!(
15811            s.validate().unwrap_err(),
15812            AplicacaoError::PolicyRetriesZero,
15813            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
15814        );
15815    }
15816
15817    #[test]
15818    fn policy_retries_cap_diagnostic_carries_offending_value() {
15819        // The diagnostic-shape pin: the offending `u32` is carried
15820        // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
15821        // variant so the surfaced error message names the value the
15822        // author wrote (`":politicas :retries (47) exceeds the
15823        // mesh-policy ceiling …"`), not just the cap. Same
15824        // self-locating diagnostic shape every other typed-cap arm
15825        // on this surface carries
15826        // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
15827        // offending byte count verbatim).
15828        let mut s = three_member_spec();
15829        s.politicas.retries = Some(47);
15830        let err = s.validate().unwrap_err();
15831        assert!(
15832            matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
15833            "got {err:?}"
15834        );
15835        let msg = err.to_string();
15836        assert!(
15837            msg.contains("47"),
15838            ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
15839        );
15840    }
15841
15842    #[test]
15843    fn policy_retries_cap_is_aws_app_mesh_aligned() {
15844        // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
15845        // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
15846        // schema cap — the only upstream mesh-policy schema that
15847        // documents an explicit hard cap. Pinning the literal value
15848        // here surfaces a future drift (a relaxation to 20, a
15849        // tightening to 5) as a deliberate test edit, not a silent
15850        // contract narrowing.
15851        assert_eq!(POLICY_RETRIES_MAX, 10);
15852    }
15853
15854    #[test]
15855    fn rejects_circuit_breaker_zero_max_failures() {
15856        let mut s = three_member_spec();
15857        s.politicas.circuit_breaker = Some(CircuitBreaker {
15858            max_failures: 0,
15859            window: Duration::from_secs(60),
15860        });
15861        assert_eq!(
15862            s.validate().unwrap_err(),
15863            AplicacaoError::PolicyBreakerZeroFailures
15864        );
15865    }
15866
15867    #[test]
15868    fn rejects_circuit_breaker_max_failures_above_cap() {
15869        // The fail-before-pass-after pin: `1001` is structurally one
15870        // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
15871        // silently passed validate on every pre-gate codebase
15872        // because the typed slot's only check was the zero-floor
15873        // arm. The breaker-no-op vector only surfaced at the runtime
15874        // substrate (Envoy / Cilium L7 outlier-detection overlay)
15875        // far from the source caixa.lisp with no field naming the
15876        // offending policy.
15877        let mut s = three_member_spec();
15878        s.politicas.circuit_breaker = Some(CircuitBreaker {
15879            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
15880            window: Duration::from_secs(60),
15881        });
15882        assert_eq!(
15883            s.validate().unwrap_err(),
15884            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
15885                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
15886            }
15887        );
15888    }
15889
15890    #[test]
15891    fn rejects_circuit_breaker_max_failures_far_above_cap() {
15892        // The `u32::MAX` worst case — the four-billion-failure
15893        // threshold a typo (`(:max-failures 4294967295)`) or a
15894        // struct-literal copy-paste lands in the slot. Pin the cap
15895        // arm's coverage explicitly across the full `u32` overflow
15896        // so a future relaxation that drops the upper bound surfaces
15897        // here.
15898        let mut s = three_member_spec();
15899        s.politicas.circuit_breaker = Some(CircuitBreaker {
15900            max_failures: u32::MAX,
15901            window: Duration::from_secs(60),
15902        });
15903        assert_eq!(
15904            s.validate().unwrap_err(),
15905            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
15906                max_failures: u32::MAX,
15907            }
15908        );
15909    }
15910
15911    #[test]
15912    fn accepts_circuit_breaker_max_failures_at_cap() {
15913        // The boundary value — exactly
15914        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
15915        // cap is inclusive on the top edge, matching the
15916        // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
15917        // discipline on the sibling capped axes. Pin the boundary
15918        // explicitly so a future off-by-one tightening
15919        // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
15920        // surfaces here as a test failure rather than a silent
15921        // contract narrowing.
15922        let mut s = three_member_spec();
15923        s.politicas.circuit_breaker = Some(CircuitBreaker {
15924            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
15925            window: Duration::from_secs(60),
15926        });
15927        s.validate()
15928            .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
15929    }
15930
15931    #[test]
15932    fn accepts_circuit_breaker_max_failures_typical_values() {
15933        // The documented production-playbook band positive-control
15934        // sweep — every value Hystrix / Istio / Envoy / Polly /
15935        // Resilience4j recommend (5..=50) must pass, plus a sweep
15936        // through the hyperscale band (100, 500, 1000) the cap
15937        // accepts. Pin the inclusive validated set explicitly so a
15938        // future tightening of the ceiling surfaces here.
15939        for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
15940            let mut s = three_member_spec();
15941            s.politicas.circuit_breaker = Some(CircuitBreaker {
15942                max_failures: n,
15943                window: Duration::from_secs(60),
15944            });
15945            s.validate()
15946                .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
15947        }
15948    }
15949
15950    #[test]
15951    fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
15952        // The cross-arm ordering pin: `0` is structurally outside
15953        // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
15954        // (cap), but the zero-floor diagnostic is the more
15955        // self-locating one (it directly names the omit-axis
15956        // remediation), so the validate gate must fire on zero
15957        // first. Same shape every other zero-then-shape ordering on
15958        // this surface uses
15959        // ([`AplicacaoError::PolicyRetriesZero`] then
15960        // [`AplicacaoError::PolicyRetriesExceedsCap`];
15961        // [`AplicacaoError::PolicyTimeoutZero`] then
15962        // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
15963        let mut s = three_member_spec();
15964        s.politicas.circuit_breaker = Some(CircuitBreaker {
15965            max_failures: 0,
15966            window: Duration::from_secs(60),
15967        });
15968        assert_eq!(
15969            s.validate().unwrap_err(),
15970            AplicacaoError::PolicyBreakerZeroFailures,
15971            "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
15972        );
15973    }
15974
15975    #[test]
15976    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
15977        // The cross-arm ordering pin between the cap and the
15978        // sibling `:window` gates (zero-window, canonical-window).
15979        // A breaker carrying both an over-cap `max_failures` AND a
15980        // structurally invalid window (zero, sub-ms) must surface
15981        // the cap diagnostic first — the cap arm is wired
15982        // immediately after the zero-failure arm and strictly
15983        // before the window arms, so the offending value the
15984        // diagnostic names matches the order the author would
15985        // discover the gates by reading top-to-bottom through
15986        // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
15987        // future refactor that reorders the arms surfaces here as a
15988        // test failure rather than a silent diagnostic regression.
15989        let mut s = three_member_spec();
15990        s.politicas.circuit_breaker = Some(CircuitBreaker {
15991            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
15992            window: Duration::ZERO,
15993        });
15994        assert_eq!(
15995            s.validate().unwrap_err(),
15996            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
15997                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
15998            },
15999            "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
16000        );
16001    }
16002
16003    #[test]
16004    fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
16005        // The diagnostic-shape pin: the offending `u32` is carried
16006        // verbatim into the
16007        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
16008        // variant so the surfaced error message names the value the
16009        // author wrote (`":politicas :circuit-breaker :max-failures
16010        // (50000) exceeds the mesh-policy ceiling …"`), not just
16011        // the cap. Same self-locating diagnostic shape every other
16012        // typed-cap arm on this surface carries
16013        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
16014        // offending retry count verbatim,
16015        // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
16016        // offending byte count verbatim).
16017        let mut s = three_member_spec();
16018        s.politicas.circuit_breaker = Some(CircuitBreaker {
16019            max_failures: 50_000,
16020            window: Duration::from_secs(60),
16021        });
16022        let err = s.validate().unwrap_err();
16023        assert!(
16024            matches!(
16025                err,
16026                AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
16027                    max_failures: 50_000
16028                }
16029            ),
16030            "got {err:?}"
16031        );
16032        let msg = err.to_string();
16033        assert!(
16034            msg.contains("50000"),
16035            ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
16036        );
16037    }
16038
16039    #[test]
16040    fn policy_breaker_max_failures_cap_pins_canonical_value() {
16041        // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
16042        // value at 1000 — an order of magnitude above every
16043        // documented production-playbook recommendation band
16044        // (Hystrix `requestVolumeThreshold` default 20, Istio
16045        // `outlierDetection.consecutive5xxErrors` default 5, Envoy
16046        // `outlier_detection.consecutive_5xx` default 5, Polly /
16047        // Resilience4j typical 5..=50) and below the
16048        // clearly-pathological "effectively no protection" floor
16049        // (10_000, 100_000, u32::MAX). Pinning the literal value
16050        // here surfaces a future drift (a relaxation to 10_000, a
16051        // tightening to 100) as a deliberate test edit, not a
16052        // silent contract narrowing.
16053        assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
16054    }
16055
16056    #[test]
16057    fn rejects_circuit_breaker_zero_window() {
16058        let mut s = three_member_spec();
16059        s.politicas.circuit_breaker = Some(CircuitBreaker {
16060            max_failures: 5,
16061            window: Duration::ZERO,
16062        });
16063        assert_eq!(
16064            s.validate().unwrap_err(),
16065            AplicacaoError::PolicyBreakerZeroWindow
16066        );
16067    }
16068
16069    #[test]
16070    fn rejects_zero_rate_limit() {
16071        let mut s = three_member_spec();
16072        s.politicas.rate_limit = Some(RateLimit {
16073            rate: 0,
16074            window: Duration::from_secs(1),
16075        });
16076        assert_eq!(
16077            s.validate().unwrap_err(),
16078            AplicacaoError::PolicyRateLimitZero
16079        );
16080    }
16081
16082    #[test]
16083    fn rejects_rate_limit_zero_window() {
16084        // `RateLimit { rate: 100, window: Duration::ZERO }` is
16085        // constructible programmatically (the typed `Duration` field
16086        // imposes no nonzero invariant) but renders through
16087        // `rate_limit_codec::render` as `"100/0s"` — a fragment the
16088        // codec's `parse` rejects as `unknown rate-limit window unit
16089        // "0s"`. Until this validate-time gate landed the typed slot
16090        // accepted the value silently and the round-trip break only
16091        // surfaced at deserialize time (potentially in a downstream
16092        // consumer that never re-validates). Pin the rejection at
16093        // `AplicacaoSpec::validate` so the typed slot's valid set
16094        // matches the codec's round-trippable set structurally.
16095        let mut s = three_member_spec();
16096        s.politicas.rate_limit = Some(RateLimit {
16097            rate: 100,
16098            window: Duration::ZERO,
16099        });
16100        assert_eq!(
16101            s.validate().unwrap_err(),
16102            AplicacaoError::PolicyRateLimitWindowNotCanonical {
16103                window: Duration::ZERO
16104            }
16105        );
16106    }
16107
16108    #[test]
16109    fn rejects_rate_limit_arbitrary_seconds_window() {
16110        // 45 seconds is a valid `Duration` but not one of the three
16111        // canonical rate-limit windows the codec round-trips
16112        // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
16113        // refuses on round-trip — same round-trip-break shape the
16114        // zero-window arm above pins, with a non-zero magnitude to
16115        // guard against a future "reject only zero" half-measure.
16116        let mut s = three_member_spec();
16117        let window = Duration::from_secs(45);
16118        s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
16119        assert_eq!(
16120            s.validate().unwrap_err(),
16121            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
16122        );
16123    }
16124
16125    #[test]
16126    fn rejects_rate_limit_two_minute_window() {
16127        // 120 seconds = 2 minutes is a "looks-canonical" but
16128        // not-canonical window: it's a clean integer multiple of the
16129        // minute unit, but the codec only round-trips the
16130        // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
16131        // A `Duration::from_secs(120)` window renders as `"100/120s"`
16132        // which the parser rejects. Pinning this case rules out a
16133        // future "accept any clean multiple of s/m/h" relaxation
16134        // that would silently break the codec contract.
16135        let mut s = three_member_spec();
16136        let window = Duration::from_secs(120);
16137        s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
16138        assert_eq!(
16139            s.validate().unwrap_err(),
16140            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
16141        );
16142    }
16143
16144    #[test]
16145    fn rejects_rate_limit_subsecond_window() {
16146        // A sub-second window (e.g. 500ms) is a valid `Duration` but
16147        // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
16148        // Pin the rejection so a future relaxation can't silently
16149        // admit fractional-second windows that the codec can't
16150        // round-trip.
16151        let mut s = three_member_spec();
16152        let window = Duration::from_millis(500);
16153        s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
16154        assert_eq!(
16155            s.validate().unwrap_err(),
16156            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
16157        );
16158    }
16159
16160    #[test]
16161    fn rejects_policy_rate_limit_above_cap() {
16162        // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
16163        // is structurally one past the cap and silently passed
16164        // validate on every pre-gate codebase because the typed slot's
16165        // only `rate` check was the zero-floor arm. The no-op-limiter
16166        // shape only surfaced at the runtime substrate (Envoy's
16167        // `local_rate_limit.token_bucket.max_tokens`, the future
16168        // Cilium L7 rate-limit overlay) far from the source caixa.lisp
16169        // with no field naming the offending policy.
16170        let mut s = three_member_spec();
16171        s.politicas.rate_limit = Some(RateLimit {
16172            rate: POLICY_RATE_LIMIT_MAX + 1,
16173            window: Duration::from_secs(1),
16174        });
16175        assert_eq!(
16176            s.validate().unwrap_err(),
16177            AplicacaoError::PolicyRateLimitExceedsCap {
16178                rate: POLICY_RATE_LIMIT_MAX + 1
16179            }
16180        );
16181    }
16182
16183    #[test]
16184    fn rejects_policy_rate_limit_far_above_cap() {
16185        // The `u32::MAX` worst case — the four-billion-token rate-limit
16186        // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
16187        // copy-paste lands in the slot. Pin the cap arm's coverage
16188        // explicitly across the full `u32` overflow so a future
16189        // relaxation that drops the upper bound surfaces here. Peer to
16190        // `rejects_policy_retries_far_above_cap` on the sibling
16191        // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
16192        // on the sibling `:max-failures` axis.
16193        let mut s = three_member_spec();
16194        s.politicas.rate_limit = Some(RateLimit {
16195            rate: u32::MAX,
16196            window: Duration::from_secs(1),
16197        });
16198        assert_eq!(
16199            s.validate().unwrap_err(),
16200            AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
16201        );
16202    }
16203
16204    #[test]
16205    fn accepts_policy_rate_limit_at_cap() {
16206        // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
16207        // must validate. The cap is inclusive on the top edge, matching
16208        // every other typed upper bound in this crate
16209        // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
16210        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
16211        // across all three canonical windows so a future off-by-one
16212        // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
16213        // window-conditional cap surfaces here as a test failure rather
16214        // than a silent contract narrowing.
16215        for secs in [1u64, 60, 3600] {
16216            let mut s = three_member_spec();
16217            s.politicas.rate_limit = Some(RateLimit {
16218                rate: POLICY_RATE_LIMIT_MAX,
16219                window: Duration::from_secs(secs),
16220            });
16221            s.validate().unwrap_or_else(|e| {
16222                panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
16223            });
16224        }
16225    }
16226
16227    #[test]
16228    fn accepts_policy_rate_limit_typical_values() {
16229        // The documented production-playbook recommendation band —
16230        // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
16231        // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
16232        // Enterprise ~1M per-hour. Every value in the validated set
16233        // must pass; pin the band explicitly so a future tightening
16234        // surfaces here.
16235        for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
16236            for secs in [1u64, 60, 3600] {
16237                let mut s = three_member_spec();
16238                s.politicas.rate_limit = Some(RateLimit {
16239                    rate,
16240                    window: Duration::from_secs(secs),
16241                });
16242                s.validate().unwrap_or_else(|e| {
16243                    panic!("rate={rate} window={secs}s must validate; got {e:?}")
16244                });
16245            }
16246        }
16247    }
16248
16249    #[test]
16250    fn policy_rate_limit_zero_takes_precedence_over_cap() {
16251        // The cross-arm ordering pin: `rate == 0` is structurally
16252        // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
16253        // (cap), but the zero-floor diagnostic is the more
16254        // self-locating one (it directly names the omit-axis
16255        // remediation). Pin the order so a future refactor that
16256        // reorders the arms surfaces here as a test failure rather
16257        // than a silent diagnostic regression. Same shape every other
16258        // zero-then-cap ordering on this surface uses
16259        // ([`AplicacaoError::PolicyRetriesZero`] then
16260        // [`AplicacaoError::PolicyRetriesExceedsCap`];
16261        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
16262        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
16263        let mut s = three_member_spec();
16264        s.politicas.rate_limit = Some(RateLimit {
16265            rate: 0,
16266            window: Duration::from_secs(1),
16267        });
16268        assert_eq!(
16269            s.validate().unwrap_err(),
16270            AplicacaoError::PolicyRateLimitZero,
16271            "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
16272        );
16273    }
16274
16275    #[test]
16276    fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
16277        // Two-axis-bad pin: rate above cap *and* window non-canonical.
16278        // The validate gate must fire on the rate cap first — the
16279        // amplification-shape (no-op limiter) diagnostic is the more
16280        // fundamental one; the window-canonical diagnostic is the
16281        // narrower codec-round-trip shape. Pin the ordering so a future
16282        // refactor that reorders the rate-then-window check arms
16283        // surfaces here as a test failure rather than a silent
16284        // diagnostic regression.
16285        let mut s = three_member_spec();
16286        s.politicas.rate_limit = Some(RateLimit {
16287            rate: POLICY_RATE_LIMIT_MAX + 1,
16288            window: Duration::from_secs(45),
16289        });
16290        assert_eq!(
16291            s.validate().unwrap_err(),
16292            AplicacaoError::PolicyRateLimitExceedsCap {
16293                rate: POLICY_RATE_LIMIT_MAX + 1
16294            },
16295            "above-cap rate must surface the cap diagnostic, not the window diagnostic"
16296        );
16297    }
16298
16299    #[test]
16300    fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
16301        // The diagnostic-shape pin: the offending `u32` is carried
16302        // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
16303        // variant so the surfaced error message names the value the
16304        // author wrote (`":politicas :rate-limit rate (5000000) exceeds
16305        // the mesh-policy ceiling …"`), not just the cap. Same
16306        // self-locating diagnostic shape every other typed-cap arm on
16307        // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
16308        // carries the offending retries count verbatim,
16309        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
16310        // the offending failure count verbatim).
16311        let mut s = three_member_spec();
16312        s.politicas.rate_limit = Some(RateLimit {
16313            rate: 5_000_000,
16314            window: Duration::from_secs(1),
16315        });
16316        let err = s.validate().unwrap_err();
16317        assert!(
16318            matches!(
16319                err,
16320                AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
16321            ),
16322            "got {err:?}"
16323        );
16324        let msg = err.to_string();
16325        assert!(
16326            msg.contains("5000000"),
16327            ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
16328        );
16329    }
16330
16331    #[test]
16332    fn policy_rate_limit_cap_pins_canonical_value() {
16333        // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
16334        // 1_000_000 — two-to-three orders of magnitude above every
16335        // documented production-playbook recommendation band (Envoy /
16336        // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
16337        // Gateway 10_000..=100_000 per-minute) and below the
16338        // clearly-pathological "paste-from-binary blob" floor
16339        // (100_000_000, u32::MAX). Pinning the literal value here
16340        // surfaces a future drift (a relaxation to 10_000_000, a
16341        // tightening to 100_000) as a deliberate test edit, not a
16342        // silent contract narrowing.
16343        assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
16344    }
16345
16346    #[test]
16347    fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
16348        // Both axes are invalid here: rate == 0 *and* window is
16349        // non-canonical. The validate gate must fire on rate first
16350        // (matching the existing `rejects_zero_rate_limit` ordering),
16351        // so the existing diagnostic continues to lead with the
16352        // simpler "zero rate" framing. Pinning the order of checks
16353        // so a future refactor that reorders the arms surfaces here
16354        // as a test failure rather than a silent diagnostic
16355        // regression.
16356        let mut s = three_member_spec();
16357        s.politicas.rate_limit = Some(RateLimit {
16358            rate: 0,
16359            window: Duration::from_secs(45),
16360        });
16361        assert_eq!(
16362            s.validate().unwrap_err(),
16363            AplicacaoError::PolicyRateLimitZero
16364        );
16365    }
16366
16367    #[test]
16368    fn rate_limit_canonical_windows_validate() {
16369        // The three canonical windows the codec round-trips
16370        // losslessly — 1s / 60s / 3600s — must all pass `validate()`
16371        // unchanged. Pin the full canonical set as a positive case
16372        // (the existing `rate_limit_round_trip_seconds` /
16373        // `rate_limit_round_trip_minutes` tests pin the
16374        // serialize-then-deserialize property at the codec layer; this
16375        // test pins the validate-side complement so a future tightening
16376        // of the canonical set — e.g. dropping `:hour` — surfaces here
16377        // as a test failure rather than a silent contract narrowing).
16378        for secs in [1u64, 60, 3600] {
16379            let mut s = three_member_spec();
16380            s.politicas.rate_limit = Some(RateLimit {
16381                rate: 100,
16382                window: Duration::from_secs(secs),
16383            });
16384            s.validate().expect("canonical window must validate");
16385        }
16386    }
16387
16388    #[test]
16389    fn rate_limit_validated_value_round_trips_through_codec() {
16390        // The structural property the validate gate enforces:
16391        // every `RateLimit` past `AplicacaoSpec::validate` round-trips
16392        // losslessly through the `rate_limit_codec` (serialize → string
16393        // → deserialize → equal value). Pin this end-to-end so a future
16394        // change to either side (the validate gate's accepted window
16395        // set, the codec's parse/render unit set) that breaks the
16396        // alignment surfaces here. The previous-state shape (typed
16397        // slot accepts arbitrary `Duration`, codec only round-trips
16398        // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
16399        // window — the validate gate now forecloses that.
16400        for secs in [1u64, 60, 3600] {
16401            let mut s = three_member_spec();
16402            s.politicas.rate_limit = Some(RateLimit {
16403                rate: 250,
16404                window: Duration::from_secs(secs),
16405            });
16406            s.validate().unwrap();
16407            let json = serde_json::to_string(&s.politicas).unwrap();
16408            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
16409            assert_eq!(
16410                back.rate_limit, s.politicas.rate_limit,
16411                "every validated :rate-limit must round-trip losslessly through the codec"
16412            );
16413        }
16414    }
16415
16416    #[test]
16417    fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
16418        // The hour-window canonical form (`"<n>/h"`) was missing from
16419        // the prior `rate_limit_round_trip_seconds` / `_minutes` test
16420        // pair. Now that the validate gate pins 3600s as part of the
16421        // canonical set, pin its serialize-side render shape too so
16422        // the third leg of the s/m/h tripod is explicitly tested.
16423        let policy = MeshPolicy {
16424            rate_limit: Some(RateLimit {
16425                rate: 10000,
16426                window: Duration::from_secs(3600),
16427            }),
16428            ..Default::default()
16429        };
16430        let json = serde_json::to_string(&policy).unwrap();
16431        assert!(
16432            json.contains("\"10000/h\""),
16433            "hour-window canonical form must render with `h` suffix (got: {json})"
16434        );
16435        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
16436        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
16437    }
16438
16439    #[test]
16440    fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
16441        // Pin the substrate-primitive [`RateLimit::canonical_unit`]
16442        // typed accessor's accepted-window set against the codec's
16443        // accepted set explicitly. A future addition to the codec
16444        // (e.g. accepting `:day`/`:week` as authoring units) must be
16445        // accompanied by a parallel addition here, and a regression
16446        // that drops one of the three canonical units from either
16447        // side surfaces as a test failure. The accessor is the
16448        // single source of truth for the canonical-window set —
16449        // [`AplicacaoSpec::validate_politicas`]'s canonical-window
16450        // gate and [`rate_limit_codec::render`]'s canonical arm both
16451        // read through it — this test enshrines that its
16452        // `Duration → Option<RateLimitUnit>` projection matches the
16453        // codec's parse / render arms' accepted-window set exactly.
16454        //
16455        // Predecessor: this pin previously read the module-private
16456        // free helper `is_canonical_rate_limit_window` — a delegate
16457        // that composed [`RateLimitUnit::from_window`] with `.is_some()`
16458        // — but the helper had no production consumers left after the
16459        // validate-gate migration onto [`RateLimit::canonical_unit`]
16460        // and was deleted; the closed-set arm-window bijection now
16461        // lives on exactly one typed dispatch on the substrate
16462        // primitive.
16463        let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
16464            RateLimit { rate: 1, window }.canonical_unit()
16465        };
16466        assert!(canonical_unit(Duration::from_secs(1)).is_some());
16467        assert!(canonical_unit(Duration::from_secs(60)).is_some());
16468        assert!(canonical_unit(Duration::from_secs(3600)).is_some());
16469        // Non-canonical windows the accessor rejects.
16470        assert!(canonical_unit(Duration::ZERO).is_none());
16471        assert!(canonical_unit(Duration::from_secs(2)).is_none());
16472        assert!(canonical_unit(Duration::from_secs(30)).is_none());
16473        assert!(canonical_unit(Duration::from_secs(120)).is_none());
16474        assert!(canonical_unit(Duration::from_secs(86400)).is_none());
16475        // Sub-second windows: even `Duration::from_millis(1000)` is
16476        // exactly 1s and accepted; `Duration::from_millis(500)` is
16477        // sub-second and rejected.
16478        assert!(canonical_unit(Duration::from_millis(1000)).is_some());
16479        assert!(canonical_unit(Duration::from_millis(500)).is_none());
16480        assert!(canonical_unit(Duration::from_millis(1500)).is_none());
16481    }
16482
16483    #[test]
16484    fn rate_limit_unit_table_projections_are_mutual_inverses() {
16485        // Bidirection pin against the closed-set typed enum
16486        // [`RateLimitUnit`] arm-table (the canonical
16487        // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
16488        // of the rate-limit unit surface reads from). The two
16489        // projection directions [`RateLimitUnit::from_suffix`] /
16490        // [`RateLimitUnit::window`] (str → Duration, exposed as one
16491        // typed dispatch through [`RateLimitUnit::window_from_suffix`])
16492        // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
16493        // (Duration → str, exposed as one typed dispatch through
16494        // [`RateLimit::canonical_unit`] composed with
16495        // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
16496        // codec's parse arm ([`rate_limit_codec::parse`] via
16497        // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
16498        // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
16499        // and the validate gate ([`AplicacaoSpec::validate_politicas`]
16500        // via [`RateLimit::canonical_unit`]) all key off. A future
16501        // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
16502        // sub-second window) is one variant + one arm per method on the
16503        // closed-set enum; the compiler-enforced exhaustiveness on
16504        // every consumer's `match self` arms picks it up by
16505        // construction. This pin enshrines that both projection
16506        // directions agree on every canonical arm row and neither
16507        // leaks a spurious entry the other doesn't recognize.
16508        //
16509        // Predecessor: this test previously read the two vestigial
16510        // module-private free helpers `rate_limit_window_unit` and
16511        // `rate_limit_window_from_unit` on the `Duration → &str` and
16512        // `&str → Duration` axes; the former was deleted after its
16513        // sole production consumer ([`rate_limit_codec::render`])
16514        // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
16515        // the latter is folded here into the substrate primitive
16516        // [`RateLimitUnit::window_from_suffix`] so both projection
16517        // directions live on the closed-set enum's arm-table.
16518        for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
16519            let window = super::RateLimitUnit::window_from_suffix(unit)
16520                .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
16521            assert_eq!(
16522                window,
16523                Duration::from_secs(secs),
16524                "unit {unit:?} must resolve to {secs}s"
16525            );
16526            let projected_suffix = RateLimit { rate: 1, window }
16527                .canonical_unit()
16528                .map(super::RateLimitUnit::as_suffix);
16529            assert_eq!(
16530                projected_suffix,
16531                Some(unit),
16532                "Duration({secs}s) must render as {unit:?} \
16533                 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
16534            );
16535        }
16536        // Non-table units yield None on the `unit → Duration`
16537        // projection — a future `"d"` addition to the table would
16538        // flip this arm; today it pins the current three-row table's
16539        // rejection semantics.
16540        assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
16541        assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
16542        assert!(super::RateLimitUnit::window_from_suffix("").is_none());
16543        // Non-table Durations yield None on the `Duration → unit`
16544        // projection — pins that the two projections agree on the
16545        // "not in the table" semantic too, so a drift where the
16546        // parse-side accepts a value the render-side can't emit is
16547        // a build error at the two-arm pair, not a silent codec
16548        // round-trip break.
16549        let projected_suffix = |window: Duration| -> Option<&'static str> {
16550            RateLimit { rate: 1, window }
16551                .canonical_unit()
16552                .map(super::RateLimitUnit::as_suffix)
16553        };
16554        assert!(projected_suffix(Duration::from_secs(2)).is_none());
16555        assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
16556        assert!(projected_suffix(Duration::from_millis(1500)).is_none());
16557    }
16558
16559    #[test]
16560    fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
16561        // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
16562        // substrate-primitive `&str → Duration` associated method the
16563        // codec's parse arm ([`rate_limit_codec::parse`]) now routes
16564        // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
16565        // to the same [`Duration`] the two-step composition
16566        // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
16567        // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
16568        // `"MIN"`) must project to [`None`] on both paths. A future
16569        // implementation of `window_from_suffix` that took a shortcut
16570        // through a per-suffix `match` table (bypassing the arm-table's
16571        // `Self::from_suffix` scan and the arm-table's `Self::window`
16572        // dispatch) would silently split the accept-set — the parse
16573        // arm would accept a suffix the enum's arm-table doesn't know,
16574        // or reject a suffix the enum's arm-table does; this pin
16575        // surfaces that drift at caixa-core build time rather than at a
16576        // downstream serde round-trip audit on a live `MeshPolicy`.
16577        //
16578        // Same byte-parity discipline the sibling
16579        // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
16580        // pin carries on the peer `Duration → RateLimitUnit` axis via
16581        // [`RateLimit::canonical_unit`], and the peer
16582        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
16583        // carries on the bidirectional arm-table axis — extended here
16584        // onto the fifth (and last unlifted) projection axis on the
16585        // closed-set enum's arm-table.
16586        let composition = |suffix: &str| -> Option<Duration> {
16587            super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
16588        };
16589        for suffix in ["s", "m", "h"] {
16590            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
16591            let via_composition = composition(suffix);
16592            assert_eq!(
16593                via_method, via_composition,
16594                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
16595                 from_suffix({suffix:?}).map(window) — the substrate-primitive \
16596                 method must delegate to the arm-table's two typed dispatches, \
16597                 not shortcut through a per-suffix match table"
16598            );
16599            assert!(
16600                via_method.is_some(),
16601                "canonical suffix {suffix:?} must resolve to Some(Duration) via \
16602                 RateLimitUnit::window_from_suffix"
16603            );
16604        }
16605        for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
16606            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
16607            let via_composition = composition(suffix);
16608            assert_eq!(
16609                via_method, via_composition,
16610                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
16611                 from_suffix({suffix:?}).map(window) on the non-arm rejection \
16612                 axis too"
16613            );
16614            assert!(
16615                via_method.is_none(),
16616                "non-arm suffix {suffix:?} must project to None via \
16617                 RateLimitUnit::window_from_suffix — a future extension that \
16618                 accepted this suffix without a corresponding arm on the enum \
16619                 would split the codec's parse-accepted set from the enum's \
16620                 arm-table"
16621            );
16622        }
16623        // And the codec's parse arm now reads through this method: a
16624        // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
16625        // the same `Duration` the method returns for its unit, closing
16626        // the two-consumer drift surface (the codec's parse arm and the
16627        // enum's arm-table) with one typed dispatch on the substrate
16628        // primitive.
16629        for suffix in ["s", "m", "h"] {
16630            let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
16631            let mp: MeshPolicy = serde_json::from_str(&wire)
16632                .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
16633            let parsed = mp.rate_limit().expect("rate_limit payload present");
16634            let via_method = super::RateLimitUnit::window_from_suffix(suffix)
16635                .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
16636            assert_eq!(
16637                parsed.window(),
16638                via_method,
16639                "codec parse arm on {wire:?} must resolve the window through \
16640                 RateLimitUnit::window_from_suffix, not a divergent path"
16641            );
16642        }
16643    }
16644
16645    #[test]
16646    fn rate_limit_unit_all_enumerates_every_arm_once() {
16647        // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
16648        // enumerate every arm of the closed-set enum exactly once, in
16649        // the canonical shortest-to-longest window order (Second before
16650        // Minute before Hour) — the same order the sibling
16651        // [`crate::supervisor::RestartStrategy`] /
16652        // [`crate::supervisor::RestartPolicy`] /
16653        // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
16654        // typed enums carry (the arm declared first is the arm listed
16655        // first). A future variant addition that extends the enum
16656        // without appending to [`RateLimitUnit::ALL`] leaves the
16657        // exhaustive iteration surface silently short one arm — the
16658        // codec's parse arm would then reject the new suffix even
16659        // though the enum knows it. This pin closes the drift.
16660        assert_eq!(
16661            super::RateLimitUnit::ALL,
16662            &[
16663                super::RateLimitUnit::Second,
16664                super::RateLimitUnit::Minute,
16665                super::RateLimitUnit::Hour,
16666            ],
16667            "RateLimitUnit::ALL must enumerate every arm exactly once, \
16668             in canonical shortest-to-longest window order"
16669        );
16670    }
16671
16672    #[test]
16673    fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
16674        // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
16675        // every arm's [`RateLimitUnit::as_suffix`] output must parse
16676        // back through [`RateLimitUnit::from_suffix`] to the same
16677        // variant. A future arm addition that lands `as_suffix` but
16678        // forgets `from_suffix` (`from_suffix` iterates
16679        // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
16680        // is the load-bearing carrier of the round-trip; the sibling
16681        // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
16682        // the `ALL` half) trips here at caixa-core build time rather
16683        // than surfacing as a codec round-trip miss (a `render` emit
16684        // that lands a suffix the paired `parse` cannot decode).
16685        for unit in super::RateLimitUnit::ALL {
16686            let suffix = unit.as_suffix();
16687            let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
16688                panic!(
16689                    "RateLimitUnit::from_suffix({suffix:?}) must accept every \
16690                     RateLimitUnit::as_suffix output — got None for {unit:?}"
16691                )
16692            });
16693            assert_eq!(
16694                parsed, *unit,
16695                "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
16696                 must return RateLimitUnit::{unit:?}"
16697            );
16698        }
16699    }
16700
16701    #[test]
16702    fn rate_limit_unit_from_window_and_window_round_trip() {
16703        // Total round-trip pin on the `(from_window, window)` pair:
16704        // every arm's [`RateLimitUnit::window`] output must parse back
16705        // through [`RateLimitUnit::from_window`] to the same variant.
16706        // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
16707        // on the peer `Duration` axis — the two round-trip pins
16708        // together enshrine that both projections of the typed
16709        // canonical-unit bijection are total on the arm-set.
16710        for unit in super::RateLimitUnit::ALL {
16711            let window = unit.window();
16712            let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
16713                panic!(
16714                    "RateLimitUnit::from_window({window:?}) must accept every \
16715                     RateLimitUnit::window output — got None for {unit:?}"
16716                )
16717            });
16718            assert_eq!(
16719                parsed, *unit,
16720                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
16721                 must return RateLimitUnit::{unit:?}"
16722            );
16723        }
16724    }
16725
16726    #[test]
16727    fn rate_limit_unit_from_window_accessor_is_const_fn() {
16728        // Fail-before-pass-after pin: witnesses the
16729        // [`RateLimitUnit::from_window`] `const`-eval posture via a
16730        // `const fn` wrapper `from_window_via_const_fn(window: Duration)
16731        // -> Option<RateLimitUnit>` whose body calls
16732        // `RateLimitUnit::from_window(window)`, well-formed only when
16733        // the callee is itself `const fn` (any future downgrade to
16734        // non-`const` fails at caixa-core build time with E0015 `cannot
16735        // call non-const function`, strictly stronger than a runtime
16736        // `assert!`, side-stepping the destructor-in-const restriction
16737        // that blocks direct `const _: Option<RateLimitUnit> =
16738        // RateLimitUnit::from_window(...)` items on `Duration`'s
16739        // carrier). The runtime body sweeps every closed-set
16740        // [`RateLimitUnit::ALL`] arm plus a representative non-canonical
16741        // rejection sample (`Duration::from_millis(500)` sub-second
16742        // residue) and asserts the wrapped and direct dispatches agree
16743        // — a violation means the wrapper stopped compiling under a
16744        // future `const`-posture downgrade, or the reverse resolver's
16745        // arm-set silently split from the peer `Self::window` emitter's
16746        // arm-set. Peer of the sibling
16747        // [`crate::supervisor::tests::child_spec_restart_accessor_is_const_fn`]
16748        // (152c868) /
16749        // [`crate::supervisor::tests::supervisor_spec_estrategia_accessor_is_const_fn`]
16750        // (152c868) /
16751        // [`entrada_port_accessor_is_const_fn`] (bafa004) /
16752        // [`placement_estrategia_accessor_is_const_fn`] (bafa004)
16753        // `const`-eval-surface pins on the peer M2 / M3 substrate-
16754        // primitive `Copy`-return accessor axes, extended onto the
16755        // reverse `Duration → RateLimitUnit` projection axis on the
16756        // M3 mesh-slot rate-limit closed-set typed enum.
16757        const fn from_window_via_const_fn(window: Duration) -> Option<super::RateLimitUnit> {
16758            super::RateLimitUnit::from_window(window)
16759        }
16760        for unit in super::RateLimitUnit::ALL {
16761            let window = unit.window();
16762            let via_wrapper = from_window_via_const_fn(window);
16763            let direct = super::RateLimitUnit::from_window(window);
16764            assert_eq!(
16765                via_wrapper, direct,
16766                "RateLimitUnit::from_window({window:?}) via const fn \
16767                 wrapper must agree with direct dispatch for {unit:?}"
16768            );
16769            assert_eq!(
16770                via_wrapper,
16771                Some(*unit),
16772                "RateLimitUnit::from_window({window:?}) via const fn \
16773                 wrapper must return Some({unit:?}) for the peer \
16774                 window() output"
16775            );
16776        }
16777        assert!(from_window_via_const_fn(Duration::from_millis(500)).is_none());
16778        assert!(from_window_via_const_fn(Duration::from_secs(30)).is_none());
16779    }
16780
16781    #[test]
16782    fn rate_limit_unit_from_window_composes_through_window_accessor() {
16783        // Composition-witness pin on the routing-through-peer discipline:
16784        // [`RateLimitUnit::from_window`]'s per-arm probes each dispatch
16785        // through the peer `pub const fn` [`RateLimitUnit::window`]
16786        // canonical-`Duration` projection rather than a hand-authored
16787        // per-arm second-magnitude literal — a future arm-magnitude edit
16788        // on the sibling `window()` accessor (a `Second → 2s` typo, a
16789        // `Hour → 3599s` off-by-one) must therefore reach this reverse
16790        // resolver by construction. A pin that hard-coded the three
16791        // second-magnitudes here would silently split from the peer
16792        // emitter on any such edit; instead, this pin asserts the
16793        // composition invariant `from_window(u.window()) == Some(u)`
16794        // holds byte-for-byte on every closed-set [`RateLimitUnit::ALL`]
16795        // arm — a violation means either the peer `Self::window`
16796        // accessor drifted (breaking every downstream consumer that
16797        // reads through it), or the reverse resolver stopped routing
16798        // through the peer (introducing a hand-authored literal that
16799        // silently disagrees with the emitter). Either failure is a
16800        // caixa-core-build-time surface, not a downstream renderer
16801        // round-trip regression.
16802        //
16803        // Peer of the sibling
16804        // [`crate::render::assert_str_reexport_identity`] discipline on
16805        // the substrate-primitive `&'static str` re-export axis and the
16806        // [`rate_limit_unit_from_window_and_window_round_trip`]
16807        // round-trip pin on the peer projection direction; extends the
16808        // one-canonical-dispatch-per-projection discipline onto the
16809        // reverse-resolver's per-arm probe axis.
16810        for unit in super::RateLimitUnit::ALL {
16811            let window_via_peer = unit.window();
16812            let resolved = super::RateLimitUnit::from_window(window_via_peer);
16813            assert_eq!(
16814                resolved,
16815                Some(*unit),
16816                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
16817                 must return Some({unit:?}) — the reverse resolver's per-arm \
16818                 probes must route through the peer `Self::window` accessor \
16819                 so any future arm-magnitude edit reaches both projection \
16820                 directions by construction"
16821            );
16822        }
16823    }
16824
16825    #[test]
16826    fn rate_limit_canonical_unit_accessor_is_const_fn() {
16827        // Fail-before-pass-after pin: witnesses the
16828        // [`RateLimit::canonical_unit`] `const`-eval posture via a
16829        // `const fn` wrapper
16830        // `canonical_unit_via_const_fn(rl: &RateLimit) -> Option<RateLimitUnit>`
16831        // whose body calls `rl.canonical_unit()`, well-formed only when
16832        // the callee is itself `const fn` (any future downgrade to
16833        // non-`const` fails at caixa-core build time with E0015 `cannot
16834        // call non-const method`). The runtime body sweeps every
16835        // closed-set [`RateLimitUnit::ALL`] arm — for each arm,
16836        // constructs a typed [`RateLimit`] with the peer `Self::window`
16837        // canonical `Duration`, then asserts both the wrapper and the
16838        // direct dispatch agree and both return `Some(unit)`. Composes
16839        // with the sibling
16840        // [`rate_limit_unit_from_window_accessor_is_const_fn`] pin: the
16841        // typed [`RateLimit`] projection layer's `const`-posture is
16842        // load-bearing on the reverse resolver's `const`-posture, and
16843        // both must migrate together (a downgrade of either surface
16844        // splits the paired `const`-eval-surface pass on the M3
16845        // mesh-slot rate-limit `Duration ↔ Self` bijection).
16846        const fn canonical_unit_via_const_fn(
16847            rl: &super::RateLimit,
16848        ) -> Option<super::RateLimitUnit> {
16849            rl.canonical_unit()
16850        }
16851        for unit in super::RateLimitUnit::ALL {
16852            let rl = super::RateLimit {
16853                rate: 1,
16854                window: unit.window(),
16855            };
16856            let via_wrapper = canonical_unit_via_const_fn(&rl);
16857            let direct = rl.canonical_unit();
16858            assert_eq!(
16859                via_wrapper, direct,
16860                "RateLimit::canonical_unit() via const fn wrapper must \
16861                 agree with direct dispatch for {unit:?}"
16862            );
16863            assert_eq!(
16864                via_wrapper,
16865                Some(*unit),
16866                "RateLimit::canonical_unit() via const fn wrapper must \
16867                 return Some({unit:?}) for a RateLimit whose window is \
16868                 the peer RateLimitUnit::{unit:?}.window() output"
16869            );
16870        }
16871    }
16872
16873    #[test]
16874    fn rate_limit_unit_projections_are_pairwise_distinct() {
16875        // Distinctness pin: [`RateLimitUnit::as_suffix`] and
16876        // [`RateLimitUnit::window`] outputs must be pairwise distinct
16877        // across every arm — an accidental copy-paste flip that
16878        // reroutes one arm's suffix or window to also match another
16879        // silently collapses two arms onto one, so
16880        // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
16881        // (both using `find` on `Self::ALL`) would return whichever
16882        // arm the linear scan lands on first — a match-arm-ordering-
16883        // dependent outcome the closed-set typed-enum shape is meant
16884        // to rule out structurally. Peer of the sibling
16885        // `caixa_kind_wire_consts_are_pairwise_distinct` /
16886        // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
16887        // other closed-set typed-enum discriminator axes.
16888        let all = super::RateLimitUnit::ALL;
16889        for (i, a) in all.iter().enumerate() {
16890            for (j, b) in all.iter().enumerate() {
16891                if i != j {
16892                    assert_ne!(
16893                        a.as_suffix(),
16894                        b.as_suffix(),
16895                        "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
16896                         must be distinct — a collision silently collapses two \
16897                         arms onto one under from_suffix's linear scan"
16898                    );
16899                    assert_ne!(
16900                        a.window(),
16901                        b.window(),
16902                        "RateLimitUnit::{a:?}.window() and {b:?}.window() \
16903                         must be distinct — a collision silently collapses two \
16904                         arms onto one under from_window's linear scan"
16905                    );
16906                }
16907            }
16908        }
16909    }
16910
16911    #[test]
16912    fn rate_limit_unit_display_routes_through_as_suffix() {
16913        // Route pin: [`std::fmt::Display`] must byte-equal
16914        // [`RateLimitUnit::as_suffix`] on every arm — the single
16915        // source of truth for the canonical suffix. A future
16916        // reimplementation that hand-rolls the arms instead of
16917        // delegating to [`RateLimitUnit::as_suffix`] would silently
16918        // desynchronize `format!("{u}")` from the codec's parse arm
16919        // (which uses `as_suffix` to compare suffixes). Peer of the
16920        // sibling `caixa_kind_display_routes_through_as_str_helper` /
16921        // `placement_strategy_display_routes_through_as_str_helper`
16922        // pins on the peer closed-set typed-enum Display axes.
16923        for unit in super::RateLimitUnit::ALL {
16924            assert_eq!(
16925                unit.to_string(),
16926                unit.as_suffix(),
16927                "RateLimitUnit::{unit:?} Display must route through \
16928                 as_suffix (single source of truth: the canonical suffix \
16929                 the codec parses and renders)"
16930            );
16931        }
16932    }
16933
16934    #[test]
16935    fn rate_limit_unit_from_window_rejects_non_canonical() {
16936        // Rejection pin on the parser's accept-set: any Duration
16937        // outside the three-arm [`RateLimitUnit::window`] output set
16938        // (sub-second residue, or a second-magnitude outside `{1, 60,
16939        // 3600}`) must return `None`. A future accidental widening of
16940        // the accept-set (rounding down sub-second residue to the
16941        // nearest arm, admitting `Duration::from_secs(30)` as a
16942        // half-minute unit) would silently drift the parser's accept-
16943        // set from the emitter's — a validated slot with a
16944        // non-canonical window would then round-trip through the
16945        // codec to a canonical form the author never wrote.
16946        assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
16947        assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
16948        assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
16949        assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
16950        assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
16951        assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
16952        assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
16953    }
16954
16955    #[test]
16956    fn rate_limit_unit_from_suffix_rejects_unknown() {
16957        // Rejection pin on the suffix parser's accept-set: any string
16958        // outside the three-arm [`RateLimitUnit::as_suffix`] output
16959        // set must return `None`. Peer of the sibling
16960        // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
16961        // the [`crate::CaixaKind`] `from_wire` accept-set.
16962        for bad in [
16963            "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
16964            " s",
16965        ] {
16966            assert!(
16967                super::RateLimitUnit::from_suffix(bad).is_none(),
16968                "RateLimitUnit::from_suffix({bad:?}) must return None — the \
16969                 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
16970                 outputs"
16971            );
16972        }
16973    }
16974
16975    #[test]
16976    fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
16977        // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
16978        // every canonical `:window` magnitude the validate gate
16979        // accepts must map to the paired [`RateLimitUnit`] arm through
16980        // this accessor. A future validate-gate rebrand that widened
16981        // the accepted-window set without extending [`RateLimitUnit`]
16982        // would silently split the accessor's `Some`-return set from
16983        // the validate gate's accept-set — a slot that satisfies
16984        // validate would land at the accessor with `None`, so a
16985        // consumer past validate that pattern-matches on the returned
16986        // `Some` would silently miss the newly-accepted magnitude.
16987        for (window_secs, expected) in [
16988            (1u64, super::RateLimitUnit::Second),
16989            (60, super::RateLimitUnit::Minute),
16990            (3600, super::RateLimitUnit::Hour),
16991        ] {
16992            let rl = RateLimit {
16993                rate: 100,
16994                window: Duration::from_secs(window_secs),
16995            };
16996            assert_eq!(
16997                rl.canonical_unit(),
16998                Some(expected),
16999                "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
17000                 must return Some({expected:?})"
17001            );
17002        }
17003        // Non-canonical windows the validate gate rejects also return
17004        // None here — the accessor is the typed-enum projection of
17005        // the sibling `is_canonical_rate_limit_window` predicate.
17006        let bad = RateLimit {
17007            rate: 100,
17008            window: Duration::from_secs(30),
17009        };
17010        assert!(
17011            bad.canonical_unit().is_none(),
17012            "RateLimit with a non-canonical window must return None from \
17013             canonical_unit — the validate gate rejects the same set"
17014        );
17015    }
17016
17017    #[test]
17018    fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
17019        // Fail-before-pass-after byte-parity pin: for every canonical
17020        // window the [`rate_limit_codec::render`] arm's emitted string
17021        // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
17022        // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
17023        // the vestigial free helper [`rate_limit_window_unit`] (a
17024        // `find_map`-walked `Duration → &'static str` delegate) onto the
17025        // substrate primitive [`RateLimit::canonical_unit`] typed method
17026        // (a closed-set `match self.window` arm on
17027        // [`RateLimitUnit::from_window`], projected through
17028        // [`RateLimitUnit::as_suffix`] via the enum's
17029        // [`std::fmt::Display`] impl). A future re-routing of the render
17030        // arm through a differently-computed unit projection would break
17031        // this pin at build time rather than as a silent per-consumer
17032        // codec round-trip drift far from the substrate primitive edit.
17033        //
17034        // Sibling to the peer
17035        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
17036        // on the free-helper axis: that pin locks the two projections
17037        // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
17038        // on the closed-set arm table; this pin locks the codec's render
17039        // arm reads through the typed accessor rather than the free
17040        // helper. Two production consumers of the canonical-unit axis
17041        // now key off one typed dispatch on the substrate primitive.
17042        for (window_secs, unit) in [
17043            (1u64, super::RateLimitUnit::Second),
17044            (60, super::RateLimitUnit::Minute),
17045            (3600, super::RateLimitUnit::Hour),
17046        ] {
17047            let rl = RateLimit {
17048                rate: 42,
17049                window: Duration::from_secs(window_secs),
17050            };
17051            let policy = MeshPolicy {
17052                rate_limit: Some(rl),
17053                ..Default::default()
17054            };
17055            let json = serde_json::to_string(&policy).unwrap();
17056            let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
17057            assert!(
17058                json.contains(&expected),
17059                "rate_limit_codec::render must emit {expected} (via \
17060                 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
17061                 for a {window_secs}s window; serialized MeshPolicy was: {json}"
17062            );
17063            // And the accessor route resolves to the same typed unit
17064            // the render arm's Display formatting is asked to produce —
17065            // so a future edit that split the two paths (one through
17066            // the accessor, one through a re-introduced free helper)
17067            // trips this pin.
17068            assert_eq!(
17069                rl.canonical_unit(),
17070                Some(unit),
17071                "RateLimit::canonical_unit must return Some({unit:?}) for a \
17072                 {window_secs}s window; the codec render arm reads the same \
17073                 typed unit through this accessor"
17074            );
17075        }
17076    }
17077
17078    #[test]
17079    fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
17080        // Fail-before-pass-after byte-parity pin on the validate gate's
17081        // canonical-window shape probe: every non-canonical `:window`
17082        // the free-helper predicate [`is_canonical_rate_limit_window`]
17083        // rejects is also rejected by the substrate primitive
17084        // [`RateLimit::canonical_unit`] `.is_none()` route the validate
17085        // gate now reads through, and vice versa on the accepted set
17086        // (the three canonical windows). Locks the migration from the
17087        // free helper onto the substrate primitive: a future re-routing
17088        // of one of the two paths through a differently-computed unit
17089        // projection would silently split the codec's accepted set from
17090        // the validate gate's accepted set — a two-consumer drift the
17091        // codec-round-trip pin
17092        // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
17093        // above closes on the render arm and this pin closes on the
17094        // validate arm.
17095        for canonical_window_secs in [1u64, 60, 3600] {
17096            let mut s = three_member_spec();
17097            let rl = RateLimit {
17098                rate: 100,
17099                window: Duration::from_secs(canonical_window_secs),
17100            };
17101            s.politicas.rate_limit = Some(rl);
17102            assert!(
17103                s.validate().is_ok(),
17104                "canonical {canonical_window_secs}s window must pass \
17105                 validate_politicas — the validate gate now reads \
17106                 RateLimit::canonical_unit().is_none() and the accessor \
17107                 returns Some on every canonical arm"
17108            );
17109            assert!(
17110                rl.canonical_unit().is_some(),
17111                "canonical {canonical_window_secs}s window must resolve to \
17112                 Some on RateLimit::canonical_unit — the validate gate reads \
17113                 this accessor directly"
17114            );
17115        }
17116        for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
17117            let mut s = three_member_spec();
17118            let rl = RateLimit {
17119                rate: 100,
17120                window: Duration::from_secs(non_canonical_window_secs),
17121            };
17122            s.politicas.rate_limit = Some(rl);
17123            assert_eq!(
17124                s.validate().unwrap_err(),
17125                AplicacaoError::PolicyRateLimitWindowNotCanonical {
17126                    window: rl.window(),
17127                },
17128                "non-canonical {non_canonical_window_secs}s window must be \
17129                 rejected by validate_politicas — the validate gate now \
17130                 keys off RateLimit::canonical_unit().is_none()"
17131            );
17132            assert!(
17133                rl.canonical_unit().is_none(),
17134                "non-canonical {non_canonical_window_secs}s window must \
17135                 resolve to None on RateLimit::canonical_unit — the two \
17136                 paths (the free helper the validate gate previously read \
17137                 and the substrate primitive the validate gate now reads) \
17138                 must agree on the same rejected set"
17139            );
17140        }
17141        // And the substrate-primitive [`RateLimit::canonical_unit`]
17142        // accessor's accepted-window set matches the codec's parse arm's
17143        // accepted-suffix set on every canonical / non-canonical shape,
17144        // so a future silent drift between the codec's accepted set and
17145        // the validate gate's accepted set is a build error at test time
17146        // (both consumers key off the same closed-set enum's `match self`
17147        // arms). The predecessor free helper `is_canonical_rate_limit_window`
17148        // — a delegate that composed [`RateLimitUnit::from_window`] with
17149        // `.is_some()` — was deleted after this migration; the
17150        // canonical-window set now lives on exactly one typed dispatch
17151        // on the substrate primitive.
17152        for (secs, expected) in [
17153            (1u64, true),
17154            (60, true),
17155            (3600, true),
17156            (2, false),
17157            (30, false),
17158            (86_400, false),
17159        ] {
17160            let window = Duration::from_secs(secs);
17161            let rl = RateLimit { rate: 1, window };
17162            assert_eq!(
17163                rl.canonical_unit().is_some(),
17164                expected,
17165                "RateLimit::canonical_unit().is_some() must agree with the \
17166                 codec-accepted canonical-window set on {secs}s"
17167            );
17168            let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
17169                1 => "s",
17170                60 => "m",
17171                3600 => "h",
17172                _ => return,
17173            })
17174            .is_some_and(|d| d == window);
17175            if expected {
17176                assert!(
17177                    suffix_from_axis,
17178                    "the codec's `&str → Duration` axis \
17179                     ({secs}s) must round-trip to the same Duration the \
17180                     substrate primitive's accessor returns Some on"
17181                );
17182            }
17183        }
17184    }
17185
17186    #[test]
17187    fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
17188        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
17189        // derive: for each of the three variants, exactly one of the
17190        // generated `is_second` / `is_minute` / `is_hour` predicates
17191        // returns `true` and the other two return `false`. Peer of
17192        // the sibling
17193        // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
17194        // sibling `IsVariant`-derived closed-set typed-enum pins.
17195        let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
17196            (super::RateLimitUnit::Second, [true, false, false]),
17197            (super::RateLimitUnit::Minute, [false, true, false]),
17198            (super::RateLimitUnit::Hour, [false, false, true]),
17199        ];
17200        for (variant, expected) in rows {
17201            let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
17202            assert_eq!(
17203                observed, expected,
17204                "RateLimitUnit::{variant:?} is_* predicates must partition \
17205                 the arm set (second, minute, hour); got {observed:?}"
17206            );
17207        }
17208    }
17209
17210    #[test]
17211    fn rejects_policy_timeout_sub_millisecond() {
17212        // A purely sub-millisecond `Duration` (`from_micros(500)` =
17213        // 500_000 ns) is not the zero `Duration` — the `is_zero()`
17214        // arm passes — but `as_millis() == 0`, so the shared codec's
17215        // `render` arm returns the literal `"0s"`, which the
17216        // codec's `parse` arm then deserializes as `Duration::ZERO`
17217        // and the `PolicyTimeoutZero` zero-floor gate would reject
17218        // on re-validate. Pin the rejection at the typed slot's
17219        // canonical-floor gate so the round-trip break surfaces at
17220        // validate time, naming the offending `Duration`, rather
17221        // than at the next serialize → deserialize round-trip far
17222        // from the source `caixa.lisp`.
17223        let mut s = three_member_spec();
17224        let timeout = Duration::from_micros(500);
17225        s.politicas.timeout = Some(timeout);
17226        assert_eq!(
17227            s.validate().unwrap_err(),
17228            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
17229        );
17230    }
17231
17232    #[test]
17233    fn rejects_policy_timeout_non_integer_millisecond() {
17234        // A `Duration` with non-integer-millisecond residue
17235        // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
17236        // through the shared codec's `render` arm as `"1ms"` (the
17237        // `as_millis()` floor truncates), which the codec's `parse`
17238        // arm then deserializes as `Duration::from_millis(1)` =
17239        // 1_000_000 ns — silently *different* from the original.
17240        // Pin the rejection so this round-trip break surfaces at
17241        // validate time, where the offending `Duration` is named,
17242        // rather than as a silent value-laundered round-trip on the
17243        // next codec round-trip.
17244        let mut s = three_member_spec();
17245        let timeout = Duration::from_micros(1500);
17246        s.politicas.timeout = Some(timeout);
17247        assert_eq!(
17248            s.validate().unwrap_err(),
17249            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
17250        );
17251    }
17252
17253    #[test]
17254    fn accepts_policy_timeout_integer_millisecond_forms() {
17255        // The codec's accepted set — integer multiples of 1ms — is
17256        // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
17257        // `1h` all pass the canonical gate. Pin the canonical-forms
17258        // sweep so a future tightening of the codec's grammar (e.g.
17259        // dropping `:ms`) surfaces here as a test failure rather
17260        // than a silent contract narrowing on the typed slot.
17261        for timeout in [
17262            Duration::from_millis(1),
17263            Duration::from_millis(500),
17264            Duration::from_millis(1500),
17265            Duration::from_secs(30),
17266            Duration::from_secs(120),
17267            Duration::from_secs(3600),
17268        ] {
17269            let mut s = three_member_spec();
17270            s.politicas.timeout = Some(timeout);
17271            s.validate()
17272                .expect("integer-millisecond :timeout must validate");
17273        }
17274    }
17275
17276    #[test]
17277    fn policy_timeout_zero_takes_precedence_over_canonical() {
17278        // `Duration::ZERO` carries `subsec_nanos() == 0` and would
17279        // pass the canonical-millisecond gate; the more self-locating
17280        // `PolicyTimeoutZero` arm (which names the omit-axis
17281        // remediation directly) must fire first. Pin the ordering so
17282        // a future refactor that reorders the arms surfaces here as a
17283        // test failure rather than a silent diagnostic regression.
17284        let mut s = three_member_spec();
17285        s.politicas.timeout = Some(Duration::ZERO);
17286        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
17287    }
17288
17289    #[test]
17290    fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
17291        // The diagnostic envelope carries the offending `Duration`
17292        // verbatim so the author can grep their `caixa.lisp` for
17293        // `:timeout "<value>"` and fix it in one edit. Same
17294        // diagnostic shape every other typed-slot canonical-form
17295        // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
17296        // peer `:rate-limit :window` axis.
17297        let mut s = three_member_spec();
17298        let timeout = Duration::from_nanos(1_000_001);
17299        s.politicas.timeout = Some(timeout);
17300        match s.validate().unwrap_err() {
17301            AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
17302                assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
17303            }
17304            other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
17305        }
17306    }
17307
17308    #[test]
17309    fn rejects_policy_timeout_above_cap() {
17310        // The fail-before-pass-after pin: 3601s = 1h + 1s is
17311        // structurally one canonical-tick past the
17312        // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
17313        // integer-millisecond magnitude the canonical-form arm above
17314        // accepts cleanly, that the codec round-trips losslessly as
17315        // `"3601s"`, and that silently passed validate on every
17316        // pre-gate codebase because the typed slot's only checks were
17317        // the zero-floor and canonical-form arms. The mesh-level
17318        // deadline degenerates only at the runtime substrate (Envoy
17319        // / Cilium L7 timeout overlay) far from the source
17320        // `caixa.lisp` with no field naming the offending policy.
17321        let mut s = three_member_spec();
17322        let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
17323        s.politicas.timeout = Some(timeout);
17324        assert_eq!(
17325            s.validate().unwrap_err(),
17326            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
17327        );
17328    }
17329
17330    #[test]
17331    fn rejects_policy_timeout_one_millisecond_above_cap() {
17332        // Boundary case: exactly 1ms past the cap (the granularity
17333        // the canonical-form gate enforces). Catches a future
17334        // "strictly less than" half-measure and pins the diagnostic
17335        // to name the offending `Duration` verbatim. Peer of
17336        // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
17337        // boundary pin on the sibling `:limits :memory` top edge.
17338        let mut s = three_member_spec();
17339        let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
17340        s.politicas.timeout = Some(timeout);
17341        assert_eq!(
17342            s.validate().unwrap_err(),
17343            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
17344        );
17345    }
17346
17347    #[test]
17348    fn rejects_policy_timeout_far_above_cap() {
17349        // The "obvious authoring footgun" case: a `(:timeout "24h")`
17350        // or `(:timeout "86400s")` — values the canonical-form arm
17351        // accepts as integer-millisecond magnitudes, the codec
17352        // round-trips losslessly through serde, but the mesh-level
17353        // policy cannot honor (a 24-hour synchronous-`:contratos`
17354        // deadline is operationally indistinguishable from
17355        // omit-the-axis). Until this gate landed validate accepted
17356        // it. Pin both common above-cap values (24h, 7d) so a future
17357        // relaxation that drops the upper bound surfaces here.
17358        for timeout in [
17359            Duration::from_secs(86_400),    // 24h
17360            Duration::from_secs(604_800),   // 7d
17361            Duration::from_secs(1_000_000), // ~11.5 days
17362        ] {
17363            let mut s = three_member_spec();
17364            s.politicas.timeout = Some(timeout);
17365            assert_eq!(
17366                s.validate().unwrap_err(),
17367                AplicacaoError::PolicyTimeoutExceedsCap { timeout }
17368            );
17369        }
17370    }
17371
17372    #[test]
17373    fn accepts_policy_timeout_at_cap() {
17374        // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
17375        // must validate. The cap is inclusive on the top edge,
17376        // matching the [`POLICY_RETRIES_MAX`] /
17377        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
17378        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
17379        // sibling capped axes. Pin the boundary explicitly so a
17380        // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
17381        // instead of `>`) surfaces here as a test failure rather
17382        // than a silent contract narrowing.
17383        let mut s = three_member_spec();
17384        s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
17385        s.validate()
17386            .expect("timeout == POLICY_TIMEOUT_MAX must validate");
17387    }
17388
17389    #[test]
17390    fn accepts_policy_timeout_typical_values() {
17391        // The documented production-playbook band positive-control
17392        // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
17393        // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
17394        // plus a sweep through the long-running-workflow band
17395        // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
17396        // validated set explicitly so a future tightening of the
17397        // ceiling surfaces here as a deliberate test edit, not a
17398        // silent contract narrowing.
17399        for timeout in [
17400            Duration::from_millis(1),
17401            Duration::from_millis(500),
17402            Duration::from_secs(1),
17403            Duration::from_secs(10),
17404            Duration::from_secs(15), // Envoy default
17405            Duration::from_secs(30),
17406            Duration::from_secs(60), // AWS App Mesh typical
17407            Duration::from_secs(300),
17408            Duration::from_secs(900),
17409            Duration::from_secs(1800),
17410            Duration::from_secs(3600), // exactly 1h, the cap
17411        ] {
17412            let mut s = three_member_spec();
17413            s.politicas.timeout = Some(timeout);
17414            s.validate()
17415                .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
17416        }
17417    }
17418
17419    #[test]
17420    fn policy_timeout_zero_takes_precedence_over_cap() {
17421        // The cross-arm ordering pin: `Duration::ZERO` is
17422        // structurally outside both `>= 1ms` (zero-floor) and
17423        // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
17424        // diagnostic is the more self-locating one (it directly
17425        // names the omit-axis remediation), so the validate gate
17426        // must fire on zero first. Same shape every other
17427        // zero-then-shape ordering on this surface uses
17428        // ([`AplicacaoError::PolicyRetriesZero`] then
17429        // [`AplicacaoError::PolicyRetriesExceedsCap`];
17430        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
17431        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
17432        let mut s = three_member_spec();
17433        s.politicas.timeout = Some(Duration::ZERO);
17434        assert_eq!(
17435            s.validate().unwrap_err(),
17436            AplicacaoError::PolicyTimeoutZero,
17437            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
17438        );
17439    }
17440
17441    #[test]
17442    fn policy_timeout_canonical_takes_precedence_over_cap() {
17443        // The cross-arm ordering pin: a `Duration` that is *both*
17444        // sub-millisecond (non-canonical-form) and structurally
17445        // above the cap surfaces the canonical-form diagnostic
17446        // first, because the round-trip-shape break is the more
17447        // fundamental issue (the value can't even round-trip
17448        // through the codec, so the cap diagnostic naming
17449        // `1ms..=1h` would be misleading — there's no integer-ms
17450        // form of the offending value). Pin the order so a future
17451        // refactor that reorders the arms surfaces here as a test
17452        // failure rather than a silent diagnostic regression.
17453        let mut s = three_member_spec();
17454        // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
17455        // *and* total magnitude above the 1h cap.
17456        let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
17457        s.politicas.timeout = Some(timeout);
17458        assert_eq!(
17459            s.validate().unwrap_err(),
17460            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
17461            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
17462        );
17463    }
17464
17465    #[test]
17466    fn policy_timeout_cap_diagnostic_carries_offending_value() {
17467        // The diagnostic-shape pin: the offending `Duration` is
17468        // carried verbatim into the
17469        // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
17470        // surfaced error message names the value the author wrote
17471        // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
17472        // exceeds the mesh-policy ceiling …"`), not just the cap.
17473        // Same self-locating diagnostic shape every other typed-cap
17474        // arm on this surface carries
17475        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
17476        // offending retry count verbatim).
17477        let mut s = three_member_spec();
17478        let timeout = Duration::from_secs(7200); // 2h
17479        s.politicas.timeout = Some(timeout);
17480        let err = s.validate().unwrap_err();
17481        assert!(
17482            matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
17483            "got {err:?}"
17484        );
17485        let msg = err.to_string();
17486        assert!(
17487            msg.contains("7200"),
17488            ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
17489        );
17490    }
17491
17492    #[test]
17493    fn policy_timeout_cap_pins_canonical_value() {
17494        // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
17495        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
17496        // the shared duration codec emits as a clean canonical
17497        // string (`"<n>h"`). Pinning the literal value here surfaces
17498        // a future drift (a relaxation to 24h, a tightening to 5m)
17499        // as a deliberate test edit, not a silent contract
17500        // narrowing. Same shape every other typed-cap value pin on
17501        // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
17502        assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
17503        assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
17504    }
17505
17506    #[test]
17507    fn policy_timeout_cap_value_round_trips_through_codec() {
17508        // The codec round-trip property the cap arm preserves: the
17509        // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
17510        // the shared duration codec — every value at the cap renders
17511        // to a clean canonical string (`"1h"`) and parses back to
17512        // the same `Duration`. Pin this so a future drift between
17513        // the cap constant and the codec's largest emitted unit
17514        // surfaces here. Same shape every other typed boundary pin
17515        // on this surface uses
17516        // (`wasm32_memory_cap_matches_parsed_4_gib`).
17517        let policy = MeshPolicy {
17518            timeout: Some(POLICY_TIMEOUT_MAX),
17519            ..Default::default()
17520        };
17521        let json = serde_json::to_string(&policy).unwrap();
17522        // The codec emits `"1h"` for the canonical 1-hour magnitude.
17523        assert!(
17524            json.contains("\"1h\""),
17525            "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
17526        );
17527        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17528        assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
17529    }
17530
17531    #[test]
17532    fn rejects_circuit_breaker_window_sub_millisecond() {
17533        // Peer of the `:timeout` sub-millisecond arm on the second
17534        // typed-`Duration` `:politicas` axis: a purely sub-ms
17535        // `Duration` (`from_micros(500)`) renders through the shared
17536        // codec as `"0s"`, which the codec parses back to
17537        // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
17538        // zero-floor gate then rejects on re-validate.
17539        let mut s = three_member_spec();
17540        let window = Duration::from_micros(500);
17541        s.politicas.circuit_breaker = Some(CircuitBreaker {
17542            max_failures: 5,
17543            window,
17544        });
17545        assert_eq!(
17546            s.validate().unwrap_err(),
17547            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
17548        );
17549    }
17550
17551    #[test]
17552    fn rejects_circuit_breaker_window_non_integer_millisecond() {
17553        // Peer of the `:timeout` non-integer-ms arm: a `Duration`
17554        // with non-integer-millisecond residue renders through the
17555        // shared codec as the truncated `"<n>ms"` form, parsing back
17556        // to a *different* `Duration` on the next round-trip.
17557        let mut s = three_member_spec();
17558        let window = Duration::from_micros(1500);
17559        s.politicas.circuit_breaker = Some(CircuitBreaker {
17560            max_failures: 5,
17561            window,
17562        });
17563        assert_eq!(
17564            s.validate().unwrap_err(),
17565            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
17566        );
17567    }
17568
17569    #[test]
17570    fn accepts_circuit_breaker_window_integer_millisecond_forms() {
17571        // The canonical-forms sweep on the breaker axis: every
17572        // integer-ms multiple the codec round-trips losslessly
17573        // passes the canonical gate.
17574        for window in [
17575            Duration::from_millis(1),
17576            Duration::from_millis(500),
17577            Duration::from_millis(1500),
17578            Duration::from_secs(30),
17579            Duration::from_secs(60),
17580            Duration::from_secs(3600),
17581        ] {
17582            let mut s = three_member_spec();
17583            s.politicas.circuit_breaker = Some(CircuitBreaker {
17584                max_failures: 5,
17585                window,
17586            });
17587            s.validate()
17588                .expect("integer-millisecond :circuit-breaker :window must validate");
17589        }
17590    }
17591
17592    #[test]
17593    fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
17594        // `Duration::ZERO` would pass the canonical-ms gate (the
17595        // sub-ns residue is zero) but must surface the narrower
17596        // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
17597        // remediation.
17598        let mut s = three_member_spec();
17599        s.politicas.circuit_breaker = Some(CircuitBreaker {
17600            max_failures: 5,
17601            window: Duration::ZERO,
17602        });
17603        assert_eq!(
17604            s.validate().unwrap_err(),
17605            AplicacaoError::PolicyBreakerZeroWindow
17606        );
17607    }
17608
17609    #[test]
17610    fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
17611        // Both axes invalid: max_failures == 0 *and* window is
17612        // sub-ms. The validate gate must fire on max_failures first
17613        // (matching the existing ordering pin
17614        // `rejects_circuit_breaker_zero_max_failures` enshrines), so
17615        // the existing diagnostic continues to lead with the simpler
17616        // "zero threshold" framing.
17617        let mut s = three_member_spec();
17618        s.politicas.circuit_breaker = Some(CircuitBreaker {
17619            max_failures: 0,
17620            window: Duration::from_micros(500),
17621        });
17622        assert_eq!(
17623            s.validate().unwrap_err(),
17624            AplicacaoError::PolicyBreakerZeroFailures
17625        );
17626    }
17627
17628    #[test]
17629    fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
17630        let mut s = three_member_spec();
17631        let window = Duration::from_nanos(60_000_000_001);
17632        s.politicas.circuit_breaker = Some(CircuitBreaker {
17633            max_failures: 5,
17634            window,
17635        });
17636        match s.validate().unwrap_err() {
17637            AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
17638                assert_eq!(w, window, "diagnostic must carry the offending Duration");
17639            }
17640            other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
17641        }
17642    }
17643
17644    #[test]
17645    fn rejects_circuit_breaker_window_above_cap() {
17646        // The fail-before-pass-after pin: 3601s = 1h + 1s is
17647        // structurally one canonical-tick past the
17648        // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
17649        // integer-millisecond magnitude the canonical-form arm above
17650        // accepts cleanly, that the codec round-trips losslessly as
17651        // `"3601s"`, and that silently passed validate on every
17652        // pre-gate codebase because the typed slot's only checks were
17653        // the zero-floor and canonical-form arms. The
17654        // rolling-window-to-lifetime-counter degeneration surfaces
17655        // only at the runtime substrate (Envoy's outlier_detection
17656        // interval, the future CiliumClusterwideEnvoyConfig overlay)
17657        // far from the source `caixa.lisp` with no field naming the
17658        // offending policy.
17659        let mut s = three_member_spec();
17660        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
17661        s.politicas.circuit_breaker = Some(CircuitBreaker {
17662            max_failures: 5,
17663            window,
17664        });
17665        assert_eq!(
17666            s.validate().unwrap_err(),
17667            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
17668        );
17669    }
17670
17671    #[test]
17672    fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
17673        // Boundary case: exactly 1ms past the cap (the granularity the
17674        // canonical-form gate enforces). Catches a future "strictly
17675        // less than" half-measure and pins the diagnostic to name the
17676        // offending `Duration` verbatim. Peer of
17677        // `rejects_policy_timeout_one_millisecond_above_cap` on the
17678        // sibling duration-typed `:politicas :timeout` top edge.
17679        let mut s = three_member_spec();
17680        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
17681        s.politicas.circuit_breaker = Some(CircuitBreaker {
17682            max_failures: 5,
17683            window,
17684        });
17685        assert_eq!(
17686            s.validate().unwrap_err(),
17687            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
17688        );
17689    }
17690
17691    #[test]
17692    fn rejects_circuit_breaker_window_far_above_cap() {
17693        // The "obvious authoring footgun" case: a `(:window "24h")` or
17694        // `(:window "86400s")` — values the canonical-form arm
17695        // accepts as integer-millisecond magnitudes, the codec
17696        // round-trips losslessly through serde, but the
17697        // rolling-window breaker contract cannot honor (a 24-hour
17698        // rolling failure window is operationally a lifetime counter).
17699        // Until this gate landed validate accepted it. Pin both common
17700        // above-cap values (24h, 7d) so a future relaxation that
17701        // drops the upper bound surfaces here.
17702        for window in [
17703            Duration::from_secs(86_400),    // 24h
17704            Duration::from_secs(604_800),   // 7d
17705            Duration::from_secs(1_000_000), // ~11.5 days
17706        ] {
17707            let mut s = three_member_spec();
17708            s.politicas.circuit_breaker = Some(CircuitBreaker {
17709                max_failures: 5,
17710                window,
17711            });
17712            assert_eq!(
17713                s.validate().unwrap_err(),
17714                AplicacaoError::PolicyBreakerWindowExceedsCap { window }
17715            );
17716        }
17717    }
17718
17719    #[test]
17720    fn accepts_circuit_breaker_window_at_cap() {
17721        // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
17722        // (1h) — must validate. The cap is inclusive on the top edge,
17723        // matching the [`POLICY_TIMEOUT_MAX`] /
17724        // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
17725        // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
17726        // sibling capped axes. Pin the boundary explicitly so a
17727        // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
17728        // instead of `>`) surfaces here as a test failure rather than
17729        // a silent contract narrowing.
17730        let mut s = three_member_spec();
17731        s.politicas.circuit_breaker = Some(CircuitBreaker {
17732            max_failures: 5,
17733            window: POLICY_BREAKER_WINDOW_MAX,
17734        });
17735        s.validate()
17736            .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
17737    }
17738
17739    #[test]
17740    fn accepts_circuit_breaker_window_typical_values() {
17741        // The documented production-playbook band positive-control
17742        // sweep — every value Hystrix / resilience4j / Istio / Envoy
17743        // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
17744        // through the long-tail failure-detection band (15m, 30m, 1h)
17745        // the cap accepts. Pin the inclusive validated set explicitly
17746        // so a future tightening of the ceiling surfaces here as a
17747        // deliberate test edit, not a silent contract narrowing.
17748        for window in [
17749            Duration::from_millis(1),
17750            Duration::from_millis(500),
17751            Duration::from_secs(1),
17752            Duration::from_secs(10), // Hystrix / Istio / Envoy default
17753            Duration::from_secs(30),
17754            Duration::from_secs(60),  // resilience4j typical
17755            Duration::from_secs(300), // AWS App Mesh typical
17756            Duration::from_secs(900),
17757            Duration::from_secs(1800),
17758            Duration::from_secs(3600), // exactly 1h, the cap
17759        ] {
17760            let mut s = three_member_spec();
17761            s.politicas.circuit_breaker = Some(CircuitBreaker {
17762                max_failures: 5,
17763                window,
17764            });
17765            s.validate()
17766                .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
17767        }
17768    }
17769
17770    #[test]
17771    fn circuit_breaker_zero_window_takes_precedence_over_cap() {
17772        // The cross-arm ordering pin: `Duration::ZERO` is structurally
17773        // outside both `>= 1ms` (zero-floor) and
17774        // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
17775        // diagnostic is the more self-locating one (it directly names
17776        // the omit-axis remediation), so the validate gate must fire
17777        // on zero first. Same shape every other zero-then-cap
17778        // ordering on this surface uses
17779        // ([`AplicacaoError::PolicyTimeoutZero`] then
17780        // [`AplicacaoError::PolicyTimeoutExceedsCap`];
17781        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
17782        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
17783        let mut s = three_member_spec();
17784        s.politicas.circuit_breaker = Some(CircuitBreaker {
17785            max_failures: 5,
17786            window: Duration::ZERO,
17787        });
17788        assert_eq!(
17789            s.validate().unwrap_err(),
17790            AplicacaoError::PolicyBreakerZeroWindow,
17791            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
17792        );
17793    }
17794
17795    #[test]
17796    fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
17797        // The cross-arm ordering pin: a `Duration` that is *both*
17798        // sub-millisecond (non-canonical-form) and structurally above
17799        // the cap surfaces the canonical-form diagnostic first,
17800        // because the round-trip-shape break is the more fundamental
17801        // issue (the value can't even round-trip through the codec, so
17802        // the cap diagnostic naming `1ms..=1h` would be misleading —
17803        // there's no integer-ms form of the offending value). Pin the
17804        // order so a future refactor that reorders the arms surfaces
17805        // here as a test failure rather than a silent diagnostic
17806        // regression. Peer of
17807        // `policy_timeout_canonical_takes_precedence_over_cap` on the
17808        // sibling duration-typed `:politicas :timeout` axis.
17809        let mut s = three_member_spec();
17810        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
17811        s.politicas.circuit_breaker = Some(CircuitBreaker {
17812            max_failures: 5,
17813            window,
17814        });
17815        assert_eq!(
17816            s.validate().unwrap_err(),
17817            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
17818            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
17819        );
17820    }
17821
17822    #[test]
17823    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
17824        // The cross-arm ordering pin between the two breaker axes: a
17825        // `CircuitBreaker` whose *both* `max_failures` is above its
17826        // cap *and* `window` is above its cap surfaces the
17827        // max-failures cap diagnostic first, because the validate
17828        // gate visits the failures arm before the window arm. Pin the
17829        // order so a future refactor that reorders the breaker arms
17830        // surfaces here.
17831        let mut s = three_member_spec();
17832        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
17833        s.politicas.circuit_breaker = Some(CircuitBreaker {
17834            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
17835            window,
17836        });
17837        assert_eq!(
17838            s.validate().unwrap_err(),
17839            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
17840                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
17841            },
17842            "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
17843        );
17844    }
17845
17846    #[test]
17847    fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
17848        // The diagnostic-shape pin: the offending `Duration` is
17849        // carried verbatim into the
17850        // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
17851        // the surfaced error message names the value the author wrote
17852        // (`":politicas :circuit-breaker :window (Duration { secs:
17853        // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
17854        // just the cap. Same self-locating diagnostic shape every
17855        // other typed-cap arm on this surface carries
17856        // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
17857        // offending `Duration` verbatim).
17858        let mut s = three_member_spec();
17859        let window = Duration::from_secs(7200); // 2h
17860        s.politicas.circuit_breaker = Some(CircuitBreaker {
17861            max_failures: 5,
17862            window,
17863        });
17864        let err = s.validate().unwrap_err();
17865        assert!(
17866            matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
17867            "got {err:?}"
17868        );
17869        let msg = err.to_string();
17870        assert!(
17871            msg.contains("7200"),
17872            ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
17873        );
17874    }
17875
17876    #[test]
17877    fn circuit_breaker_window_cap_pins_canonical_value() {
17878        // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
17879        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
17880        // shared duration codec emits as a clean canonical string
17881        // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
17882        // the sibling duration-typed `:politicas :timeout` axis (the
17883        // two duration-typed `:politicas` axes share a uniform top
17884        // edge). Pinning the literal value here surfaces a future
17885        // drift (a relaxation to 24h, a tightening to 5m) as a
17886        // deliberate test edit, not a silent contract narrowing. Same
17887        // shape every other typed-cap value pin on this surface uses
17888        // (`policy_timeout_cap_pins_canonical_value`).
17889        assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
17890        assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
17891        assert_eq!(
17892            POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
17893            "the two duration-typed `:politicas` caps share the same top edge"
17894        );
17895    }
17896
17897    #[test]
17898    fn circuit_breaker_window_cap_value_round_trips_through_codec() {
17899        // The codec round-trip property the cap arm preserves: the
17900        // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
17901        // through the shared duration codec — every value at the cap
17902        // renders to a clean canonical string (`"1h"`) and parses back
17903        // to the same `Duration`. Pin this so a future drift between
17904        // the cap constant and the codec's largest emitted unit
17905        // surfaces here. Same shape every other typed boundary pin on
17906        // this surface uses
17907        // (`policy_timeout_cap_value_round_trips_through_codec`).
17908        let policy = MeshPolicy {
17909            circuit_breaker: Some(CircuitBreaker {
17910                max_failures: 5,
17911                window: POLICY_BREAKER_WINDOW_MAX,
17912            }),
17913            ..Default::default()
17914        };
17915        let json = serde_json::to_string(&policy).unwrap();
17916        // The codec emits `"1h"` for the canonical 1-hour magnitude.
17917        assert!(
17918            json.contains("\"1h\""),
17919            "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
17920        );
17921        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17922        assert_eq!(
17923            back.circuit_breaker.unwrap().window,
17924            POLICY_BREAKER_WINDOW_MAX
17925        );
17926    }
17927
17928    #[test]
17929    fn is_integer_millisecond_duration_predicate_tracks_codec() {
17930        // Pin the predicate's accepted set against the codec's
17931        // accepted set explicitly. The codec parses
17932        // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
17933        // accepted value is an integer-millisecond multiple — so the
17934        // predicate must accept exactly that set. Same shape every
17935        // other predicate-on-the-typed-slot helper carries
17936        // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
17937        // Read directly from the codec-owned predicate — the crate's
17938        // single source of truth every typed-`Duration` axis now routes
17939        // through via
17940        // [`crate::render::require_positive_canonical_bounded_duration`].
17941        use super::supervisor::duration_codec::is_integer_millisecond_duration;
17942        assert!(is_integer_millisecond_duration(Duration::ZERO));
17943        assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
17944        assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
17945        assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
17946        assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
17947        assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
17948        // Non-integer-millisecond residue: rejected.
17949        assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
17950        assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
17951        assert!(!is_integer_millisecond_duration(Duration::from_micros(
17952            1500
17953        )));
17954        assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
17955        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
17956            999_999
17957        )));
17958        // The 1-ns-past-1ms boundary: rejected (no longer a clean
17959        // integer-millisecond multiple).
17960        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
17961            1_000_001
17962        )));
17963    }
17964
17965    #[test]
17966    fn policy_timeout_validated_value_round_trips_through_codec() {
17967        // The structural property the canonical-ms gate enforces:
17968        // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
17969        // round-trips losslessly through the shared `duration_codec`
17970        // (serialize → string → deserialize → equal value). Pin this
17971        // end-to-end so a future change to either side (the validate
17972        // gate's accepted granularity, the codec's parse/render unit
17973        // set) that breaks the alignment surfaces here. The
17974        // previous-state shape (typed slot accepts arbitrary
17975        // `Duration`, codec only round-trips integer-ms) would fail
17976        // this test for any `Duration::from_micros(1500)` timeout —
17977        // the validate gate now forecloses that.
17978        for timeout in [
17979            Duration::from_millis(1),
17980            Duration::from_millis(1500),
17981            Duration::from_secs(30),
17982            Duration::from_secs(3600),
17983        ] {
17984            let mut s = three_member_spec();
17985            s.politicas.timeout = Some(timeout);
17986            s.validate().unwrap();
17987            let json = serde_json::to_string(&s.politicas).unwrap();
17988            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17989            assert_eq!(
17990                back.timeout, s.politicas.timeout,
17991                "every validated :timeout must round-trip losslessly through the codec"
17992            );
17993        }
17994    }
17995
17996    #[test]
17997    fn circuit_breaker_window_validated_value_round_trips_through_codec() {
17998        // Peer of the `:timeout` round-trip property on the breaker
17999        // axis.
18000        for window in [
18001            Duration::from_millis(1),
18002            Duration::from_millis(1500),
18003            Duration::from_secs(30),
18004            Duration::from_secs(3600),
18005        ] {
18006            let mut s = three_member_spec();
18007            s.politicas.circuit_breaker = Some(CircuitBreaker {
18008                max_failures: 5,
18009                window,
18010            });
18011            s.validate().unwrap();
18012            let json = serde_json::to_string(&s.politicas).unwrap();
18013            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18014            assert_eq!(
18015                back.circuit_breaker.unwrap().window,
18016                window,
18017                "every validated :circuit-breaker :window must round-trip losslessly"
18018            );
18019        }
18020    }
18021
18022    #[test]
18023    fn empty_politicas_validates() {
18024        // Omitting every policy axis is fine — defaults express "no
18025        // policy on this axis", not "policy = 0". The fixture's typical
18026        // values continue to validate; this test pins that
18027        // MeshPolicy::default() is a clean pass through validate().
18028        let mut s = three_member_spec();
18029        s.politicas = MeshPolicy::default();
18030        s.validate().unwrap();
18031    }
18032
18033    #[test]
18034    fn typical_politicas_validates_with_every_axis_set() {
18035        // The full §III.1 example block (timeout + retries + breaker +
18036        // mtls + rate-limit) — every axis nonzero — must remain a
18037        // clean pass.
18038        let mut s = three_member_spec();
18039        s.politicas = MeshPolicy {
18040            timeout: Some(Duration::from_secs(30)),
18041            retries: Some(3),
18042            circuit_breaker: Some(CircuitBreaker {
18043                max_failures: 5,
18044                window: Duration::from_secs(60),
18045            }),
18046            mtls_required: Some(true),
18047            rate_limit: Some(RateLimit {
18048                rate: 100,
18049                window: Duration::from_secs(1),
18050            }),
18051        };
18052        s.validate().unwrap();
18053    }
18054
18055    #[test]
18056    fn rejects_empty_cluster_name() {
18057        let mut s = three_member_spec();
18058        s.placement.clusters = vec!["rio".into(), "".into()];
18059        assert_eq!(
18060            s.validate().unwrap_err(),
18061            AplicacaoError::PlacementClusterEmpty
18062        );
18063    }
18064
18065    #[test]
18066    fn rejects_duplicate_cluster_names() {
18067        let mut s = three_member_spec();
18068        s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
18069        let err = s.validate().unwrap_err();
18070        assert!(
18071            matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
18072            "got {err:?}"
18073        );
18074    }
18075
18076    #[test]
18077    fn rejects_placement_cluster_with_uppercase() {
18078        // The canonical "I copied the cluster's display name verbatim"
18079        // typo — K8s context names are lowercase per DNS-1123 label
18080        // rule, but org docs often round-trip a TitleCase identifier
18081        // (`Rio`, `Mar-East`) from an ADR. Mirrors the
18082        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
18083        // on the peer name axis.
18084        let mut s = three_member_spec();
18085        s.placement.clusters = vec!["Rio".into(), "mar".into()];
18086        let err = s.validate().unwrap_err();
18087        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
18088            panic!("expected PlacementClusterInvalid, got other variant");
18089        };
18090        assert_eq!(cluster, "Rio");
18091        assert!(
18092            reason.contains("uppercase"),
18093            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
18094        );
18095        assert!(
18096            reason.contains("\"rio\""),
18097            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
18098        );
18099    }
18100
18101    #[test]
18102    fn rejects_placement_cluster_with_underscore() {
18103        // The canonical "I'm thinking of an env var / hostname slug"
18104        // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
18105        // schema. K8s context filtering on `my_cluster` silently misses
18106        // the cluster the author intended; the gate moves it to caixa-
18107        // build time. Same shape as `rejects_membro_caixa_with_underscore`
18108        // (3f9d7a0).
18109        let mut s = three_member_spec();
18110        s.placement.clusters = vec!["my_cluster".into()];
18111        let err = s.validate().unwrap_err();
18112        assert!(
18113            matches!(
18114                err,
18115                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
18116                    if cluster == "my_cluster" && reason.contains('_')
18117            ),
18118            "got {err:?}"
18119        );
18120    }
18121
18122    #[test]
18123    fn rejects_placement_cluster_with_dot() {
18124        // A `:placement :clusters` entry is a single DNS-1123 *label*,
18125        // not a subdomain — even though K8s context names sometimes
18126        // carry a dotted form via kubeconfig conventions, the strictest
18127        // floor among the use sites (DNS-1035 cluster.x-k8s.io
18128        // `metadata.name`, Cilium identity label values) wins. The "I
18129        // want to namespace my cluster names with `.`" intent is
18130        // expressed via `-` (`mar-east`).
18131        let mut s = three_member_spec();
18132        s.placement.clusters = vec!["team.rio".into()];
18133        let err = s.validate().unwrap_err();
18134        assert!(
18135            matches!(
18136                err,
18137                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
18138                    if cluster == "team.rio" && reason.contains('.')
18139            ),
18140            "got {err:?}"
18141        );
18142    }
18143
18144    #[test]
18145    fn rejects_placement_cluster_with_leading_hyphen() {
18146        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
18147        // with an alphanumeric. The K8s apiserver rejects `-rio`
18148        // outright; the rendered fan-out would emit a `metadata.name:
18149        // "-rio"` that fails admission far from the source caixa.lisp.
18150        let mut s = three_member_spec();
18151        s.placement.clusters = vec!["-rio".into()];
18152        let err = s.validate().unwrap_err();
18153        assert!(
18154            matches!(
18155                err,
18156                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
18157                    if cluster == "-rio" && reason.contains("start and end")
18158            ),
18159            "got {err:?}"
18160        );
18161    }
18162
18163    #[test]
18164    fn rejects_placement_cluster_with_trailing_hyphen() {
18165        // The symmetric arm of the boundary rule. Pin separately so
18166        // both ends are covered against a future relaxation that only
18167        // checks one boundary (parallel to
18168        // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
18169        let mut s = three_member_spec();
18170        s.placement.clusters = vec!["rio-".into()];
18171        let err = s.validate().unwrap_err();
18172        assert!(
18173            matches!(
18174                err,
18175                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
18176                    if cluster == "rio-"
18177            ),
18178            "got {err:?}"
18179        );
18180    }
18181
18182    #[test]
18183    fn rejects_placement_cluster_with_unicode() {
18184        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
18185        // before it reaches K8s. The byte-by-byte ASCII validity check
18186        // rejects multi-byte UTF-8 sequences by the first byte that
18187        // fails `[a-z0-9-]`.
18188        let mut s = three_member_spec();
18189        s.placement.clusters = vec!["rió".into()];
18190        let err = s.validate().unwrap_err();
18191        assert!(
18192            matches!(
18193                err,
18194                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
18195                    if cluster == "rió"
18196            ),
18197            "got {err:?}"
18198        );
18199    }
18200
18201    #[test]
18202    fn rejects_placement_cluster_with_whitespace() {
18203        // Whitespace is the canonical "I pasted from a sketch / doc"
18204        // footgun. The apiserver rejects every cluster `metadata.name`
18205        // value carrying whitespace.
18206        let mut s = three_member_spec();
18207        s.placement.clusters = vec!["rio cluster".into()];
18208        let err = s.validate().unwrap_err();
18209        assert!(
18210            matches!(
18211                err,
18212                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
18213                    if cluster == "rio cluster"
18214            ),
18215            "got {err:?}"
18216        );
18217    }
18218
18219    #[test]
18220    fn rejects_placement_cluster_too_long() {
18221        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
18222        // pin. The diagnostic names both the cap (63) and the actual
18223        // length so the author can shorten in one edit. Mirrors
18224        // `rejects_membro_caixa_too_long` (3f9d7a0).
18225        let mut s = three_member_spec();
18226        let too_long = "a".repeat(64);
18227        s.placement.clusters = vec![too_long.clone()];
18228        let err = s.validate().unwrap_err();
18229        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
18230            panic!("expected PlacementClusterInvalid");
18231        };
18232        assert_eq!(cluster, too_long);
18233        assert!(
18234            reason.contains("63") && reason.contains("64"),
18235            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
18236        );
18237    }
18238
18239    #[test]
18240    fn placement_cluster_max_length_validates() {
18241        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
18242        // future tightening (e.g. dropping to 62) surfaces here as a
18243        // regression, mirroring `membro_caixa_max_length_validates`
18244        // (3f9d7a0).
18245        let mut s = three_member_spec();
18246        s.placement.clusters = vec!["a".repeat(63)];
18247        s.validate().unwrap();
18248    }
18249
18250    #[test]
18251    fn accepts_canonical_placement_cluster_forms() {
18252        // The DNS-1123 label shapes a caixa author is realistically
18253        // going to write for cluster names: single-word lowercase
18254        // (`rio`), regional hyphen-joined (`mar-east`), single
18255        // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
18256        // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
18257        // Pin every leg so a future tightening that bans (e.g.) digit-
18258        // start identifiers surfaces here.
18259        for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
18260            let mut s = three_member_spec();
18261            s.placement.clusters = vec![form.into()];
18262            s.validate().unwrap_or_else(|e| {
18263                panic!("canonical cluster form {form:?} must validate, got {e:?}")
18264            });
18265        }
18266    }
18267
18268    #[test]
18269    fn placement_cluster_empty_takes_precedence_over_invalid() {
18270        // Order pin: the existing `PlacementClusterEmpty` diagnostic
18271        // (which doesn't try to parse) fires before the new
18272        // `PlacementClusterInvalid` parse-side diagnostic, so an empty
18273        // `:clusters` entry keeps its narrower error message — the new
18274        // gate would also reject `""`, but the empty-string arm is the
18275        // more self-locating diagnostic. Mirrors the
18276        // `membro_caixa_empty_takes_precedence_over_invalid` pin
18277        // (3f9d7a0).
18278        let mut s = three_member_spec();
18279        s.placement.clusters = vec!["rio".into(), "".into()];
18280        let err = s.validate().unwrap_err();
18281        assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
18282    }
18283
18284    #[test]
18285    fn placement_cluster_invalid_fires_before_duplicate_check() {
18286        // Order pin: a malformed-shape `:clusters` entry surfaces *its
18287        // own* diagnostic, even when a later entry would otherwise
18288        // collapse onto a duplicate name. The per-entry shape gate runs
18289        // inline before the duplicate-key insert, parallel to
18290        // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
18291        let mut s = three_member_spec();
18292        s.placement.clusters = vec!["Rio".into(), "rio".into()];
18293        let err = s.validate().unwrap_err();
18294        assert!(
18295            matches!(
18296                err,
18297                AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
18298            ),
18299            "got {err:?}"
18300        );
18301    }
18302
18303    #[test]
18304    fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
18305        // The diagnostic-shape pin: the error names the offending
18306        // `:clusters` value verbatim so the author can grep their
18307        // caixa.lisp without re-running the build, and carries a
18308        // non-empty `reason` naming the specific violation. Same shape
18309        // every typed-shape gate enshrines
18310        // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
18311        // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
18312        let mut s = three_member_spec();
18313        s.placement.clusters = vec!["BAD_CLUSTER".into()];
18314        let err = s.validate().unwrap_err();
18315        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
18316            panic!("expected PlacementClusterInvalid");
18317        };
18318        assert_eq!(cluster, "BAD_CLUSTER");
18319        assert!(
18320            !reason.is_empty(),
18321            "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
18322        );
18323    }
18324
18325    #[test]
18326    fn rejects_sharded_with_empty_clusters() {
18327        // §III.1: Sharded uses :clusters as the shard pool. An empty
18328        // pool means "shard across no clusters" — meaningless, same as
18329        // Replicated with no hosts.
18330        let mut s = three_member_spec();
18331        s.placement.estrategia = PlacementStrategy::Sharded;
18332        s.placement.shard_key = Some("$tenantId".into());
18333        s.placement.clusters = vec![];
18334        assert!(matches!(
18335            s.validate().unwrap_err(),
18336            AplicacaoError::PlacementWithoutClusters {
18337                estrategia: PlacementStrategy::Sharded
18338            }
18339        ));
18340    }
18341
18342    #[test]
18343    fn rejects_sharded_with_empty_shard_key() {
18344        let mut s = three_member_spec();
18345        s.placement.estrategia = PlacementStrategy::Sharded;
18346        s.placement.shard_key = Some("".into());
18347        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
18348    }
18349
18350    #[test]
18351    fn rejects_shard_key_under_replicated_strategy() {
18352        // The fail-before-pass-after pin: a `:placement (:estrategia
18353        // Replicated :shard-key "tenantId")` manifest carries the
18354        // hash-keyed-distribution slot on a strategy that never consumes
18355        // it. Before the gate the typed slot's value silently vanished
18356        // at the renderer layer (caixa-mesh emits `placement.shardKey`
18357        // verbatim regardless of strategy; the Akka-style cluster-
18358        // sharding reconciler keys off `estrategia == Sharded` and
18359        // ignores the slot otherwise), with no diagnostic. Lifting the
18360        // rejection to a build-time gate makes the
18361        // `shard_key.is_some() == matches!(estrategia, Sharded)`
18362        // partition a structural property of every validated
18363        // [`Placement`].
18364        let mut s = three_member_spec();
18365        // The fixture already uses Replicated; just add a shard-key.
18366        s.placement.shard_key = Some("$tenantId".into());
18367        let err = s.validate().unwrap_err();
18368        let AplicacaoError::ShardKeyOnNonSharded {
18369            estrategia,
18370            shard_key,
18371        } = err
18372        else {
18373            panic!("expected ShardKeyOnNonSharded, got {err:?}");
18374        };
18375        assert_eq!(estrategia, PlacementStrategy::Replicated);
18376        assert_eq!(shard_key, "$tenantId");
18377    }
18378
18379    #[test]
18380    fn rejects_shard_key_under_singlenode_strategy() {
18381        // Peer of the Replicated case above on the SingleNode arm: OTP
18382        // distributed-app takeover (one cluster runs at a time) has no
18383        // hash-keyed routing axis to consume `:shard-key` either, so
18384        // the rejection fires on both non-Sharded arms uniformly.
18385        let mut s = three_member_spec();
18386        s.placement.estrategia = PlacementStrategy::SingleNode;
18387        s.placement.shard_key = Some("$tenantId".into());
18388        let err = s.validate().unwrap_err();
18389        let AplicacaoError::ShardKeyOnNonSharded {
18390            estrategia,
18391            shard_key,
18392        } = err
18393        else {
18394            panic!("expected ShardKeyOnNonSharded, got {err:?}");
18395        };
18396        assert_eq!(estrategia, PlacementStrategy::SingleNode);
18397        assert_eq!(shard_key, "$tenantId");
18398    }
18399
18400    #[test]
18401    fn rejects_empty_shard_key_under_replicated_strategy() {
18402        // The `Some("")` case under non-Sharded is rejected by
18403        // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
18404        // fires before the empty-value gate), not
18405        // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
18406        // the `Sharded` arm). Pin the partition so a future reorder of
18407        // the validate_placement match arms doesn't silently swap which
18408        // diagnostic the author sees — both are author errors, but
18409        // ShardKeyOnNonSharded names which strategy is the actual fix
18410        // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
18411        // only says "pick a non-empty key".
18412        let mut s = three_member_spec();
18413        s.placement.shard_key = Some(String::new());
18414        let err = s.validate().unwrap_err();
18415        assert!(
18416            matches!(
18417                err,
18418                AplicacaoError::ShardKeyOnNonSharded {
18419                    estrategia: PlacementStrategy::Replicated,
18420                    ref shard_key,
18421                } if shard_key.is_empty()
18422            ),
18423            "got {err:?}"
18424        );
18425    }
18426
18427    #[test]
18428    fn replicated_without_shard_key_validates() {
18429        // The complement of the rejection: `:placement :estrategia
18430        // Replicated` with `:shard-key None` is the canonical happy
18431        // path on every existing fixture. Pin the no-shard-key case so
18432        // the new gate doesn't accidentally fire on `None`.
18433        let mut s = three_member_spec();
18434        assert!(matches!(
18435            s.placement.estrategia,
18436            PlacementStrategy::Replicated
18437        ));
18438        s.placement.shard_key = None;
18439        s.validate().unwrap();
18440    }
18441
18442    #[test]
18443    fn singlenode_without_shard_key_validates() {
18444        // Peer of the Replicated no-shard-key case on the SingleNode
18445        // arm — both non-Sharded strategies must validate cleanly when
18446        // the slot is omitted.
18447        let mut s = three_member_spec();
18448        s.placement.estrategia = PlacementStrategy::SingleNode;
18449        s.placement.shard_key = None;
18450        s.validate().unwrap();
18451    }
18452
18453    fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
18454        // Fixture builder for the `:placement :shard-key` shape gate
18455        // tests: a three-member Aplicacao on the `Sharded` strategy
18456        // with the supplied `:shard-key` slot. Co-locates the
18457        // arm-construction so every test below carries one line of
18458        // setup (the offending `:shard-key` value) and the assertion.
18459        let mut s = three_member_spec();
18460        s.placement.estrategia = PlacementStrategy::Sharded;
18461        s.placement.shard_key = Some(key.into());
18462        s
18463    }
18464
18465    #[test]
18466    fn rejects_shard_key_with_embedded_space() {
18467        // The canonical paste-from-aligned-doc footgun:
18468        // `:shard-key "$tenant Id"` — the Akka-style entity-id
18469        // extractor reads the slot as a single-token reference, and an
18470        // embedded space breaks the token boundary at the runtime
18471        // hash-extractor pass with no diagnostic naming the offending
18472        // entry.
18473        let s = sharded_spec_with_key("$tenant Id");
18474        let err = s.validate().unwrap_err();
18475        assert!(
18476            matches!(
18477                err,
18478                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
18479                    if shard_key == "$tenant Id" && reason.contains("space")
18480            ),
18481            "got {err:?}"
18482        );
18483    }
18484
18485    #[test]
18486    fn rejects_shard_key_with_leading_space() {
18487        // Leading-space arm of the embedded-whitespace footgun — the
18488        // paste-from-aligned-doc / paste-from-CSV-cell variant where
18489        // the leading column-padding leaked into the slot.
18490        let s = sharded_spec_with_key(" $tenantId");
18491        let err = s.validate().unwrap_err();
18492        assert!(
18493            matches!(
18494                err,
18495                AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
18496                    if shard_key == " $tenantId"
18497            ),
18498            "got {err:?}"
18499        );
18500    }
18501
18502    #[test]
18503    fn rejects_shard_key_with_trailing_newline() {
18504        // The canonical paste-from-shell-heredoc footgun — every
18505        // `<<EOF` heredoc terminator paste leaves a trailing newline
18506        // the YAML emitter then folds away inconsistently across
18507        // emitter implementations.
18508        let s = sharded_spec_with_key("$tenantId\n");
18509        let err = s.validate().unwrap_err();
18510        assert!(
18511            matches!(
18512                err,
18513                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
18514                    if shard_key == "$tenantId\n" && reason.contains("0x0a")
18515            ),
18516            "got {err:?}"
18517        );
18518    }
18519
18520    #[test]
18521    fn rejects_shard_key_with_embedded_tab() {
18522        // The paste-from-aligned-doc tab-stop variant — tabs land
18523        // alongside spaces in copy-paste from formatted columns.
18524        let s = sharded_spec_with_key("$tenant\tId");
18525        let err = s.validate().unwrap_err();
18526        assert!(
18527            matches!(
18528                err,
18529                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
18530                    if shard_key == "$tenant\tId" && reason.contains("tab")
18531            ),
18532            "got {err:?}"
18533        );
18534    }
18535
18536    #[test]
18537    fn rejects_shard_key_with_control_character() {
18538        // The paste-from-binary / paste-from-screen-cleared-terminal
18539        // footgun — an embedded `\x01` (SOH) byte that some YAML
18540        // emitters silently strip and others escape as ``,
18541        // breaking round-trip across emitter implementations.
18542        let s = sharded_spec_with_key("$tenant\u{0001}Id");
18543        let err = s.validate().unwrap_err();
18544        assert!(
18545            matches!(
18546                err,
18547                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
18548                    if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
18549            ),
18550            "got {err:?}"
18551        );
18552    }
18553
18554    #[test]
18555    fn rejects_shard_key_with_non_ascii() {
18556        // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
18557        // footgun — non-ASCII bytes normalize differently between the
18558        // caixa-mesh-side YAML emitter and the in-cluster reconciler's
18559        // YAML parser, the same entity ID can silently map to two
18560        // distinct shards on a re-render.
18561        let s = sharded_spec_with_key("$tenàntId");
18562        let err = s.validate().unwrap_err();
18563        assert!(
18564            matches!(
18565                err,
18566                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
18567                    if shard_key == "$tenàntId" && reason.contains("non-ASCII")
18568            ),
18569            "got {err:?}"
18570        );
18571    }
18572
18573    #[test]
18574    fn rejects_shard_key_too_long() {
18575        // Length cap pin: 64 bytes — one byte over the
18576        // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
18577        // here is a paste-from-doc multi-line blob landing in
18578        // `:shard-key` instead of a single-token extractor expression.
18579        let too_long = "a".repeat(64);
18580        let s = sharded_spec_with_key(&too_long);
18581        let err = s.validate().unwrap_err();
18582        let AplicacaoError::ShardKeyInvalid {
18583            ref shard_key,
18584            ref reason,
18585        } = err
18586        else {
18587            panic!("expected ShardKeyInvalid, got {err:?}");
18588        };
18589        assert_eq!(shard_key, &too_long);
18590        assert!(
18591            reason.contains("63") && reason.contains("64"),
18592            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
18593        );
18594    }
18595
18596    #[test]
18597    fn shard_key_max_length_validates() {
18598        // Boundary pin: 63 bytes exactly — the
18599        // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
18600        // dropping to 62) surfaces here as a regression, mirroring
18601        // `placement_cluster_max_length_validates` /
18602        // `placement_affinity_max_length_validates` on the peer
18603        // identifier-shaped slots.
18604        let s = sharded_spec_with_key(&"a".repeat(63));
18605        s.validate().unwrap();
18606    }
18607
18608    #[test]
18609    fn accepts_canonical_shard_key_forms() {
18610        // The Akka-style entity-id extractor shapes a caixa author is
18611        // realistically going to write — pin every leg so a future
18612        // tightening that bans (e.g.) the `${...}` interpolation
18613        // variant or the `metadata.<field>` JSONPath form surfaces
18614        // here as a regression. The canonical forms span:
18615        //
18616        //   - bare property name (`tenantId`, `customerId`)
18617        //   - Akka `ExtractEntityId` placeholder (`$tenantId`)
18618        //   - JSONPath-style nested reference (`metadata.tenantId`,
18619        //     `$.user.id`)
18620        //   - interpolation-style template (`${tenant}`)
18621        //   - snake_case property name (`customer_id`)
18622        //   - kebab-case property name (`customer-id` — accepted
18623        //     because the slot is a printable-ASCII single-token
18624        //     reference, not a DNS-1123 label like
18625        //     `:placement :affinity` / `:clusters`)
18626        //   - single character (`a`, `$` — boundary)
18627        for form in [
18628            "tenantId",
18629            "customerId",
18630            "$tenantId",
18631            "metadata.tenantId",
18632            "$.user.id",
18633            "${tenant}",
18634            "customer_id",
18635            "customer-id",
18636            "a",
18637            "$",
18638        ] {
18639            let s = sharded_spec_with_key(form);
18640            s.validate().unwrap_or_else(|e| {
18641                panic!("canonical shard-key form {form:?} must validate, got {e:?}")
18642            });
18643        }
18644    }
18645
18646    #[test]
18647    fn shard_key_empty_takes_precedence_over_invalid() {
18648        // Order pin: the existing `ShardedKeyEmpty` diagnostic
18649        // (reserved for the `Sharded` `Some("")` arm) fires before the
18650        // new `ShardKeyInvalid` parse-side diagnostic, so an empty
18651        // `:shard-key` keeps its narrower error message — the new gate
18652        // would also reject `""` defensively, but the empty-string arm
18653        // is the more self-locating diagnostic. Mirrors the
18654        // `placement_cluster_empty_takes_precedence_over_invalid` pin
18655        // on the peer identifier-shaped slot.
18656        let s = sharded_spec_with_key("");
18657        let err = s.validate().unwrap_err();
18658        assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
18659    }
18660
18661    #[test]
18662    fn shard_key_invalid_diagnostic_carries_offending_value() {
18663        // The diagnostic-shape pin: the error names the offending
18664        // `:shard-key` value verbatim so the author can grep their
18665        // caixa.lisp without re-running the build, and carries a
18666        // parser-shaped `reason:` naming the specific violation —
18667        // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
18668        // on the peer identifier-shaped slot.
18669        let s = sharded_spec_with_key("$tenant Id");
18670        let err = s.validate().unwrap_err();
18671        let AplicacaoError::ShardKeyInvalid {
18672            ref shard_key,
18673            ref reason,
18674        } = err
18675        else {
18676            panic!("expected ShardKeyInvalid, got {err:?}");
18677        };
18678        assert_eq!(shard_key, "$tenant Id");
18679        assert!(
18680            !reason.is_empty(),
18681            "reason must name the specific violation, got empty string"
18682        );
18683    }
18684
18685    #[test]
18686    fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
18687        // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
18688        // `:shard-key` carried on non-Sharded strategies) fires before
18689        // the shape gate, so a malformed `:shard-key` carried on (e.g.)
18690        // a `Replicated` strategy surfaces the more self-locating
18691        // strategy-mismatch diagnostic (naming the actual fix — drop
18692        // the slot, or switch to Sharded) rather than the shape
18693        // diagnostic. The strategy-mismatch arm is the more actionable
18694        // diagnostic: a malformed shard-key on Replicated is "you
18695        // shouldn't have a :shard-key here at all", not "your
18696        // :shard-key value is malformed".
18697        let mut s = three_member_spec();
18698        // Replicated is the default fixture strategy.
18699        s.placement.shard_key = Some("$tenant Id".into());
18700        let err = s.validate().unwrap_err();
18701        assert!(
18702            matches!(
18703                err,
18704                AplicacaoError::ShardKeyOnNonSharded {
18705                    estrategia: PlacementStrategy::Replicated,
18706                    ..
18707                }
18708            ),
18709            "got {err:?}"
18710        );
18711    }
18712
18713    #[test]
18714    fn rejects_empty_affinity_hint() {
18715        let mut s = three_member_spec();
18716        s.placement.affinity = Some("".into());
18717        assert_eq!(
18718            s.validate().unwrap_err(),
18719            AplicacaoError::PlacementAffinityEmpty
18720        );
18721    }
18722
18723    #[test]
18724    fn placement_without_affinity_validates() {
18725        // Omitting :affinity is fine — the placement engine falls back
18726        // to the default heuristic. Pin the no-hint case so the
18727        // affinity-empty rejection doesn't accidentally fire on `None`.
18728        let mut s = three_member_spec();
18729        s.placement.affinity = None;
18730        s.validate().unwrap();
18731    }
18732
18733    #[test]
18734    fn rejects_placement_affinity_with_uppercase() {
18735        // The canonical "I copied the ADR's display name verbatim" typo
18736        // — placement hints land verbatim in K8s label-selector
18737        // territory, where the apiserver enforces the DNS-1123 label
18738        // rule (lowercase-only) on every identity-keyed admission axis.
18739        // Mirrors `rejects_placement_cluster_with_uppercase` on the
18740        // sibling slot.
18741        let mut s = three_member_spec();
18742        s.placement.affinity = Some("DataLocality".into());
18743        let err = s.validate().unwrap_err();
18744        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
18745            panic!("expected PlacementAffinityInvalid, got other variant");
18746        };
18747        assert_eq!(affinity, "DataLocality");
18748        assert!(
18749            reason.contains("uppercase"),
18750            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
18751        );
18752        assert!(
18753            reason.contains("\"datalocality\""),
18754            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
18755        );
18756    }
18757
18758    #[test]
18759    fn rejects_placement_affinity_with_underscore() {
18760        // The canonical "I'm thinking of an env var / Python identifier"
18761        // leak — `_` is forbidden by every DNS-1123 label schema. Same
18762        // shape as `rejects_placement_cluster_with_underscore` on the
18763        // sibling slot.
18764        let mut s = three_member_spec();
18765        s.placement.affinity = Some("data_locality".into());
18766        let err = s.validate().unwrap_err();
18767        assert!(
18768            matches!(
18769                err,
18770                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
18771                    if affinity == "data_locality" && reason.contains('_')
18772            ),
18773            "got {err:?}"
18774        );
18775    }
18776
18777    #[test]
18778    fn rejects_placement_affinity_with_dot() {
18779        // A `:placement :affinity` value is a single DNS-1123 *label*
18780        // (it lands as a K8s label value selector key), not a subdomain.
18781        // The "I want to namespace my hint with `.`" intent is expressed
18782        // via `-` (`data-locality-east`).
18783        let mut s = three_member_spec();
18784        s.placement.affinity = Some("data.locality".into());
18785        let err = s.validate().unwrap_err();
18786        assert!(
18787            matches!(
18788                err,
18789                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
18790                    if affinity == "data.locality" && reason.contains('.')
18791            ),
18792            "got {err:?}"
18793        );
18794    }
18795
18796    #[test]
18797    fn rejects_placement_affinity_with_unicode() {
18798        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
18799        // before it reaches K8s. The byte-by-byte ASCII validity check
18800        // rejects multi-byte UTF-8 sequences by the first byte that
18801        // fails `[a-z0-9-]`.
18802        let mut s = three_member_spec();
18803        s.placement.affinity = Some("data-localité".into());
18804        let err = s.validate().unwrap_err();
18805        assert!(
18806            matches!(
18807                err,
18808                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
18809                    if affinity == "data-localité"
18810            ),
18811            "got {err:?}"
18812        );
18813    }
18814
18815    #[test]
18816    fn rejects_placement_affinity_with_leading_hyphen() {
18817        // DNS-1123 boundary rule: labels must start with an
18818        // alphanumeric. Pin separately from the trailing-hyphen arm so
18819        // a future relaxation that only checks one boundary surfaces
18820        // here as a regression (parallel to
18821        // `rejects_placement_cluster_with_leading_hyphen`).
18822        let mut s = three_member_spec();
18823        s.placement.affinity = Some("-data-locality".into());
18824        let err = s.validate().unwrap_err();
18825        assert!(
18826            matches!(
18827                err,
18828                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
18829                    if affinity == "-data-locality" && reason.contains("start and end")
18830            ),
18831            "got {err:?}"
18832        );
18833    }
18834
18835    #[test]
18836    fn rejects_placement_affinity_with_trailing_hyphen() {
18837        // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
18838        // ends are covered against a future relaxation.
18839        let mut s = three_member_spec();
18840        s.placement.affinity = Some("data-locality-".into());
18841        let err = s.validate().unwrap_err();
18842        assert!(
18843            matches!(
18844                err,
18845                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
18846                    if affinity == "data-locality-"
18847            ),
18848            "got {err:?}"
18849        );
18850    }
18851
18852    #[test]
18853    fn rejects_placement_affinity_with_whitespace() {
18854        // Whitespace is the canonical "I pasted from a sketch / doc"
18855        // footgun. The apiserver rejects every label-selector value
18856        // carrying whitespace.
18857        let mut s = three_member_spec();
18858        s.placement.affinity = Some("data locality".into());
18859        let err = s.validate().unwrap_err();
18860        assert!(
18861            matches!(
18862                err,
18863                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
18864                    if affinity == "data locality"
18865            ),
18866            "got {err:?}"
18867        );
18868    }
18869
18870    #[test]
18871    fn rejects_placement_affinity_too_long() {
18872        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
18873        // pin. The diagnostic names both the cap (63) and the actual
18874        // length so the author can shorten in one edit. Mirrors
18875        // `rejects_placement_cluster_too_long`.
18876        let mut s = three_member_spec();
18877        let too_long = "a".repeat(64);
18878        s.placement.affinity = Some(too_long.clone());
18879        let err = s.validate().unwrap_err();
18880        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
18881            panic!("expected PlacementAffinityInvalid");
18882        };
18883        assert_eq!(affinity, too_long);
18884        assert!(
18885            reason.contains("63") && reason.contains("64"),
18886            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
18887        );
18888    }
18889
18890    #[test]
18891    fn placement_affinity_max_length_validates() {
18892        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
18893        // future tightening (e.g. dropping to 62) surfaces here as a
18894        // regression, mirroring `placement_cluster_max_length_validates`.
18895        let mut s = three_member_spec();
18896        s.placement.affinity = Some("a".repeat(63));
18897        s.validate().unwrap();
18898    }
18899
18900    #[test]
18901    fn accepts_canonical_placement_affinity_forms() {
18902        // The DNS-1123 label shapes a caixa author is realistically
18903        // going to write for placement hints: the M3 canonical examples
18904        // (`data-locality`, `low-latency`, `anti-affinity`), the
18905        // single-token form (`affinity`), the single-character boundary
18906        // (`a`), the digit-start (DNS-1123 allows this, unlike
18907        // DNS-1035), and a regional-suffixed form. Pin every leg so a
18908        // future tightening that bans (e.g.) digit-start identifiers
18909        // surfaces here.
18910        for form in [
18911            "data-locality",
18912            "low-latency",
18913            "anti-affinity",
18914            "affinity",
18915            "a",
18916            "3-tier",
18917            "locality-east",
18918        ] {
18919            let mut s = three_member_spec();
18920            s.placement.affinity = Some(form.into());
18921            s.validate().unwrap_or_else(|e| {
18922                panic!("canonical affinity form {form:?} must validate, got {e:?}")
18923            });
18924        }
18925    }
18926
18927    #[test]
18928    fn placement_affinity_empty_takes_precedence_over_invalid() {
18929        // Order pin: the existing `PlacementAffinityEmpty` diagnostic
18930        // (which doesn't try to parse) fires before the new
18931        // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
18932        // `:affinity` keeps its narrower error message — the new gate
18933        // would also reject `""`, but the empty-string arm is the more
18934        // self-locating diagnostic. Mirrors the
18935        // `placement_cluster_empty_takes_precedence_over_invalid` pin.
18936        let mut s = three_member_spec();
18937        s.placement.affinity = Some(String::new());
18938        let err = s.validate().unwrap_err();
18939        assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
18940    }
18941
18942    #[test]
18943    fn placement_affinity_invalid_diagnostic_carries_offending_value() {
18944        // The diagnostic shape pin: every rejection carries the offending
18945        // `affinity:` verbatim plus a parser-shaped `reason:` so the
18946        // author can grep their caixa.lisp for `:affinity "<hint>"` and
18947        // fix it in one edit. Mirrors the
18948        // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
18949        // pin on the sibling slot.
18950        let mut s = three_member_spec();
18951        s.placement.affinity = Some("Data_Locality".into());
18952        let err = s.validate().unwrap_err();
18953        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
18954            panic!("expected PlacementAffinityInvalid");
18955        };
18956        assert_eq!(affinity, "Data_Locality");
18957        assert!(
18958            !reason.is_empty(),
18959            "diagnostic reason must not be empty (got: {reason:?})"
18960        );
18961    }
18962
18963    #[test]
18964    fn singlenode_with_takeover_candidates_validates() {
18965        // OTP distributed-application convention (MESH-COMPOSITION
18966        // §II.1): SingleNode runs on one cluster at a time but the
18967        // :clusters list enumerates the takeover candidates. Multiple
18968        // entries are not a contradiction — they are the failover pool.
18969        let mut s = three_member_spec();
18970        s.placement.estrategia = PlacementStrategy::SingleNode;
18971        s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
18972        s.validate().unwrap();
18973    }
18974
18975    // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
18976
18977    #[test]
18978    fn mesh_policy_default_is_empty() {
18979        // The Default impl carries None on every axis — the typed
18980        // analog of an unset `:politicas (())` slot. Renderers that
18981        // overlay the policy onto a cluster artifact key off this
18982        // predicate to skip the slot entirely; pinning so a future
18983        // axis added to MeshPolicy can't silently break the contract
18984        // (a new field whose Default is non-None would flip is_empty
18985        // to false on every existing caixa, surfacing here).
18986        assert!(MeshPolicy::default().is_empty());
18987    }
18988
18989    #[test]
18990    fn mesh_policy_with_only_timeout_is_not_empty() {
18991        let p = MeshPolicy {
18992            timeout: Some(Duration::from_secs(30)),
18993            ..Default::default()
18994        };
18995        assert!(!p.is_empty());
18996    }
18997
18998    #[test]
18999    fn mesh_policy_with_only_retries_is_not_empty() {
19000        let p = MeshPolicy {
19001            retries: Some(3),
19002            ..Default::default()
19003        };
19004        assert!(!p.is_empty());
19005    }
19006
19007    #[test]
19008    fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
19009        let p = MeshPolicy {
19010            circuit_breaker: Some(CircuitBreaker {
19011                max_failures: 5,
19012                window: Duration::from_secs(60),
19013            }),
19014            ..Default::default()
19015        };
19016        assert!(!p.is_empty());
19017    }
19018
19019    #[test]
19020    fn mesh_policy_with_only_mtls_required_is_not_empty() {
19021        // Even `mtls_required: Some(false)` (an explicit opt-out) is
19022        // not empty — the author *named* the axis, the renderer needs
19023        // to honor that vs. fall back to the cluster default.
19024        let p = MeshPolicy {
19025            mtls_required: Some(false),
19026            ..Default::default()
19027        };
19028        assert!(!p.is_empty());
19029    }
19030
19031    #[test]
19032    fn mesh_policy_with_only_rate_limit_is_not_empty() {
19033        let p = MeshPolicy {
19034            rate_limit: Some(RateLimit {
19035                rate: 100,
19036                window: Duration::from_secs(1),
19037            }),
19038            ..Default::default()
19039        };
19040        assert!(!p.is_empty());
19041    }
19042
19043    #[test]
19044    fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
19045        // The three-member happy-path fixture sets timeout + retries +
19046        // mtls_required — every populated axis must read non-empty.
19047        // Pin the round-trip so the M3.x per-:politicas emitter (the
19048        // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
19049        // on is_empty() to decide whether to emit at all without
19050        // re-deriving the contract from inline field probes.
19051        assert!(!three_member_spec().politicas.is_empty());
19052    }
19053
19054    // ── shared duration codec: cross-slot integer-magnitude gate ──
19055    //
19056    // The integer-magnitude discipline applied to
19057    // `supervisor::duration_codec::parse` lifts onto every typed slot
19058    // that routes through the shared codec — `MeshPolicy::timeout`
19059    // (`:politicas :timeout`) and `CircuitBreaker::window`
19060    // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
19061    // These cross-slot tests pin that the gate fires at the serde
19062    // layer for both typed slots, not just for the supervisor side.
19063
19064    #[test]
19065    fn policy_timeout_serde_rejects_fractional_seconds() {
19066        // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
19067        // so the shared codec's integer-magnitude gate applies on
19068        // deserialize. `"1.5s"` previously parsed to 1500ms and round-
19069        // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
19070        // deserialize with the canonical-form diagnostic naming the
19071        // offending `"1.5"` and the remediation `"1500ms"`.
19072        let payload = r#"{"timeout":"1.5s"}"#;
19073        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19074        let msg = err.to_string();
19075        assert!(
19076            msg.contains("not a non-negative integer"),
19077            "expected integer-magnitude diagnostic in {msg:?}"
19078        );
19079        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
19080        assert!(
19081            msg.contains("\"1500ms\""),
19082            "missing canonical-form remediation in {msg:?}"
19083        );
19084    }
19085
19086    #[test]
19087    fn policy_timeout_serde_rejects_leading_plus_sign() {
19088        // Pin the leading-`+` arm cross-slot — the prior f64 parser
19089        // accepted `"+30s"` silently and round-tripped to `"30s"`.
19090        let payload = r#"{"timeout":"+30s"}"#;
19091        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19092        let msg = err.to_string();
19093        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
19094    }
19095
19096    #[test]
19097    fn circuit_breaker_window_serde_rejects_fractional_minutes() {
19098        // `CircuitBreaker::window` uses `with =
19099        // "supervisor::duration_codec_required"` (the required-Duration
19100        // variant that delegates to the same shared parser). `"0.5m"`
19101        // parsed to 30s and round-tripped to `"30s"` on next emit —
19102        // DRIFT closed.
19103        let payload = format!(
19104            r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
19105            max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
19106            window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
19107        );
19108        let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
19109        let msg = err.to_string();
19110        assert!(
19111            msg.contains("not a non-negative integer"),
19112            "expected integer-magnitude diagnostic in {msg:?}"
19113        );
19114        assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
19115        assert!(
19116            msg.contains("\"30s\""),
19117            "missing canonical-form remediation in {msg:?}"
19118        );
19119    }
19120
19121    #[test]
19122    fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
19123        // Pin the happy-path on the cross-slot side: every canonical
19124        // author shape `render` ever emits parses cleanly through the
19125        // shared codec on the `CircuitBreaker` slot. The
19126        // codec's accepted set (post-gate) is exactly its emitted set
19127        // for the integer-magnitude class.
19128        for window_lit in ["30s", "500ms", "2m", "1h"] {
19129            let payload = format!(
19130                r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
19131                max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
19132                window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
19133            );
19134            let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
19135                panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
19136            });
19137            assert_eq!(cb.max_failures, 5);
19138        }
19139    }
19140
19141    // ── rate_limit_codec: integer-magnitude gate ──
19142    //
19143    // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
19144    // / 737a676 / d53c922 trajectory landed on every typed-duration /
19145    // typed-byte-size codec in caixa-core lifts onto the fifth typed
19146    // codec — `rate_limit_codec` — through the digit-only magnitude
19147    // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
19148    // These tests pin the gate at the serde layer for `:politicas
19149    // :rate-limit` (the only typed slot the codec backs), and at the
19150    // codec-internal `parse` layer for the canonical positive cases.
19151
19152    #[test]
19153    fn rate_limit_serde_rejects_fractional_rate() {
19154        // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
19155        // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
19156        // wording, which didn't name the canonical-form remediation or
19157        // the round-trip drift the next emit would produce. Now refused
19158        // at deserialize with the canonical-form diagnostic naming the
19159        // offending `"1.5"` magnitude and the round-trip drift wording.
19160        let payload = r#"{"rateLimit":"1.5/s"}"#;
19161        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19162        let msg = err.to_string();
19163        assert!(
19164            msg.contains("not a non-negative integer"),
19165            "expected integer-magnitude diagnostic in {msg:?}"
19166        );
19167        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
19168        assert!(
19169            msg.contains("THEORY.md"),
19170            "missing render-determinism contract citation in {msg:?}"
19171        );
19172    }
19173
19174    #[test]
19175    fn rate_limit_serde_rejects_leading_plus_sign() {
19176        // `u32::from_str("+100")` returns `Ok(100)` (Rust's
19177        // permissive-`+` parse), so `"+100/s"` silently parsed to
19178        // `RateLimit { 100, 1s }` and round-tripped through `render` to
19179        // `"100/s"` — a *different* canonical string on the next emit,
19180        // breaking the THEORY.md Part V render-determinism contract
19181        // exactly the way the peer duration codecs' `"+30s"` case did.
19182        // This is the load-bearing class the digit-only gate closes
19183        // beyond what `u32::from_str`'s strictness covers on its own.
19184        let payload = r#"{"rateLimit":"+100/s"}"#;
19185        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19186        let msg = err.to_string();
19187        assert!(
19188            msg.contains("not a non-negative integer"),
19189            "expected integer-magnitude diagnostic in {msg:?}"
19190        );
19191        assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
19192    }
19193
19194    #[test]
19195    fn rate_limit_serde_rejects_leading_minus_sign() {
19196        // The signed-negative arm: `"-1/s"` lands on the
19197        // non-canonical-but-numeric branch via the `i64` fallback (the
19198        // `f64` parse also succeeds), surfacing the canonical-form
19199        // diagnostic. Replaces the prior value-laundered "not a u32"
19200        // wording with the unified diagnostic across signs.
19201        let payload = r#"{"rateLimit":"-1/s"}"#;
19202        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19203        let msg = err.to_string();
19204        assert!(
19205            msg.contains("not a non-negative integer"),
19206            "expected integer-magnitude diagnostic in {msg:?}"
19207        );
19208        assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
19209    }
19210
19211    #[test]
19212    fn rate_limit_serde_rejects_decimal_shaped_integer() {
19213        // `"100.0/s"` is integer-valued numerically but not in the
19214        // codec's accepted set — `render` emits `"100/s"`, so the
19215        // round-trip would drift. Lifted to the canonical-form
19216        // diagnostic peer with the duration codec's `"1.0s"` case
19217        // (1c55a2a).
19218        let payload = r#"{"rateLimit":"100.0/s"}"#;
19219        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19220        let msg = err.to_string();
19221        assert!(
19222            msg.contains("not a non-negative integer"),
19223            "expected integer-magnitude diagnostic in {msg:?}"
19224        );
19225        assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
19226    }
19227
19228    #[test]
19229    fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
19230        // Non-numeric, non-digit-only input lands on the existing
19231        // narrower `"not a u32"` arm (preserved for diagnostic-shape
19232        // stability on the parser-shape footgun case). Pin this so a
19233        // future relaxation of the numeric-fallback predicate doesn't
19234        // silently collapse garbage onto the canonical-form arm — same
19235        // partition the peer duration codecs draw between
19236        // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
19237        let payload = r#"{"rateLimit":"abc/s"}"#;
19238        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19239        let msg = err.to_string();
19240        assert!(
19241            msg.contains("not a u32"),
19242            "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
19243        );
19244        assert!(
19245            !msg.contains("not a non-negative integer"),
19246            "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
19247        );
19248    }
19249
19250    #[test]
19251    fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
19252        // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
19253        // u32's range. The digit-only gate passes; `u32::from_str`
19254        // fails on overflow. Surface that with the overflow-shaped
19255        // diagnostic naming the offending magnitude verbatim, peer
19256        // with `supervisor::duration_codec`'s overflow arm. Pinning
19257        // the wording so a future refactor doesn't silently collapse
19258        // overflow onto the canonical-form arm.
19259        let payload = r#"{"rateLimit":"4294967296/s"}"#;
19260        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19261        let msg = err.to_string();
19262        assert!(
19263            msg.contains("overflows u32"),
19264            "expected overflow diagnostic in {msg:?}"
19265        );
19266        assert!(
19267            msg.contains("\"4294967296\""),
19268            "missing offending magnitude in {msg:?}"
19269        );
19270    }
19271
19272    #[test]
19273    fn rate_limit_serde_rejects_leading_zero_magnitude() {
19274        // `"0100/s"` is digit-only, so the existing
19275        // non-digit-only / sign / fractional arm doesn't catch it —
19276        // `u32::from_str("0100")` returns `Ok(100)`, so before this
19277        // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
19278        // round-tripped through `render` to `"100/s"` — a *different*
19279        // canonical string on the next emit, breaking the THEORY.md
19280        // Part V render-determinism contract exactly the way the
19281        // peer `"+100/s"` case did before the leading-`+` arm landed.
19282        // This is the load-bearing class the leading-zero gate closes
19283        // beyond what the existing digit-only / sign / fractional
19284        // gates cover, and the peer arm to the leading-`+` test
19285        // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
19286        // canonical-form-drift axis.
19287        let payload = r#"{"rateLimit":"0100/s"}"#;
19288        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19289        let msg = err.to_string();
19290        assert!(
19291            msg.contains("non-canonical leading zero"),
19292            "expected leading-zero diagnostic in {msg:?}"
19293        );
19294        assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
19295        assert!(
19296            msg.contains("THEORY.md"),
19297            "missing render-determinism contract citation in {msg:?}"
19298        );
19299    }
19300
19301    #[test]
19302    fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
19303        // `"00/s"` is the degenerate leading-zero case — every byte
19304        // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
19305        // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
19306        // a *different* canonical string, same render-determinism
19307        // violation. The single-byte `"0/s"` itself is in the
19308        // accepted set (round-trips losslessly through `render`,
19309        // refused downstream by `PolicyRateLimitZero`); the
19310        // multi-byte `"00/s"` is not. Pins the boundary between the
19311        // accepted single-`0` and the rejected leading-zero class.
19312        let payload = r#"{"rateLimit":"00/s"}"#;
19313        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19314        let msg = err.to_string();
19315        assert!(
19316            msg.contains("non-canonical leading zero"),
19317            "expected leading-zero diagnostic in {msg:?}"
19318        );
19319        assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
19320    }
19321
19322    #[test]
19323    fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
19324        // Cross-window pin — the gate is window-agnostic; the
19325        // leading-zero class is a property of the magnitude, not the
19326        // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
19327        // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
19328        // single-window coverage extended across the three canonical
19329        // windows the codec accepts.
19330        let payload = r#"{"rateLimit":"007/h"}"#;
19331        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19332        let msg = err.to_string();
19333        assert!(
19334            msg.contains("non-canonical leading zero"),
19335            "expected leading-zero diagnostic in {msg:?}"
19336        );
19337        assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
19338    }
19339
19340    #[test]
19341    fn rate_limit_serde_rejects_leading_whitespace() {
19342        // `" 100/s"` — the canonical paste-from-aligned-doc /
19343        // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
19344        // the top-level `s.trim()` silently ate the leading space and
19345        // parsed the value to `RateLimit { 100, 1s }`, which then
19346        // round-tripped through `render` to `"100/s"` (a *different*
19347        // canonical string on the next emit) — the exact
19348        // canonical-form-drift class the leading-`+` / leading-zero
19349        // arms already close, extended to the whitespace byte class.
19350        let payload = r#"{"rateLimit":" 100/s"}"#;
19351        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19352        let msg = err.to_string();
19353        assert!(
19354            msg.contains("contains whitespace byte"),
19355            "expected whitespace diagnostic in {msg:?}"
19356        );
19357        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
19358        assert!(
19359            msg.contains("THEORY.md"),
19360            "missing render-determinism contract citation in {msg:?}"
19361        );
19362    }
19363
19364    #[test]
19365    fn rate_limit_serde_rejects_trailing_whitespace() {
19366        // `"100/s "` — the canonical shell-history / trailing-space
19367        // paste footgun. Before this gate the top-level `s.trim()`
19368        // silently ate the trailing space and parsed to
19369        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
19370        // next emit — same canonical-form drift as the leading-space
19371        // sibling, closed on the same whitespace-byte arm.
19372        let payload = r#"{"rateLimit":"100/s "}"#;
19373        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19374        let msg = err.to_string();
19375        assert!(
19376            msg.contains("contains whitespace byte"),
19377            "expected whitespace diagnostic in {msg:?}"
19378        );
19379        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
19380    }
19381
19382    #[test]
19383    fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
19384        // `"100 / s"` — the canonical typographically-spaced author
19385        // shape (the same idiom every prose reference to a rate limit
19386        // renders as, mistakenly retained when the value is pasted
19387        // into a codec-shaped slot). Before this gate the per-part
19388        // `rate_str.trim()` / `unit.trim()` calls silently ate both
19389        // spaces on either side of `/` and parsed to
19390        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
19391        // codec's *internal* whitespace-tolerance vector, orthogonal
19392        // to the leading / trailing surface but the same canonical-
19393        // form-drift class. Pins the arm as strictly stronger than the
19394        // pre-existing top-level `s.trim()` behavior: it fires on
19395        // whitespace anywhere in the value, not just at the string
19396        // boundary.
19397        let payload = r#"{"rateLimit":"100 / s"}"#;
19398        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19399        let msg = err.to_string();
19400        assert!(
19401            msg.contains("contains whitespace byte"),
19402            "expected whitespace diagnostic in {msg:?}"
19403        );
19404        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
19405    }
19406
19407    #[test]
19408    fn rate_limit_serde_rejects_tab_byte() {
19409        // `"\t100/s"` — the canonical paste-from-indented-doc /
19410        // paste-from-YAML-block-scalar footgun where a tab byte leads
19411        // the magnitude. Pins that the gate covers tab (`0x09`) as
19412        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
19413        // members and both would be silently swallowed by `s.trim()`
19414        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
19415        // space alone to the full ASCII-whitespace set (space `0x20`,
19416        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
19417        // the tab arm as a representative of the non-space members.
19418        let payload = r#"{"rateLimit":"\t100/s"}"#;
19419        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19420        let msg = err.to_string();
19421        assert!(
19422            msg.contains("contains whitespace byte"),
19423            "expected whitespace diagnostic in {msg:?}"
19424        );
19425        assert!(
19426            msg.contains("0x09"),
19427            "missing offending tab byte in {msg:?}"
19428        );
19429    }
19430
19431    // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
19432    //
19433    // Successor to the ASCII-whitespace arm (1ad7755) on
19434    // `rate_limit_codec` — closes the strictly-complementary class the
19435    // byte-scan cannot see, through the lifted
19436    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
19437
19438    #[test]
19439    fn rate_limit_serde_rejects_leading_nbsp() {
19440        // NBSP prefix — paste-from-typography footgun. Byte-scan
19441        // misses, `str::trim` silently strips it, value drifts to
19442        // `"100/s"` on next serialize.
19443        let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
19444        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19445        let msg = err.to_string();
19446        assert!(
19447            msg.contains("non-ASCII Unicode whitespace character"),
19448            "expected non-ASCII whitespace diagnostic in {msg:?}"
19449        );
19450        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
19451    }
19452
19453    #[test]
19454    fn rate_limit_serde_rejects_internal_em_space() {
19455        // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
19456        // paste-from-typography footgun on the `<integer>/<unit>`
19457        // shape.
19458        let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
19459        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19460        let msg = err.to_string();
19461        assert!(
19462            msg.contains("non-ASCII Unicode whitespace character"),
19463            "expected non-ASCII whitespace diagnostic in {msg:?}"
19464        );
19465        assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
19466    }
19467
19468    #[test]
19469    fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
19470        // Positive-control pin: every ASCII-only canonical form the
19471        // renderer emits stays accepted through the new arm.
19472        for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
19473            let payload = format!(r#"{{"rateLimit":{lit}}}"#);
19474            let p: MeshPolicy = serde_json::from_str(&payload)
19475                .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
19476            assert!(p.rate_limit.is_some());
19477        }
19478    }
19479
19480    #[test]
19481    fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
19482        // The boundary case — `"0/s"` is the canonical form
19483        // `render(RateLimit { 0, 1s })` emits, so the codec accepts
19484        // it at the parse layer; the downstream
19485        // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
19486        // `rate == 0` at the typed-validate layer above. Pins the
19487        // partition: the leading-zero gate at the codec layer does
19488        // not poach the rate-zero semantic-validation arm at the
19489        // typed-validate layer above (a future stricter codec must
19490        // not reject `"0/s"` here, or it'd collapse the diagnostic
19491        // partitioning that lets `PolicyRateLimitZero` name the
19492        // offending typed slot).
19493        let payload = r#"{"rateLimit":"0/s"}"#;
19494        let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
19495            panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
19496        });
19497        let rl = policy.rate_limit.expect("rate_limit must be Some");
19498        assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
19499        assert_eq!(
19500            rl.window,
19501            Duration::from_secs(1),
19502            "single-`0` magnitude with `s` unit must parse to window=1s"
19503        );
19504    }
19505
19506    #[test]
19507    fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
19508        // The complementary boundary pin — every magnitude
19509        // `render` emits starts with `[1-9]` (or is the single byte
19510        // `"0"`), so the canonical-form predicate is `(len == 1) ||
19511        // (first byte != '0')`. Pinning the `len > 1 && first byte ==
19512        // '1'` case explicitly so a future tightening of the gate
19513        // (e.g. an over-eager "no leading digit < 5" rule, or a
19514        // mistakenly anchored start-of-magnitude byte check) lands
19515        // here before the canonical-forms-iterating test would catch
19516        // it.
19517        let payload = r#"{"rateLimit":"100/s"}"#;
19518        let policy: MeshPolicy = serde_json::from_str(payload)
19519            .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
19520        let rl = policy.rate_limit.expect("rate_limit must be Some");
19521        assert_eq!(
19522            rl.rate, 100,
19523            "canonical-100 magnitude must parse to rate=100"
19524        );
19525    }
19526
19527    #[test]
19528    fn rate_limit_serde_accepts_integer_canonical_forms() {
19529        // Pin the happy-path: every canonical author shape `render`
19530        // ever emits parses cleanly through the codec post-gate. The
19531        // codec's accepted set (post-gate) is exactly its emitted set
19532        // for the integer-magnitude class — same property
19533        // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
19534        // gates guarantee on the peer codecs. Iterating across rate
19535        // magnitudes (including `"0"`, which the codec accepts even
19536        // though `validate_politicas` rejects `rate == 0` at the typed
19537        // layer above) closes the codec contract at the parse layer
19538        // independently of the validate layer.
19539        for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
19540            for unit_lit in ["s", "m", "h"] {
19541                let lit = format!("{rate_lit}/{unit_lit}");
19542                let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
19543                let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
19544                    panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
19545                });
19546                let rl = policy.rate_limit.expect("rate_limit must be Some");
19547                assert_eq!(
19548                    rl.rate,
19549                    rate_lit.parse::<u32>().unwrap(),
19550                    "rate mismatch for {lit:?}"
19551                );
19552            }
19553        }
19554    }
19555
19556    #[test]
19557    fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
19558        // The structural property the gate enforces: serialize ∘
19559        // deserialize is the identity on every canonical author shape.
19560        // Peer of `parse_byte_size`'s and `parse_duration`'s
19561        // `_round_trips_through_render_for_every_canonical_form` tests
19562        // on the rate-limit axis. Before the gate, `"+100/s"` violated
19563        // this (`parse` → `RateLimit { 100, 1s }` → `render` →
19564        // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
19565        for rate in [1u32, 100, 5000, 1_000_000] {
19566            for (window, unit) in [
19567                (Duration::from_secs(1), "s"),
19568                (Duration::from_secs(60), "m"),
19569                (Duration::from_secs(3600), "h"),
19570            ] {
19571                let policy = MeshPolicy {
19572                    rate_limit: Some(RateLimit { rate, window }),
19573                    ..Default::default()
19574                };
19575                let json = serde_json::to_string(&policy).unwrap();
19576                let expected = format!("\"{rate}/{unit}\"");
19577                assert!(
19578                    json.contains(&expected),
19579                    "expected {expected:?} in {json:?}"
19580                );
19581                let back: MeshPolicy = serde_json::from_str(&json).unwrap();
19582                assert_eq!(
19583                    back.rate_limit, policy.rate_limit,
19584                    "round-trip for {json:?}"
19585                );
19586            }
19587        }
19588    }
19589
19590    // ── self-membership cross-slot gate ──────────────────────────────
19591
19592    #[test]
19593    fn validate_no_self_membership_rejects_self_named_membro() {
19594        // An Aplicacao whose `:membros` lists its own `:nome` is a
19595        // one-node lacre-closure recursion — rejected, naming the parent.
19596        let membros = vec![
19597            membro("catalog", "^0.1"),
19598            membro("checkout", "^0.1"),
19599            membro("cart", "^0.1"),
19600        ];
19601        let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
19602        assert!(
19603            matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
19604            "got {err:?}"
19605        );
19606    }
19607
19608    #[test]
19609    fn validate_no_self_membership_accepts_distinct_membros() {
19610        // Positive control: distinct member names (including a member
19611        // that is itself an Aplicacao — recursive composition is valid,
19612        // MESH-COMPOSITION §V) pass the gate.
19613        let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
19614        validate_no_self_membership(&membros, "checkout").unwrap();
19615    }
19616
19617    #[test]
19618    fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
19619        // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
19620        // `NoMembros` arm (the more-fundamental "graph must have nodes"
19621        // gate), not by this cross-slot self-edge gate. Keeping the
19622        // self-membership predicate vacuously-ok on the empty input
19623        // matches its supervisor-axis peer
19624        // (`validate_no_self_supervision_empty_children_is_ok`) and
19625        // makes the gate composable from any future call site (an M4
19626        // CR materializer's per-membros validator) without re-checking
19627        // emptiness.
19628        validate_no_self_membership(&[], "checkout").unwrap();
19629    }
19630
19631    #[test]
19632    fn validate_no_self_membership_diagnostic_names_offending_caixa() {
19633        // Pinning the Display: the self-membership diagnostic must name
19634        // the offending caixa verbatim + the "lists itself" framing the
19635        // author can grep for, so the cluster-far failure surfaces at
19636        // build time with one-line remediation. Same diagnostic shape
19637        // as the supervisor-axis `ChildSupervisesSelf` peer.
19638        let membros = vec![membro("orquestra", "^0.1")];
19639        let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
19640        let msg = err.to_string();
19641        assert!(
19642            msg.contains("orquestra"),
19643            "diagnostic must name the offending caixa nome (got: {msg:?})"
19644        );
19645        assert!(
19646            msg.contains("lists itself"),
19647            "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
19648        );
19649    }
19650
19651    #[test]
19652    fn default_servico_port_constant_pins_canonical_8080_literal() {
19653        // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
19654        // at the verbatim `8080` literal both consumers (the
19655        // `Entrada::port` serde default via [`default_port`] and the
19656        // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
19657        // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
19658        // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
19659        // discipline (a085b26) on the per-renderer canonical-K8s-axis
19660        // string-constant axis: a future refactor that drifts the
19661        // constant out from under either consumer surfaces here ahead
19662        // of every per-renderer's first emission. The literal value
19663        // matches the well-known HTTP-alt port the `pleme-computeunit`
19664        // library chart already emits as its `trigger.service.port`
19665        // default — by construction the same value the substrate
19666        // assumes about every Servico's in-cluster L4 listener.
19667        assert_eq!(
19668            DEFAULT_SERVICO_PORT, 8080,
19669            "canonical Servico port literal must remain `8080` verbatim — \
19670             this is the value both the `Entrada::port` serde default and the \
19671             caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
19672        );
19673    }
19674
19675    #[test]
19676    fn default_port_helper_returns_canonical_servico_port_constant() {
19677        // The bridge-arm — pins that the [`default_port`] helper
19678        // [`Entrada::port`]'s `#[serde(default = "default_port")]`
19679        // attribute hooks routes through the lifted
19680        // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
19681        // literal. A future refactor that re-introduces the `8080`
19682        // literal at the helper's return site (silently re-opening
19683        // the drift footgun this lift closed) surfaces here ahead of
19684        // every author-side `(:entrada (:host … :para …))` slot
19685        // without an explicit `:port`. Peer with the
19686        // `default_namespace_re_export_points_at_caixa_core_canonical`
19687        // pin on the caixa-mesh-side re-export axis.
19688        assert_eq!(
19689            default_port(),
19690            DEFAULT_SERVICO_PORT,
19691            "the serde-default helper must route through the lifted constant"
19692        );
19693    }
19694
19695    #[test]
19696    fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
19697        // The end-to-end pin — an author-surface `(:entrada (:host …
19698        // :para …))` without an explicit `:port` slot deserializes to
19699        // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
19700        // verbatim. Routes the canonical lifted constant through both
19701        // the serde-default machinery (the `#[serde(default =
19702        // "default_port")]` attribute) and the typed-value-shape
19703        // contract (the resulting [`Entrada::port`] value). A future
19704        // refactor that drifts either axis — replacing the serde
19705        // hook's helper, changing the typed slot's wire shape — would
19706        // surface here before any per-renderer's CNP / Gateway /
19707        // HTTPRoute emission consumed the drifted default.
19708        let entrada: Entrada =
19709            serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
19710        assert_eq!(
19711            entrada.port, DEFAULT_SERVICO_PORT,
19712            "the serde default must materialize as the lifted canonical Servico port"
19713        );
19714    }
19715
19716    #[test]
19717    fn servico_port_min_pins_canonical_accept_set_floor() {
19718        // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
19719        // verbatim `1` literal every typed `:entrada :port` acceptance
19720        // gate keys off. Peer with the
19721        // [`default_servico_port_constant_pins_canonical_8080_literal`]
19722        // discipline on the canonical-Servico-port-constant axis: a
19723        // future refactor that drifts the accept-set floor out from
19724        // under the sole consumer at [`AplicacaoSpec::validate`]'s
19725        // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
19726        // every per-`:entrada` `EntradaPortZero` diagnostic. The
19727        // literal value matches the IANA-registered TCP/UDP port
19728        // space floor (`1..=65535` — port `0` is the "any ephemeral"
19729        // sentinel, not a well-defined destination the substrate's
19730        // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
19731        // axis can honor).
19732        assert_eq!(
19733            SERVICO_PORT_MIN, 1,
19734            "canonical Servico port accept-set floor must remain `1` verbatim — \
19735             this is the value the `AplicacaoSpec::validate` gate at \
19736             `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
19737        );
19738    }
19739
19740    #[test]
19741    fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
19742        // The cross-const invariant pin — the substrate's canonical
19743        // default port must satisfy its own accept-set floor by
19744        // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
19745        // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
19746        // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
19747        // override the operator pins through a future
19748        // `:placement :default-port` slot that lands out-of-range, a
19749        // per-edition Servico-port migration that lifted the floor
19750        // above the previous default without coordinating the pair —
19751        // would silently invalidate the serde-default emission at
19752        // every author-side `(:entrada (:host … :para …))` slot
19753        // without an explicit `:port`: the default port would fall
19754        // below the accept-set floor, the `AplicacaoSpec::validate`
19755        // gate would reject every default-carrying Aplicacao as
19756        // `EntradaPortZero`, and the substrate's typed
19757        // `(defcaixa … :kind Aplicacao)` surface would fail validate
19758        // on every Aplicacao whose author omitted `:entrada :port`
19759        // for the substrate's chosen default — a class of authoring-
19760        // surface footguns the compile-time pin structurally closes.
19761        // Peer with the
19762        // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
19763        // (27f9b34) cross-const invariant pin discipline on the peer
19764        // canonical-Helm-per-values-block child-chart-enablement-toggle
19765        // axis pair.
19766        assert!(
19767            SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
19768            "the substrate's canonical default port ({DEFAULT_SERVICO_PORT}) must \
19769             satisfy its own accept-set floor (SERVICO_PORT_MIN = {SERVICO_PORT_MIN}) — \
19770             every default-carrying `(:entrada (:host … :para …))` slot without an \
19771             explicit `:port` inherits `DEFAULT_SERVICO_PORT` through the serde default \
19772             hook and must pass the `AplicacaoSpec::validate` floor gate by construction"
19773        );
19774    }
19775
19776    #[test]
19777    fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
19778        // The gate-site pin — asserts the `AplicacaoSpec::validate`
19779        // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
19780        // `EntradaPortZero` diagnostic on the below-floor input
19781        // `port: 0` (the only below-floor value the `u16` field can
19782        // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
19783        // is the singleton `{0}`). A future refactor that drifts the
19784        // gate off the lifted const (silently re-introducing an
19785        // inline `if e.port == 0` byte-check) surfaces here — the
19786        // pin cannot distinguish `< 1` from `== 0` on the current
19787        // floor, but it *does* pin that the diagnostic fires on `0`
19788        // through whichever gate is wired, so any future accept-set
19789        // floor migration (a hypothetical unprivileged-only
19790        // migration lifting `SERVICO_PORT_MIN` to `1024`) must
19791        // update this test alongside the const declaration —
19792        // structurally guaranteeing the gate + accept-set + pin
19793        // trio move together. Peer with the
19794        // [`rejects_zero_entrada_port`] behavioral pin on the same
19795        // per-`:entrada :port` axis — that pin asserts the pre-lift
19796        // behavioral contract (`port: 0` → `EntradaPortZero`); this
19797        // pin adds the structural link to the lifted floor const.
19798        assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
19799        let mut s = three_member_spec();
19800        s.entrada.as_mut().unwrap().port = 0;
19801        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
19802    }
19803
19804    // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
19805
19806    #[test]
19807    fn membro_serde_keys_match_lifted_membro_key_consts() {
19808        // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
19809        // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
19810        // name the exact camelCase JSON keys the
19811        // `#[serde(rename_all = "camelCase")]` attribute on
19812        // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
19813        // that each canonical byte-sequence appears verbatim in the
19814        // JSON — a future accidental `rename_all = "snake_case"` /
19815        // `"kebab-case"` / verbatim-field-name flip at the derive
19816        // attribute (any of which would silently break every downstream
19817        // JSON consumer that reaches for one of the two consts via
19818        // `Value::get(...)`) surfaces here as a build-time test failure
19819        // at `aplicacao.rs`, not as an apply-time
19820        // `.get(<stale-canonical-const>)` returning `None` far from the
19821        // derive-attr drift's commit. Peer with the sibling
19822        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
19823        // (40cc4e5) pin on the M2 supervision-tree top-level axis —
19824        // same discipline the SupervisorSpec top-level lift established,
19825        // extended here to the M3 [`Membro`] per-`:membros` axis.
19826        let m = Membro {
19827            caixa: "catalog".into(),
19828            versao: "^0.1".into(),
19829        };
19830        let json = serde_json::to_string(&m).unwrap();
19831        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
19832            let quoted = format!("\"{key}\"");
19833            assert!(
19834                json.contains(&quoted),
19835                "serialized Membro must carry the lifted MEMBRO_KEY_* \
19836                 byte-sequence {quoted} verbatim in the JSON emission \
19837                 (got: {json})",
19838            );
19839        }
19840    }
19841
19842    #[test]
19843    fn membro_key_consts_are_pairwise_distinct() {
19844        // Cross-axis drift-detection pin: a future collapse of the two
19845        // canonical [`Membro`] per-entry byte-strings onto the same
19846        // value (e.g. an accidental copy-paste flip of
19847        // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
19848        // silently reroute every downstream probe on one axis onto the
19849        // sibling axis's overlay entry and pass every propagation-probe
19850        // test that expected only the stale axis's value. Peer of the
19851        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
19852        // (40cc4e5).
19853        let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
19854        for (i, a) in all.iter().enumerate() {
19855            for b in all.iter().skip(i + 1) {
19856                assert_ne!(
19857                    a, b,
19858                    "MEMBRO_KEY_* consts must be pairwise-distinct \
19859                     canonical byte-sequences — got `{a}` == `{b}`",
19860                );
19861            }
19862        }
19863    }
19864
19865    // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
19866    //    URL-path fallback resolver every HTTPRoute-aware renderer
19867    //    reaching for a per-rule path-list resolution routes through.
19868    //    The four pin tests below fix the four-way accept-set the
19869    //    resolver must always honor: (:paths-non-empty-verbatim,
19870    //    :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
19871    //    :paths-preserves-order-across-multiple-entries) — drift on any
19872    //    arm surfaces at caixa-core build time rather than at cluster-
19873    //    apply time. Peer discipline with `MeshPolicy::is_empty` on the
19874    //    sibling `:politicas` typed-primitive dispatch axis.
19875
19876    fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
19877        Entrada {
19878            host: "example.com".into(),
19879            para: "cart".into(),
19880            paths: paths.into_iter().map(String::from).collect(),
19881            port: DEFAULT_SERVICO_PORT,
19882        }
19883    }
19884
19885    #[test]
19886    fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
19887        // The typed `:entrada :paths` slot carries an author-declared
19888        // list — the resolver returns each entry verbatim, no
19889        // catch-all substitution. The canonical "author declared
19890        // paths, honor them verbatim" arm of the path-list dispatch.
19891        let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
19892        assert_eq!(
19893            e.resolved_paths(),
19894            vec!["/api/cart", "/api/products"],
19895            "resolved_paths must return each `:entrada :paths` entry \
19896             verbatim when the typed slot is non-empty (got {:?})",
19897            e.resolved_paths(),
19898        );
19899    }
19900
19901    #[test]
19902    fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
19903        // Empty `:entrada :paths` slot — the resolver substitutes the
19904        // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
19905        // catch-all fallback verbatim. Pins the empty-arm of the
19906        // resolver's four-way accept-set against a future silent
19907        // detour that returned an empty Vec (which would emit an
19908        // HTTPRoute with zero rules — silently dropping every
19909        // external `:entrada` flow at admission time), routed to a
19910        // different fallback shape, or dropped the catch-all
19911        // altogether.
19912        let e = entrada_with_paths(vec![]);
19913        assert_eq!(
19914            e.resolved_paths(),
19915            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
19916            "resolved_paths on empty `:entrada :paths` must fall back \
19917             to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
19918             all — got {:?}",
19919            e.resolved_paths(),
19920        );
19921    }
19922
19923    #[test]
19924    fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
19925        // Single-entry `:entrada :paths` — the resolver returns the
19926        // single declared path verbatim, NOT the catch-all fallback
19927        // (author declared a path, honor it — the empty-arm and the
19928        // len-1 arm are semantically distinct axes of the resolver's
19929        // accept-set). Pins that the resolver treats "author declared
19930        // one path" as authored input, not as the empty case.
19931        let e = entrada_with_paths(vec!["/api/only"]);
19932        assert_eq!(
19933            e.resolved_paths(),
19934            vec!["/api/only"],
19935            "resolved_paths on single-entry `:entrada :paths` must \
19936             return the declared path verbatim, NOT the catch-all \
19937             fallback (got {:?})",
19938            e.resolved_paths(),
19939        );
19940    }
19941
19942    #[test]
19943    fn resolved_paths_preserves_author_declared_order() {
19944        // The `:entrada :paths` list is author-ordered — the resolver
19945        // preserves the author's declaration order verbatim, since
19946        // per-rule dispatch order at the K8s Gateway API HTTPRoute
19947        // consumer is significant (first-match-wins under the
19948        // path-prefix matcher). Pins against a future silent
19949        // re-sort / dedup / normalize detour that reordered author
19950        // input.
19951        let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
19952        assert_eq!(
19953            e.resolved_paths(),
19954            vec!["/z/last", "/a/first", "/m/mid"],
19955            "resolved_paths must preserve author-declared `:entrada \
19956             :paths` order verbatim — got {:?}",
19957            e.resolved_paths(),
19958        );
19959    }
19960
19961    // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
19962    //    slot `&[String]` slice accessor every per-`:entrada` consumer
19963    //    that must see the author's declaration verbatim (not the
19964    //    fallback-applied projection the sibling `resolved_paths`
19965    //    returns) routes through. The three pin tests below fix the
19966    //    accept-set the accessor must honor: (:non-empty-byte-equal,
19967    //    :empty-projects-empty-slice, :preserves-author-declared-order)
19968    //    — drift on any arm surfaces at caixa-core build time rather
19969    //    than at cluster-apply time. Peer discipline with the sibling
19970    //    [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
19971    //    peer M3 mesh-slot `Vec<String>`-carry axis.
19972
19973    #[test]
19974    fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
19975        // Byte-equal pin: [`Entrada::paths`] must project the raw
19976        // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
19977        // slice borrowed from the typed slot's own [`Vec<String>`]
19978        // storage — no re-ordering, no dedup, no per-entry normalization,
19979        // no fallback substitution (the fallback-applying projection is
19980        // the sibling [`Entrada::resolved_paths`] resolver). Pins against
19981        // a future silent detour that re-normalized the list, dropped
19982        // duplicates the [`AplicacaoSpec::validate`]
19983        // `EntradaPathDuplicate` refusal already rejects at build time,
19984        // or (most severe) accidentally routed through the fallback-
19985        // applying sibling and returned the substrate catch-all when
19986        // the author declared an empty list — collapsing the raw-slot
19987        // and fallback-applied axes into one and breaking the
19988        // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
19989        //
19990        // Peer of the sibling
19991        // [`Placement::clusters`]-shape byte-equal pin
19992        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
19993        // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
19994        let fixtures: Vec<Vec<String>> = vec![
19995            Vec::new(),
19996            vec!["/api/cart".into()],
19997            vec!["/api/cart".into(), "/api/products".into()],
19998            vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
19999        ];
20000        for paths in fixtures {
20001            let e = Entrada {
20002                host: "example.com".into(),
20003                para: "cart".into(),
20004                paths: paths.clone(),
20005                port: DEFAULT_SERVICO_PORT,
20006            };
20007            assert_eq!(
20008                e.paths(),
20009                paths.as_slice(),
20010                "Entrada::paths must return :entrada :paths verbatim \
20011                 (got {:?}, expected {:?})",
20012                e.paths(),
20013                paths.as_slice(),
20014            );
20015            assert_eq!(
20016                e.paths(),
20017                e.paths.as_slice(),
20018                "Entrada::paths accessor and .paths.as_slice() field \
20019                 access must byte-equal — the accessor is the substrate-\
20020                 primitive typed dispatch every downstream per-`:entrada` \
20021                 raw-slot path-list consumer must route through",
20022            );
20023            assert_eq!(
20024                e.paths().len(),
20025                e.paths.len(),
20026                "Entrada::paths().len() must byte-equal self.paths.len() \
20027                 — a length drift would silently split the paired \
20028                 pre-flight cascade-head `.is_empty()` probe input in \
20029                 the sibling [`Entrada::resolved_paths`] resolver from \
20030                 the per-entry validate loop's traversal input in \
20031                 [`AplicacaoSpec::validate`]",
20032            );
20033        }
20034    }
20035
20036    #[test]
20037    fn resolved_paths_reads_through_lifted_paths_accessor() {
20038        // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
20039        // pre-flight `.paths().is_empty()` cascade-head probe (which
20040        // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
20041        // catch-all fallback arm when the accessor projects the empty
20042        // slice) and the per-entry `.paths().iter().map(String::as_str)`
20043        // projection (which must reach every entry in the same order
20044        // the accessor projects, so the sibling
20045        // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
20046        // per-entry projection stay in lockstep by construction) must
20047        // both key off the lifted accessor. Pins the two-site coherence
20048        // by exercising each production consumer end-to-end: (1) the
20049        // catch-all-fallback arm under the empty slice, (2) the
20050        // author-declared-verbatim arm under a two-entry cohort whose
20051        // per-entry projection must byte-equal the input's per-entry
20052        // author-declared paths in the author's declared order.
20053        //
20054        // Peer of the sibling M3
20055        // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
20056        // `validate_placement_reads_through_lifted_clusters_accessor`
20057        // on the sibling `Placement::clusters` reader-site convergence.
20058        let empty = entrada_with_paths(vec![]);
20059        assert_eq!(
20060            empty.resolved_paths(),
20061            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
20062            "resolved_paths on empty :entrada :paths must trip the \
20063             lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
20064             catch-all fallback — routing through the lifted paths() \
20065             accessor must not silently drop the fallback arm",
20066        );
20067
20068        let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
20069        assert_eq!(
20070            declared.resolved_paths(),
20071            vec!["/api/cart", "/api/products"],
20072            "resolved_paths on non-empty :entrada :paths must return each \
20073             entry verbatim in the author's declared order — routing \
20074             through the lifted paths() accessor must not silently \
20075             reorder or drop entries",
20076        );
20077        // Byte-equal pin against the raw-slot accessor to keep the
20078        // fallback-applying resolver's per-entry projection input in
20079        // lockstep with the raw-slot accessor's projection.
20080        let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
20081        assert_eq!(
20082            declared.resolved_paths(),
20083            raw_projected,
20084            "resolved_paths non-empty projection must byte-equal the \
20085             lifted paths() accessor's per-entry String::as_str projection \
20086             — the two projections share the same input slice by \
20087             construction, so any drift here would surface a silent \
20088             re-ordering / dedup / normalization detour in the resolver",
20089        );
20090    }
20091
20092    #[test]
20093    fn validate_reads_through_lifted_entrada_paths_accessor() {
20094        // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
20095        // per-entry value-shape gate's `for p in e.paths()` traversal
20096        // (which must reach every entry in the same order the accessor
20097        // projects, so both the per-entry `EntradaPathEmpty` /
20098        // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
20099        // the duplicate-detection HashSet insert that trips
20100        // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
20101        // projection) must route through the lifted accessor. Pins the
20102        // coherence by exercising each production consumer end-to-end:
20103        // (1) the `EntradaPathEmpty` refusal fires on the second entry
20104        // of a two-entry cohort whose head is valid but tail is empty
20105        // (which requires the loop to reach the second entry through
20106        // the accessor), and (2) the `EntradaPathDuplicate` refusal
20107        // fires on the second entry of a two-entry cohort that shares
20108        // a path (which requires the loop to reach both entries — a
20109        // first-entry-only projection would silently pass since the
20110        // dedup HashSet has room for the first insert).
20111        //
20112        // Peer of the sibling
20113        // `validate_placement_reads_through_lifted_clusters_accessor`
20114        // on the sibling `Placement::clusters` reader-site convergence.
20115        let base = crate::AplicacaoSpec {
20116            membros: vec![crate::Membro {
20117                caixa: "cart".into(),
20118                versao: "^0.1".into(),
20119            }],
20120            contratos: Vec::new(),
20121            politicas: crate::MeshPolicy::default(),
20122            placement: crate::Placement {
20123                estrategia: crate::PlacementStrategy::SingleNode,
20124                clusters: vec!["rio".into()],
20125                shard_key: None,
20126                affinity: None,
20127            },
20128            entrada: Some(Entrada {
20129                host: "example.com".into(),
20130                para: "cart".into(),
20131                paths: vec!["/api/cart".into(), String::new()],
20132                port: DEFAULT_SERVICO_PORT,
20133            }),
20134        };
20135        assert_eq!(
20136            base.validate(),
20137            Err(crate::AplicacaoError::EntradaPathEmpty),
20138            "validate must trip EntradaPathEmpty on the second entry of \
20139             a two-entry cohort — routing through the lifted paths() \
20140             accessor must not silently short-circuit the loop at the \
20141             valid head entry",
20142        );
20143
20144        let mut dup = base;
20145        dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
20146        assert_eq!(
20147            dup.validate(),
20148            Err(crate::AplicacaoError::EntradaPathDuplicate {
20149                path: "/api/cart".into(),
20150            }),
20151            "validate must trip EntradaPathDuplicate on the second entry \
20152             of a two-entry cohort that shares a path — routing through \
20153             the lifted paths() accessor must not silently short-circuit \
20154             the dedup HashSet insert at the first entry",
20155        );
20156    }
20157
20158    // ── Entrada::hostname / Entrada::hostnames — the substrate-
20159    //    canonical per-`:entrada` DNS-hostname resolver pair every
20160    //    Gateway-API-aware renderer reaching for a per-listener
20161    //    singular `hostname:` filter (Gateway) or a per-route plural
20162    //    `spec.hostnames[]` filter list (HTTPRoute) routes through.
20163    //    The three pin tests below fix the two-way accept-set the pair
20164    //    must always honor: (:singular-byte-equal-to-host,
20165    //    :plural-is-singleton-of-singular, :plural-len-is-one) — drift
20166    //    on any arm surfaces at caixa-core build time rather than at
20167    //    cluster-apply time when the API server refuses the HTTPRoute
20168    //    for non-intersecting hostname filters. Peer discipline with
20169    //    the sibling `resolved_paths` accept-set pin block above on the
20170    //    per-`:entrada` path-list resolver axis.
20171
20172    fn entrada_with_host(host: &str) -> Entrada {
20173        Entrada {
20174            host: host.into(),
20175            para: "cart".into(),
20176            paths: Vec::new(),
20177            port: DEFAULT_SERVICO_PORT,
20178        }
20179    }
20180
20181    #[test]
20182    fn hostname_returns_entrada_host_byte_equal() {
20183        // The canonical singular-axis pin: [`Entrada::hostname`] must
20184        // return the `:entrada :host` field byte-for-byte, borrowed
20185        // from the typed slot's own [`String`] storage. Pins against a
20186        // future silent detour that re-normalized the host (an
20187        // accidental `.to_lowercase()` — validate_entrada_host already
20188        // enforces lowercase, so any re-normalization is redundant + a
20189        // drift surface between the validator and the accessor), a
20190        // trailing-`.` fully-qualified DNS shape substitution, or a
20191        // Punycode round-trip that lowered a Unicode host through IDNA.
20192        let e = entrada_with_host("checkout.quero.cloud");
20193        assert_eq!(
20194            e.hostname(),
20195            "checkout.quero.cloud",
20196            "Entrada::hostname must return :entrada :host verbatim \
20197             (got {:?})",
20198            e.hostname(),
20199        );
20200        assert_eq!(
20201            e.hostname(),
20202            e.host.as_str(),
20203            "Entrada::hostname must byte-equal the .host field access",
20204        );
20205    }
20206
20207    #[test]
20208    fn hostnames_returns_singleton_of_hostname_accessor() {
20209        // The pair-invariant pin: [`Entrada::hostnames`] must always
20210        // return exactly `vec![hostname()]` — the singleton list whose
20211        // sole entry is the substrate's canonical per-`:entrada`
20212        // singular hostname. Pins the two-consumer coherence axis: the
20213        // Gateway listener's singular `hostname:` filter and the
20214        // HTTPRoute's plural `spec.hostnames[]` filter list must
20215        // agree, else the Gateway API v1.x conformance layer rejects
20216        // the HTTPRoute at attach time with
20217        // `Accepted:False/NoMatchingParent` (the parent Gateway's
20218        // listener hostname doesn't intersect the route's hostname
20219        // filter list) — a divergence whose apply-time symptom is far
20220        // from any single-site commit and never surfaces in the
20221        // emitted YAML. Pinning the pair-invariant here makes any
20222        // future accidental split (an accidental `.to_string() + "."`
20223        // trailing-`.` on the plural side that didn't land on the
20224        // singular side, an accidental prefix stripping on one axis,
20225        // an accidental wildcard prepend the SNI fan-out overlay
20226        // authors on the plural side without a paired singular
20227        // migration) trip at caixa-core build time.
20228        let e = entrada_with_host("checkout.quero.cloud");
20229        assert_eq!(
20230            e.hostnames(),
20231            vec![e.hostname()],
20232            "Entrada::hostnames must return `vec![hostname()]` under \
20233             the pair-invariant — got {:?} vs. singleton {:?}",
20234            e.hostnames(),
20235            vec![e.hostname()],
20236        );
20237    }
20238
20239    #[test]
20240    fn hostnames_is_singleton_under_single_host_author_surface() {
20241        // The singleton-shape pin: under today's single-hostname-per-
20242        // `:entrada` author surface (the `:host` slot is a single
20243        // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
20244        // must always return a list of length exactly one. Pins
20245        // against a future silent detour that returned an empty list
20246        // (which would emit an HTTPRoute with `spec.hostnames: []` —
20247        // matching every incoming Host header regardless of the
20248        // Aplicacao's declared ingress apex, silently over-matching
20249        // every foreign VirtualHost the parent Gateway also fronts) or
20250        // a duplicated entry (which the Gateway API v1.x parser
20251        // accepts as a `[]-length-2 list of equal hostnames]` but
20252        // whose semantics differ from the intended singleton). The
20253        // author-surface extension point ("a future `:entrada
20254        // :alt-hosts` list overlay" the docstring names) is the sole
20255        // future axis that flips this pin — that migration will re-
20256        // author this test to pin the new plural cardinality.
20257        let e = entrada_with_host("checkout.quero.cloud");
20258        assert_eq!(
20259            e.hostnames().len(),
20260            1,
20261            "Entrada::hostnames must be a singleton under today's \
20262             single-hostname-per-`:entrada` author surface — got \
20263             length {}: {:?}",
20264            e.hostnames().len(),
20265            e.hostnames(),
20266        );
20267    }
20268
20269    // ── Entrada::destination — the substrate-canonical per-`:entrada`
20270    //    destination-Servico scalar accessor every Gateway-API
20271    //    HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
20272    //    discriminator arg (HTTPRoute name composer) or a per-rule
20273    //    `backendRefs[0].name` axis routes through. The two pin tests
20274    //    below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
20275    //    either arm surfaces at caixa-core build time rather than at
20276    //    cluster-apply time when an HTTPRoute's `metadata.name` and
20277    //    `backendRefs[]` silently disagree on which destination Servico
20278    //    the ingress fronts. Peer discipline with the sibling
20279    //    `resolved_paths` + `hostname` + `hostnames` accept-set pin
20280    //    blocks above on the per-`:entrada` path-list / DNS-hostname
20281    //    resolver axes.
20282
20283    #[test]
20284    fn destination_returns_entrada_para_byte_equal() {
20285        // The canonical destination-scalar pin: [`Entrada::destination`]
20286        // must return the `:entrada :para` field byte-for-byte, borrowed
20287        // from the typed slot's own [`String`] storage. Pins against a
20288        // future silent detour that re-normalized the destination (an
20289        // accidental `.to_lowercase()` — the destination Servico is
20290        // already validated as a DNS-1123 label upstream, so any
20291        // re-normalization is redundant + a drift surface between the
20292        // validator and the accessor), a namespace-prefix rewrite (an
20293        // accidental `format!("{namespace}/{para}")` per-CR fully-
20294        // qualified rewrite that didn't land on the peer axis), or a
20295        // per-cluster suffix stamp the operator authors on one
20296        // consumer without the other.
20297        for para in ["cart", "checkout", "catalog", "orders-v2"] {
20298            let e = Entrada {
20299                host: "checkout.quero.cloud".into(),
20300                para: para.into(),
20301                paths: Vec::new(),
20302                port: DEFAULT_SERVICO_PORT,
20303            };
20304            assert_eq!(
20305                e.destination(),
20306                para,
20307                "Entrada::destination must return :entrada :para verbatim \
20308                 (got {:?}, expected {para:?})",
20309                e.destination(),
20310            );
20311            assert_eq!(
20312                e.destination(),
20313                e.para.as_str(),
20314                "Entrada::destination must byte-equal the .para field access",
20315            );
20316        }
20317    }
20318
20319    #[test]
20320    fn destination_borrows_from_entrada_para_storage() {
20321        // The borrow-not-copy pin: [`Entrada::destination`] must
20322        // return a `&str` slice that borrows from the typed slot's
20323        // own [`String`] storage — same-address invariant with
20324        // `entrada.para.as_str()`. Pins against a future silent detour
20325        // that allocated a fresh `String` (`self.para.clone()` in the
20326        // body would type-check but silently drop the borrow, and
20327        // every downstream consumer that assumed the returned slice
20328        // outlives `&self` would break on a stale-reference use-after-
20329        // free). Peer with the sibling `hostname_returns_entrada_
20330        // host_byte_equal` on the singular-DNS-hostname axis.
20331        let e = entrada_with_host("checkout.quero.cloud");
20332        let dest = e.destination();
20333        let para_slice = e.para.as_str();
20334        assert_eq!(
20335            dest.as_ptr(),
20336            para_slice.as_ptr(),
20337            "Entrada::destination must borrow from the .para String's \
20338             backing storage — a fresh allocation here means the \
20339             accessor no longer names the substrate-primitive typed \
20340             dispatch and every downstream consumer would silently \
20341             carry a detached copy",
20342        );
20343        assert_eq!(
20344            dest.len(),
20345            para_slice.len(),
20346            "Entrada::destination and .para.as_str() must byte-equal in \
20347             length as well as in address",
20348        );
20349    }
20350
20351    #[test]
20352    fn port_returns_entrada_port_verbatim_across_permutations() {
20353        // The canonical L4-port-scalar pin: [`Entrada::port`] must
20354        // return the `:entrada :port` field verbatim as a `u16` across
20355        // every author-declared value in the validated accept-set
20356        // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
20357        // silent detour that clamped the port (an accidental
20358        // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
20359        // land on the peer [`AplicacaoSpec::port_for_destination`]
20360        // resolver), rewrote it through a per-cluster port-remap table
20361        // the operator authors on one consumer without the other, or
20362        // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
20363        // serde-default value (which would silently collapse the
20364        // distinction between "author explicitly declared `:port 8080`"
20365        // and "author omitted the slot and inherited the default" the
20366        // future per-cluster override slot depends on). Peer with the
20367        // sibling `destination_returns_entrada_para_byte_equal` +
20368        // `hostname_returns_entrada_host_byte_equal` pins on the
20369        // per-`:entrada` `&str` scalar axes.
20370        for port in [
20371            SERVICO_PORT_MIN,
20372            DEFAULT_SERVICO_PORT,
20373            8443u16,
20374            9090u16,
20375            u16::MAX,
20376        ] {
20377            let e = Entrada {
20378                host: "checkout.quero.cloud".into(),
20379                para: "cart".into(),
20380                paths: Vec::new(),
20381                port,
20382            };
20383            assert_eq!(
20384                e.port(),
20385                port,
20386                "Entrada::port must return :entrada :port verbatim \
20387                 (got {}, expected {port})",
20388                e.port(),
20389            );
20390            assert_eq!(
20391                e.port(),
20392                e.port,
20393                "Entrada::port accessor and .port field access must \
20394                 byte-equal — the accessor is the substrate-primitive \
20395                 typed dispatch every downstream L4-port consumer must \
20396                 route through",
20397            );
20398        }
20399    }
20400
20401    #[test]
20402    fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
20403        // Two-consumer coherence pin: the
20404        // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
20405        // (which reads through [`Entrada::port`] to compare against
20406        // [`SERVICO_PORT_MIN`]) and the
20407        // [`AplicacaoSpec::port_for_destination`] resolver (which reads
20408        // through [`Entrada::port`] to emit the per-destination
20409        // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
20410        // lifted accessor, so any future rebrand on the typed slot's
20411        // reader shape lands at exactly one place. Pins the two-site
20412        // coherence by exercising a below-floor port through validate
20413        // (which must reject) and a validated in-accept-set port through
20414        // port_for_destination (which must emit the same value the
20415        // accessor returns).
20416        let mut spec = three_member_spec();
20417        if let Some(e) = spec.entrada.as_mut() {
20418            e.port = 0;
20419        }
20420        assert_eq!(
20421            spec.validate().unwrap_err(),
20422            AplicacaoError::EntradaPortZero,
20423            "validate must reject `:entrada :port 0` through the lifted \
20424             Entrada::port accessor — port zero lies below \
20425             SERVICO_PORT_MIN and the validator routes through port() \
20426             to name the floor",
20427        );
20428
20429        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
20430            let mut spec = three_member_spec();
20431            if let Some(e) = spec.entrada.as_mut() {
20432                e.port = port;
20433            }
20434            spec.validate().expect(
20435                "entrada with in-accept-set :port must validate — the \
20436                 structural-floor gate reads through Entrada::port",
20437            );
20438            let entrada_ref = spec.entrada().expect(":entrada present");
20439            assert_eq!(
20440                spec.port_for_destination(entrada_ref.destination()),
20441                entrada_ref.port(),
20442                "port_for_destination(entrada.destination()) must equal \
20443                 entrada.port() — the two consumers of the per-:entrada \
20444                 L4-port axis (validator, per-destination resolver) both \
20445                 route through Entrada::port",
20446            );
20447        }
20448    }
20449
20450    #[test]
20451    fn wit_contract_source_returns_de_byte_equal_across_permutations() {
20452        // The canonical caller-Servico-scalar pin: [`WitContract::source`]
20453        // must return the `:contratos :de` field byte-for-byte, borrowed
20454        // from the typed slot's own [`String`] storage. Peer of the
20455        // sibling `destination_returns_entrada_para_byte_equal` pin on
20456        // the per-`:entrada` axis — same "the substrate-primitive
20457        // accessor must byte-equal the raw field access verbatim across
20458        // every author-declared value" discipline extended to the
20459        // per-`:contratos` caller arm. Pins against a future silent
20460        // detour that re-normalized the caller (an accidental
20461        // `.to_lowercase()` — every `:contratos :de` is validated as a
20462        // DNS-1123 label upstream via `validate_contrato_caixa`, so any
20463        // re-normalization is redundant + a drift surface between the
20464        // validator and the accessor), a namespace-prefix rewrite (an
20465        // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
20466        // rewrite that didn't land on the peer axis), or a per-cluster
20467        // suffix stamp the operator authors on one consumer without the
20468        // other.
20469        for de in ["cart", "checkout", "catalog", "orders-v2"] {
20470            let c = WitContract {
20471                de: de.into(),
20472                para: "downstream".into(),
20473                wit: "wasi:http/proxy".into(),
20474                endpoint: Some("/lookup".into()),
20475                subject: None,
20476                slot: None,
20477            };
20478            assert_eq!(
20479                c.source(),
20480                de,
20481                "WitContract::source must return :contratos :de verbatim \
20482                 (got {:?}, expected {de:?})",
20483                c.source(),
20484            );
20485            assert_eq!(
20486                c.source(),
20487                c.de.as_str(),
20488                "WitContract::source must byte-equal the .de field access",
20489            );
20490        }
20491    }
20492
20493    #[test]
20494    fn wit_contract_source_borrows_from_de_storage() {
20495        // The borrow-not-copy pin: [`WitContract::source`] must return a
20496        // `&str` slice that borrows from the typed slot's own [`String`]
20497        // storage — same-address invariant with `c.de.as_str()`. Pins
20498        // against a future silent detour that allocated a fresh `String`
20499        // (`self.de.clone()` in the body would type-check but silently
20500        // drop the borrow, and every downstream consumer that assumed
20501        // the returned slice outlives `&self` would break on a stale-
20502        // reference use-after-free). Peer of the sibling
20503        // `destination_borrows_from_entrada_para_storage` on the
20504        // per-`:entrada` axis.
20505        let c = WitContract {
20506            de: "cart".into(),
20507            para: "catalog".into(),
20508            wit: "wasi:http/proxy".into(),
20509            endpoint: Some("/lookup".into()),
20510            subject: None,
20511            slot: None,
20512        };
20513        let src = c.source();
20514        let de_slice = c.de.as_str();
20515        assert_eq!(
20516            src.as_ptr(),
20517            de_slice.as_ptr(),
20518            "WitContract::source must borrow from the .de String's \
20519             backing storage — a fresh allocation here means the \
20520             accessor no longer names the substrate-primitive typed \
20521             dispatch and every downstream consumer would silently \
20522             carry a detached copy",
20523        );
20524        assert_eq!(
20525            src.len(),
20526            de_slice.len(),
20527            "WitContract::source and .de.as_str() must byte-equal in \
20528             length as well as in address",
20529        );
20530    }
20531
20532    #[test]
20533    fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
20534        // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
20535        // must return the `:contratos :para` field byte-for-byte,
20536        // borrowed from the typed slot's own [`String`] storage. Peer of
20537        // the sibling `destination_returns_entrada_para_byte_equal` on
20538        // the per-`:entrada` axis — both accessors name "the destination-
20539        // Servico byte-string" concept on their respective mesh-slot
20540        // atoms (per-ingress apex vs. per-typed-edge callee) and both
20541        // must project the underlying `.para` field verbatim so every
20542        // downstream renderer that composes them with peer accessors
20543        // (e.g. `spec.port_for_destination(c.destination())` at the CNP
20544        // per-edge L4 port emit site) reads the same byte-string the
20545        // author declared.
20546        for para in ["catalog", "payment", "orders", "inventory-v3"] {
20547            let c = WitContract {
20548                de: "cart".into(),
20549                para: para.into(),
20550                wit: "wasi:http/proxy".into(),
20551                endpoint: Some("/lookup".into()),
20552                subject: None,
20553                slot: None,
20554            };
20555            assert_eq!(
20556                c.destination(),
20557                para,
20558                "WitContract::destination must return :contratos :para \
20559                 verbatim (got {:?}, expected {para:?})",
20560                c.destination(),
20561            );
20562            assert_eq!(
20563                c.destination(),
20564                c.para.as_str(),
20565                "WitContract::destination must byte-equal the .para \
20566                 field access",
20567            );
20568        }
20569    }
20570
20571    #[test]
20572    fn wit_contract_destination_borrows_from_para_storage() {
20573        // The borrow-not-copy pin: [`WitContract::destination`] must
20574        // return a `&str` slice that borrows from the typed slot's own
20575        // [`String`] storage — same-address invariant with
20576        // `c.para.as_str()`. Peer of the sibling
20577        // `destination_borrows_from_entrada_para_storage` on the
20578        // per-`:entrada` axis.
20579        let c = WitContract {
20580            de: "cart".into(),
20581            para: "catalog".into(),
20582            wit: "wasi:http/proxy".into(),
20583            endpoint: Some("/lookup".into()),
20584            subject: None,
20585            slot: None,
20586        };
20587        let dest = c.destination();
20588        let para_slice = c.para.as_str();
20589        assert_eq!(
20590            dest.as_ptr(),
20591            para_slice.as_ptr(),
20592            "WitContract::destination must borrow from the .para \
20593             String's backing storage — a fresh allocation here means \
20594             the accessor no longer names the substrate-primitive typed \
20595             dispatch and every downstream consumer would silently \
20596             carry a detached copy",
20597        );
20598        assert_eq!(
20599            dest.len(),
20600            para_slice.len(),
20601            "WitContract::destination and .para.as_str() must byte-equal \
20602             in length as well as in address",
20603        );
20604    }
20605
20606    #[test]
20607    fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
20608        // The canonical per-`:contratos` WIT-world-reference scalar pin:
20609        // [`WitContract::world_ref`] must return the `:contratos :wit`
20610        // field byte-for-byte, borrowed from the typed slot's own
20611        // [`String`] storage. Sibling of the peer per-`:contratos`
20612        // [`WitContract::source`] / [`WitContract::destination`]
20613        // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
20614        // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
20615        // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
20616        // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
20617        // "the substrate-primitive accessor must byte-equal the raw
20618        // field access verbatim across every author-declared value"
20619        // discipline extended to the per-`:contratos` WIT-world arm.
20620        // Pins against a future silent detour that re-canonicalized the
20621        // WIT world reference (an accidental `.to_lowercase()` pass that
20622        // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
20623        // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
20624        // gate is already lowercase-prefixed so any re-normalization is
20625        // redundant + a drift surface between the validator and the
20626        // accessor), an M4-promotion-shape rewrite that formatted a
20627        // typed WIT-world enum through [`Display`] and silently drifted
20628        // the printer output from the source `caixa.lisp`, or a per-
20629        // cluster WIT-alias rewrite that didn't land on the peer field-
20630        // access sites. Five values sweep the shape-dispatch accept-set
20631        // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
20632        // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
20633        // `wasi:keyvalue/`).
20634        for (wit, endpoint, subject, slot) in [
20635            ("wasi:http/proxy", Some("/lookup"), None, None),
20636            ("http:proxy", Some("/health"), None, None),
20637            ("nats:pub-sub", None, Some("orders.paid"), None),
20638            ("kafka:events", None, Some("checkout-events"), None),
20639            ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
20640        ] {
20641            let c = WitContract {
20642                de: "cart".into(),
20643                para: "downstream".into(),
20644                wit: wit.into(),
20645                endpoint: endpoint.map(str::to_string),
20646                subject: subject.map(str::to_string),
20647                slot: slot.map(str::to_string),
20648            };
20649            assert_eq!(
20650                c.world_ref(),
20651                wit,
20652                "WitContract::world_ref must return :contratos :wit \
20653                 verbatim (got {:?}, expected {wit:?})",
20654                c.world_ref(),
20655            );
20656            assert_eq!(
20657                c.world_ref(),
20658                c.wit.as_str(),
20659                "WitContract::world_ref must byte-equal the .wit field \
20660                 access",
20661            );
20662        }
20663    }
20664
20665    #[test]
20666    fn wit_contract_world_ref_borrows_from_wit_storage() {
20667        // The borrow-not-copy pin: [`WitContract::world_ref`] must
20668        // return a `&str` slice that borrows from the typed slot's own
20669        // [`String`] storage — same-address invariant with
20670        // `c.wit.as_str()`. Pins against a future silent detour that
20671        // allocated a fresh `String` (`self.wit.clone()` in the body
20672        // would type-check but silently drop the borrow, and every
20673        // downstream consumer that assumed the returned slice outlives
20674        // `&self` would break on a stale-reference use-after-free — the
20675        // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
20676        // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
20677        // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
20678        // / [`is_pubsub`][WitContract::is_pubsub] /
20679        // [`is_store`][WitContract::is_store] methods route through —
20680        // each borrow from the WitContract's own storage and each would
20681        // silently misbehave if this accessor produced a detached copy).
20682        // Peer of the sibling per-`:contratos` [`WitContract::source`] /
20683        // [`WitContract::destination`] and per-`:entrada`
20684        // [`Entrada::destination`] / [`Entrada::hostname`] and
20685        // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
20686        // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
20687        let c = WitContract {
20688            de: "cart".into(),
20689            para: "catalog".into(),
20690            wit: "wasi:http/proxy".into(),
20691            endpoint: Some("/lookup".into()),
20692            subject: None,
20693            slot: None,
20694        };
20695        let world = c.world_ref();
20696        let wit_slice = c.wit.as_str();
20697        assert_eq!(
20698            world.as_ptr(),
20699            wit_slice.as_ptr(),
20700            "WitContract::world_ref must borrow from the .wit String's \
20701             backing storage — a fresh allocation here means the \
20702             accessor no longer names the substrate-primitive typed \
20703             dispatch and every downstream consumer would silently carry \
20704             a detached copy",
20705        );
20706        assert_eq!(
20707            world.len(),
20708            wit_slice.len(),
20709            "WitContract::world_ref and .wit.as_str() must byte-equal in \
20710             length as well as in address",
20711        );
20712    }
20713
20714    #[test]
20715    fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
20716        // Sibling-triple invariant pin composing all three per-`:contratos`
20717        // substrate-primitive typed dispatches — [`WitContract::source`]
20718        // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
20719        // [`WitContract::world_ref`] — at the joint
20720        // `(source(), destination(), world_ref())` call shape every
20721        // renderer that fans on per-edge caller-callee-shape identity
20722        // keys off. The invariant, evaluated per-contract:
20723        //
20724        //   (c.source(), c.destination(), c.world_ref())
20725        //   == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
20726        //
20727        // Closes the last unlifted per-`:contratos` scalar axis — every
20728        // downstream consumer that reads the triple now routes through
20729        // exactly three typed dispatches on the substrate primitive,
20730        // not two typed + one open-coded field access. A future refactor
20731        // that silently split any one accessor's projection (an
20732        // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
20733        // canonicalization that didn't reach the peer `source`/
20734        // `destination` arms, an accidental `source()` per-cluster
20735        // caller-alias rewrite that didn't land on the `world_ref` peer)
20736        // surfaces at caixa-core build time. Peer of the sibling per-
20737        // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
20738        // per-`:entrada` `(hostname(), destination())` (6db982c /
20739        // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
20740        // axes, extended to the per-`:contratos` triple.
20741        for (de, para, wit, endpoint, subject, slot) in [
20742            (
20743                "cart",
20744                "catalog",
20745                "wasi:http/proxy",
20746                Some("/lookup"),
20747                None,
20748                None,
20749            ),
20750            (
20751                "checkout",
20752                "orders",
20753                "nats:pub-sub",
20754                None,
20755                Some("orders.paid"),
20756                None,
20757            ),
20758            (
20759                "cart",
20760                "kv",
20761                "wasi:keyvalue/store",
20762                None,
20763                None,
20764                Some("carts/{cart_id}"),
20765            ),
20766            (
20767                "orders-v2",
20768                "inventory-v3",
20769                "http:proxy",
20770                Some("/reserve"),
20771                None,
20772                None,
20773            ),
20774        ] {
20775            let c = WitContract {
20776                de: de.into(),
20777                para: para.into(),
20778                wit: wit.into(),
20779                endpoint: endpoint.map(str::to_string),
20780                subject: subject.map(str::to_string),
20781                slot: slot.map(str::to_string),
20782            };
20783            assert_eq!(
20784                (c.source(), c.destination(), c.world_ref()),
20785                (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
20786                "(WitContract::source, ::destination, ::world_ref) must \
20787                 project (.de, .para, .wit) verbatim across every author-\
20788                 declared triple (got ({:?}, {:?}, {:?}), expected \
20789                 ({de:?}, {para:?}, {wit:?}))",
20790                c.source(),
20791                c.destination(),
20792                c.world_ref(),
20793            );
20794        }
20795    }
20796
20797    #[test]
20798    fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
20799        // The canonical per-`:contratos` owned-form caller-callee-pair
20800        // pin: [`WitContract::edge_pair`] must return the
20801        // `(source(), destination())` tuple in owned form byte-for-byte,
20802        // projected through the lifted [`WitContract::source`] /
20803        // [`WitContract::destination`] scalar accessors. Pins the
20804        // composite-projection invariant on the per-`:contratos`
20805        // mesh-slot atom — every author-declared `(de, para)` pair must
20806        // round-trip verbatim through the substrate primitive's typed
20807        // dispatch, so the nine [`AplicacaoError`] diagnostic-
20808        // construction sites the accessor now feeds
20809        // ([`AplicacaoError::EmptyWit`],
20810        // [`AplicacaoError::ContratoEndpointEmpty`],
20811        // [`AplicacaoError::ContratoEndpointNotAbsolute`],
20812        // [`AplicacaoError::ContratoEndpointInvalid`],
20813        // [`AplicacaoError::ContratoSubjectEmpty`],
20814        // [`AplicacaoError::ContratoSubjectInvalid`],
20815        // [`AplicacaoError::ContratoSlotEmpty`],
20816        // [`AplicacaoError::ContratoSlotInvalid`],
20817        // [`AplicacaoError::ContratoDuplicate`]) all read the same
20818        // `(de, para)` label pair every author sees at the source
20819        // `caixa.lisp`. Pins against a future silent detour that swapped
20820        // the `.0` / `.1` arms (an accidental `(destination(),
20821        // source())` re-order in the body would silently invert every
20822        // downstream diagnostic's `de:` / `para:` label pair, silently
20823        // reversing the direction of every operator-facing typed error
20824        // arrow), a fresh-allocation shape drift (an accidental
20825        // `.to_string()` on one arm but not the other would leave the
20826        // owned/borrowed pair mismatched vs. the sibling `source()` /
20827        // `destination()` returns), or an M4 per-cluster caller/callee-
20828        // alias rewrite that landed on `source()` without reaching
20829        // `destination()` (or vice versa). Peer of the sibling per-
20830        // `:contratos` `(source, destination, world_ref)` triple
20831        // pin above on the mesh-slot-atom scalar-value axes, extended
20832        // to the owned-form pair-projection axis.
20833        for (de, para, wit, endpoint, subject, slot) in [
20834            (
20835                "cart",
20836                "catalog",
20837                "wasi:http/proxy",
20838                Some("/lookup"),
20839                None,
20840                None,
20841            ),
20842            (
20843                "checkout",
20844                "orders",
20845                "nats:pub-sub",
20846                None,
20847                Some("orders.paid"),
20848                None,
20849            ),
20850            (
20851                "cart",
20852                "kv",
20853                "wasi:keyvalue/store",
20854                None,
20855                None,
20856                Some("carts/{cart_id}"),
20857            ),
20858            (
20859                "orders-v2",
20860                "inventory-v3",
20861                "http:proxy",
20862                Some("/reserve"),
20863                None,
20864                None,
20865            ),
20866        ] {
20867            let c = WitContract {
20868                de: de.into(),
20869                para: para.into(),
20870                wit: wit.into(),
20871                endpoint: endpoint.map(str::to_string),
20872                subject: subject.map(str::to_string),
20873                slot: slot.map(str::to_string),
20874            };
20875            assert_eq!(
20876                c.edge_pair(),
20877                (de.to_string(), para.to_string()),
20878                "WitContract::edge_pair must return (:contratos :de, \
20879                 :contratos :para) as an owned tuple verbatim (got {:?}, \
20880                 expected ({de:?}, {para:?}))",
20881                c.edge_pair(),
20882            );
20883        }
20884    }
20885
20886    #[test]
20887    fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
20888        // The composition pin: [`WitContract::edge_pair`] must return
20889        // exactly `(source().to_string(), destination().to_string())` —
20890        // the owned form of the sibling accessor pair — so any future
20891        // refactor that silently re-authored the caller-arm / callee-arm
20892        // projection to bypass the lifted scalar accessors (an accidental
20893        // `(self.de.clone(), self.para.clone())` regression back to the
20894        // raw field-access shape, an M4-typed-caller-enum `Display`
20895        // re-canonicalization on `source()` that didn't reach
20896        // `edge_pair()`, a per-cluster alias rewrite the operator lands
20897        // on `destination()` without reaching this composite projection)
20898        // trips at caixa-core build time. Pins the "typed dispatch
20899        // composes with typed dispatch, not with raw field access"
20900        // discipline every downstream diagnostic-construction site now
20901        // routes through — a `de:` / `para:` label pair whose
20902        // projection silently drifted off the substrate primitive's
20903        // scalar accessors would silently split the diagnostic's self-
20904        // locating signal from the source `caixa.lisp` author's view.
20905        // Peer of the sibling per-`:politicas` `is_empty` /
20906        // `validate_politicas` accessor-routing-pin family on the M3
20907        // mesh-slot family (18575, 18739, 18918, 19140, 19371).
20908        let c = WitContract {
20909            de: "cart".into(),
20910            para: "catalog".into(),
20911            wit: "wasi:http/proxy".into(),
20912            endpoint: Some("/lookup".into()),
20913            subject: None,
20914            slot: None,
20915        };
20916        assert_eq!(
20917            c.edge_pair(),
20918            (c.source().to_string(), c.destination().to_string()),
20919            "WitContract::edge_pair must compose exactly \
20920             (source().to_string(), destination().to_string()) — a \
20921             bypass of either sibling accessor here would silently \
20922             decouple the composite-projection axis from the \
20923             substrate-primitive scalar accessors every downstream \
20924             consumer routes through",
20925        );
20926    }
20927
20928    #[test]
20929    fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
20930     {
20931        // The canonical per-`:contratos` owned-form
20932        // caller-callee-world-ref-triple pin:
20933        // [`WitContract::edge_triple`] must return the
20934        // `(source(), destination(), world_ref())` tuple in owned form
20935        // byte-for-byte, projected through the lifted
20936        // [`WitContract::source`] / [`WitContract::destination`] /
20937        // [`WitContract::world_ref`] scalar accessors. Pins the
20938        // composite-projection invariant on the per-`:contratos`
20939        // mesh-slot atom — every author-declared `(de, para, wit)`
20940        // triple must round-trip verbatim through the substrate
20941        // primitive's typed dispatch, so the nine
20942        // [`AplicacaoError`] diagnostic-construction sites the
20943        // accessor now feeds (the [`WitTarget`]-dispatch's eight
20944        // wrong-target / missing-target / invalid-wit / capability-
20945        // with-payload arms in [`WitContract::target`], plus the
20946        // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
20947        // diagnostic constructor in [`AplicacaoSpec::validate`]) all
20948        // read the same `(de, para, wit)` triple every author sees at
20949        // the source `caixa.lisp`. Pins against a future silent
20950        // detour that swapped any two arms (an accidental `(destination(),
20951        // source(), world_ref())` re-order in the body would silently
20952        // invert every downstream diagnostic's `de:` / `para:` label
20953        // pair, silently reversing the direction of every operator-
20954        // facing typed error arrow), a fresh-allocation shape drift
20955        // (an accidental `.to_string()` skipped on one arm would leave
20956        // the owned/borrowed triple mismatched vs. the sibling
20957        // `source()` / `destination()` / `world_ref()` returns), or an
20958        // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
20959        // canonicalization pass that landed on one accessor without
20960        // reaching the peers. Peer of the sibling per-`:contratos`
20961        // caller-callee-pair
20962        // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
20963        // pin on the mesh-slot-atom composite-projection axis,
20964        // extended to the triple-projection axis.
20965        for (de, para, wit, endpoint, subject, slot) in [
20966            (
20967                "cart",
20968                "catalog",
20969                "wasi:http/proxy",
20970                Some("/lookup"),
20971                None,
20972                None,
20973            ),
20974            (
20975                "checkout",
20976                "orders",
20977                "nats:pub-sub",
20978                None,
20979                Some("orders.paid"),
20980                None,
20981            ),
20982            (
20983                "cart",
20984                "kv",
20985                "wasi:keyvalue/store",
20986                None,
20987                None,
20988                Some("carts/{cart_id}"),
20989            ),
20990            (
20991                "orders-v2",
20992                "inventory-v3",
20993                "http:proxy",
20994                Some("/reserve"),
20995                None,
20996                None,
20997            ),
20998        ] {
20999            let c = WitContract {
21000                de: de.into(),
21001                para: para.into(),
21002                wit: wit.into(),
21003                endpoint: endpoint.map(str::to_string),
21004                subject: subject.map(str::to_string),
21005                slot: slot.map(str::to_string),
21006            };
21007            assert_eq!(
21008                c.edge_triple(),
21009                (de.to_string(), para.to_string(), wit.to_string()),
21010                "WitContract::edge_triple must return (:contratos :de, \
21011                 :contratos :para, :contratos :wit) as an owned triple \
21012                 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
21013                c.edge_triple(),
21014            );
21015        }
21016    }
21017
21018    #[test]
21019    fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
21020        // The composition pin: [`WitContract::edge_triple`] must return
21021        // exactly `(source().to_string(), destination().to_string(),
21022        // world_ref().to_string())` — the owned form of the sibling
21023        // scalar-accessor triple — so any future refactor that silently
21024        // re-authored one arm's projection to bypass the lifted scalar
21025        // accessors (an accidental `(self.de.clone(), self.para.clone(),
21026        // self.wit.clone())` regression back to the raw field-access
21027        // shape the internal `edge` closure and the ContratoDuplicate
21028        // diagnostic both carried before this lift landed, an
21029        // M4-typed-caller-enum `Display` re-canonicalization on
21030        // `source()` that didn't reach `edge_triple()`, a per-cluster
21031        // alias rewrite the operator lands on `destination()` /
21032        // `world_ref()` without reaching this composite projection)
21033        // trips at caixa-core build time. Pins the "typed dispatch
21034        // composes with typed dispatch, not with raw field access"
21035        // discipline every downstream diagnostic-construction site now
21036        // routes through — a `de:` / `para:` / `wit:` triple whose
21037        // projection silently drifted off the substrate primitive's
21038        // scalar accessors would silently split the diagnostic's self-
21039        // locating signal from the source `caixa.lisp` author's view.
21040        // Peer of the sibling per-`:contratos` edge_pair composition-
21041        // pin above on the mesh-slot-atom composite-projection axis.
21042        let c = WitContract {
21043            de: "cart".into(),
21044            para: "catalog".into(),
21045            wit: "wasi:http/proxy".into(),
21046            endpoint: Some("/lookup".into()),
21047            subject: None,
21048            slot: None,
21049        };
21050        assert_eq!(
21051            c.edge_triple(),
21052            (
21053                c.source().to_string(),
21054                c.destination().to_string(),
21055                c.world_ref().to_string(),
21056            ),
21057            "WitContract::edge_triple must compose exactly \
21058             (source().to_string(), destination().to_string(), \
21059             world_ref().to_string()) — a bypass of any sibling accessor \
21060             here would silently decouple the composite-projection axis \
21061             from the substrate-primitive scalar accessors every \
21062             downstream consumer routes through",
21063        );
21064    }
21065
21066    #[test]
21067    fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
21068        // The canonical semantics-pin: [`WitContract::edge_triple`] must
21069        // project the full `(de, para, wit)` identity of a `:contratos`
21070        // edge — the sub-triple every triple-carrying
21071        // [`AplicacaoError::Contrato*`] diagnostic weaves into its
21072        // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
21073        // missing-target, capability-with-payload, invalid-wit, and the
21074        // duplicate-gate). Rejects a drift in shape (an accidental
21075        // silent detour that returned a `(de, para)` pair or added an
21076        // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
21077        // would trip here because the return type would no longer
21078        // pattern-match the eight `let (de, para, wit) = edge();`
21079        // destructures the [`WitContract::target`] dispatch feeds off
21080        // + the paired duplicate-gate `let (de, para, wit) =
21081        // c.edge_triple();` destructure in
21082        // [`AplicacaoSpec::validate`]). Peer of the sibling per-
21083        // `:contratos` caller-callee-pair pin above extended to the
21084        // triple projection surface: closes the "one composite
21085        // accessor per typed diagnostic-construction sub-tuple"
21086        // discipline on the per-`:contratos` mesh-slot-atom axis.
21087        let c = WitContract {
21088            de: "checkout".into(),
21089            para: "orders".into(),
21090            wit: "nats:pub-sub".into(),
21091            endpoint: None,
21092            subject: Some("orders.paid".into()),
21093            slot: None,
21094        };
21095        let (de, para, wit) = c.edge_triple();
21096        assert_eq!(de, "checkout");
21097        assert_eq!(para, "orders");
21098        assert_eq!(wit, "nats:pub-sub");
21099    }
21100
21101    #[test]
21102    fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
21103     {
21104        // The composition pin: [`WitContract::identity`] must return
21105        // exactly `(source(), destination(), world_ref(), endpoint(),
21106        // subject(), slot())` — the borrowed form of the six-scalar-
21107        // accessor identity axis. Any future refactor that silently
21108        // re-authored one arm's projection to bypass a scalar accessor
21109        // (a `self.de.as_str()` regression back to raw field access on
21110        // any of the three required arms, a `self.endpoint.as_deref()`
21111        // regression on any of the three optional arms, an M4 per-
21112        // cluster caller/callee-alias rewrite the operator lands on
21113        // `source()` / `destination()` without reaching this composite
21114        // projection) trips at caixa-core build time. Sweeps four
21115        // permutations of the WIT-shape × payload lattice — HTTP with
21116        // endpoint, pub-sub with subject, store with slot, payload-less
21117        // capability — so every payload arm is exercised. Peer of the
21118        // sibling per-`:contratos`
21119        // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
21120        // composition pin on the mesh-slot-atom composite-projection
21121        // axis; extends the discipline from the (de, para, wit) prefix
21122        // onto the full-identity axis carrying the three payload arms.
21123        for (de, para, wit, endpoint, subject, slot) in [
21124            (
21125                "cart",
21126                "catalog",
21127                "wasi:http/proxy",
21128                Some("/lookup"),
21129                None,
21130                None,
21131            ),
21132            (
21133                "checkout",
21134                "orders",
21135                "nats:pub-sub",
21136                None,
21137                Some("orders.paid"),
21138                None,
21139            ),
21140            (
21141                "cart",
21142                "kv",
21143                "wasi:keyvalue/store",
21144                None,
21145                None,
21146                Some("carts/{cart_id}"),
21147            ),
21148            ("audit", "sink", "wasi:logging", None, None, None),
21149        ] {
21150            let c = WitContract {
21151                de: de.into(),
21152                para: para.into(),
21153                wit: wit.into(),
21154                endpoint: endpoint.map(str::to_owned),
21155                subject: subject.map(str::to_owned),
21156                slot: slot.map(str::to_owned),
21157            };
21158            assert_eq!(
21159                c.identity(),
21160                (
21161                    c.source(),
21162                    c.destination(),
21163                    c.world_ref(),
21164                    c.endpoint(),
21165                    c.subject(),
21166                    c.slot(),
21167                ),
21168                "WitContract::identity must compose exactly \
21169                 (source(), destination(), world_ref(), endpoint(), \
21170                 subject(), slot()) — a bypass of any sibling accessor \
21171                 here would silently decouple the identity-projection \
21172                 axis from the substrate-primitive scalar accessors \
21173                 every dedup-key consumer routes through",
21174            );
21175        }
21176    }
21177
21178    #[test]
21179    fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
21180        // The canonical semantics-pin: [`WitContract::identity`] must
21181        // project the six-axis (de, para, wit, endpoint, subject, slot)
21182        // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
21183        // gate keys off — two `WitContract`s that agree on all six axes
21184        // are the same typed edge declared twice, the graph-edge
21185        // analogue of duplicate `:membros` / `:placement :clusters` /
21186        // `:entrada :paths` entries. Rejects a shape drift (an
21187        // accidental silent detour that returned a prefix tuple or
21188        // added an extra field) by pattern-matching the six-arm shape.
21189        // Peer of the sibling per-`:contratos`
21190        // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
21191        // pin extended from the (de, para, wit) prefix onto the full
21192        // six-axis identity that the dedup key rides.
21193        let c = WitContract {
21194            de: "cart".into(),
21195            para: "catalog".into(),
21196            wit: "wasi:http/proxy".into(),
21197            endpoint: Some("/products/:id".into()),
21198            subject: None,
21199            slot: None,
21200        };
21201        let (de, para, wit, endpoint, subject, slot) = c.identity();
21202        assert_eq!(de, "cart");
21203        assert_eq!(para, "catalog");
21204        assert_eq!(wit, "wasi:http/proxy");
21205        assert_eq!(endpoint, Some("/products/:id"));
21206        assert_eq!(subject, None);
21207        assert_eq!(slot, None);
21208
21209        // Two byte-identical contracts must produce equal identities —
21210        // the dedup key's foundational invariant.
21211        let c2 = c.clone();
21212        assert_eq!(c.identity(), c2.identity());
21213
21214        // Any change on any of the six axes must break the identity —
21215        // sweeps by mutating one axis at a time.
21216        let mut mutated = c.clone();
21217        mutated.de = "search".into();
21218        assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
21219        let mut mutated = c.clone();
21220        mutated.para = "warehouse".into();
21221        assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
21222        let mut mutated = c.clone();
21223        mutated.wit = "http:legacy".into();
21224        assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
21225        let mut mutated = c.clone();
21226        mutated.endpoint = Some("/search".into());
21227        assert_ne!(
21228            c.identity(),
21229            mutated.identity(),
21230            "endpoint axis must partition"
21231        );
21232        let mut mutated = c.clone();
21233        mutated.subject = Some("orders.paid".into());
21234        assert_ne!(
21235            c.identity(),
21236            mutated.identity(),
21237            "subject axis must partition"
21238        );
21239        let mut mutated = c;
21240        mutated.slot = Some("carts/{id}".into());
21241        assert_ne!(mutated.identity().5, None, "slot axis must partition");
21242    }
21243
21244    #[test]
21245    fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
21246        // The canonical per-`:contratos` structural-self-edge pin:
21247        // [`WitContract::is_self_loop`] must return `true` when the
21248        // `:de` and `:para` fields agree byte-for-byte, across every
21249        // WIT-shape variant the per-edge shape family carries. Pins
21250        // the shape-agnostic identity-space partition the
21251        // [`AplicacaoSpec::validate`] self-edge gate at
21252        // caixa-core/src/aplicacao.rs:5559 fires against — all four
21253        // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
21254        // under the same one predicate. Four permutations sweep the
21255        // accept-set: HTTP with endpoint, pub-sub with subject, KV
21256        // store with slot, and payload-less capability.
21257        for (nome, wit, endpoint, subject, slot) in [
21258            ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
21259            ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
21260            (
21261                "kv",
21262                "wasi:keyvalue/store",
21263                None,
21264                None,
21265                Some("carts/{cart_id}"),
21266            ),
21267            ("audit", "wasi:logging", None, None, None),
21268        ] {
21269            let c = WitContract {
21270                de: nome.into(),
21271                para: nome.into(),
21272                wit: wit.into(),
21273                endpoint: endpoint.map(str::to_string),
21274                subject: subject.map(str::to_string),
21275                slot: slot.map(str::to_string),
21276            };
21277            assert!(
21278                c.is_self_loop(),
21279                "WitContract::is_self_loop must return true when \
21280                 :contratos :de == :contratos :para (got false on \
21281                 {nome:?} under {wit:?})",
21282            );
21283        }
21284    }
21285
21286    #[test]
21287    fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
21288        // The complement pin: [`WitContract::is_self_loop`] must return
21289        // `false` on every well-shaped inter-Servico contract (the
21290        // author-intended `:contratos` shape MESH-COMPOSITION §III.1
21291        // names — "Servico A calls Servico B" between two distinct
21292        // graph nodes). Pins against a future silent detour that
21293        // inverted the predicate (an accidental `!= ` swap for `==`
21294        // would silently reject every legitimate inter-Servico edge
21295        // and admit every self-edge — the exact inversion of the
21296        // author-intended shape). Four permutations sweep the same
21297        // WIT-shape accept-set the sibling positive-arm test carries.
21298        for (de, para, wit, endpoint, subject, slot) in [
21299            (
21300                "cart",
21301                "catalog",
21302                "wasi:http/proxy",
21303                Some("/lookup"),
21304                None,
21305                None,
21306            ),
21307            (
21308                "checkout",
21309                "orders",
21310                "nats:pub-sub",
21311                None,
21312                Some("orders.paid"),
21313                None,
21314            ),
21315            (
21316                "cart",
21317                "kv",
21318                "wasi:keyvalue/store",
21319                None,
21320                None,
21321                Some("carts/{cart_id}"),
21322            ),
21323            ("audit", "sink", "wasi:logging", None, None, None),
21324        ] {
21325            let c = WitContract {
21326                de: de.into(),
21327                para: para.into(),
21328                wit: wit.into(),
21329                endpoint: endpoint.map(str::to_string),
21330                subject: subject.map(str::to_string),
21331                slot: slot.map(str::to_string),
21332            };
21333            assert!(
21334                !c.is_self_loop(),
21335                "WitContract::is_self_loop must return false when \
21336                 :contratos :de differs from :contratos :para (got true \
21337                 on {de:?} → {para:?} under {wit:?})",
21338            );
21339        }
21340    }
21341
21342    #[test]
21343    fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
21344        // The composition pin: [`WitContract::is_self_loop`] must
21345        // resolve to exactly `self.source() == self.destination()` —
21346        // the equality probe of the sibling scalar-accessor pair — so
21347        // any future refactor that silently re-authored the predicate
21348        // to bypass the lifted scalar accessors (an accidental
21349        // `self.de == self.para` regression back to the raw field-
21350        // access shape, an M4-typed-caller-enum identity-comparison
21351        // rule that landed on `source()` without reaching
21352        // `destination()`, a per-cluster alias rewrite the operator
21353        // pins on `destination()` without reaching this predicate)
21354        // trips at caixa-core build time. Pins the "typed dispatch
21355        // composes with typed dispatch, not with raw field access"
21356        // discipline the sibling [`WitContract::edge_pair`] /
21357        // [`WitContract::edge_triple`] composite-projection accessors
21358        // already carry, extended onto the per-edge endpoint-equality
21359        // predicate axis. Positive and complement arms both fire.
21360        let self_edge = WitContract {
21361            de: "cart".into(),
21362            para: "cart".into(),
21363            wit: "wasi:http/proxy".into(),
21364            endpoint: Some("/lookup".into()),
21365            subject: None,
21366            slot: None,
21367        };
21368        assert_eq!(
21369            self_edge.is_self_loop(),
21370            self_edge.source() == self_edge.destination(),
21371            "WitContract::is_self_loop must compose exactly \
21372             `source() == destination()` — a bypass of either sibling \
21373             accessor here would silently decouple the endpoint-\
21374             equality predicate from the substrate-primitive scalar \
21375             accessors every downstream consumer routes through",
21376        );
21377        let inter_edge = WitContract {
21378            de: "cart".into(),
21379            para: "catalog".into(),
21380            wit: "wasi:http/proxy".into(),
21381            endpoint: Some("/lookup".into()),
21382            subject: None,
21383            slot: None,
21384        };
21385        assert_eq!(
21386            inter_edge.is_self_loop(),
21387            inter_edge.source() == inter_edge.destination(),
21388            "WitContract::is_self_loop must compose exactly \
21389             `source() == destination()` on the complement arm too",
21390        );
21391    }
21392
21393    #[test]
21394    fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
21395        // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
21396        // pin: [`WitContract::endpoint`] must return the `:contratos
21397        // :endpoint` field byte-for-byte, borrowed from the typed slot's
21398        // own `Option<String>` storage. Peer of the sibling
21399        // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
21400        // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
21401        // mesh-slot `Option<String>` optional-scalar axes — same "the
21402        // substrate-primitive accessor must byte-equal the raw field
21403        // access verbatim across every author-declared value" discipline
21404        // extended to the per-`:contratos` HTTP-payload-carrier arm.
21405        // Pins against a future silent detour that re-canonicalized the
21406        // endpoint (an accidental percent-encoding pass that didn't
21407        // reach the peer field-access site at the dedup key, a per-CR
21408        // fully-qualified prefix rewrite the operator authors on one
21409        // consumer without the other, or an M4 typed-path-template
21410        // `Display` re-canonicalization that silently drifted the
21411        // printer output from the source `caixa.lisp`). Four values
21412        // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
21413        // gate upstream admits (short root-path, dashed, param-shaped,
21414        // deep-hierarchy).
21415        for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
21416            let c = WitContract {
21417                de: "cart".into(),
21418                para: "catalog".into(),
21419                wit: "wasi:http/proxy".into(),
21420                endpoint: Some(endpoint.into()),
21421                subject: None,
21422                slot: None,
21423            };
21424            assert_eq!(
21425                c.endpoint(),
21426                Some(endpoint),
21427                "WitContract::endpoint must return :contratos :endpoint \
21428                 verbatim (got {:?}, expected Some({endpoint:?}))",
21429                c.endpoint(),
21430            );
21431            assert_eq!(
21432                c.endpoint(),
21433                c.endpoint.as_deref(),
21434                "WitContract::endpoint must byte-equal the .endpoint \
21435                 field's `.as_deref()` projection",
21436            );
21437        }
21438    }
21439
21440    #[test]
21441    fn wit_contract_endpoint_none_when_field_is_none() {
21442        // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
21443        // payload-carrier accessor pin: when the typed slot is absent —
21444        // the canonical shape under a non-HTTP `:wit` world per the
21445        // [`WitContract::target`]-enforced shape ↔ target partition
21446        // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
21447        // carries `:slot`, [`WitTarget::Capability`] carries none) —
21448        // [`WitContract::endpoint`] must return `None`. Pins against a
21449        // future silent detour that projected the absent slot to a
21450        // `Some("")` empty-string default (the canonical `Option<String>`
21451        // → `String` collapse footgun the sibling M2
21452        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
21453        // emptiness predicates already guard on the peer M2 typed-slot
21454        // surfaces), a `Some("None")` stringified-None round-trip, or a
21455        // `Some` arm whose contents were derived from a sibling slot (an
21456        // accidental fallback to the `:subject` / `:slot` payload that
21457        // read the pub-sub / store payload into the endpoint axis).
21458        // Three contracts sweep the accept-set every non-HTTP `:wit`
21459        // world lands on — pub-sub NATS, key/value, and payload-less
21460        // capability.
21461        for (wit, subject, slot) in [
21462            ("nats:pub-sub", Some("orders.paid"), None),
21463            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
21464            ("wasi:cli/environment", None, None),
21465        ] {
21466            let c = WitContract {
21467                de: "cart".into(),
21468                para: "downstream".into(),
21469                wit: wit.into(),
21470                endpoint: None,
21471                subject: subject.map(str::to_string),
21472                slot: slot.map(str::to_string),
21473            };
21474            assert!(
21475                c.endpoint().is_none(),
21476                "WitContract::endpoint must return None when the typed \
21477                 slot is absent under :wit {wit:?} (got {:?})",
21478                c.endpoint(),
21479            );
21480            assert_eq!(
21481                c.endpoint(),
21482                c.endpoint.as_deref(),
21483                "WitContract::endpoint must byte-equal the .endpoint \
21484                 field's `.as_deref()` projection in the absent arm",
21485            );
21486        }
21487    }
21488
21489    #[test]
21490    fn wit_contract_endpoint_borrows_from_endpoint_storage() {
21491        // The borrow-not-copy pin: [`WitContract::endpoint`] must return
21492        // an `Option<&str>` whose `Some` arm borrows from the typed
21493        // slot's own [`String`] storage — same-address invariant with
21494        // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
21495        // detour that allocated a fresh `String`
21496        // (`self.endpoint.clone().map(...)` in the body would type-check
21497        // but silently drop the borrow, and every downstream consumer
21498        // that assumed the returned slice outlives `&self` would break
21499        // on a stale-reference use-after-free — the [`WitContract::target`]
21500        // Http-arm payload extraction rebinds the returned `Option<&str>`
21501        // through `.ok_or_else(...)` and threads the `&str` payload into
21502        // [`WitTarget::Http { endpoint: &'a str }`], the
21503        // [`AplicacaoSpec::validate`] duplicate-`:contratos`
21504        // [`ContratoIdentity`] dedup key threads the returned
21505        // `Option<&str>` into the six-tuple's HTTP arm — each borrow
21506        // from the WitContract's own storage and each would silently
21507        // misbehave if this accessor produced a detached copy). Peer of
21508        // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
21509        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
21510        // shaped optional-scalar axes — first extension of the
21511        // `Option<&str>` borrow-not-copy discipline onto the
21512        // per-`:contratos` HTTP-shaped payload-carrier axis.
21513        let c = WitContract {
21514            de: "cart".into(),
21515            para: "catalog".into(),
21516            wit: "wasi:http/proxy".into(),
21517            endpoint: Some("/lookup".into()),
21518            subject: None,
21519            slot: None,
21520        };
21521        let ep = c.endpoint().expect("Some arm");
21522        let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
21523        assert_eq!(
21524            ep.as_ptr(),
21525            storage_slice.as_ptr(),
21526            "WitContract::endpoint must borrow from the .endpoint \
21527             String's backing storage — a fresh allocation here means \
21528             the accessor no longer names the substrate-primitive typed \
21529             dispatch and every downstream consumer would silently \
21530             carry a detached copy",
21531        );
21532        assert_eq!(
21533            ep.len(),
21534            storage_slice.len(),
21535            "WitContract::endpoint and .endpoint.as_deref() must byte-\
21536             equal in length as well as in address",
21537        );
21538    }
21539
21540    #[test]
21541    fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
21542        // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
21543        // pin: [`WitContract::subject`] must return the `:contratos
21544        // :subject` field byte-for-byte, borrowed from the typed slot's
21545        // own `Option<String>` storage. Peer of the sibling per-`:contratos`
21546        // [`WitContract::endpoint`] (7020470) accessor pin on the M3
21547        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
21548        // optional-scalar axis — same "the substrate-primitive accessor
21549        // must byte-equal the raw field access verbatim across every
21550        // author-declared value" discipline extended to the pub-sub arm.
21551        // Pins against a future silent detour that re-canonicalized the
21552        // subject (an accidental `.to_lowercase()` normalization that
21553        // didn't reach the peer field-access site at the dedup key, a
21554        // per-CR fully-qualified prefix rewrite the operator authors on
21555        // one consumer without the other, or an M4 typed-subject-template
21556        // `Display` re-canonicalization that silently drifted the printer
21557        // output from the source `caixa.lisp`). Four values sweep the
21558        // NATS accept-set every pub-sub author-declared subject lands on
21559        // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
21560        for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
21561            let c = WitContract {
21562                de: "cart".into(),
21563                para: "notifier".into(),
21564                wit: "nats:pub-sub".into(),
21565                endpoint: None,
21566                subject: Some(subject.into()),
21567                slot: None,
21568            };
21569            assert_eq!(
21570                c.subject(),
21571                Some(subject),
21572                "WitContract::subject must return :contratos :subject \
21573                 verbatim (got {:?}, expected Some({subject:?}))",
21574                c.subject(),
21575            );
21576            assert_eq!(
21577                c.subject(),
21578                c.subject.as_deref(),
21579                "WitContract::subject must byte-equal the .subject \
21580                 field's `.as_deref()` projection",
21581            );
21582        }
21583    }
21584
21585    #[test]
21586    fn wit_contract_subject_none_when_field_is_none() {
21587        // The absent-`:subject` arm of the per-`:contratos` pub-sub-
21588        // shaped payload-carrier accessor pin: when the typed slot is
21589        // absent — the canonical shape under a non-pub-sub `:wit` world
21590        // per the [`WitContract::target`]-enforced shape ↔ target
21591        // partition ([`WitTarget::Http`] carries `:endpoint`,
21592        // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
21593        // carries none) — [`WitContract::subject`] must return `None`.
21594        // Pins against a future silent detour that projected the absent
21595        // slot to a `Some("")` empty-string default (the canonical
21596        // `Option<String>` → `String` collapse footgun the sibling M2
21597        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
21598        // emptiness predicates already guard on the peer M2 typed-slot
21599        // surfaces), a `Some("None")` stringified-None round-trip, or a
21600        // `Some` arm whose contents were derived from a sibling slot (an
21601        // accidental fallback to the `:endpoint` / `:slot` payload that
21602        // read the HTTP / store payload into the subject axis). Three
21603        // contracts sweep the accept-set every non-pub-sub `:wit` world
21604        // lands on — HTTP proxy, key/value store, and payload-less
21605        // capability.
21606        for (wit, endpoint, slot) in [
21607            ("wasi:http/proxy", Some("/lookup"), None),
21608            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
21609            ("wasi:cli/environment", None, None),
21610        ] {
21611            let c = WitContract {
21612                de: "cart".into(),
21613                para: "downstream".into(),
21614                wit: wit.into(),
21615                endpoint: endpoint.map(str::to_string),
21616                subject: None,
21617                slot: slot.map(str::to_string),
21618            };
21619            assert!(
21620                c.subject().is_none(),
21621                "WitContract::subject must return None when the typed \
21622                 slot is absent under :wit {wit:?} (got {:?})",
21623                c.subject(),
21624            );
21625            assert_eq!(
21626                c.subject(),
21627                c.subject.as_deref(),
21628                "WitContract::subject must byte-equal the .subject \
21629                 field's `.as_deref()` projection in the absent arm",
21630            );
21631        }
21632    }
21633
21634    #[test]
21635    fn wit_contract_subject_borrows_from_subject_storage() {
21636        // The borrow-not-copy pin: [`WitContract::subject`] must return
21637        // an `Option<&str>` whose `Some` arm borrows from the typed
21638        // slot's own [`String`] storage — same-address invariant with
21639        // `c.subject.as_deref().unwrap()`. Pins against a future silent
21640        // detour that allocated a fresh `String`
21641        // (`self.subject.clone().map(...)` in the body would type-check
21642        // but silently drop the borrow, and every downstream consumer
21643        // that assumed the returned slice outlives `&self` would break
21644        // on a stale-reference use-after-free — the [`WitContract::target`]
21645        // PubSub-arm payload extraction rebinds the returned
21646        // `Option<&str>` through `.ok_or_else(...)` and threads the
21647        // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
21648        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
21649        // [`ContratoIdentity`] dedup key threads the returned
21650        // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
21651        // from the WitContract's own storage and each would silently
21652        // misbehave if this accessor produced a detached copy). Peer of
21653        // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
21654        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
21655        // shaped optional-scalar axis — second extension of the
21656        // `Option<&str>` borrow-not-copy discipline onto the
21657        // per-`:contratos` payload-carrier family, this time on the
21658        // pub-sub arm.
21659        let c = WitContract {
21660            de: "cart".into(),
21661            para: "notifier".into(),
21662            wit: "nats:pub-sub".into(),
21663            endpoint: None,
21664            subject: Some("orders.paid".into()),
21665            slot: None,
21666        };
21667        let sub = c.subject().expect("Some arm");
21668        let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
21669        assert_eq!(
21670            sub.as_ptr(),
21671            storage_slice.as_ptr(),
21672            "WitContract::subject must borrow from the .subject \
21673             String's backing storage — a fresh allocation here means \
21674             the accessor no longer names the substrate-primitive typed \
21675             dispatch and every downstream consumer would silently \
21676             carry a detached copy",
21677        );
21678        assert_eq!(
21679            sub.len(),
21680            storage_slice.len(),
21681            "WitContract::subject and .subject.as_deref() must byte-\
21682             equal in length as well as in address",
21683        );
21684    }
21685
21686    #[test]
21687    fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
21688        // The canonical per-`:contratos` key/value-store-shaped
21689        // `:slot`-scalar pin: [`WitContract::slot`] must return the
21690        // `:contratos :slot` field byte-for-byte, borrowed from the
21691        // typed slot's own `Option<String>` storage. Peer of the
21692        // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
21693        // [`WitContract::subject`] (90de675) accessor pins on the M3
21694        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
21695        // optional-scalar axis — same "the substrate-primitive
21696        // accessor must byte-equal the raw field access verbatim
21697        // across every author-declared value" discipline extended to
21698        // the store arm. Pins against a future silent detour that
21699        // re-canonicalized the slot template (an accidental
21700        // `.to_lowercase()` bucket-prefix normalization that didn't
21701        // reach the peer field-access site at the dedup key, a per-CR
21702        // fully-qualified prefix rewrite the operator authors on one
21703        // consumer without the other, or an M4 typed-key-template
21704        // `Display` re-canonicalization that silently drifted the
21705        // printer output from the source `caixa.lisp`). Four values
21706        // sweep the wasi:keyvalue accept-set every store-shaped
21707        // author-declared slot lands on (flat bucket, single-param
21708        // template, multi-param template, nested-hierarchy template).
21709        for slot in [
21710            "sessions",
21711            "carts/{cart_id}",
21712            "orders/{tenant}/{order_id}",
21713            "cache/tenant-a/orders/{id}",
21714        ] {
21715            let c = WitContract {
21716                de: "cart".into(),
21717                para: "kv".into(),
21718                wit: "wasi:keyvalue/store".into(),
21719                endpoint: None,
21720                subject: None,
21721                slot: Some(slot.into()),
21722            };
21723            assert_eq!(
21724                c.slot(),
21725                Some(slot),
21726                "WitContract::slot must return :contratos :slot \
21727                 verbatim (got {:?}, expected Some({slot:?}))",
21728                c.slot(),
21729            );
21730            assert_eq!(
21731                c.slot(),
21732                c.slot.as_deref(),
21733                "WitContract::slot must byte-equal the .slot field's \
21734                 `.as_deref()` projection",
21735            );
21736        }
21737    }
21738
21739    #[test]
21740    fn wit_contract_slot_none_when_field_is_none() {
21741        // The absent-`:slot` arm of the per-`:contratos` store-shaped
21742        // payload-carrier accessor pin: when the typed slot is absent —
21743        // the canonical shape under a non-store `:wit` world per the
21744        // [`WitContract::target`]-enforced shape ↔ target partition
21745        // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
21746        // carries `:subject`, [`WitTarget::Capability`] carries none) —
21747        // [`WitContract::slot`] must return `None`. Pins against a
21748        // future silent detour that projected the absent slot to a
21749        // `Some("")` empty-string default (the canonical
21750        // `Option<String>` → `String` collapse footgun the sibling M2
21751        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
21752        // emptiness predicates already guard on the peer M2 typed-slot
21753        // surfaces), a `Some("None")` stringified-None round-trip, or
21754        // a `Some` arm whose contents were derived from a sibling
21755        // slot (an accidental fallback to the `:endpoint` / `:subject`
21756        // payload that read the HTTP / pub-sub payload into the store
21757        // axis). Three contracts sweep the accept-set every non-store
21758        // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
21759        // payload-less capability.
21760        for (wit, endpoint, subject) in [
21761            ("wasi:http/proxy", Some("/lookup"), None),
21762            ("nats:pub-sub", None, Some("orders.paid")),
21763            ("wasi:cli/environment", None, None),
21764        ] {
21765            let c = WitContract {
21766                de: "cart".into(),
21767                para: "downstream".into(),
21768                wit: wit.into(),
21769                endpoint: endpoint.map(str::to_string),
21770                subject: subject.map(str::to_string),
21771                slot: None,
21772            };
21773            assert!(
21774                c.slot().is_none(),
21775                "WitContract::slot must return None when the typed \
21776                 slot is absent under :wit {wit:?} (got {:?})",
21777                c.slot(),
21778            );
21779            assert_eq!(
21780                c.slot(),
21781                c.slot.as_deref(),
21782                "WitContract::slot must byte-equal the .slot field's \
21783                 `.as_deref()` projection in the absent arm",
21784            );
21785        }
21786    }
21787
21788    #[test]
21789    fn wit_contract_slot_borrows_from_slot_storage() {
21790        // The borrow-not-copy pin: [`WitContract::slot`] must return
21791        // an `Option<&str>` whose `Some` arm borrows from the typed
21792        // slot's own [`String`] storage — same-address invariant with
21793        // `c.slot.as_deref().unwrap()`. Pins against a future silent
21794        // detour that allocated a fresh `String`
21795        // (`self.slot.clone().map(...)` in the body would type-check
21796        // but silently drop the borrow, and every downstream consumer
21797        // that assumed the returned slice outlives `&self` would
21798        // break on a stale-reference use-after-free — the
21799        // [`WitContract::target`] Store-arm payload extraction rebinds
21800        // the returned `Option<&str>` through `.ok_or_else(...)` and
21801        // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
21802        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
21803        // [`ContratoIdentity`] dedup key threads the returned
21804        // `Option<&str>` into the six-tuple's store arm — each borrow
21805        // from the WitContract's own storage and each would silently
21806        // misbehave if this accessor produced a detached copy). Peer
21807        // of the sibling per-`:contratos` [`WitContract::endpoint`]
21808        // (7020470) / [`WitContract::subject`] (90de675)
21809        // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
21810        // shaped optional-scalar axis — third and final extension of
21811        // the `Option<&str>` borrow-not-copy discipline onto the
21812        // per-`:contratos` payload-carrier family, this time on the
21813        // store arm.
21814        let c = WitContract {
21815            de: "cart".into(),
21816            para: "kv".into(),
21817            wit: "wasi:keyvalue/store".into(),
21818            endpoint: None,
21819            subject: None,
21820            slot: Some("carts/{cart_id}".into()),
21821        };
21822        let slot = c.slot().expect("Some arm");
21823        let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
21824        assert_eq!(
21825            slot.as_ptr(),
21826            storage_slice.as_ptr(),
21827            "WitContract::slot must borrow from the .slot String's \
21828             backing storage — a fresh allocation here means the \
21829             accessor no longer names the substrate-primitive typed \
21830             dispatch and every downstream consumer would silently \
21831             carry a detached copy",
21832        );
21833        assert_eq!(
21834            slot.len(),
21835            storage_slice.len(),
21836            "WitContract::slot and .slot.as_deref() must byte-equal \
21837             in length as well as in address",
21838        );
21839    }
21840
21841    #[test]
21842    fn membro_nome_returns_caixa_byte_equal_across_permutations() {
21843        // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
21844        // [`Membro::nome`] must return the `:membros :caixa` field
21845        // byte-for-byte, borrowed from the typed slot's own [`String`]
21846        // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
21847        // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
21848        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
21849        // slot-atom scalar-value axes — same "the substrate-primitive
21850        // accessor must byte-equal the raw field access verbatim across
21851        // every author-declared value" discipline extended to the
21852        // per-`:membros` member-identity arm. Pins against a future
21853        // silent detour that re-normalized the member identity (an
21854        // accidental `.to_lowercase()` — every `:membros :caixa` is
21855        // validated as a DNS-1123 label upstream via
21856        // [`validate_membro_caixa`], so any re-normalization is
21857        // redundant + a drift surface between the validator and the
21858        // accessor), a namespace-prefix rewrite (an accidental
21859        // `format!("{namespace}/{caixa}")` per-CR fully-qualified
21860        // rewrite that didn't land on the peer axes), or a per-cluster
21861        // alias stamp the operator authors on one consumer without the
21862        // other. Four values sweep the accept-set the DNS-1123 gate
21863        // upstream admits (short single-word / dashed / v-suffixed
21864        // member names).
21865        for name in ["cart", "checkout", "catalog", "orders-v2"] {
21866            let m = Membro {
21867                caixa: name.into(),
21868                versao: "^0.1".into(),
21869            };
21870            assert_eq!(
21871                m.nome(),
21872                name,
21873                "Membro::nome must return :membros :caixa verbatim \
21874                 (got {:?}, expected {name:?})",
21875                m.nome(),
21876            );
21877            assert_eq!(
21878                m.nome(),
21879                m.caixa.as_str(),
21880                "Membro::nome must byte-equal the .caixa field access",
21881            );
21882        }
21883    }
21884
21885    #[test]
21886    fn membro_nome_borrows_from_caixa_storage() {
21887        // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
21888        // slice that borrows from the typed slot's own [`String`]
21889        // storage — same-address invariant with `m.caixa.as_str()`. Pins
21890        // against a future silent detour that allocated a fresh `String`
21891        // (`self.caixa.clone()` in the body would type-check but
21892        // silently drop the borrow, and every downstream consumer that
21893        // assumed the returned slice outlives `&self` would break on a
21894        // stale-reference use-after-free — the `HashSet<&str>` collector
21895        // at [`AplicacaoSpec::validate`]'s `names` seed, the
21896        // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
21897        // [`AplicacaoSpec::detect_sync_cycles`], the
21898        // [`crate::render::insert_first_seen`] dedup key at
21899        // [`AplicacaoSpec::validate_membros`] — each borrow from the
21900        // Membro's own storage and each would silently misbehave if
21901        // this accessor produced a detached copy). Peer of the sibling
21902        // per-`:contratos` [`WitContract::source`] /
21903        // [`WitContract::destination`] and per-`:entrada`
21904        // [`Entrada::destination`] borrow-invariant pins on the mesh-
21905        // slot-atom scalar-value axes.
21906        let m = Membro {
21907            caixa: "checkout".into(),
21908            versao: "^0.1".into(),
21909        };
21910        let name = m.nome();
21911        let caixa_slice = m.caixa.as_str();
21912        assert_eq!(
21913            name.as_ptr(),
21914            caixa_slice.as_ptr(),
21915            "Membro::nome must borrow from the .caixa String's backing \
21916             storage — a fresh allocation here means the accessor no \
21917             longer names the substrate-primitive typed dispatch and \
21918             every downstream consumer would silently carry a detached \
21919             copy",
21920        );
21921        assert_eq!(
21922            name.len(),
21923            caixa_slice.len(),
21924            "Membro::nome and .caixa.as_str() must byte-equal in length \
21925             as well as in address",
21926        );
21927    }
21928
21929    #[test]
21930    fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
21931        // The canonical per-`:membros` member-`:versao`-scalar pin:
21932        // [`Membro::versao_requirement`] must return the
21933        // `:membros :versao` field byte-for-byte, borrowed from the typed
21934        // slot's own [`String`] storage. Sibling of the peer
21935        // `membro_nome_returns_caixa_byte_equal_across_permutations`
21936        // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
21937        // — same "the substrate-primitive accessor must byte-equal the
21938        // raw field access verbatim across every author-declared value"
21939        // discipline extended to the per-`:membros` member-`:versao`
21940        // requirement-string arm. Pins against a future silent detour
21941        // that re-canonicalized the requirement (an accidental
21942        // `.to_string()` via [`parse_requirement`] → [`Display`] round-
21943        // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
21944        // drifted the printer output away from the source `caixa.lisp`,
21945        // an accidental whitespace trim on `"^ 0.1"` that no consumer
21946        // ever produced from the field-access side, an accidental
21947        // per-cluster lacre-projected concrete-version rewrite that
21948        // didn't land on the peer field-access sites). Five values sweep
21949        // the accept-set the shared
21950        // [`crate::render::require_valid_versao_requirement`] gate
21951        // admits (caret / tilde / exact / wildcard / bare-major).
21952        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
21953            let m = Membro {
21954                caixa: "cart".into(),
21955                versao: req.into(),
21956            };
21957            assert_eq!(
21958                m.versao_requirement(),
21959                req,
21960                "Membro::versao_requirement must return :membros :versao \
21961                 verbatim (got {:?}, expected {req:?})",
21962                m.versao_requirement(),
21963            );
21964            assert_eq!(
21965                m.versao_requirement(),
21966                m.versao.as_str(),
21967                "Membro::versao_requirement must byte-equal the .versao \
21968                 field access",
21969            );
21970        }
21971    }
21972
21973    #[test]
21974    fn membro_versao_requirement_borrows_from_versao_storage() {
21975        // The borrow-not-copy pin: [`Membro::versao_requirement`] must
21976        // return a `&str` slice that borrows from the typed slot's own
21977        // [`String`] storage — same-address invariant with
21978        // `m.versao.as_str()`. Pins against a future silent detour that
21979        // allocated a fresh `String` (`self.versao.clone()` in the body
21980        // would type-check but silently drop the borrow, and every
21981        // downstream consumer that assumed the returned slice outlives
21982        // `&self` would break on a stale-reference use-after-free). Peer
21983        // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
21984        // per-`:contratos` [`WitContract::source`] /
21985        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
21986        // [`Entrada::destination`] (6db982c) borrow-invariant pins on
21987        // the mesh-slot-atom scalar-value axes.
21988        let m = Membro {
21989            caixa: "checkout".into(),
21990            versao: "^0.1".into(),
21991        };
21992        let req = m.versao_requirement();
21993        let versao_slice = m.versao.as_str();
21994        assert_eq!(
21995            req.as_ptr(),
21996            versao_slice.as_ptr(),
21997            "Membro::versao_requirement must borrow from the .versao \
21998             String's backing storage — a fresh allocation here means \
21999             the accessor no longer names the substrate-primitive typed \
22000             dispatch and every downstream consumer would silently carry \
22001             a detached copy",
22002        );
22003        assert_eq!(
22004            req.len(),
22005            versao_slice.len(),
22006            "Membro::versao_requirement and .versao.as_str() must byte-\
22007             equal in length as well as in address",
22008        );
22009    }
22010
22011    #[test]
22012    fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
22013        // Sibling-pair invariant pin composing both per-`:membros`
22014        // substrate-primitive typed dispatches — [`Membro::nome`]
22015        // (4a32abf) and [`Membro::versao_requirement`] — at the joint
22016        // `(nome(), versao_requirement())` call shape every renderer
22017        // that fans on per-member identity + version pin keys off. The
22018        // invariant, evaluated per-member:
22019        //
22020        //   (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
22021        //
22022        // Closes the last unlifted per-`:membros` scalar axis — every
22023        // downstream consumer that reads the pair now routes through
22024        // exactly two typed dispatches on the substrate primitive, not
22025        // one typed + one open-coded field access. A future refactor
22026        // that silently split either accessor's projection (an
22027        // accidental `nome()` namespace-prefix rewrite that didn't
22028        // reach the peer, an accidental `versao_requirement()` lacre-
22029        // projected concrete-version rewrite that didn't land on the
22030        // `nome()` peer) surfaces at caixa-core build time. Peer of the
22031        // sibling per-`:entrada` `(hostname(), destination())` and
22032        // per-`:contratos` `(source(), destination())` pair invariants
22033        // on the mesh-slot-atom scalar-value axes.
22034        for (caixa, versao) in [
22035            ("cart", "^0.1"),
22036            ("checkout", "~0.1.2"),
22037            ("catalog", "0.1.0"),
22038            ("orders-v2", "*"),
22039        ] {
22040            let m = Membro {
22041                caixa: caixa.into(),
22042                versao: versao.into(),
22043            };
22044            assert_eq!(
22045                (m.nome(), m.versao_requirement()),
22046                (m.caixa.as_str(), m.versao.as_str()),
22047                "(Membro::nome, Membro::versao_requirement) must project \
22048                 (.caixa, .versao) verbatim across every author-declared \
22049                 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
22050                m.nome(),
22051                m.versao_requirement(),
22052            );
22053        }
22054    }
22055
22056    #[test]
22057    fn validate_membros_empty_gate_routes_through_nome_accessor() {
22058        // Composition pin: [`AplicacaoSpec::validate_membros`]'s
22059        // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
22060        // not the raw `.caixa` field access. Structurally: setting
22061        // ONLY the `.caixa` field to `""` on an otherwise-well-formed
22062        // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
22063        // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
22064        // (i.e. the empty string) — so the emptiness predicate the
22065        // refusal arm reaches under is the accessor-projected value,
22066        // not a peer field that would silently drift under a future
22067        // accessor-side rewrite.
22068        //
22069        // Pins against a future silent detour that (a) re-derived the
22070        // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
22071        // instead of `self.nome().is_empty()`, silently disagreeing with
22072        // every peer consumer (the `validate_membro_caixa(m.nome())`
22073        // call one line below, the dedup-key `insert_first_seen(&mut
22074        // seen, m.nome(), …)` two lines below, the emit-side per-
22075        // `programs[]` entry-`name:` at caixa-mesh/src/lib.rs:133),
22076        // (b) accessor-side introduced a per-tenant alias arm the
22077        // caller was unaware of, silently rewriting an author-declared
22078        // `:caixa "checkout"` to `""` — the raw-field-access gate
22079        // would fail-open while the accessor-routed peer consumers
22080        // would fail-closed, splitting the diagnostic from the actual
22081        // failure surface.
22082        //
22083        // Peer of the sibling
22084        // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
22085        // (c0110f1) composition pin — same "the shape-gate predicate
22086        // must route through the substrate-primitive typed dispatch"
22087        // discipline extended onto the per-`:membros` empty-`:caixa`
22088        // refusal-arm axis. Closes the last unlifted `.caixa` production-
22089        // code read site on `Membro` — after this converge every
22090        // caixa-core `.caixa` field access outside the accessor's own
22091        // body is either a test-side field-setter (in-module tests
22092        // constructing invalid-shape inputs) or a doc-comment reference.
22093        let mut s = three_member_spec();
22094        s.membros[1].caixa = String::new();
22095        assert!(
22096            s.membros[1].nome().is_empty(),
22097            "Membro::nome must byte-equal the .caixa field access — an \
22098             accessor-side detour that no longer projects the raw field \
22099             would silently split this drift-detection test from the \
22100             validate() refusal arm",
22101        );
22102        assert_eq!(
22103            s.membros[1].nome(),
22104            s.membros[1].caixa.as_str(),
22105            "Membro::nome and .caixa.as_str() must byte-equal on an \
22106             empty-`:caixa` entry — the emptiness gate keys off the \
22107             accessor by construction",
22108        );
22109        assert_eq!(
22110            s.validate().unwrap_err(),
22111            AplicacaoError::MembroCaixaEmpty,
22112            "validate_membros' emptiness gate must fire MembroCaixaEmpty \
22113             on an entry whose accessor-projected `nome()` is empty",
22114        );
22115    }
22116
22117    #[test]
22118    fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
22119        // The canonical per-`:placement` Akka-cluster-sharding
22120        // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
22121        // the `:placement :shard-key` field byte-for-byte, borrowed
22122        // from the typed slot's own `Option<String>` storage. Peer of
22123        // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
22124        // per-`:contratos` [`WitContract::source`] /
22125        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
22126        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
22127        // slot-atom scalar-value axes — same "the substrate-primitive
22128        // accessor must byte-equal the raw field access verbatim across
22129        // every author-declared value" discipline extended to the
22130        // per-`:placement` Akka-cluster-sharding key extractor arm.
22131        // Pins against a future silent detour that re-normalized the
22132        // key (an accidental `.to_lowercase()` — every non-empty
22133        // `:shard-key` is validated as a printable-ASCII single-token
22134        // reference upstream via [`validate_placement_shard_key`], so
22135        // any re-normalization is redundant + a drift surface between
22136        // the validator and the accessor), a per-cluster alias rewrite
22137        // the operator authors on one consumer without the other, or an
22138        // accidental variable-prefix strip (`$tenantId` → `tenantId`)
22139        // that didn't land on the peer field-access sites. Four values
22140        // sweep the accept-set the shape gate admits — bare identifier,
22141        // `$`-prefixed variable, dotted path, `${}`-quoted variable —
22142        // the four canonical Akka-style entity-id extractor shapes the
22143        // future M4 cluster-sharding reconciler hashes.
22144        for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
22145            let p = Placement {
22146                estrategia: PlacementStrategy::Sharded,
22147                clusters: vec!["rio".into()],
22148                affinity: None,
22149                shard_key: Some(key.into()),
22150            };
22151            assert_eq!(
22152                p.shard_key(),
22153                Some(key),
22154                "Placement::shard_key must return :placement :shard-key \
22155                 verbatim (got {:?}, expected Some({key:?}))",
22156                p.shard_key(),
22157            );
22158            assert_eq!(
22159                p.shard_key(),
22160                p.shard_key.as_deref(),
22161                "Placement::shard_key must byte-equal the .shard_key \
22162                 field's `.as_deref()` projection",
22163            );
22164        }
22165    }
22166
22167    #[test]
22168    fn placement_shard_key_none_when_field_is_none() {
22169        // The absent-`:shard-key` arm of the per-`:placement`
22170        // Akka-cluster-sharding accessor pin: when the typed slot is
22171        // absent — the canonical shape under `:estrategia Replicated` /
22172        // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
22173        // enforced `shard_key.is_some() == matches!(estrategia,
22174        // Sharded)` partition — [`Placement::shard_key`] must return
22175        // `None`. Pins against a future silent detour that projected
22176        // the absent slot to a `Some("")` empty-string default (the
22177        // canonical `Option<String>` → `String` collapse footgun the
22178        // sibling M2 [`crate::LimitsSpec::is_empty`] /
22179        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
22180        // already guard on the peer M2 typed-slot surfaces), a
22181        // `Some("None")` stringified-None round-trip, or a `Some` arm
22182        // whose contents were derived from a sibling slot (an
22183        // accidental fallback to `estrategia.as_str()` that read the
22184        // strategy discriminator into the key axis). Two placements
22185        // sweep the accept-set every `validate`-passing non-`Sharded`
22186        // shape lands on — `Replicated` (Erlang/OTP distributed-app
22187        // takeover) and `SingleNode` (single-node hosting).
22188        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
22189            let p = Placement {
22190                estrategia,
22191                clusters: vec!["rio".into()],
22192                affinity: None,
22193                shard_key: None,
22194            };
22195            assert!(
22196                p.shard_key().is_none(),
22197                "Placement::shard_key must return None when the typed \
22198                 slot is absent under :estrategia {estrategia:?} (got {:?})",
22199                p.shard_key(),
22200            );
22201            assert_eq!(
22202                p.shard_key(),
22203                p.shard_key.as_deref(),
22204                "Placement::shard_key must byte-equal the .shard_key \
22205                 field's `.as_deref()` projection in the absent arm",
22206            );
22207        }
22208    }
22209
22210    #[test]
22211    fn placement_shard_key_borrows_from_shard_key_storage() {
22212        // The borrow-not-copy pin: [`Placement::shard_key`] must return
22213        // an `Option<&str>` whose `Some` arm borrows from the typed
22214        // slot's own [`String`] storage — same-address invariant with
22215        // `p.shard_key.as_deref().unwrap()`. Pins against a future
22216        // silent detour that allocated a fresh `String`
22217        // (`self.shard_key.clone().map(...)` in the body would type-
22218        // check but silently drop the borrow, and every downstream
22219        // consumer that assumed the returned slice outlives `&self`
22220        // would break on a stale-reference use-after-free — the
22221        // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
22222        // gate's `Some(k)`-bound match arm reads `k: &str` under the
22223        // accessor's return type and would silently misbehave if this
22224        // accessor produced a detached copy). Peer of the sibling
22225        // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
22226        // [`WitContract::source`] / [`WitContract::destination`]
22227        // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
22228        // (6db982c) borrow-invariant pins on the mesh-slot-atom
22229        // scalar-value axes — first extension of the discipline onto
22230        // an `Option<String>`-shaped optional-scalar axis.
22231        let p = Placement {
22232            estrategia: PlacementStrategy::Sharded,
22233            clusters: vec!["rio".into()],
22234            affinity: None,
22235            shard_key: Some("tenantId".into()),
22236        };
22237        let key = p.shard_key().expect("Some arm");
22238        let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
22239        assert_eq!(
22240            key.as_ptr(),
22241            storage_slice.as_ptr(),
22242            "Placement::shard_key must borrow from the .shard_key \
22243             String's backing storage — a fresh allocation here means \
22244             the accessor no longer names the substrate-primitive typed \
22245             dispatch and every downstream consumer would silently \
22246             carry a detached copy",
22247        );
22248        assert_eq!(
22249            key.len(),
22250            storage_slice.len(),
22251            "Placement::shard_key and .shard_key.as_deref() must byte-\
22252             equal in length as well as in address",
22253        );
22254    }
22255
22256    #[test]
22257    fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
22258        // The canonical per-`:placement` M3-Adaptive-compression-hint
22259        // scalar pin: [`Placement::affinity`] must return the
22260        // `:placement :affinity` field byte-for-byte, borrowed from the
22261        // typed slot's own `Option<String>` storage. Peer of the sibling
22262        // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
22263        // pin on the sibling `Option<&str>` optional-scalar axis — same
22264        // "the substrate-primitive accessor must byte-equal the raw
22265        // field access verbatim across every author-declared value"
22266        // discipline extended to the peer per-`:placement` M3-Adaptive-
22267        // compression-hint arm. Pins against a future silent detour
22268        // that re-normalized the hint (an accidental `.to_lowercase()`
22269        // — every `:affinity` is already validated as a DNS-1123 label
22270        // upstream via [`validate_placement_affinity`], so any re-
22271        // normalization is redundant + a drift surface between the
22272        // validator and the accessor), a per-cluster alias rewrite the
22273        // operator authors on one consumer without the other, or an
22274        // accidental hint-family collapse (`low-latency` → `latency`
22275        // that dropped the qualifier prefix). Four values sweep the
22276        // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
22277        // canonical adaptive-compression-weight biases the future M4
22278        // placement engine reads.
22279        for hint in [
22280            "data-locality",
22281            "low-latency",
22282            "high-throughput",
22283            "cost-optimized",
22284        ] {
22285            let p = Placement {
22286                estrategia: PlacementStrategy::Replicated,
22287                clusters: vec!["rio".into()],
22288                affinity: Some(hint.into()),
22289                shard_key: None,
22290            };
22291            assert_eq!(
22292                p.affinity(),
22293                Some(hint),
22294                "Placement::affinity must return :placement :affinity \
22295                 verbatim (got {:?}, expected Some({hint:?}))",
22296                p.affinity(),
22297            );
22298            assert_eq!(
22299                p.affinity(),
22300                p.affinity.as_deref(),
22301                "Placement::affinity must byte-equal the .affinity \
22302                 field's `.as_deref()` projection",
22303            );
22304        }
22305    }
22306
22307    #[test]
22308    fn placement_affinity_none_when_field_is_none() {
22309        // The absent-`:affinity` arm of the per-`:placement`
22310        // M3-Adaptive-compression-hint accessor pin: when the typed
22311        // slot is absent — the canonical shape of an Aplicacao that
22312        // leaves the compression weighting up to the placement engine's
22313        // cluster-default arm — [`Placement::affinity`] must return
22314        // `None`. Pins against a future silent detour that projected
22315        // the absent slot to a `Some("")` empty-string default (the
22316        // canonical `Option<String>` → `String` collapse footgun the
22317        // sibling M2 [`crate::LimitsSpec::is_empty`] /
22318        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
22319        // already guard on the peer M2 typed-slot surfaces), a
22320        // `Some("None")` stringified-None round-trip, a `Some` arm
22321        // whose contents were derived from a sibling slot (an
22322        // accidental fallback to `estrategia.as_str()` that read the
22323        // strategy discriminator into the hint axis), or a
22324        // `Some("default")` implicit-default that would silently biases
22325        // the routing without the author having written one. Three
22326        // placements sweep the accept-set every `validate`-passing
22327        // `:affinity None` shape lands on — one per PlacementStrategy
22328        // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
22329        // with a shard-key), since `:affinity` is orthogonal to
22330        // `:estrategia` in the typed grammar.
22331        for (estrategia, shard_key) in [
22332            (PlacementStrategy::SingleNode, None),
22333            (PlacementStrategy::Replicated, None),
22334            (PlacementStrategy::Sharded, Some("tenantId".to_string())),
22335        ] {
22336            let p = Placement {
22337                estrategia,
22338                clusters: vec!["rio".into()],
22339                affinity: None,
22340                shard_key,
22341            };
22342            assert!(
22343                p.affinity().is_none(),
22344                "Placement::affinity must return None when the typed \
22345                 slot is absent under :estrategia {estrategia:?} (got {:?})",
22346                p.affinity(),
22347            );
22348            assert_eq!(
22349                p.affinity(),
22350                p.affinity.as_deref(),
22351                "Placement::affinity must byte-equal the .affinity \
22352                 field's `.as_deref()` projection in the absent arm",
22353            );
22354        }
22355    }
22356
22357    #[test]
22358    fn placement_affinity_borrows_from_affinity_storage() {
22359        // The borrow-not-copy pin: [`Placement::affinity`] must return
22360        // an `Option<&str>` whose `Some` arm borrows from the typed
22361        // slot's own [`String`] storage — same-address invariant with
22362        // `p.affinity.as_deref().unwrap()`. Pins against a future
22363        // silent detour that allocated a fresh `String`
22364        // (`self.affinity.clone().map(...)` in the body would type-
22365        // check but silently drop the borrow, and every downstream
22366        // consumer that assumed the returned slice outlives `&self`
22367        // would break on a stale-reference use-after-free — the
22368        // [`AplicacaoSpec::validate_placement`] per-hint value-shape
22369        // gate reads the accessor's `&str` return through the
22370        // [`validate_placement_affinity`] `&str` parameter and would
22371        // silently misbehave if this accessor produced a detached
22372        // copy). Peer of the sibling per-`:placement`
22373        // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
22374        // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
22375        // extends the discipline onto the sibling per-`:placement`
22376        // M3-Adaptive-compression-hint arm.
22377        let p = Placement {
22378            estrategia: PlacementStrategy::Replicated,
22379            clusters: vec!["rio".into()],
22380            affinity: Some("data-locality".into()),
22381            shard_key: None,
22382        };
22383        let hint = p.affinity().expect("Some arm");
22384        let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
22385        assert_eq!(
22386            hint.as_ptr(),
22387            storage_slice.as_ptr(),
22388            "Placement::affinity must borrow from the .affinity \
22389             String's backing storage — a fresh allocation here means \
22390             the accessor no longer names the substrate-primitive typed \
22391             dispatch and every downstream consumer would silently \
22392             carry a detached copy",
22393        );
22394        assert_eq!(
22395            hint.len(),
22396            storage_slice.len(),
22397            "Placement::affinity and .affinity.as_deref() must byte-\
22398             equal in length as well as in address",
22399        );
22400    }
22401
22402    #[test]
22403    fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
22404        // The canonical per-`:placement` distribution-strategy-scalar
22405        // pin: [`Placement::estrategia`] must return the `:placement
22406        // :estrategia` field verbatim as a [`PlacementStrategy`],
22407        // `Copy`-projected from the typed slot's own `PlacementStrategy`
22408        // storage across every variant in the closed accept-set
22409        // (`SingleNode` — Erlang/OTP distributed-app takeover;
22410        // `Replicated` — active-active across every named cluster;
22411        // `Sharded` — Akka-style hash-keyed entity distribution). Pins
22412        // against a future silent detour that re-derived the strategy
22413        // from a peer axis (an accidental fallback to
22414        // `if shard_key.is_some() { Sharded } else { Replicated }`
22415        // collapse that read the shard-key axis into the strategy
22416        // discriminator), a variant remap the operator authors on one
22417        // consumer without the other, or a stale-derive detour that
22418        // substituted [`PlacementStrategy::default`] when the field
22419        // held any explicit variant (which would silently collapse the
22420        // distinction between "author explicitly declared `:estrategia
22421        // Replicated`" and "author omitted the slot and inherited the
22422        // default" the future per-cluster override slot depends on).
22423        // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
22424        // pin on the `Copy`-return `u16` scalar axis — same "the
22425        // substrate-primitive accessor must byte-equal the raw field
22426        // access verbatim across every author-declared value" discipline
22427        // extended onto the per-`:placement` distribution-strategy
22428        // `Copy`-composite-enum scalar axis.
22429        for estrategia in [
22430            PlacementStrategy::SingleNode,
22431            PlacementStrategy::Replicated,
22432            PlacementStrategy::Sharded,
22433        ] {
22434            // Route the paired `:shard-key` fixture-builder through the
22435            // typed cross-slot invariant predicate
22436            // [`PlacementStrategy::requires_shard_key`] rather than the
22437            // [`gen_platform::IsVariant`]-derived [`PlacementStrategy::is_sharded`]
22438            // arm-identity predicate — same discipline the sibling
22439            // `placement_strategy_variants_round_trip` fixture builder now
22440            // reads through.
22441            let shard_key = estrategia
22442                .requires_shard_key()
22443                .then(|| "tenantId".to_string());
22444            let p = Placement {
22445                estrategia,
22446                clusters: vec!["rio".into()],
22447                affinity: None,
22448                shard_key,
22449            };
22450            assert_eq!(
22451                p.estrategia(),
22452                estrategia,
22453                "Placement::estrategia must return :placement :estrategia \
22454                 verbatim (got {:?}, expected {estrategia:?})",
22455                p.estrategia(),
22456            );
22457            assert_eq!(
22458                p.estrategia(),
22459                p.estrategia,
22460                "Placement::estrategia accessor and .estrategia field \
22461                 access must byte-equal — the accessor is the substrate-\
22462                 primitive typed dispatch every downstream distribution-\
22463                 strategy consumer must route through",
22464            );
22465        }
22466    }
22467
22468    #[test]
22469    fn validate_placement_reads_through_lifted_estrategia_accessor() {
22470        // Three-consumer coherence pin: the
22471        // [`AplicacaoSpec::validate_placement`]
22472        // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
22473        // `estrategia:` field (which reads through
22474        // [`Placement::estrategia`] to name the strategy the empty
22475        // `:clusters` list was declared against), the same method's
22476        // `Sharded ↔ non-Sharded` `match` partition dispatch (which
22477        // reads through [`Placement::estrategia`] to fan across the
22478        // shape-gate cascades), and the non-`Sharded`-arm
22479        // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
22480        // `estrategia:` field (which reads through
22481        // [`Placement::estrategia`] to name the strategy the declared-
22482        // but-inert `:shard-key` was authored under) must all key off
22483        // the lifted accessor, so any future rebrand on the typed
22484        // slot's reader shape lands at exactly one place. Pins the
22485        // three-site coherence by exercising each error surface end-
22486        // to-end and asserting the surfaced `estrategia:` field byte-
22487        // equals the accessor's return. Peer of the sibling per-
22488        // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
22489        // pin on the M3 mesh-slot `Copy`-return scalar axis.
22490
22491        // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
22492        // whose `estrategia:` field must byte-equal the accessor's return
22493        // for every variant in the closed accept-set.
22494        for estrategia in [
22495            PlacementStrategy::SingleNode,
22496            PlacementStrategy::Replicated,
22497            PlacementStrategy::Sharded,
22498        ] {
22499            let mut spec = three_member_spec();
22500            spec.placement.estrategia = estrategia;
22501            spec.placement.clusters = Vec::new();
22502            // Route the paired `:shard-key` spec-mutator through the typed
22503            // cross-slot invariant predicate
22504            // [`PlacementStrategy::requires_shard_key`] rather than the
22505            // [`gen_platform::IsVariant`]-derived
22506            // [`PlacementStrategy::is_sharded`] arm-identity predicate —
22507            // same discipline the sibling
22508            // `placement_strategy_variants_round_trip` and
22509            // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
22510            // fixture builders now read through.
22511            spec.placement.shard_key = estrategia
22512                .requires_shard_key()
22513                .then(|| "tenantId".to_string());
22514            let err = spec.validate().unwrap_err();
22515            match err {
22516                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
22517                    assert_eq!(
22518                        e,
22519                        spec.placement.estrategia(),
22520                        "PlacementWithoutClusters.estrategia must byte-equal \
22521                         Placement::estrategia() — the error carrier reads \
22522                         through the lifted accessor",
22523                    );
22524                }
22525                other => panic!(
22526                    "expected PlacementWithoutClusters, got {other:?} for \
22527                     estrategia={estrategia:?}"
22528                ),
22529            }
22530        }
22531
22532        // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
22533        // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
22534        // must byte-equal the accessor's return for both non-`Sharded`
22535        // strategies.
22536        for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
22537            let mut spec = three_member_spec();
22538            spec.placement.estrategia = estrategia;
22539            spec.placement.shard_key = Some("tenantId".into());
22540            let err = spec.validate().unwrap_err();
22541            match err {
22542                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
22543                    assert_eq!(
22544                        e,
22545                        spec.placement.estrategia(),
22546                        "ShardKeyOnNonSharded.estrategia must byte-equal \
22547                         Placement::estrategia() — the non-Sharded-arm \
22548                         refusal reads through the lifted accessor",
22549                    );
22550                }
22551                other => panic!(
22552                    "expected ShardKeyOnNonSharded, got {other:?} for \
22553                     estrategia={estrategia:?}"
22554                ),
22555            }
22556        }
22557    }
22558
22559    // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
22560    //
22561    // The [`Placement::clusters`] accessor lift is the second slice-return
22562    // (`&[T]`) accessor on any typed slot — sibling to the seed M2
22563    // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
22564    // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
22565    // below cover (1) the accessor's byte-equal projection against the raw
22566    // field access across the empty / singleton / cohort fixtures the
22567    // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
22568    // and the per-cluster validate loop fan between, and (2) the two-
22569    // consumer coherence of the paired pre-flight refusal probe and the
22570    // per-cluster validate loop routing through the accessor on both arms.
22571
22572    #[test]
22573    fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
22574        // The canonical per-`:placement` cluster-pool-scalar-shape pin:
22575        // [`Placement::clusters`] must return the `:placement :clusters`
22576        // typed `Vec<String>` verbatim as a `&[String]` slice-view over
22577        // the same backing buffer the raw `self.clusters.as_slice()`
22578        // field access borrows from, byte-equal across every
22579        // representative fixture in the accept-set — the empty slice
22580        // (the pre-validation sentinel every
22581        // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
22582        // the singleton slice (the minimal `SingleNode`-shape cohort),
22583        // and multi-entry cohorts (the peer `Replicated` / `Sharded`
22584        // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
22585        //
22586        // Pins against a future silent detour that returned
22587        // `&Vec<String>` (which would type-check but leak the storage-
22588        // side `Vec`'s grow/push/reserve surface no consumer of the
22589        // typed view reaches for), a fresh-allocated `Vec<String>` copy
22590        // (which would type-check via a coercion but silently break
22591        // every downstream caller that relied on the slice sharing the
22592        // backing buffer's identity), or an out-of-order or length-
22593        // drifted projection (which would silently split the paired
22594        // pre-flight `.is_empty()` refusal probe's input from the per-
22595        // cluster validate loop's traversal input).
22596        //
22597        // Peer of the sibling M2
22598        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
22599        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
22600        // `:supervisor` static-child-list axis, extended onto the M3
22601        // per-`:placement` distribution-target-list `Vec`-carry axis.
22602        let fixtures: Vec<Vec<String>> = vec![
22603            Vec::new(),
22604            vec!["rio".into()],
22605            vec!["rio".into(), "mar".into()],
22606            vec!["rio".into(), "mar".into(), "plo".into()],
22607        ];
22608        for clusters in fixtures {
22609            let p = Placement {
22610                clusters: clusters.clone(),
22611                ..Placement::default()
22612            };
22613            assert_eq!(
22614                p.clusters(),
22615                clusters.as_slice(),
22616                "Placement::clusters must return :placement :clusters \
22617                 verbatim (got {:?}, expected {:?})",
22618                p.clusters(),
22619                clusters.as_slice(),
22620            );
22621            assert_eq!(
22622                p.clusters(),
22623                p.clusters.as_slice(),
22624                "Placement::clusters accessor and .clusters.as_slice() \
22625                 field access must byte-equal — the accessor is the \
22626                 substrate-primitive typed dispatch every downstream \
22627                 cluster-pool consumer must route through",
22628            );
22629            assert_eq!(
22630                p.clusters().len(),
22631                p.clusters.len(),
22632                "Placement::clusters().len() must byte-equal \
22633                 self.clusters.len() — a length-drift would silently \
22634                 split the paired pre-flight `.is_empty()` refusal \
22635                 probe input from the per-cluster validate loop's \
22636                 traversal input",
22637            );
22638        }
22639    }
22640
22641    #[test]
22642    fn validate_placement_reads_through_lifted_clusters_accessor() {
22643        // Two-consumer coherence pin: the
22644        // [`AplicacaoSpec::validate_placement`] pre-flight
22645        // `self.placement.clusters().is_empty()` refusal probe (which
22646        // must trip [`AplicacaoError::PlacementWithoutClusters`] when
22647        // the accessor projects the empty slice) and the per-cluster
22648        // validate loop's `for c in self.placement.clusters()`
22649        // traversal (which must reach every entry in the same order
22650        // the accessor projects, so both the per-entry value-shape
22651        // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
22652        // and the duplicate-detection HashSet insert that trips
22653        // [`AplicacaoError::PlacementClusterDuplicate`] key off the
22654        // accessor's projection) must both key off the lifted
22655        // accessor, so any future rebrand on the typed slot's reader
22656        // shape lands at exactly one place. Pins the two-site
22657        // coherence by exercising each production consumer end-to-end:
22658        // (1) the `PlacementWithoutClusters` refusal under the empty
22659        // slice, (2) the `PlacementClusterInvalid` refusal fires on
22660        // the second entry of a two-cluster cohort whose head is
22661        // valid but tail is not (which requires the loop to reach the
22662        // second entry through the accessor), and (3) the
22663        // `PlacementClusterDuplicate` refusal fires on the second
22664        // entry of a two-cluster cohort that shares a name (which
22665        // requires the loop to reach both entries — a first-entry-only
22666        // projection would silently pass since the dedup HashSet has
22667        // room for the first insert).
22668        //
22669        // Peer of the sibling M2
22670        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
22671        // (bc92bce) coherence pin on the per-`:supervisor` static-
22672        // child-list axis, extended onto the M3 per-`:placement`
22673        // distribution-target-list `Vec`-carry axis.
22674
22675        // (1) Pre-flight `.is_empty()` probe: the empty slice must
22676        // trip `PlacementWithoutClusters`.
22677        let mut spec = three_member_spec();
22678        spec.placement.clusters = Vec::new();
22679        match spec.validate().unwrap_err() {
22680            AplicacaoError::PlacementWithoutClusters { .. } => {}
22681            other => panic!("expected PlacementWithoutClusters, got {other:?}"),
22682        }
22683        assert!(
22684            spec.placement.clusters().is_empty(),
22685            "the pre-flight refusal input must be the empty slice per \
22686             the accessor's projection",
22687        );
22688
22689        // (2) Per-cluster validate loop: a two-cluster cohort with an
22690        // invalid tail entry must trip `PlacementClusterInvalid` on
22691        // the tail — the loop must reach the second entry through
22692        // the accessor.
22693        let mut spec = three_member_spec();
22694        spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
22695        match spec.validate().unwrap_err() {
22696            AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
22697                assert_eq!(
22698                    cluster, "BAD_CLUSTER",
22699                    "PlacementClusterInvalid.cluster must carry the \
22700                     tail entry the loop reached through the accessor",
22701                );
22702            }
22703            other => panic!("expected PlacementClusterInvalid, got {other:?}"),
22704        }
22705        assert_eq!(
22706            spec.placement.clusters().len(),
22707            2,
22708            "the per-cluster validate loop's traversal input must be \
22709             a two-element slice per the accessor's projection",
22710        );
22711
22712        // (3) Per-cluster validate loop: a two-cluster cohort that
22713        // shares a name must trip `PlacementClusterDuplicate` on the
22714        // second entry — the loop must reach both entries through the
22715        // accessor for the dedup HashSet's second insert to collide.
22716        let mut spec = three_member_spec();
22717        spec.placement.clusters = vec!["rio".into(), "rio".into()];
22718        match spec.validate().unwrap_err() {
22719            AplicacaoError::PlacementClusterDuplicate { cluster } => {
22720                assert_eq!(
22721                    cluster, "rio",
22722                    "PlacementClusterDuplicate.cluster must carry the \
22723                     shared cluster name verbatim",
22724                );
22725            }
22726            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
22727        }
22728        assert_eq!(
22729            spec.placement.clusters().len(),
22730            2,
22731            "the per-cluster validate loop's traversal input must be \
22732             a two-element slice per the accessor's projection",
22733        );
22734    }
22735
22736    #[test]
22737    fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
22738        // The canonical per-`:membros` member-list-slice-shape pin:
22739        // [`AplicacaoSpec::membros`] must return the `:membros` typed
22740        // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
22741        // same backing buffer the raw `self.membros.as_slice()` field
22742        // access borrows from, byte-equal across every representative
22743        // fixture in the accept-set — the empty slice (the pre-
22744        // validation sentinel every [`AplicacaoError::NoMembros`]
22745        // refusal keys off), the singleton slice (the minimal one-
22746        // Servico Aplicacao shape), and multi-entry cohorts (the peer
22747        // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
22748        // load-bearing identity of the application graph).
22749        //
22750        // Pins against a future silent detour that returned
22751        // `&Vec<Membro>` (which would type-check but leak the storage-
22752        // side `Vec`'s grow/push/reserve surface no consumer of the
22753        // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
22754        // (which would type-check via a coercion but silently break
22755        // every downstream caller that relied on the slice sharing the
22756        // backing buffer's identity), or an out-of-order or length-
22757        // drifted projection (which would silently split the paired
22758        // `HashSet<&str>` name-set seed's collect input from the
22759        // pre-flight `.is_empty()` refusal probe's input from the per-
22760        // member validate loop's traversal input from the
22761        // programs.yaml emitter's per-entry fan-out loop's input from
22762        // the `feira app graph` per-member print traversal's input).
22763        //
22764        // Peer of the sibling M2
22765        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
22766        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
22767        // `:supervisor` static-child-list axis and the sibling M3
22768        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
22769        // (a6e18d7) `&[String]` byte-equal pin on the per-
22770        // `:placement` distribution-target-list axis — extends the
22771        // slice-return-accessor byte-equal-projection discipline onto
22772        // the outermost M3 mesh-slot type's per-Aplicacao member-list
22773        // `Vec`-carry axis.
22774        let fixtures: Vec<Vec<Membro>> = vec![
22775            Vec::new(),
22776            vec![membro("catalog", "^0.1")],
22777            vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
22778            vec![
22779                membro("catalog", "^0.1"),
22780                membro("cart", "^0.1"),
22781                membro("payment", "^0.2"),
22782            ],
22783        ];
22784        for membros in fixtures {
22785            let s = AplicacaoSpec {
22786                membros: membros.clone(),
22787                contratos: Vec::new(),
22788                politicas: MeshPolicy::default(),
22789                placement: Placement::default(),
22790                entrada: None,
22791            };
22792            assert_eq!(
22793                s.membros(),
22794                membros.as_slice(),
22795                "AplicacaoSpec::membros must return :membros verbatim \
22796                 (got {:?}, expected {:?})",
22797                s.membros(),
22798                membros.as_slice(),
22799            );
22800            assert_eq!(
22801                s.membros(),
22802                s.membros.as_slice(),
22803                "AplicacaoSpec::membros accessor and .membros.as_slice() \
22804                 field access must byte-equal — the accessor is the \
22805                 substrate-primitive typed dispatch every downstream \
22806                 member-list consumer must route through",
22807            );
22808            assert_eq!(
22809                s.membros().len(),
22810                s.membros.len(),
22811                "AplicacaoSpec::membros().len() must byte-equal \
22812                 self.membros.len() — a length-drift would silently \
22813                 split the paired `HashSet<&str>` name-set seed's \
22814                 collect input from the pre-flight `.is_empty()` \
22815                 refusal probe input from the per-member validate \
22816                 loop's traversal input",
22817            );
22818        }
22819    }
22820
22821    #[test]
22822    fn validate_reads_through_lifted_membros_accessor() {
22823        // Three-consumer coherence pin: the
22824        // [`AplicacaoSpec::validate_membros`] pre-flight
22825        // `self.membros().is_empty()` refusal probe (which must trip
22826        // [`AplicacaoError::NoMembros`] when the accessor projects the
22827        // empty slice), the same method's per-member validate loop's
22828        // `for m in self.membros()` traversal (which must reach every
22829        // entry in the same order the accessor projects, so both the
22830        // per-entry empty-`:caixa` gate that trips
22831        // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
22832        // detection `insert_first_seen` that trips
22833        // [`AplicacaoError::MembroDuplicate`] key off the accessor's
22834        // projection), and the peer [`AplicacaoSpec::validate`]'s
22835        // `HashSet<&str>` name-set seed's
22836        // `self.membros().iter().map(Membro::nome).collect()` collect
22837        // input (which every `:contratos` `:de` / `:para` membership
22838        // lookup rejects an unknown name against) must all three key
22839        // off the lifted accessor, so any future rebrand on the typed
22840        // slot's reader shape lands at exactly one place. Pins the
22841        // three-site coherence by exercising each production consumer
22842        // end-to-end: (1) the `NoMembros` refusal under the empty
22843        // slice, (2) the `MembroCaixaEmpty` refusal fires on the
22844        // second entry of a two-member cohort whose head is valid but
22845        // tail has an empty `:caixa` (which requires the loop to
22846        // reach the second entry through the accessor), and (3) the
22847        // `MembroDuplicate` refusal fires on the second entry of a
22848        // two-member cohort that shares a `:caixa` name (which
22849        // requires the loop to reach both entries through the
22850        // accessor for the dedup HashSet's second insert to collide).
22851        //
22852        // Peer of the sibling M2
22853        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
22854        // (bc92bce) coherence pin on the per-`:supervisor` static-
22855        // child-list axis and the sibling M3
22856        // `validate_placement_reads_through_lifted_clusters_accessor`
22857        // (a6e18d7) coherence pin on the per-`:placement` distribution-
22858        // target-list axis — extends the slice-return-accessor
22859        // multi-consumer coherence discipline onto the outermost M3
22860        // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
22861
22862        // (1) Pre-flight `.is_empty()` probe: the empty slice must
22863        // trip `NoMembros`.
22864        let mut spec = three_member_spec();
22865        spec.membros = Vec::new();
22866        assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
22867        assert!(
22868            spec.membros().is_empty(),
22869            "the pre-flight refusal input must be the empty slice per \
22870             the accessor's projection",
22871        );
22872
22873        // (2) Per-member validate loop: a two-member cohort with an
22874        // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
22875        // the tail — the loop must reach the second entry through
22876        // the accessor.
22877        let mut spec = three_member_spec();
22878        spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
22879        assert_eq!(
22880            spec.validate().unwrap_err(),
22881            AplicacaoError::MembroCaixaEmpty,
22882        );
22883        assert_eq!(
22884            spec.membros().len(),
22885            2,
22886            "the per-member validate loop's traversal input must be \
22887             a two-element slice per the accessor's projection",
22888        );
22889
22890        // (3) Per-member validate loop: a two-member cohort that
22891        // shares a `:caixa` name must trip `MembroDuplicate` on the
22892        // second entry — the loop must reach both entries through the
22893        // accessor for the dedup HashSet's second insert to collide.
22894        let mut spec = three_member_spec();
22895        spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
22896        match spec.validate().unwrap_err() {
22897            AplicacaoError::MembroDuplicate { caixa } => {
22898                assert_eq!(
22899                    caixa, "catalog",
22900                    "MembroDuplicate.caixa must carry the shared \
22901                     member name verbatim",
22902                );
22903            }
22904            other => panic!("expected MembroDuplicate, got {other:?}"),
22905        }
22906        assert_eq!(
22907            spec.membros().len(),
22908            2,
22909            "the per-member validate loop's traversal input must be \
22910             a two-element slice per the accessor's projection",
22911        );
22912    }
22913
22914    #[test]
22915    fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
22916        // The canonical per-`:contratos` contract-list-slice-shape pin:
22917        // [`AplicacaoSpec::contratos`] must return the `:contratos`
22918        // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
22919        // slice-view over the same backing buffer the raw
22920        // `self.contratos.as_slice()` field access borrows from, byte-
22921        // equal across every representative fixture in the accept-set —
22922        // the empty slice (the pre-validation "internal-only mesh" shape
22923        // an Aplicacao whose members exchange no typed edges renders
22924        // through), the singleton slice (the minimal one-edge Aplicacao
22925        // shape), and multi-entry cohorts (the peer multi-edge shapes
22926        // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
22927        // of the application graph).
22928        //
22929        // Pins against a future silent detour that returned
22930        // `&Vec<WitContract>` (which would type-check but leak the
22931        // storage-side `Vec`'s grow/push/reserve surface no consumer of
22932        // the typed view reaches for), a fresh-allocated
22933        // `Vec<WitContract>` copy (which would type-check via a coercion
22934        // but silently break every downstream caller that relied on the
22935        // slice sharing the backing buffer's identity), or an out-of-
22936        // order or length-drifted projection (which would silently split
22937        // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
22938        // seed's traversal input from the `detect_sync_cycles` per-edge
22939        // adjacency-list seed's traversal input from the
22940        // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
22941        // BTreeMap grouping loop's traversal input from the
22942        // `feira app graph` per-contract print traversal's input).
22943        //
22944        // Peer of the immediately-adjacent sibling M3
22945        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
22946        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
22947        // node-list axis, the sibling M3
22948        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
22949        // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
22950        // distribution-target-list axis, and the sibling M2
22951        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
22952        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
22953        // `:supervisor` static-child-list axis — extends the slice-
22954        // return-accessor byte-equal-projection discipline onto the
22955        // outermost M3 mesh-slot type's per-Aplicacao contract-list
22956        // `Vec`-carry axis, closing the last unlifted per-
22957        // `AplicacaoSpec` `Vec`-carry axis.
22958        let fixtures: Vec<Vec<WitContract>> = vec![
22959            Vec::new(),
22960            vec![contract_http("cart", "catalog", "/products/:id")],
22961            vec![
22962                contract_http("cart", "catalog", "/products/:id"),
22963                contract_http("cart", "payment", "/charge"),
22964            ],
22965            vec![
22966                contract_http("cart", "catalog", "/products/:id"),
22967                contract_http("cart", "payment", "/charge"),
22968                contract_http("payment", "catalog", "/audit"),
22969            ],
22970        ];
22971        for contratos in fixtures {
22972            let s = AplicacaoSpec {
22973                membros: vec![
22974                    membro("catalog", "^0.1"),
22975                    membro("cart", "^0.1"),
22976                    membro("payment", "^0.2"),
22977                ],
22978                contratos: contratos.clone(),
22979                politicas: MeshPolicy::default(),
22980                placement: Placement::default(),
22981                entrada: None,
22982            };
22983            assert_eq!(
22984                s.contratos(),
22985                contratos.as_slice(),
22986                "AplicacaoSpec::contratos must return :contratos verbatim \
22987                 (got {:?}, expected {:?})",
22988                s.contratos(),
22989                contratos.as_slice(),
22990            );
22991            assert_eq!(
22992                s.contratos(),
22993                s.contratos.as_slice(),
22994                "AplicacaoSpec::contratos accessor and \
22995                 .contratos.as_slice() field access must byte-equal — \
22996                 the accessor is the substrate-primitive typed dispatch \
22997                 every downstream contract-list consumer must route \
22998                 through",
22999            );
23000            assert_eq!(
23001                s.contratos().len(),
23002                s.contratos.len(),
23003                "AplicacaoSpec::contratos().len() must byte-equal \
23004                 self.contratos.len() — a length-drift would silently \
23005                 split the paired per-edge validate-loop's traversal \
23006                 input from the sync-cycle adjacency-list seed's \
23007                 traversal input from the cilium_network_policies \
23008                 per-`(:de, :para)` BTreeMap grouping loop's traversal \
23009                 input from the `feira app graph` per-contract print \
23010                 traversal's input",
23011            );
23012        }
23013    }
23014
23015    #[test]
23016    fn validate_reads_through_lifted_contratos_accessor() {
23017        // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
23018        // per-`:contratos` validate-loop's `for c in self.contratos()`
23019        // traversal (which must reach every entry in the same order the
23020        // accessor projects, so both the per-entry
23021        // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
23022        // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
23023        // dedup `HashSet` insert key off the accessor's projection),
23024        // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
23025        // `for c in self.contratos()` adjacency-list seed (which drives
23026        // the sync-subgraph deadlock-detection gate via
23027        // [`AplicacaoError::SyncCycle`]), and the peer
23028        // [`caixa_mesh::cilium_network_policies`]'s
23029        // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
23030        // grouping loop (which drives the per-CNP fan-out) must all
23031        // three key off the lifted accessor, so any future rebrand on
23032        // the typed slot's reader shape lands at exactly one place. Pins
23033        // the three-site coherence by exercising the two caixa-core
23034        // production consumers end-to-end: (1) the empty-`:contratos`
23035        // slice must validate without a per-edge diagnostic (the
23036        // per-edge loop is a no-op under the empty projection), (2) the
23037        // `ContratoMemberMissing` refusal fires on the second entry of a
23038        // two-edge cohort whose head references a valid member but tail
23039        // references a phantom name (which requires the loop to reach
23040        // the second entry through the accessor), and (3) the
23041        // `SyncCycle` refusal fires on a self-referential two-edge
23042        // cohort through the sync-cycle detector's peer projection
23043        // (which requires the detector to iterate the accessor's
23044        // projection to add the back-edge to its adjacency list).
23045        //
23046        // Peer of the sibling M3
23047        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
23048        // three-consumer coherence pin on the per-`:membros` node-list
23049        // axis and the sibling M3
23050        // `validate_placement_reads_through_lifted_clusters_accessor`
23051        // (a6e18d7) coherence pin on the per-`:placement` distribution-
23052        // target-list axis — extends the slice-return-accessor multi-
23053        // consumer coherence discipline onto the outermost M3 mesh-slot
23054        // type's per-Aplicacao contract-list `Vec`-carry axis.
23055
23056        // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
23057        // and no per-edge diagnostic surfaces. Validate succeeds on
23058        // the well-formed `:membros` head.
23059        let mut spec = three_member_spec();
23060        spec.contratos = Vec::new();
23061        assert!(
23062            spec.validate().is_ok(),
23063            "empty :contratos must validate — the per-edge loop is a \
23064             no-op under the accessor's empty projection",
23065        );
23066        assert!(
23067            spec.contratos().is_empty(),
23068            "the per-edge validate loop's traversal input must be the \
23069             empty slice per the accessor's projection",
23070        );
23071
23072        // (2) Per-edge validate loop: a two-edge cohort whose tail
23073        // references a phantom `:para` member must trip
23074        // `ContratoMemberMissing` on the tail — the loop must reach
23075        // the second entry through the accessor for the membership
23076        // lookup to fail on the phantom name.
23077        let mut spec = three_member_spec();
23078        spec.contratos = vec![
23079            contract_http("cart", "catalog", "/products/:id"),
23080            contract_http("cart", "phantom", "/x"),
23081        ];
23082        let err = spec.validate().unwrap_err();
23083        assert!(
23084            matches!(
23085                err,
23086                AplicacaoError::ContratoMemberMissing { ref caixa }
23087                    if caixa == "phantom"
23088            ),
23089            "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
23090        );
23091        assert_eq!(
23092            spec.contratos().len(),
23093            2,
23094            "the per-edge validate loop's traversal input must be \
23095             a two-element slice per the accessor's projection",
23096        );
23097
23098        // (3) Sync-cycle detector: a two-edge synchronous cohort
23099        // whose second edge closes the sync-subgraph back onto the
23100        // first must trip [`AplicacaoError::ContratoCycle`] — the
23101        // detector must iterate the accessor's projection to add
23102        // both edges to its adjacency list, so a length-drift on
23103        // the accessor's projection would silently disagree with
23104        // the sync-cycle detector on which edge closes the loop.
23105        // Peer projection to the `validate` per-edge loop above:
23106        // the sync-cycle detector routes through the same lifted
23107        // accessor, so a rebrand of the reader shape lands at one
23108        // place. Uses a two-edge cohort (cart → catalog → cart)
23109        // because the per-edge `ContratoSelfLoop` gate fires before
23110        // the sync-cycle detector on a single self-referential edge
23111        // (`cart → cart`) — the cycle-detector's input must be a
23112        // multi-edge cohort for its per-edge traversal input to be
23113        // observably wider than the per-edge validate loop's input.
23114        let mut spec = three_member_spec();
23115        spec.contratos = vec![
23116            contract_http("cart", "catalog", "/products/:id"),
23117            contract_http("catalog", "cart", "/callback"),
23118        ];
23119        let err = spec.validate().unwrap_err();
23120        assert!(
23121            matches!(err, AplicacaoError::ContratoCycle { .. }),
23122            "expected ContratoCycle from the sync-cycle detector on a \
23123             two-edge back-edge cohort, got {err:?}",
23124        );
23125        assert_eq!(
23126            spec.contratos().len(),
23127            2,
23128            "the sync-cycle detector's traversal input must be a \
23129             two-element slice per the accessor's projection",
23130        );
23131    }
23132
23133    #[test]
23134    fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
23135        // The canonical per-`:politicas` outer-composite-reference-shape
23136        // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
23137        // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
23138        // the same backing storage the raw `&self.politicas` field
23139        // access borrows from, byte-equal across every representative
23140        // fixture in the accept-set — the default `MeshPolicy` (the
23141        // author-empty "no policy on any axis" shape whose
23142        // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
23143        // shapes carrying one axis at a time
23144        // (`{mtls_required, timeout, retries, circuit_breaker,
23145        // rate_limit}` — the minimal five-axis fan-out over the
23146        // per-axis lifted accessor family every downstream mesh-artifact
23147        // emitter dispatches on), and the multi-axis composite (the
23148        // canonical `three_member_spec` fixture's `{timeout, retries,
23149        // mtls_required}` triple — the load-bearing shape every
23150        // Aplicacao-scoped fixture in this suite constructs).
23151        //
23152        // Pins against a future silent detour that returned a fresh-
23153        // cloned `MeshPolicy` copy (which would type-check via a `Clone`
23154        // impl but silently break every downstream caller that relied
23155        // on the reference sharing the composite's backing identity), a
23156        // reference to an operator-resolved overlay (the future
23157        // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
23158        // acknowledges — its resolution must land at exactly this
23159        // accessor body, not silently divert the raw slot away from a
23160        // second consumer), or an axis-shuffled projection (a future
23161        // detour that swapped `timeout` and `retries` through the
23162        // accessor would silently split the paired `validate_politicas`
23163        // per-axis bracket-dispatch's traversal input from the peer
23164        // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
23165        // emitter's fan-out input from the peer
23166        // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
23167        // overlay emitter's fan-out input).
23168        //
23169        // Peer of the sibling M3
23170        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
23171        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
23172        // node-list `Vec`-carry axis and the sibling M3
23173        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
23174        // (0dcc926) `&[WitContract]` byte-equal pin on the per-
23175        // `:contratos` edge-list `Vec`-carry axis — extends the outer-
23176        // accessor byte-equal-projection discipline onto the outermost
23177        // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
23178        // reference axis, the first `&Composite`-return accessor on the
23179        // outer [`AplicacaoSpec`] type.
23180        let fixtures: Vec<MeshPolicy> = vec![
23181            MeshPolicy::default(),
23182            MeshPolicy {
23183                mtls_required: Some(true),
23184                ..MeshPolicy::default()
23185            },
23186            MeshPolicy {
23187                mtls_required: Some(false),
23188                ..MeshPolicy::default()
23189            },
23190            MeshPolicy {
23191                timeout: Some(Duration::from_secs(30)),
23192                ..MeshPolicy::default()
23193            },
23194            MeshPolicy {
23195                retries: Some(3),
23196                ..MeshPolicy::default()
23197            },
23198            MeshPolicy {
23199                circuit_breaker: Some(CircuitBreaker {
23200                    max_failures: 5,
23201                    window: Duration::from_secs(30),
23202                }),
23203                ..MeshPolicy::default()
23204            },
23205            MeshPolicy {
23206                rate_limit: Some(RateLimit {
23207                    rate: 100,
23208                    window: Duration::from_secs(1),
23209                }),
23210                ..MeshPolicy::default()
23211            },
23212            MeshPolicy {
23213                timeout: Some(Duration::from_secs(30)),
23214                retries: Some(3),
23215                mtls_required: Some(true),
23216                ..MeshPolicy::default()
23217            },
23218        ];
23219        for politicas in fixtures {
23220            let s = AplicacaoSpec {
23221                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
23222                contratos: Vec::new(),
23223                politicas: politicas.clone(),
23224                placement: Placement::default(),
23225                entrada: None,
23226            };
23227            assert_eq!(
23228                *s.politicas(),
23229                politicas,
23230                "AplicacaoSpec::politicas must return :politicas verbatim \
23231                 (got {:?}, expected {:?})",
23232                s.politicas(),
23233                politicas,
23234            );
23235            assert!(
23236                std::ptr::eq(s.politicas(), &s.politicas),
23237                "AplicacaoSpec::politicas accessor and &self.politicas \
23238                 field access must borrow the same backing storage — \
23239                 the accessor is the substrate-primitive typed dispatch \
23240                 every downstream mesh-policy composite consumer must \
23241                 route through, and a reference-identity split would \
23242                 silently break every consumer that relied on the \
23243                 borrow sharing the composite's storage",
23244            );
23245            assert_eq!(
23246                s.politicas().is_empty(),
23247                s.politicas.is_empty(),
23248                "AplicacaoSpec::politicas().is_empty() must byte-equal \
23249                 self.politicas.is_empty() — an emptiness-drift would \
23250                 silently split the paired `validate_politicas` \
23251                 per-axis bracket-dispatch's seed from the peer \
23252                 caixa-mesh CNP mTLS-overlay emitter's key from the \
23253                 peer caixa-mesh HTTPRoute timeout+retry overlay \
23254                 emitter's key",
23255            );
23256        }
23257    }
23258
23259    #[test]
23260    fn validate_politicas_reads_through_lifted_politicas_accessor() {
23261        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
23262        // per-axis bracket-dispatch seed (`let p = self.politicas();`,
23263        // followed by the per-axis fan-out `p.timeout()` /
23264        // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
23265        // the lifted axis-level accessor family) must key off the
23266        // lifted outer accessor, so any future rebrand on the typed
23267        // slot's outer-composite reader shape lands at exactly one
23268        // place. Pins the multi-axis coherence by exercising each
23269        // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
23270        // a `Some(Duration::ZERO)` timeout under the outer accessor's
23271        // reference projection, (2) `PolicyRetriesZero` fires on a
23272        // `Some(0)` retries under the same projection, and (3) an
23273        // empty [`MeshPolicy::default`] passes `validate_politicas` —
23274        // the outer accessor's reference-projection reaches every
23275        // per-axis branch without silently short-circuiting any.
23276        //
23277        // Peer of the sibling M3
23278        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
23279        // three-consumer coherence pin on the per-`:membros` node-list
23280        // axis and the sibling M3
23281        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
23282        // three-consumer coherence pin on the per-`:contratos`
23283        // edge-list axis — extends the multi-consumer coherence
23284        // discipline onto the outermost M3 mesh-slot type's per-
23285        // Aplicacao mesh-policy composite-reference axis, the first
23286        // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
23287        // type.
23288
23289        // (1) `PolicyTimeoutZero` refusal under the outer accessor's
23290        // reference projection: a `Some(Duration::ZERO)` timeout must
23291        // trip the zero-floor gate. The bracket-dispatch's first arm
23292        // reads `p.timeout()` on the reference returned by the outer
23293        // accessor.
23294        let mut spec = three_member_spec();
23295        spec.politicas.timeout = Some(Duration::ZERO);
23296        spec.politicas.retries = None;
23297        spec.politicas.circuit_breaker = None;
23298        spec.politicas.rate_limit = None;
23299        assert_eq!(
23300            spec.validate().unwrap_err(),
23301            AplicacaoError::PolicyTimeoutZero,
23302        );
23303        assert!(
23304            std::ptr::eq(spec.politicas(), &spec.politicas),
23305            "the `validate_politicas` per-axis bracket-dispatch's \
23306             traversal input must be the same backing composite the \
23307             accessor's reference projection borrows from",
23308        );
23309
23310        // (2) `PolicyRetriesZero` refusal under the outer accessor's
23311        // reference projection: a `Some(0)` retries must trip the
23312        // zero-floor gate. The bracket-dispatch's second arm reads
23313        // `p.retries()` on the reference returned by the outer accessor.
23314        let mut spec = three_member_spec();
23315        spec.politicas.timeout = None;
23316        spec.politicas.retries = Some(0);
23317        spec.politicas.circuit_breaker = None;
23318        spec.politicas.rate_limit = None;
23319        assert_eq!(
23320            spec.validate().unwrap_err(),
23321            AplicacaoError::PolicyRetriesZero,
23322        );
23323
23324        // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
23325        // — every per-axis arm short-circuits on `None`, so the outer
23326        // accessor's reference projection reaches the fall-through
23327        // `Ok(())` without any per-axis refusal firing.
23328        let mut spec = three_member_spec();
23329        spec.politicas = MeshPolicy::default();
23330        assert!(
23331            spec.validate().is_ok(),
23332            "an empty `MeshPolicy` must pass `validate_politicas` — \
23333             every per-axis arm short-circuits on `None` under the \
23334             outer accessor's reference projection",
23335        );
23336        assert!(
23337            spec.politicas().is_empty(),
23338            "the outer accessor's reference projection must be the \
23339             empty composite per the `MeshPolicy::default()` fixture",
23340        );
23341    }
23342
23343    #[test]
23344    #[allow(clippy::too_many_lines)]
23345    fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
23346        // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
23347        // per-axis bracket-dispatch's `:timeout` and `:retries` arms
23348        // must both key off the lifted axis-level accessors
23349        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
23350        // the peer `:circuit-breaker` / `:rate-limit` arms already
23351        // routing through [`MeshPolicy::circuit_breaker`] /
23352        // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
23353        // per axis on the substrate primitive" shape at the fan-out
23354        // (four axes, four accessors, no raw-field-access site
23355        // anywhere on the bracket-dispatch). Pins the per-axis
23356        // coherence at the accept-set boundaries the bracket carves:
23357        //   1. accessor byte-equal to raw field on every representative
23358        //      accept-set value (`None`, sub-cap, at-cap, past-cap
23359        //      sentinel) — a future accessor drift that no longer
23360        //      shipped the raw slot verbatim would surface here,
23361        //   2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
23362        //      routed through the accessor's projection, proving the
23363        //      first arm reads through the accessor rather than a
23364        //      silent-detour peer-axis field access,
23365        //   3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
23366        //      through the accessor's projection, proving the second
23367        //      arm reads through the accessor,
23368        //   4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
23369        //      passes validate under the accessor projection (paired
23370        //      with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
23371        //      sibling axis), pinning the upper-boundary accept-arm
23372        //      also routes through the accessor.
23373        //
23374        // Peer of the sibling M3
23375        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
23376        // outer-composite-reference coherence pin (which asserts the
23377        // `let p = self.politicas()` seed); extends the discipline onto
23378        // the per-axis fan-out layer that consumes the seed's
23379        // reference. Same shape as
23380        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
23381        // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
23382        // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
23383        // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
23384
23385        // (1) Accessor byte-equal to raw field on the `:timeout` axis
23386        // across the accept-set boundaries the bracket dispatch's
23387        // three-arm gate carves out
23388        // ([`crate::render::require_positive_canonical_bounded_duration`]
23389        // — zero-floor + canonical-form + upper-cap).
23390        for timeout in [
23391            None,
23392            Some(Duration::ZERO),
23393            Some(Duration::from_millis(1)),
23394            Some(POLICY_TIMEOUT_MAX),
23395        ] {
23396            let p = MeshPolicy {
23397                timeout,
23398                ..MeshPolicy::default()
23399            };
23400            assert_eq!(
23401                p.timeout(),
23402                p.timeout,
23403                "MeshPolicy::timeout accessor must byte-equal the raw \
23404                 .timeout field across every accept-set boundary the \
23405                 validate_politicas :timeout arm carves out — a drift \
23406                 here would silently split the validate bracket's arm \
23407                 from the peer caixa-mesh HTTPRoute timeout-overlay \
23408                 emitter's read",
23409            );
23410        }
23411
23412        // (2) Accessor byte-equal to raw field on the `:retries` axis
23413        // across the accept-set boundaries the bracket dispatch's
23414        // two-arm gate carves out
23415        // ([`crate::render::require_positive_bounded_u32`] — zero-floor
23416        // + upper-cap).
23417        for retries in [
23418            None,
23419            Some(0u32),
23420            Some(1u32),
23421            Some(POLICY_RETRIES_MAX),
23422            Some(POLICY_RETRIES_MAX + 1),
23423            Some(u32::MAX),
23424        ] {
23425            let p = MeshPolicy {
23426                retries,
23427                ..MeshPolicy::default()
23428            };
23429            assert_eq!(
23430                p.retries(),
23431                p.retries,
23432                "MeshPolicy::retries accessor must byte-equal the raw \
23433                 .retries field across every accept-set boundary the \
23434                 validate_politicas :retries arm carves out — a drift \
23435                 here would silently split the validate bracket's arm \
23436                 from the peer caixa-mesh HTTPRoute retry-overlay \
23437                 emitter's read",
23438            );
23439        }
23440
23441        // (3) `PolicyTimeoutZero` fires on the accessor-projected
23442        // zero-floor boundary. A silent detour that no longer read
23443        // through `p.timeout()` (a peer-axis field read, an accidental
23444        // Option::and-then chain that collapsed the None arm to Some,
23445        // an accessor rebrand that clamped the return through the
23446        // upper cap) would fail to refuse here.
23447        let mut spec = three_member_spec();
23448        spec.politicas.timeout = Some(Duration::ZERO);
23449        spec.politicas.retries = None;
23450        spec.politicas.circuit_breaker = None;
23451        spec.politicas.rate_limit = None;
23452        assert_eq!(
23453            spec.politicas().timeout(),
23454            Some(Duration::ZERO),
23455            "the accessor projection must reflect the fixture's \
23456             `Some(Duration::ZERO)` :timeout verbatim",
23457        );
23458        assert_eq!(
23459            spec.validate().unwrap_err(),
23460            AplicacaoError::PolicyTimeoutZero,
23461            "the validate_politicas :timeout zero-floor arm must fire \
23462             through the lifted accessor's projection — a silent \
23463             detour to a peer-axis field would fail to refuse",
23464        );
23465
23466        // (4) `PolicyRetriesZero` fires on the accessor-projected
23467        // zero-floor boundary on the sibling `:retries` axis.
23468        let mut spec = three_member_spec();
23469        spec.politicas.timeout = None;
23470        spec.politicas.retries = Some(0);
23471        spec.politicas.circuit_breaker = None;
23472        spec.politicas.rate_limit = None;
23473        assert_eq!(
23474            spec.politicas().retries(),
23475            Some(0),
23476            "the accessor projection must reflect the fixture's \
23477             `Some(0)` :retries verbatim",
23478        );
23479        assert_eq!(
23480            spec.validate().unwrap_err(),
23481            AplicacaoError::PolicyRetriesZero,
23482            "the validate_politicas :retries zero-floor arm must fire \
23483             through the lifted accessor's projection — a silent \
23484             detour to a peer-axis field would fail to refuse",
23485        );
23486
23487        // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
23488        // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
23489        // must pass validate under the accessor projection — pins the
23490        // upper-boundary accept-arm also routes through the lifted
23491        // accessor (a drift that clamped or short-circuited at the
23492        // upper boundary would fail the whole-spec validate here).
23493        let mut spec = three_member_spec();
23494        spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
23495        spec.politicas.retries = Some(POLICY_RETRIES_MAX);
23496        spec.politicas.circuit_breaker = None;
23497        spec.politicas.rate_limit = None;
23498        assert_eq!(
23499            spec.politicas().timeout(),
23500            Some(POLICY_TIMEOUT_MAX),
23501            "the accessor projection must reflect the fixture's \
23502             at-cap :timeout verbatim",
23503        );
23504        assert_eq!(
23505            spec.politicas().retries(),
23506            Some(POLICY_RETRIES_MAX),
23507            "the accessor projection must reflect the fixture's \
23508             at-cap :retries verbatim",
23509        );
23510        assert!(
23511            spec.validate().is_ok(),
23512            "at-cap :timeout + :retries must pass validate under the \
23513             accessor projection — the upper-boundary accept-arm on \
23514             both axes routes through the lifted accessor",
23515        );
23516    }
23517
23518    #[test]
23519    fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
23520        // The canonical per-`:placement` outer-composite-reference-shape
23521        // pin: [`AplicacaoSpec::placement`] must return the `:placement`
23522        // typed `Placement` verbatim as a `&Placement` reference over the
23523        // same backing storage the raw `&self.placement` field access
23524        // borrows from, byte-equal across every representative fixture in
23525        // the accept-set — the default `Placement` (the substrate seed
23526        // shape whose [`PlacementStrategy::default`] evaluates to
23527        // `SingleNode` with an empty `:clusters` pool and both
23528        // optional-scalar axes `None`), and every canonical strategy /
23529        // cluster-pool / optional-scalar combination the
23530        // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
23531        // three [`PlacementStrategy`] variants — `SingleNode`,
23532        // `Replicated`, `Sharded` — cross-projected with a non-empty
23533        // `:clusters` pool and, on the `Sharded` arm, a non-empty
23534        // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
23535        // canonical `three_member_spec` `Replicated` fixture's
23536        // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
23537        //
23538        // Pins against a future silent detour that returned a fresh-
23539        // cloned `Placement` copy (which would type-check via a `Clone`
23540        // impl but silently break every downstream caller that relied on
23541        // the reference sharing the composite's backing identity), a
23542        // reference to an operator-resolved overlay (the future per-
23543        // cluster `:placement-overrides` slot MESH-COMPOSITION §V
23544        // acknowledges — its resolution must land at exactly this
23545        // accessor body, not silently divert the raw slot away from a
23546        // second consumer), or an axis-shuffled projection (a future
23547        // detour that swapped `clusters` and `affinity` through the
23548        // accessor would silently split the paired `validate_placement`
23549        // per-axis bracket-dispatch's traversal input from the peer
23550        // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
23551        // programs.yaml distribution-annotation emitter's fan-out input
23552        // from the peer `feira app graph` per-Aplicacao print line's
23553        // input).
23554        //
23555        // Peer of the sibling M3
23556        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
23557        // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
23558        // outer mesh-policy composite-reference axis, and of the sibling
23559        // slice-return `aplicacao_spec_membros_returns_membros_slice_
23560        // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
23561        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
23562        // across_permutations` (0dcc926) `&[WitContract]` pins — extends
23563        // the outer-accessor byte-equal-projection discipline onto the
23564        // outermost M3 mesh-slot type's per-Aplicacao distribution
23565        // composite-reference axis, the second `&Composite`-return
23566        // accessor on the outer [`AplicacaoSpec`] type.
23567        let fixtures: Vec<Placement> = vec![
23568            Placement::default(),
23569            Placement {
23570                estrategia: PlacementStrategy::SingleNode,
23571                clusters: vec!["rio".into()],
23572                affinity: None,
23573                shard_key: None,
23574            },
23575            Placement {
23576                estrategia: PlacementStrategy::Replicated,
23577                clusters: vec!["rio".into(), "mar".into()],
23578                affinity: None,
23579                shard_key: None,
23580            },
23581            Placement {
23582                estrategia: PlacementStrategy::Replicated,
23583                clusters: vec!["rio".into(), "mar".into()],
23584                affinity: Some("data-locality".into()),
23585                shard_key: None,
23586            },
23587            Placement {
23588                estrategia: PlacementStrategy::Sharded,
23589                clusters: vec!["rio".into(), "mar".into()],
23590                affinity: None,
23591                shard_key: Some("tenantId".into()),
23592            },
23593            Placement {
23594                estrategia: PlacementStrategy::Sharded,
23595                clusters: vec!["rio".into(), "mar".into(), "sol".into()],
23596                affinity: Some("low-latency".into()),
23597                shard_key: Some("metadata.tenantId".into()),
23598            },
23599        ];
23600        for placement in fixtures {
23601            let s = AplicacaoSpec {
23602                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
23603                contratos: Vec::new(),
23604                politicas: MeshPolicy::default(),
23605                placement: placement.clone(),
23606                entrada: None,
23607            };
23608            assert_eq!(
23609                *s.placement(),
23610                placement,
23611                "AplicacaoSpec::placement must return :placement verbatim \
23612                 (got {:?}, expected {:?})",
23613                s.placement(),
23614                placement,
23615            );
23616            assert!(
23617                std::ptr::eq(s.placement(), &s.placement),
23618                "AplicacaoSpec::placement accessor and &self.placement \
23619                 field access must borrow the same backing storage — the \
23620                 accessor is the substrate-primitive typed dispatch every \
23621                 downstream distribution-composite consumer must route \
23622                 through, and a reference-identity split would silently \
23623                 break every consumer that relied on the borrow sharing \
23624                 the composite's storage",
23625            );
23626            assert_eq!(
23627                s.placement().estrategia(),
23628                s.placement.estrategia,
23629                "AplicacaoSpec::placement().estrategia() must byte-equal \
23630                 self.placement.estrategia — a strategy-drift would \
23631                 silently split the paired `validate_placement` \
23632                 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
23633                 peer caixa-mesh programs.yaml `placement.estrategia` \
23634                 emitter's key from the peer `feira app graph` printer's \
23635                 strategy label",
23636            );
23637            assert_eq!(
23638                s.placement().clusters(),
23639                s.placement.clusters.as_slice(),
23640                "AplicacaoSpec::placement().clusters() must byte-equal \
23641                 self.placement.clusters — a cluster-pool drift would \
23642                 silently split the paired `validate_placement` \
23643                 pre-flight `.is_empty()` refusal probe's traversal from \
23644                 the peer caixa-mesh programs.yaml `placement.clusters` \
23645                 emitter's fan-out from the peer `feira app graph` \
23646                 printer's cluster list",
23647            );
23648        }
23649    }
23650
23651    #[test]
23652    fn validate_placement_reads_through_lifted_placement_accessor() {
23653        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
23654        // per-axis bracket-dispatch seed (`let p = self.placement();`,
23655        // followed by the per-axis fan-out `p.clusters()` /
23656        // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
23657        // lifted axis-level accessor family) must key off the lifted
23658        // outer accessor, so any future rebrand on the typed slot's
23659        // outer-composite reader shape lands at exactly one place. Pins
23660        // the multi-axis coherence by exercising each per-axis refusal
23661        // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
23662        // `:clusters` pool under the outer accessor's reference
23663        // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
23664        // strategy with a `None` `:shard-key` under the same projection,
23665        // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
23666        // with a `Some` `:shard-key` under the same projection, and
23667        // (4) the canonical `three_member_spec` `Replicated` fixture
23668        // passes `validate_placement` under the outer accessor's
23669        // reference projection — the accessor's reference-projection
23670        // reaches every per-axis branch (cluster-pool refusal, `Sharded`
23671        // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
23672        // without silently short-circuiting any.
23673        //
23674        // Peer of the sibling M3
23675        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
23676        // (534dc21) multi-axis coherence pin on the per-`:politicas`
23677        // outer mesh-policy composite-reference axis — extends the
23678        // multi-consumer coherence discipline onto the outermost M3
23679        // mesh-slot type's per-Aplicacao distribution composite-
23680        // reference axis, the second `&Composite`-return accessor on
23681        // the outer [`AplicacaoSpec`] type.
23682
23683        // (1) `PlacementWithoutClusters` refusal under the outer
23684        // accessor's reference projection: an empty `:clusters` pool
23685        // must trip the pre-flight refusal probe. The bracket-dispatch's
23686        // first arm reads `p.clusters()` on the reference returned by
23687        // the outer accessor.
23688        let mut spec = three_member_spec();
23689        spec.placement.clusters = Vec::new();
23690        assert_eq!(
23691            spec.validate().unwrap_err(),
23692            AplicacaoError::PlacementWithoutClusters {
23693                estrategia: PlacementStrategy::Replicated,
23694            },
23695        );
23696        assert!(
23697            std::ptr::eq(spec.placement(), &spec.placement),
23698            "the `validate_placement` per-axis bracket-dispatch's \
23699             traversal input must be the same backing composite the \
23700             accessor's reference projection borrows from",
23701        );
23702
23703        // (2) `ShardedWithoutKey` refusal under the outer accessor's
23704        // reference projection: a `Sharded` strategy with a `None`
23705        // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
23706        // The bracket-dispatch's third arm reads `p.estrategia()` for
23707        // the match scrutinee then `p.shard_key()` for the cascade
23708        // scrutinee, both on the reference returned by the outer
23709        // accessor.
23710        let mut spec = three_member_spec();
23711        spec.placement.estrategia = PlacementStrategy::Sharded;
23712        spec.placement.shard_key = None;
23713        assert_eq!(
23714            spec.validate().unwrap_err(),
23715            AplicacaoError::ShardedWithoutKey,
23716        );
23717
23718        // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
23719        // reference projection: a non-`Sharded` strategy with a `Some`
23720        // `:shard-key` must trip the declared-but-inert refusal. The
23721        // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
23722        // + `p.estrategia()` for the diagnostic on the reference
23723        // returned by the outer accessor.
23724        let mut spec = three_member_spec();
23725        spec.placement.estrategia = PlacementStrategy::Replicated;
23726        spec.placement.shard_key = Some("tenantId".into());
23727        assert_eq!(
23728            spec.validate().unwrap_err(),
23729            AplicacaoError::ShardKeyOnNonSharded {
23730                estrategia: PlacementStrategy::Replicated,
23731                shard_key: "tenantId".into(),
23732            },
23733        );
23734
23735        // (4) Canonical `three_member_spec` `Replicated` fixture passes
23736        // `validate_placement` — every per-axis arm reaches the fall-
23737        // through `Ok(())` without any per-axis refusal firing under the
23738        // outer accessor's reference projection.
23739        let spec = three_member_spec();
23740        assert!(
23741            spec.validate().is_ok(),
23742            "the canonical Replicated placement fixture must pass \
23743             `validate_placement` — every per-axis arm short-circuits on \
23744             valid input under the outer accessor's reference projection",
23745        );
23746        assert_eq!(
23747            spec.placement().estrategia(),
23748            PlacementStrategy::Replicated,
23749            "the outer accessor's reference projection must be the \
23750             canonical Replicated fixture's strategy",
23751        );
23752        assert_eq!(
23753            spec.placement().clusters(),
23754            &["rio", "mar"],
23755            "the outer accessor's reference projection must be the \
23756             canonical Replicated fixture's cluster pool",
23757        );
23758    }
23759
23760    #[test]
23761    fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
23762        // The canonical per-`:entrada` outer-composite-optional-
23763        // reference-shape pin: [`AplicacaoSpec::entrada`] must return
23764        // the `:entrada` typed `Option<Entrada>` verbatim as an
23765        // `Option<&Entrada>` reference over the same backing storage
23766        // the raw `self.entrada.as_ref()` field access borrows from,
23767        // byte-equal across every representative fixture in the
23768        // accept-set — the author-omitted `None` shape (the
23769        // "internal-only mesh" partition every downstream external-
23770        // gateway emitter treats as "emit nothing"), the minimal
23771        // singleton `:entrada` composite (host + destination + empty
23772        // paths + default port), the paths-carrying composite (the
23773        // canonical `three_member_spec` fixture's ["/api" "/health"]
23774        // path-list shape every HTTPRoute per-rule fan-out emitter
23775        // reads), and the non-default port composite (the canonical
23776        // custom-port shape the port-fallback resolver reads).
23777        //
23778        // Pins against a future silent detour that returned a fresh-
23779        // cloned `Entrada` copy (which would type-check via a `Clone`
23780        // impl but silently break every downstream caller that
23781        // relied on the reference sharing the composite's backing
23782        // identity), a reference to an operator-resolved overlay
23783        // (the future per-cluster `:entrada-overrides` slot the
23784        // MESH-COMPOSITION §V federation roadmap acknowledges — its
23785        // resolution must land at exactly this accessor body, not
23786        // silently divert the raw slot away from a second consumer),
23787        // a `None` → `Some(Entrada::default)` cluster-default
23788        // projection (which would collapse the load-bearing
23789        // "author-omitted `:entrada` ⇒ internal-only mesh" partition
23790        // the peer `gateway_routes` early-return + `feira app graph`
23791        // internal-only-mesh partition both read), or an axis-
23792        // shuffled projection (a future detour that swapped
23793        // `host` and `para` through the accessor would silently
23794        // split the paired `validate` per-`:entrada` shape-and-
23795        // membership gate's traversal input from the peer
23796        // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
23797        // fan-out input from the peer `feira app graph` external-
23798        // gateway summary line).
23799        //
23800        // Peer of the sibling M3
23801        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
23802        // (534dc21) `&MeshPolicy` byte-equal pin on the per-
23803        // `:politicas` outer mesh-policy composite-reference axis
23804        // and of the sibling M3
23805        // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
23806        // (9abb8f0) `&Placement` byte-equal pin on the per-
23807        // `:placement` outer distribution-composite composite-
23808        // reference axis — extends the outer-accessor byte-equal-
23809        // projection discipline onto the last unlifted outermost M3
23810        // mesh-slot type's per-Aplicacao external-gateway composite-
23811        // reference axis, the third and final `&Composite`-return
23812        // accessor on the outer [`AplicacaoSpec`] type.
23813        let fixtures: Vec<Option<Entrada>> = vec![
23814            None,
23815            Some(Entrada {
23816                host: "checkout.quero.cloud".into(),
23817                para: "cart".into(),
23818                paths: Vec::new(),
23819                port: DEFAULT_SERVICO_PORT,
23820            }),
23821            Some(Entrada {
23822                host: "checkout.quero.cloud".into(),
23823                para: "cart".into(),
23824                paths: vec!["/api".into(), "/health".into()],
23825                port: DEFAULT_SERVICO_PORT,
23826            }),
23827            Some(Entrada {
23828                host: "checkout.quero.cloud".into(),
23829                para: "cart".into(),
23830                paths: vec!["/api".into()],
23831                port: 9443,
23832            }),
23833        ];
23834        for entrada in fixtures {
23835            let s = AplicacaoSpec {
23836                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
23837                contratos: Vec::new(),
23838                politicas: MeshPolicy::default(),
23839                placement: Placement::default(),
23840                entrada: entrada.clone(),
23841            };
23842            assert_eq!(
23843                s.entrada(),
23844                entrada.as_ref(),
23845                "AplicacaoSpec::entrada must return :entrada verbatim \
23846                 (got {:?}, expected {:?})",
23847                s.entrada(),
23848                entrada.as_ref(),
23849            );
23850            match (s.entrada(), s.entrada.as_ref()) {
23851                (Some(a), Some(b)) => assert!(
23852                    std::ptr::eq(a, b),
23853                    "AplicacaoSpec::entrada accessor and \
23854                     self.entrada.as_ref() field access must borrow \
23855                     the same backing storage — the accessor is the \
23856                     substrate-primitive typed dispatch every \
23857                     downstream external-gateway composite consumer \
23858                     must route through, and a reference-identity \
23859                     split would silently break every consumer that \
23860                     relied on the borrow sharing the composite's \
23861                     storage",
23862                ),
23863                (None, None) => {}
23864                _ => panic!(
23865                    "AplicacaoSpec::entrada presence bit must byte-\
23866                     equal self.entrada.is_some() — a presence-bit \
23867                     drift would silently split the paired `validate` \
23868                     per-`:entrada` shape-and-membership gate's \
23869                     traversal head from the peer \
23870                     caixa-mesh gateway_routes early-return partition \
23871                     from the peer `feira app graph` internal-only-\
23872                     mesh partition",
23873                ),
23874            }
23875            assert_eq!(
23876                s.entrada().is_some(),
23877                s.entrada.is_some(),
23878                "AplicacaoSpec::entrada().is_some() must byte-equal \
23879                 self.entrada.is_some() — a presence-bit drift would \
23880                 silently split every downstream `Option<&Entrada>` \
23881                 consumer's partition on the internal-only-mesh arm",
23882            );
23883        }
23884    }
23885
23886    #[test]
23887    fn validate_reads_through_lifted_entrada_accessor() {
23888        // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
23889        // per-`:entrada` shape-and-membership gate (`if let Some(e) =
23890        // self.entrada() { … }`, followed by the per-axis fan-out
23891        // `validate_entrada_para(&e.para)` /
23892        // `EntradaMemberMissing` membership lookup /
23893        // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
23894        // per-`e.paths` `validate_entrada_path` traversal) must key
23895        // off the lifted outer accessor, so any future rebrand on
23896        // the typed slot's outer-composite reader shape lands at
23897        // exactly one place. Pins the multi-axis coherence by
23898        // exercising each per-axis refusal end-to-end: (1) the
23899        // author-omitted `None` shape short-circuits past every
23900        // per-`:entrada` refusal (the internal-only mesh partition
23901        // the accessor's `None` arm names), (2) `EntradaMemberMissing`
23902        // fires on a well-shaped but phantom `:para` under the outer
23903        // accessor's reference projection, and (3) the canonical
23904        // `three_member_spec` `:entrada` fixture passes `validate`
23905        // under the outer accessor's reference projection.
23906        //
23907        // Peer of the sibling M3
23908        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
23909        // (534dc21) multi-axis coherence pin on the per-`:politicas`
23910        // outer mesh-policy composite-reference axis and the sibling
23911        // M3
23912        // [`validate_placement_reads_through_lifted_placement_accessor`]
23913        // (9abb8f0) multi-axis coherence pin on the per-`:placement`
23914        // outer distribution-composite composite-reference axis —
23915        // extends the multi-consumer coherence discipline onto the
23916        // last unlifted outermost M3 mesh-slot type's per-Aplicacao
23917        // external-gateway composite-reference axis, the third and
23918        // final `&Composite`-return accessor on the outer
23919        // [`AplicacaoSpec`] type.
23920
23921        // (1) `None` :entrada — the internal-only-mesh partition
23922        // short-circuits past every per-`:entrada` refusal. The outer
23923        // accessor's reference projection reaches the fall-through
23924        // `Ok(())` on the `None` arm without any per-axis refusal
23925        // firing.
23926        let mut spec = three_member_spec();
23927        spec.entrada = None;
23928        assert!(
23929            spec.validate().is_ok(),
23930            "an author-omitted `:entrada` must pass `validate` — the \
23931             internal-only-mesh partition short-circuits past every \
23932             per-`:entrada` refusal under the outer accessor's \
23933             reference projection",
23934        );
23935        assert!(
23936            spec.entrada().is_none(),
23937            "the outer accessor's reference projection must name the \
23938             internal-only-mesh partition per the `None` fixture",
23939        );
23940
23941        // (2) `EntradaMemberMissing` refusal under the outer accessor's
23942        // reference projection: a well-shaped but phantom `:para` must
23943        // trip the membership-lookup refusal. The gate's second arm
23944        // reads `e.para` on the reference returned by the outer
23945        // accessor.
23946        let mut spec = three_member_spec();
23947        if let Some(e) = spec.entrada.as_mut() {
23948            e.para = "phantom".into();
23949        }
23950        assert_eq!(
23951            spec.validate().unwrap_err(),
23952            AplicacaoError::EntradaMemberMissing {
23953                para: "phantom".into(),
23954            },
23955        );
23956        match (spec.entrada(), spec.entrada.as_ref()) {
23957            (Some(a), Some(b)) => assert!(
23958                std::ptr::eq(a, b),
23959                "the `validate` per-`:entrada` gate's traversal head \
23960                 must be the same backing composite the accessor's \
23961                 reference projection borrows from",
23962            ),
23963            _ => panic!("fixture must carry Some(:entrada)"),
23964        }
23965
23966        // (3) Canonical `three_member_spec` `:entrada` fixture passes
23967        // `validate` — every per-axis arm reaches the fall-through
23968        // `Ok(())` without any per-axis refusal firing under the
23969        // outer accessor's reference projection.
23970        let spec = three_member_spec();
23971        assert!(
23972            spec.validate().is_ok(),
23973            "the canonical `:entrada` fixture must pass `validate` — \
23974             every per-axis arm short-circuits on valid input under \
23975             the outer accessor's reference projection",
23976        );
23977        assert!(
23978            spec.entrada().is_some(),
23979            "the outer accessor's reference projection must be the \
23980             canonical `:entrada` fixture's composite",
23981        );
23982    }
23983
23984    #[test]
23985    fn port_for_destination_reads_through_lifted_entrada_accessor() {
23986        // Peer coherence pin: the
23987        // [`AplicacaoSpec::port_for_destination`] per-destination
23988        // L4-port fallback resolver's composite-projection seed
23989        // (`self.entrada().filter(…).map_or(…)`) must key off the
23990        // lifted outer accessor. Pins the coherence by exercising
23991        // the resolver end-to-end: (1) the `None` `:entrada` shape
23992        // falls through to `DEFAULT_SERVICO_PORT` under the outer
23993        // accessor's reference projection, (2) a non-matching
23994        // destination falls through to `DEFAULT_SERVICO_PORT` under
23995        // the outer accessor's reference projection, and (3) the
23996        // matching destination resolves to the `:entrada :port`
23997        // value under the outer accessor's reference projection.
23998        //
23999        // Peer of the sibling
24000        // [`validate_reads_through_lifted_entrada_accessor`] multi-
24001        // consumer coherence pin on the same per-`:entrada` outer-
24002        // composite axis — extends the multi-consumer coherence
24003        // discipline onto the second per-`:entrada` production
24004        // consumer, the L4-port fallback resolver.
24005
24006        // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
24007        // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
24008        // arm under the outer accessor's reference projection.
24009        let mut spec = three_member_spec();
24010        spec.entrada = None;
24011        assert_eq!(
24012            spec.port_for_destination("cart"),
24013            DEFAULT_SERVICO_PORT,
24014            "the port-fallback resolver must fall through to \
24015             DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
24016             under the outer accessor's reference projection",
24017        );
24018
24019        // (2) Non-matching destination — the resolver's `filter(…)`
24020        // arm rejects a mismatched destination and falls through
24021        // to `DEFAULT_SERVICO_PORT` under the outer accessor's
24022        // reference projection.
24023        let mut spec = three_member_spec();
24024        if let Some(e) = spec.entrada.as_mut() {
24025            e.para = "cart".into();
24026            e.port = 9443;
24027        }
24028        assert_eq!(
24029            spec.port_for_destination("catalog"),
24030            DEFAULT_SERVICO_PORT,
24031            "the port-fallback resolver must fall through to \
24032             DEFAULT_SERVICO_PORT on a non-matching destination \
24033             under the outer accessor's reference projection",
24034        );
24035
24036        // (3) Matching destination — the resolver's `map_or(…)` arm
24037        // returns the `:entrada :port` value under the outer
24038        // accessor's reference projection.
24039        let mut spec = three_member_spec();
24040        if let Some(e) = spec.entrada.as_mut() {
24041            e.para = "cart".into();
24042            e.port = 9443;
24043        }
24044        assert_eq!(
24045            spec.port_for_destination("cart"),
24046            9443,
24047            "the port-fallback resolver must return the \
24048             `:entrada :port` value on a matching destination \
24049             under the outer accessor's reference projection",
24050        );
24051    }
24052
24053    #[test]
24054    fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
24055        // The canonical per-`:politicas` `:mtls-required` mTLS-
24056        // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
24057        // must return the `:politicas :mtls-required` typed bool
24058        // verbatim as an `Option<bool>`, byte-equal to the raw field
24059        // access across every value in the three-way accept-set —
24060        // `None` (cluster default applies), `Some(true)` (mTLS
24061        // handshake enforced — the sandboxing-by-default arm the
24062        // MeshPolicy's docstring names), `Some(false)` (handshake
24063        // skipped — the explicit debug-edge opt-out).
24064        //
24065        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
24066        // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
24067        // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
24068        // shape — first `Option<Copy-T>`-return accessor on the M3
24069        // mesh-slot family. Pins against a future silent detour that
24070        // re-derived the toggle from a peer axis (an accidental
24071        // `.circuit_breaker.is_some()` collapse that assumed mTLS on
24072        // whenever a breaker is set), a `None` → `Some(false)` cluster-
24073        // default projection (the canonical `Option<bool>` → `bool`
24074        // collapse footgun the surrounding `is_empty()` predicate
24075        // guards on the peer emptiness axis), or a `Some(true)` /
24076        // `Some(false)` variant swap that landed on one consumer
24077        // without the other.
24078        for required in [None, Some(true), Some(false)] {
24079            let p = MeshPolicy {
24080                mtls_required: required,
24081                ..MeshPolicy::default()
24082            };
24083            assert_eq!(
24084                p.mtls_required(),
24085                required,
24086                "MeshPolicy::mtls_required must return :politicas \
24087                 :mtls-required verbatim (got {:?}, expected {required:?})",
24088                p.mtls_required(),
24089            );
24090            assert_eq!(
24091                p.mtls_required(),
24092                p.mtls_required,
24093                "MeshPolicy::mtls_required must byte-equal the raw \
24094                 .mtls_required field access across every value in the \
24095                 three-way accept-set",
24096            );
24097        }
24098    }
24099
24100    #[test]
24101    fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
24102        // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
24103        // arm must key off [`MeshPolicy::mtls_required`], not the raw
24104        // `.mtls_required` field access. Structurally: toggling ONLY
24105        // the `mtls_required` slot on an otherwise-default MeshPolicy
24106        // must flip `is_empty()` from `true` (all-`None`) to `false`
24107        // (one axis carries a value); the flip must be observed for
24108        // both `Some(true)` and `Some(false)` since the emptiness
24109        // semantic reads "any axis carries a value" — not "any axis
24110        // carries a truthy value" — the same non-collapsing shape the
24111        // sibling M2 [`crate::LimitsSpec::is_empty`] /
24112        // [`crate::BehaviorSpec::is_empty`] predicates carry on their
24113        // peer `Option<T>`-typed slot surfaces.
24114        //
24115        // Pins against a future silent detour that re-derived the
24116        // emptiness predicate off a peer axis (an accidental
24117        // `.rate_limit.is_none()`-only chain that dropped the
24118        // `mtls_required` arm entirely), a `mtls_required == Some(_)`
24119        // collapse to a truthy-only check (which would silently
24120        // classify `Some(false)` as empty), or an accessor-side
24121        // detour that no longer names the substrate-primitive typed
24122        // dispatch (an accidental `self.mtls_required.unwrap_or(false)
24123        // == false` fallback in the accessor that would silently
24124        // classify both `None` and `Some(false)` as the same value).
24125        //
24126        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
24127        // (7cd2a28) accessor-composition pin on the sibling optional-
24128        // scalar axis — same "the emptiness / shape-gate predicate
24129        // must route through the substrate-primitive typed dispatch"
24130        // discipline extended onto the peer per-`:politicas` emptiness
24131        // predicate.
24132        let empty = MeshPolicy::default();
24133        assert!(
24134            empty.is_empty(),
24135            "MeshPolicy::default() must be is_empty() — every axis \
24136             defaults to None",
24137        );
24138        for required in [Some(true), Some(false)] {
24139            let p = MeshPolicy {
24140                mtls_required: required,
24141                ..MeshPolicy::default()
24142            };
24143            assert!(
24144                !p.is_empty(),
24145                "MeshPolicy::is_empty must return false when \
24146                 :mtls-required is {required:?} — the emptiness \
24147                 predicate reads \"any axis carries a value\", not \
24148                 \"any axis carries a truthy value\"",
24149            );
24150            assert_eq!(
24151                p.mtls_required().is_none(),
24152                p.is_empty(),
24153                "when :mtls-required is the only set axis, \
24154                 is_empty() must equal mtls_required().is_none() — \
24155                 the accessor and the emptiness predicate must \
24156                 route through the same substrate-primitive typed \
24157                 dispatch on the :mtls-required arm",
24158            );
24159        }
24160    }
24161
24162    #[test]
24163    fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
24164        // The by-copy pin: [`MeshPolicy::mtls_required`] returns
24165        // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
24166        // accessor must return by value, not by reference. Peer of the
24167        // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
24168        // borrow-invariant pin on the sibling `Option<String>` slot,
24169        // but extended onto the peer `Option<bool>` copy-invariant
24170        // shape — the accessor's returned `Option<bool>` must outlive
24171        // `&self` (multiple calls must return equal values from a
24172        // dropped-`&self` copy, since the returned Option carries no
24173        // borrow), and calling the accessor twice on the same
24174        // MeshPolicy must yield the same `Option<bool>` verbatim
24175        // (idempotent, no side effects on `&self`).
24176        //
24177        // Pins against a future silent detour that returned
24178        // `Option<&bool>` (which would type-check but silently break
24179        // every downstream caller — [`single_field_overlay`]'s first
24180        // parameter is `Option<T: Clone>`, and `&bool` would fold to a
24181        // detached copy at the call site), an accidental
24182        // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
24183        // would also type-check but return `Option<&bool>`), or a
24184        // one-arm-only accessor that reads `Some(*b)` in the Some arm
24185        // but reads a fresh Default::default() in the None arm.
24186        for required in [None, Some(true), Some(false)] {
24187            let p = MeshPolicy {
24188                mtls_required: required,
24189                ..MeshPolicy::default()
24190            };
24191            let first = p.mtls_required();
24192            let second = p.mtls_required();
24193            assert_eq!(
24194                first, second,
24195                "MeshPolicy::mtls_required must be idempotent — two \
24196                 successive calls on the same &self must return the \
24197                 same Option<bool>",
24198            );
24199            assert_eq!(
24200                first, required,
24201                "MeshPolicy::mtls_required must return :politicas \
24202                 :mtls-required verbatim by copy — got {first:?}, \
24203                 expected {required:?}",
24204            );
24205        }
24206    }
24207
24208    #[test]
24209    fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
24210        // The canonical per-`:politicas` `:retries` transient-failure-
24211        // retry-budget scalar pin: [`MeshPolicy::retries`] must return
24212        // the `:politicas :retries` typed `u32` verbatim as an
24213        // `Option<u32>`, byte-equal to the raw field access across every
24214        // representative value in the accept-set — `None` (cluster
24215        // default applies — typically "no retries beyond a single
24216        // dispatch attempt" the caixa-mesh `retry_overlay` builder
24217        // documents), `Some(1)` (the lower boundary of the
24218        // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
24219        // `AplicacaoSpec::validate_politicas` gate carves out on the
24220        // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
24221        // (the upper boundary the same gate carves out on the sibling
24222        // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
24223        // past-the-guard sentinel that pins the accessor doesn't perform
24224        // a silent bounds-collapse at the return path).
24225        //
24226        // Sibling of the peer per-`:politicas`
24227        // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
24228        // sibling `Option<Copy-T>` optional-scalar axis, extended to the
24229        // peer per-`:politicas` `Option<u32>` shape — second
24230        // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
24231        // Pins against a future silent detour that re-derived the retry
24232        // cap from a peer axis (an accidental `.circuit_breaker
24233        // .as_ref().map(|b| b.max_failures)` collapse that read the
24234        // breaker's max-failure count as a retry budget), a
24235        // `None → Some(0)` cluster-default projection (which would
24236        // silently re-introduce the `PolicyRetriesZero` refusal case at
24237        // the emit boundary), or a bounds-collapsing accessor that
24238        // clamped the return through `POLICY_RETRIES_MAX` (the
24239        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
24240        // must ship the raw slot verbatim so a validate-time gate
24241        // regression surfaces at the emit boundary rather than being
24242        // silently absorbed).
24243        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
24244            let p = MeshPolicy {
24245                retries,
24246                ..MeshPolicy::default()
24247            };
24248            assert_eq!(
24249                p.retries(),
24250                retries,
24251                "MeshPolicy::retries must return :politicas :retries \
24252                 verbatim (got {:?}, expected {retries:?})",
24253                p.retries(),
24254            );
24255            assert_eq!(
24256                p.retries(),
24257                p.retries,
24258                "MeshPolicy::retries must byte-equal the raw .retries \
24259                 field access across every value in the accept-set",
24260            );
24261        }
24262    }
24263
24264    #[test]
24265    fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
24266        // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
24267        // must key off [`MeshPolicy::retries`], not the raw `.retries`
24268        // field access. Structurally: toggling ONLY the `retries` slot
24269        // on an otherwise-default MeshPolicy must flip `is_empty()`
24270        // from `true` (all-`None`) to `false` (one axis carries a
24271        // value); the flip must be observed for every value in the
24272        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
24273        // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
24274        // the emptiness semantic reads "any axis carries a value" —
24275        // not "any axis carries a value the validate gate accepts" —
24276        // the same non-collapsing shape the peer M2
24277        // [`crate::LimitsSpec::is_empty`] /
24278        // [`crate::BehaviorSpec::is_empty`] predicates carry.
24279        //
24280        // Pins against a future silent detour that re-derived the
24281        // emptiness predicate off a peer axis (an accidental
24282        // `.rate_limit.is_none()`-only chain that dropped the
24283        // `retries` arm entirely), a `retries == Some(_)` collapse
24284        // that key-off a validate-gate-clamped bounds check (which
24285        // would silently classify a past-the-guard `Some(u32::MAX)`
24286        // as empty because it fails the `1..=POLICY_RETRIES_MAX`
24287        // check), or an accessor-side detour that no longer names the
24288        // substrate-primitive typed dispatch.
24289        //
24290        // Sibling of the peer per-`:politicas`
24291        // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
24292        // pin on the sibling `Option<Copy-T>` optional-scalar axis —
24293        // same "the emptiness predicate must route through the
24294        // substrate-primitive typed dispatch" discipline extended onto
24295        // the peer per-`:politicas` `Option<u32>` axis.
24296        let empty = MeshPolicy::default();
24297        assert!(
24298            empty.is_empty(),
24299            "MeshPolicy::default() must be is_empty() — every axis \
24300             defaults to None",
24301        );
24302        for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
24303            let p = MeshPolicy {
24304                retries,
24305                ..MeshPolicy::default()
24306            };
24307            assert!(
24308                !p.is_empty(),
24309                "MeshPolicy::is_empty must return false when \
24310                 :retries is {retries:?} — the emptiness \
24311                 predicate reads \"any axis carries a value\", not \
24312                 \"any axis carries a value the validate gate \
24313                 accepts\"",
24314            );
24315            assert_eq!(
24316                p.retries().is_none(),
24317                p.is_empty(),
24318                "when :retries is the only set axis, is_empty() \
24319                 must equal retries().is_none() — the accessor and \
24320                 the emptiness predicate must route through the same \
24321                 substrate-primitive typed dispatch on the :retries \
24322                 arm",
24323            );
24324        }
24325    }
24326
24327    #[test]
24328    fn mesh_policy_retries_projects_option_u32_by_copy() {
24329        // The by-copy pin: [`MeshPolicy::retries`] returns
24330        // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
24331        // accessor must return by value, not by reference. Sibling of
24332        // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
24333        // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
24334        // extended onto the sibling `Option<u32>` copy-invariant
24335        // shape — the accessor's returned `Option<u32>` must outlive
24336        // `&self` (multiple calls must return equal values from a
24337        // dropped-`&self` copy, since the returned Option carries no
24338        // borrow), and calling the accessor twice on the same
24339        // MeshPolicy must yield the same `Option<u32>` verbatim
24340        // (idempotent, no side effects on `&self`).
24341        //
24342        // Pins against a future silent detour that returned
24343        // `Option<&u32>` (which would type-check but silently break
24344        // every downstream caller — [`crate::render::single_field_overlay`]'s
24345        // first parameter is `Option<T: Clone>`, and `&u32` would
24346        // fold to a detached copy at the call site), an accidental
24347        // `Option::as_ref()` projection (`self.retries.as_ref()` would
24348        // also type-check but return `Option<&u32>`), or a one-arm-
24349        // only accessor that reads `Some(*n)` in the Some arm but
24350        // reads a fresh `Default::default()` (`0_u32`) in the None
24351        // arm.
24352        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
24353            let p = MeshPolicy {
24354                retries,
24355                ..MeshPolicy::default()
24356            };
24357            let first = p.retries();
24358            let second = p.retries();
24359            assert_eq!(
24360                first, second,
24361                "MeshPolicy::retries must be idempotent — two \
24362                 successive calls on the same &self must return the \
24363                 same Option<u32>",
24364            );
24365            assert_eq!(
24366                first, retries,
24367                "MeshPolicy::retries must return :politicas :retries \
24368                 verbatim by copy — got {first:?}, expected {retries:?}",
24369            );
24370        }
24371    }
24372
24373    #[test]
24374    fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
24375        // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
24376        // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
24377        // return the `:politicas :timeout` typed [`Duration`] verbatim
24378        // as an `Option<Duration>`, byte-equal to the raw field access
24379        // across every representative value in the accept-set — `None`
24380        // (cluster default applies — typically the gateway class's
24381        // implementation-side per-request wall-clock cap the caixa-mesh
24382        // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
24383        // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
24384        // set the surrounding `AplicacaoSpec::validate_politicas` gate
24385        // carves out on the sibling `PolicyTimeoutZero` /
24386        // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
24387        // (the upper boundary the same gate carves out on the sibling
24388        // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
24389        // (a past-the-guard sentinel that pins the accessor doesn't
24390        // perform a silent bounds-collapse into `None` on the zero-
24391        // Duration arm — validate rejects zero but the accessor must
24392        // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
24393        // past-the-guard sentinel that pins the accessor doesn't
24394        // perform a silent bounds-collapse at the return path).
24395        //
24396        // Sibling of the peer per-`:politicas`
24397        // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
24398        // `Option<u32>` optional-scalar axis and the peer per-
24399        // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
24400        // pin on the sibling `Option<bool>` optional-scalar axis,
24401        // extended onto the peer per-`:politicas` `Option<Duration>`
24402        // shape — third `Option<Copy-T>`-return accessor on the M3
24403        // mesh-slot family. Pins against a future silent detour that
24404        // re-derived the per-call cap from a peer axis (an accidental
24405        // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
24406        // read the breaker's rolling-window duration as a per-call
24407        // deadline), a `None → Some(Duration::MAX)` cluster-default
24408        // projection (which would silently re-introduce the
24409        // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
24410        // blocking" arm at the emit boundary), or a bounds-collapsing
24411        // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
24412        // (the `AplicacaoSpec::validate` gate owns the bounds; the
24413        // accessor must ship the raw slot verbatim so a validate-time
24414        // gate regression surfaces at the emit boundary rather than
24415        // being silently absorbed).
24416        for timeout in [
24417            None,
24418            Some(Duration::from_millis(1)),
24419            Some(POLICY_TIMEOUT_MAX),
24420            Some(Duration::ZERO),
24421            Some(Duration::MAX),
24422        ] {
24423            let p = MeshPolicy {
24424                timeout,
24425                ..MeshPolicy::default()
24426            };
24427            assert_eq!(
24428                p.timeout(),
24429                timeout,
24430                "MeshPolicy::timeout must return :politicas :timeout \
24431                 verbatim (got {:?}, expected {timeout:?})",
24432                p.timeout(),
24433            );
24434            assert_eq!(
24435                p.timeout(),
24436                p.timeout,
24437                "MeshPolicy::timeout must byte-equal the raw .timeout \
24438                 field access across every value in the accept-set",
24439            );
24440        }
24441    }
24442
24443    #[test]
24444    fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
24445        // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
24446        // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
24447        // field access. Structurally: toggling ONLY the `timeout` slot
24448        // on an otherwise-default MeshPolicy must flip `is_empty()`
24449        // from `true` (all-`None`) to `false` (one axis carries a
24450        // value); the flip must be observed for every value in the
24451        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
24452        // gate accepts (`Some(Duration::from_millis(1))`,
24453        // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
24454        // reads "any axis carries a value" — not "any axis carries a
24455        // value the validate gate accepts" — the same non-collapsing
24456        // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
24457        // [`crate::BehaviorSpec::is_empty`] predicates carry.
24458        //
24459        // Pins against a future silent detour that re-derived the
24460        // emptiness predicate off a peer axis (an accidental
24461        // `.rate_limit.is_none()`-only chain that dropped the
24462        // `timeout` arm entirely), a `timeout == Some(_)` collapse
24463        // that key-off a validate-gate-clamped bounds check (which
24464        // would silently classify a past-the-guard `Some(Duration::MAX)`
24465        // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
24466        // check), or an accessor-side detour that no longer names the
24467        // substrate-primitive typed dispatch.
24468        //
24469        // Sibling of the peer per-`:politicas`
24470        // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
24471        // the sibling `Option<u32>` optional-scalar axis and the peer
24472        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
24473        // accessor-composition pin on the sibling `Option<bool>`
24474        // optional-scalar axis — same "the emptiness predicate must
24475        // route through the substrate-primitive typed dispatch"
24476        // discipline extended onto the peer per-`:politicas`
24477        // `Option<Duration>` axis.
24478        let empty = MeshPolicy::default();
24479        assert!(
24480            empty.is_empty(),
24481            "MeshPolicy::default() must be is_empty() — every axis \
24482             defaults to None",
24483        );
24484        for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
24485            let p = MeshPolicy {
24486                timeout,
24487                ..MeshPolicy::default()
24488            };
24489            assert!(
24490                !p.is_empty(),
24491                "MeshPolicy::is_empty must return false when \
24492                 :timeout is {timeout:?} — the emptiness \
24493                 predicate reads \"any axis carries a value\", not \
24494                 \"any axis carries a value the validate gate \
24495                 accepts\"",
24496            );
24497            assert_eq!(
24498                p.timeout().is_none(),
24499                p.is_empty(),
24500                "when :timeout is the only set axis, is_empty() \
24501                 must equal timeout().is_none() — the accessor and \
24502                 the emptiness predicate must route through the same \
24503                 substrate-primitive typed dispatch on the :timeout \
24504                 arm",
24505            );
24506        }
24507    }
24508
24509    #[test]
24510    fn mesh_policy_timeout_projects_option_duration_by_copy() {
24511        // The by-copy pin: [`MeshPolicy::timeout`] returns
24512        // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
24513        // and the accessor must return by value, not by reference.
24514        // Sibling of the peer per-`:politicas`
24515        // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
24516        // sibling `Option<u32>` optional-scalar axis and the peer
24517        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
24518        // by-copy pin on the sibling `Option<bool>` optional-scalar
24519        // axis, extended onto the peer per-`:politicas`
24520        // `Option<Duration>` copy-invariant shape — the accessor's
24521        // returned `Option<Duration>` must outlive `&self` (multiple
24522        // calls must return equal values from a dropped-`&self`
24523        // copy, since the returned Option carries no borrow), and
24524        // calling the accessor twice on the same MeshPolicy must
24525        // yield the same `Option<Duration>` verbatim (idempotent, no
24526        // side effects on `&self`).
24527        //
24528        // Pins against a future silent detour that returned
24529        // `Option<&Duration>` (which would type-check but silently
24530        // break every downstream caller — [`crate::render::single_field_overlay`]'s
24531        // first parameter is `Option<T: Clone>`, and `&Duration`
24532        // would fold to a detached copy at the call site), an
24533        // accidental `Option::as_ref()` projection
24534        // (`self.timeout.as_ref()` would also type-check but return
24535        // `Option<&Duration>`), or a one-arm-only accessor that
24536        // reads `Some(*d)` in the Some arm but reads a fresh
24537        // `Default::default()` (`Duration::ZERO`) in the None arm
24538        // (which would silently re-classify every unset `:timeout`
24539        // as the `PolicyTimeoutZero`-refused zero-Duration value at
24540        // the accessor boundary).
24541        for timeout in [
24542            None,
24543            Some(Duration::from_millis(1)),
24544            Some(POLICY_TIMEOUT_MAX),
24545            Some(Duration::ZERO),
24546            Some(Duration::MAX),
24547        ] {
24548            let p = MeshPolicy {
24549                timeout,
24550                ..MeshPolicy::default()
24551            };
24552            let first = p.timeout();
24553            let second = p.timeout();
24554            assert_eq!(
24555                first, second,
24556                "MeshPolicy::timeout must be idempotent — two \
24557                 successive calls on the same &self must return the \
24558                 same Option<Duration>",
24559            );
24560            assert_eq!(
24561                first, timeout,
24562                "MeshPolicy::timeout must return :politicas :timeout \
24563                 verbatim by copy — got {first:?}, expected {timeout:?}",
24564            );
24565        }
24566    }
24567
24568    #[test]
24569    fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
24570        // The canonical per-`:politicas` `:rate-limit` Envoy-
24571        // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
24572        // [`MeshPolicy::rate_limit`] must return the `:politicas
24573        // :rate-limit` typed [`RateLimit`] verbatim as an
24574        // `Option<RateLimit>`, byte-equal to the raw field access
24575        // across every representative value in the accept-set — `None`
24576        // (cluster default applies — no per-Aplicacao rate declaration,
24577        // the gateway-class per-listener default arm the future caixa-
24578        // mesh `local_rate_limit_overlay` emitter documents),
24579        // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
24580        // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
24581        // accept-set the surrounding
24582        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
24583        // sibling `PolicyRateLimitZero` refusal, paired with the
24584        // canonical-window "1 second" arm of the three-unit
24585        // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
24586        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
24587        // (the upper boundary the same gate carves out on the sibling
24588        // `PolicyRateLimitExceedsCap` refusal, paired with the
24589        // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
24590        // (a past-the-guard sentinel that pins the accessor doesn't
24591        // perform a silent bounds-collapse into `None` on the
24592        // zero-rate/zero-window arm — validate rejects zero but the
24593        // accessor must ship the raw slot verbatim so a validate-time
24594        // gate regression surfaces at the emit boundary rather than
24595        // being silently absorbed), and
24596        // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
24597        // (a past-the-guard sentinel that pins the accessor doesn't
24598        // perform a silent bounds-collapse at the return path).
24599        //
24600        // First `Option<Copy-composite-T>`-return accessor pin on the
24601        // M3 mesh-slot family (peer of the sibling per-`:politicas`
24602        // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
24603        // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
24604        // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
24605        // Copy accessor pins, extended onto the peer per-`:politicas`
24606        // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
24607        // and the accessor returns by value). Pins against a future
24608        // silent detour that re-derived the rate declaration from a
24609        // peer axis (an accidental
24610        // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
24611        // collapse that read the breaker's trip threshold + rolling
24612        // window as a rate declaration), a `None → Some(default())`
24613        // cluster-default projection (which would silently re-
24614        // introduce a "cluster default is 0/s" arm the emit boundary
24615        // would take as "declared but inert" — the canonical
24616        // declared-but-inert footgun the sibling
24617        // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
24618        // amplification-shape axis), a bounds-collapsing accessor
24619        // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
24620        // clamped `rl.window` through [`is_canonical_rate_limit_window`]
24621        // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
24622        // accessor must ship the raw slot verbatim), or a
24623        // by-reference detour (`Option<&RateLimit>`) that broke every
24624        // downstream consumer keying off `Option<RateLimit>` by-copy.
24625        for rl in [
24626            None,
24627            Some(RateLimit {
24628                rate: 1,
24629                window: Duration::from_secs(1),
24630            }),
24631            Some(RateLimit {
24632                rate: POLICY_RATE_LIMIT_MAX,
24633                window: Duration::from_secs(3600),
24634            }),
24635            Some(RateLimit {
24636                rate: 0,
24637                window: Duration::ZERO,
24638            }),
24639            Some(RateLimit {
24640                rate: u32::MAX,
24641                window: Duration::MAX,
24642            }),
24643        ] {
24644            let p = MeshPolicy {
24645                rate_limit: rl,
24646                ..MeshPolicy::default()
24647            };
24648            assert_eq!(
24649                p.rate_limit(),
24650                rl,
24651                "MeshPolicy::rate_limit must return :politicas :rate-limit \
24652                 verbatim (got {:?}, expected {rl:?})",
24653                p.rate_limit(),
24654            );
24655            assert_eq!(
24656                p.rate_limit(),
24657                p.rate_limit,
24658                "MeshPolicy::rate_limit must byte-equal the raw \
24659                 .rate_limit field access across every value in the \
24660                 accept-set",
24661            );
24662        }
24663    }
24664
24665    #[test]
24666    fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
24667        // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
24668        // must key off [`MeshPolicy::rate_limit`], not the raw
24669        // `.rate_limit` field access. Structurally: toggling ONLY the
24670        // `rate_limit` slot on an otherwise-default MeshPolicy must
24671        // flip `is_empty()` from `true` (all-`None`) to `false` (one
24672        // axis carries a value); the flip must be observed for every
24673        // representative value in the accept-set the surrounding
24674        // [`AplicacaoSpec::validate_politicas`] gate accepts
24675        // (`Some(RateLimit { rate: 1, window: 1s })`,
24676        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
24677        // since the emptiness semantic reads "any axis carries a
24678        // value" — not "any axis carries a value the validate gate
24679        // accepts" — the same non-collapsing shape the peer M2
24680        // [`crate::LimitsSpec::is_empty`] /
24681        // [`crate::BehaviorSpec::is_empty`] predicates carry.
24682        //
24683        // Pins against a future silent detour that re-derived the
24684        // emptiness predicate off a peer axis (an accidental
24685        // `.timeout.is_none()`-only chain that dropped the
24686        // `rate_limit` arm entirely — the last unlifted inline field
24687        // access on `is_empty` before this lift), a `rate_limit ==
24688        // Some(_)` collapse that key-off a validate-gate-clamped
24689        // bounds check (which would silently classify a past-the-
24690        // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
24691        // because it fails the value-shape gate), or an accessor-
24692        // side detour that no longer names the substrate-primitive
24693        // typed dispatch.
24694        //
24695        // Fourth "the emptiness predicate must route through the
24696        // substrate-primitive typed dispatch" composition pin on the
24697        // M3 mesh-slot family — closes the last unlifted composition
24698        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
24699        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
24700        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
24701        // 7073d0f is_empty-composition pins on the sibling primitive-
24702        // Copy axes, extended onto the peer per-`:politicas`
24703        // composite-Copy `Option<RateLimit>` axis).
24704        let empty = MeshPolicy::default();
24705        assert!(
24706            empty.is_empty(),
24707            "MeshPolicy::default() must be is_empty() — every axis \
24708             defaults to None",
24709        );
24710        for rl in [
24711            RateLimit {
24712                rate: 1,
24713                window: Duration::from_secs(1),
24714            },
24715            RateLimit {
24716                rate: POLICY_RATE_LIMIT_MAX,
24717                window: Duration::from_secs(3600),
24718            },
24719        ] {
24720            let p = MeshPolicy {
24721                rate_limit: Some(rl),
24722                ..MeshPolicy::default()
24723            };
24724            assert!(
24725                !p.is_empty(),
24726                "MeshPolicy::is_empty must return false when \
24727                 :rate-limit is {rl:?} — the emptiness predicate \
24728                 reads \"any axis carries a value\", not \"any axis \
24729                 carries a value the validate gate accepts\"",
24730            );
24731            assert_eq!(
24732                p.rate_limit().is_none(),
24733                p.is_empty(),
24734                "when :rate-limit is the only set axis, is_empty() \
24735                 must equal rate_limit().is_none() — the accessor \
24736                 and the emptiness predicate must route through the \
24737                 same substrate-primitive typed dispatch on the \
24738                 :rate-limit arm",
24739            );
24740        }
24741    }
24742
24743    #[test]
24744    fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
24745        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
24746        // `:rate-limit` value-shape gate must key off
24747        // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
24748        // field bind. Structurally: a `MeshPolicy` whose only set
24749        // axis is a `Some(RateLimit { rate: 0, .. })` must surface
24750        // the `PolicyRateLimitZero` refusal exactly, and the same
24751        // MeshPolicy with the rate at the canonical lower boundary
24752        // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
24753        // The pair jointly pins the accessor + validate-gate
24754        // composition: any future silent detour that had the accessor
24755        // omit the `Some(RateLimit { rate: 0, .. })` arm (a
24756        // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
24757        // silently absorb the `PolicyRateLimitZero` refusal at the
24758        // accessor boundary — the composition pin catches that at
24759        // caixa-core build time.
24760        //
24761        // Sibling of the peer [`validate_politicas`]
24762        // `:mtls-required` / `:retries` / `:timeout` composition pins
24763        // on the sibling primitive-Copy optional-scalar axes — same
24764        // "the validate / shape-gate predicate must route through the
24765        // substrate-primitive typed dispatch" discipline extended
24766        // onto the peer per-`:politicas` composite-Copy
24767        // `Option<RateLimit>` axis. Second composition-with-accessor
24768        // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
24769        // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
24770        let mut spec = three_member_spec();
24771        spec.politicas = MeshPolicy {
24772            rate_limit: Some(RateLimit {
24773                rate: 0,
24774                window: Duration::from_secs(1),
24775            }),
24776            ..MeshPolicy::default()
24777        };
24778        assert!(
24779            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
24780            "validate_politicas must reject rate == 0 with \
24781             PolicyRateLimitZero — the accessor and the validate gate \
24782             must route through the same substrate-primitive typed \
24783             dispatch on the :rate-limit zero-floor arm",
24784        );
24785        spec.politicas = MeshPolicy {
24786            rate_limit: Some(RateLimit {
24787                rate: 1,
24788                window: Duration::from_secs(1),
24789            }),
24790            ..MeshPolicy::default()
24791        };
24792        assert!(
24793            spec.validate().is_ok(),
24794            "validate_politicas must accept rate == 1 (the canonical \
24795             lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
24796             set) with a canonical 1s window",
24797        );
24798    }
24799
24800    #[test]
24801    fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
24802        // The canonical per-`:politicas` `:circuit-breaker` Envoy-
24803        // `outlier_detection`-mesh consecutive-failure-ejection scalar
24804        // pin: [`MeshPolicy::circuit_breaker`] must return the
24805        // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
24806        // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
24807        // raw field access across every representative value in the
24808        // accept-set — `None` (cluster default applies — no
24809        // per-Aplicacao breaker declaration, the gateway-class per-
24810        // listener default arm the future caixa-mesh
24811        // `outlier_detection_overlay` emitter documents),
24812        // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
24813        // (the lower boundary of the accept-set the surrounding
24814        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
24815        // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
24816        // refusals),
24817        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
24818        // (the upper boundary the same gate carves out on the sibling
24819        // `PolicyBreakerMaxFailuresExceedsCap` /
24820        // `PolicyBreakerWindowExceedsCap` refusals),
24821        // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
24822        // (a past-the-guard sentinel that pins the accessor doesn't
24823        // perform a silent bounds-collapse into `None` on the
24824        // zero-failures/zero-window arm — validate rejects zero but
24825        // the accessor must ship the raw slot verbatim so a validate-
24826        // time gate regression surfaces at the emit boundary rather
24827        // than being silently absorbed), and
24828        // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
24829        // (a past-the-guard sentinel that pins the accessor doesn't
24830        // perform a silent bounds-collapse at the return path).
24831        //
24832        // Second `Option<Copy-composite-T>`-return accessor pin on the
24833        // M3 mesh-slot family (peer of the sibling per-`:politicas`
24834        // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
24835        // composite-Copy accessor pin, and of the sibling per-
24836        // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
24837        // [`MeshPolicy::retries`] bdfb399 /
24838        // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
24839        // accessor pins). Pins against a future silent detour that
24840        // re-derived the breaker declaration from a peer axis (an
24841        // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
24842        // collapse that read the rate-limit's bucket capacity + refill
24843        // period as a breaker declaration), a `None → Some(default())`
24844        // cluster-default projection (which would silently re-
24845        // introduce the `PolicyBreakerZeroFailures` /
24846        // `PolicyBreakerZeroWindow` refusal cases at the emit
24847        // boundary), a bounds-collapsing accessor that clamped
24848        // `cb.max_failures` through
24849        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
24850        // through [`POLICY_BREAKER_WINDOW_MAX`] (the
24851        // [`AplicacaoSpec::validate`] gate owns the bounds; the
24852        // accessor must ship the raw slot verbatim), or a
24853        // by-reference detour (`Option<&CircuitBreaker>`) that broke
24854        // every downstream consumer keying off `Option<CircuitBreaker>`
24855        // by-copy.
24856        for cb in [
24857            None,
24858            Some(CircuitBreaker {
24859                max_failures: 1,
24860                window: Duration::from_millis(1),
24861            }),
24862            Some(CircuitBreaker {
24863                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
24864                window: POLICY_BREAKER_WINDOW_MAX,
24865            }),
24866            Some(CircuitBreaker {
24867                max_failures: 0,
24868                window: Duration::ZERO,
24869            }),
24870            Some(CircuitBreaker {
24871                max_failures: u32::MAX,
24872                window: Duration::MAX,
24873            }),
24874        ] {
24875            let p = MeshPolicy {
24876                circuit_breaker: cb,
24877                ..MeshPolicy::default()
24878            };
24879            assert_eq!(
24880                p.circuit_breaker(),
24881                cb,
24882                "MeshPolicy::circuit_breaker must return :politicas \
24883                 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
24884                p.circuit_breaker(),
24885            );
24886            assert_eq!(
24887                p.circuit_breaker(),
24888                p.circuit_breaker,
24889                "MeshPolicy::circuit_breaker must byte-equal the raw \
24890                 .circuit_breaker field access across every value in \
24891                 the accept-set",
24892            );
24893        }
24894    }
24895
24896    #[test]
24897    fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
24898        // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
24899        // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
24900        // `.circuit_breaker` field access. Structurally: toggling ONLY
24901        // the `circuit_breaker` slot on an otherwise-default MeshPolicy
24902        // must flip `is_empty()` from `true` (all-`None`) to `false`
24903        // (one axis carries a value); the flip must be observed for
24904        // every representative value in the accept-set the surrounding
24905        // [`AplicacaoSpec::validate_politicas`] gate accepts
24906        // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
24907        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
24908        // since the emptiness semantic reads "any axis carries a
24909        // value" — not "any axis carries a value the validate gate
24910        // accepts" — the same non-collapsing shape the peer M2
24911        // [`crate::LimitsSpec::is_empty`] /
24912        // [`crate::BehaviorSpec::is_empty`] predicates carry.
24913        //
24914        // Pins against a future silent detour that re-derived the
24915        // emptiness predicate off a peer axis (an accidental
24916        // `.rate_limit.is_none()`-only chain that dropped the
24917        // `circuit_breaker` arm entirely — the last unlifted inline
24918        // field access on `is_empty` before this lift), a
24919        // `circuit_breaker == Some(_)` collapse that key-off a
24920        // validate-gate-clamped bounds check (which would silently
24921        // classify a past-the-guard `Some(CircuitBreaker { max_failures:
24922        // 0, window: 0s })` as empty because it fails the value-shape
24923        // gate), or an accessor-side detour that no longer names the
24924        // substrate-primitive typed dispatch.
24925        //
24926        // Fifth "the emptiness predicate must route through the
24927        // substrate-primitive typed dispatch" composition pin on the
24928        // M3 mesh-slot family — closes the last unlifted composition
24929        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
24930        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
24931        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
24932        // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
24933        // composition pins on the sibling primitive-Copy + composite-
24934        // Copy axes, extended onto the peer per-`:politicas`
24935        // composite-Copy `Option<CircuitBreaker>` axis).
24936        let empty = MeshPolicy::default();
24937        assert!(
24938            empty.is_empty(),
24939            "MeshPolicy::default() must be is_empty() — every axis \
24940             defaults to None",
24941        );
24942        for cb in [
24943            CircuitBreaker {
24944                max_failures: 1,
24945                window: Duration::from_millis(1),
24946            },
24947            CircuitBreaker {
24948                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
24949                window: POLICY_BREAKER_WINDOW_MAX,
24950            },
24951        ] {
24952            let p = MeshPolicy {
24953                circuit_breaker: Some(cb),
24954                ..MeshPolicy::default()
24955            };
24956            assert!(
24957                !p.is_empty(),
24958                "MeshPolicy::is_empty must return false when \
24959                 :circuit-breaker is {cb:?} — the emptiness predicate \
24960                 reads \"any axis carries a value\", not \"any axis \
24961                 carries a value the validate gate accepts\"",
24962            );
24963            assert_eq!(
24964                p.circuit_breaker().is_none(),
24965                p.is_empty(),
24966                "when :circuit-breaker is the only set axis, \
24967                 is_empty() must equal circuit_breaker().is_none() — \
24968                 the accessor and the emptiness predicate must route \
24969                 through the same substrate-primitive typed dispatch \
24970                 on the :circuit-breaker arm",
24971            );
24972        }
24973    }
24974
24975    #[test]
24976    fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
24977        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
24978        // `:circuit-breaker` value-shape gate must key off
24979        // [`MeshPolicy::circuit_breaker`], not the raw
24980        // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
24981        // whose only set axis is a `Some(CircuitBreaker { max_failures:
24982        // 0, .. })` must surface the `PolicyBreakerZeroFailures`
24983        // refusal exactly, and the same MeshPolicy with the breaker at
24984        // the canonical lower boundary
24985        // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
24986        // pass validate. The pair jointly pins the accessor +
24987        // validate-gate composition: any future silent detour that had
24988        // the accessor omit the `Some(CircuitBreaker { max_failures:
24989        // 0, .. })` arm (a
24990        // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
24991        // collapse) would silently absorb the
24992        // `PolicyBreakerZeroFailures` refusal at the accessor
24993        // boundary — the composition pin catches that at caixa-core
24994        // build time.
24995        //
24996        // Sibling of the peer [`validate_politicas`]
24997        // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
24998        // composition pins on the sibling primitive-Copy + composite-
24999        // Copy optional-scalar axes — same "the validate / shape-gate
25000        // predicate must route through the substrate-primitive typed
25001        // dispatch" discipline extended onto the peer per-`:politicas`
25002        // composite-Copy `Option<CircuitBreaker>` axis. Second
25003        // composition-with-accessor pin on the M3 mesh-slot
25004        // `Option<CircuitBreaker>` arm alongside the
25005        // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
25006        let mut spec = three_member_spec();
25007        spec.politicas = MeshPolicy {
25008            circuit_breaker: Some(CircuitBreaker {
25009                max_failures: 0,
25010                window: Duration::from_millis(1),
25011            }),
25012            ..MeshPolicy::default()
25013        };
25014        assert!(
25015            matches!(
25016                spec.validate(),
25017                Err(AplicacaoError::PolicyBreakerZeroFailures)
25018            ),
25019            "validate_politicas must reject max_failures == 0 with \
25020             PolicyBreakerZeroFailures — the accessor and the validate \
25021             gate must route through the same substrate-primitive \
25022             typed dispatch on the :circuit-breaker zero-floor arm",
25023        );
25024        spec.politicas = MeshPolicy {
25025            circuit_breaker: Some(CircuitBreaker {
25026                max_failures: 1,
25027                window: Duration::from_millis(1),
25028            }),
25029            ..MeshPolicy::default()
25030        };
25031        assert!(
25032            spec.validate().is_ok(),
25033            "validate_politicas must accept a CircuitBreaker at the \
25034             canonical lower boundary (max_failures = 1, window = \
25035             1ms) — the accessor and the validate gate must route \
25036             through the same substrate-primitive typed dispatch on \
25037             the :circuit-breaker arm",
25038        );
25039    }
25040
25041    #[test]
25042    fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
25043        // The canonical per-`:politicas :circuit-breaker` `:max-failures`
25044        // Envoy-outlier-detection trip-threshold scalar pin:
25045        // [`CircuitBreaker::max_failures`] must return the
25046        // `:politicas :circuit-breaker :max-failures` typed `u32`
25047        // verbatim, byte-equal to the raw field access across every
25048        // representative value in the accept-set — `1` (the lower
25049        // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
25050        // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
25051        // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
25052        // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
25053        // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
25054        // refusal), `0` (a past-the-guard sentinel that pins the accessor
25055        // doesn't perform a silent bounds-collapse into `1` on the zero
25056        // arm — validate rejects zero but the accessor must ship the
25057        // raw slot verbatim so a validate-time gate regression surfaces
25058        // at the emit boundary rather than being silently absorbed),
25059        // `u32::MAX` (a past-the-guard sentinel that pins the accessor
25060        // doesn't perform a silent bounds-collapse through
25061        // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
25062        //
25063        // First sub-struct required-scalar accessor pin on the M3
25064        // mesh-slot family — sibling in shape to the peer per-`:membros`
25065        // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
25066        // (a40b0e3) required-`String`-carry accessor pins and the peer
25067        // per-`:contratos` [`WitContract::source`] /
25068        // [`WitContract::destination`] (7f0fd43) required-`String`-carry
25069        // accessor pins, extended onto the peer per-`CircuitBreaker`
25070        // required-`u32` scalar-value axis. Pins against a future silent
25071        // detour that re-derived the trip threshold from a peer axis (an
25072        // accidental `self.window.as_secs() as u32` collapse that read
25073        // the breaker's rolling-window duration as a failure count), a
25074        // `0 → 1` cluster-default projection (which would silently absorb
25075        // the `PolicyBreakerZeroFailures` refusal case at the accessor
25076        // boundary), or a bounds-collapsing accessor that clamped the
25077        // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
25078        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
25079        // must ship the raw slot verbatim).
25080        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
25081            let cb = CircuitBreaker {
25082                max_failures,
25083                window: Duration::from_secs(60),
25084            };
25085            assert_eq!(
25086                cb.max_failures(),
25087                max_failures,
25088                "CircuitBreaker::max_failures must return :politicas \
25089                 :circuit-breaker :max-failures verbatim (got {}, \
25090                 expected {max_failures})",
25091                cb.max_failures(),
25092            );
25093            assert_eq!(
25094                cb.max_failures(),
25095                cb.max_failures,
25096                "CircuitBreaker::max_failures must byte-equal the raw \
25097                 .max_failures field access across every value in the \
25098                 u32 accept-set",
25099            );
25100        }
25101    }
25102
25103    #[test]
25104    fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
25105        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
25106        // `:circuit-breaker :max-failures` zero-floor arm must key off
25107        // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
25108        // field access. Structurally: a `CircuitBreaker { max_failures:
25109        // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
25110        // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
25111        // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
25112        // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
25113        // pass validate. The pair jointly pins the accessor +
25114        // validate-gate composition: any future silent detour that had
25115        // the accessor return a fresh `1` on the zero arm (a
25116        // `.max_failures().max(1)` collapse) would silently absorb the
25117        // `PolicyBreakerZeroFailures` refusal at the accessor boundary
25118        // and the validate gate would accept a struct-literal
25119        // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
25120        // catches that at caixa-core build time.
25121        //
25122        // Peer of the sibling per-`:politicas`
25123        // [`MeshPolicy::mtls_required`] (c0110f1) /
25124        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
25125        // (7073d0f) accessor-composition pins on the sibling optional-
25126        // scalar axes — same "the validate / shape-gate predicate must
25127        // route through the substrate-primitive typed dispatch"
25128        // discipline extended onto the peer per-`CircuitBreaker`
25129        // required-scalar composition axis.
25130        let mut spec = three_member_spec();
25131        spec.politicas = MeshPolicy {
25132            circuit_breaker: Some(CircuitBreaker {
25133                max_failures: 0,
25134                window: Duration::from_secs(60),
25135            }),
25136            ..MeshPolicy::default()
25137        };
25138        assert!(
25139            matches!(
25140                spec.validate(),
25141                Err(AplicacaoError::PolicyBreakerZeroFailures)
25142            ),
25143            "validate_politicas must reject max_failures == 0 with \
25144             PolicyBreakerZeroFailures — the accessor and the validate \
25145             gate must route through the same substrate-primitive typed \
25146             dispatch on the :max-failures zero-floor arm",
25147        );
25148        spec.politicas = MeshPolicy {
25149            circuit_breaker: Some(CircuitBreaker {
25150                max_failures: 1,
25151                window: Duration::from_secs(60),
25152            }),
25153            ..MeshPolicy::default()
25154        };
25155        assert!(
25156            spec.validate().is_ok(),
25157            "validate_politicas must accept max_failures == 1 (the \
25158             lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
25159             accept-set)",
25160        );
25161    }
25162
25163    #[test]
25164    fn circuit_breaker_max_failures_projects_u32_by_copy() {
25165        // The by-copy pin: [`CircuitBreaker::max_failures`] returns
25166        // `u32` by copy — `u32` is `Copy` and the accessor must return
25167        // by value, not by reference. Peer of the sibling
25168        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
25169        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
25170        // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
25171        // optional-scalar axes, extended onto the peer
25172        // per-`CircuitBreaker` required-`u32` copy-invariant shape —
25173        // the accessor's returned `u32` must outlive `&self` (multiple
25174        // calls must return equal values from a dropped-`&self` copy,
25175        // since the returned scalar carries no borrow), and calling
25176        // the accessor twice on the same CircuitBreaker must yield the
25177        // same `u32` verbatim (idempotent, no side effects on `&self`).
25178        //
25179        // Pins against a future silent detour that returned `&u32`
25180        // (which would type-check but silently break every downstream
25181        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
25182        // first parameter is `u32`, and `&u32` would fold to a detached
25183        // copy at the call site with a `*` deref the sibling accessors
25184        // don't need), an accidental `.max_failures.wrapping_add(0)`
25185        // detour that returned a fresh copy through an arithmetic
25186        // no-op (breaking a future `const fn` regression), or a
25187        // one-arm-only accessor that returned a saturating value on
25188        // some sentinel input (breaking the pass-through invariant the
25189        // sibling required-scalar accessors carry).
25190        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
25191            let cb = CircuitBreaker {
25192                max_failures,
25193                window: Duration::from_secs(60),
25194            };
25195            let first = cb.max_failures();
25196            let second = cb.max_failures();
25197            assert_eq!(
25198                first, second,
25199                "CircuitBreaker::max_failures must be idempotent — two \
25200                 successive calls on the same &self must return the \
25201                 same u32",
25202            );
25203            assert_eq!(
25204                first, max_failures,
25205                "CircuitBreaker::max_failures must return :politicas \
25206                 :circuit-breaker :max-failures verbatim by copy — \
25207                 got {first}, expected {max_failures}",
25208            );
25209        }
25210    }
25211
25212    #[test]
25213    fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
25214        // The canonical per-`:politicas :circuit-breaker` `:window`
25215        // Envoy-outlier-detection rolling-observation-interval scalar
25216        // pin: [`CircuitBreaker::window`] must return the
25217        // `:politicas :circuit-breaker :window` typed `Duration`
25218        // verbatim, byte-equal to the raw field access across every
25219        // representative value in the accept-set — `Duration::from_millis(1)`
25220        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
25221        // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
25222        // gate carves out on the sibling `PolicyBreakerZeroWindow`
25223        // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
25224        // same gate carves out on the sibling
25225        // `PolicyBreakerWindowExceedsCap` refusal),
25226        // `Duration::ZERO` (a past-the-guard sentinel that pins the
25227        // accessor doesn't perform a silent bounds-collapse into
25228        // `Duration::from_millis(1)` on the zero arm — validate rejects
25229        // zero but the accessor must ship the raw slot verbatim so a
25230        // validate-time gate regression surfaces at the emit boundary
25231        // rather than being silently absorbed),
25232        // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
25233        // far above the 1h cap — that pins the accessor doesn't perform
25234        // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
25235        // at the return path).
25236        //
25237        // Second sub-struct required-scalar accessor pin on the M3
25238        // mesh-slot family — sibling in shape to the just-landed
25239        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
25240        // (3a74062) required-`u32` accessor pin on the peer
25241        // per-`CircuitBreaker` required-axis, extended onto the
25242        // per-sub-struct required-`Duration` axis. Pins against a
25243        // future silent detour that re-derived the observation window
25244        // from a peer axis (an accidental
25245        // `Duration::from_secs(self.max_failures as u64)` collapse that
25246        // read the breaker's trip count as an observation-interval
25247        // duration), a `Duration::ZERO → Duration::from_millis(1)`
25248        // cluster-default projection (which would silently absorb the
25249        // `PolicyBreakerZeroWindow` refusal case at the accessor
25250        // boundary), or a bounds-collapsing accessor that clamped the
25251        // return through `POLICY_BREAKER_WINDOW_MAX` (the
25252        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
25253        // must ship the raw slot verbatim).
25254        for window in [
25255            Duration::from_millis(1),
25256            POLICY_BREAKER_WINDOW_MAX,
25257            Duration::ZERO,
25258            Duration::from_secs(86_400),
25259        ] {
25260            let cb = CircuitBreaker {
25261                max_failures: 5,
25262                window,
25263            };
25264            assert_eq!(
25265                cb.window(),
25266                window,
25267                "CircuitBreaker::window must return :politicas \
25268                 :circuit-breaker :window verbatim (got {:?}, \
25269                 expected {window:?})",
25270                cb.window(),
25271            );
25272            assert_eq!(
25273                cb.window(),
25274                cb.window,
25275                "CircuitBreaker::window must byte-equal the raw \
25276                 .window field access across every value in the \
25277                 Duration accept-set",
25278            );
25279        }
25280    }
25281
25282    #[test]
25283    fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
25284        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
25285        // `:circuit-breaker :window` zero-floor arm must key off
25286        // [`CircuitBreaker::window`], not the raw `.window` field
25287        // access. Structurally: a `CircuitBreaker { window:
25288        // Duration::ZERO, .. }` embedded in a
25289        // `:politicas :circuit-breaker` slot must surface the
25290        // `PolicyBreakerZeroWindow` refusal exactly, and a
25291        // `CircuitBreaker { window: Duration::from_millis(1), .. }`
25292        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
25293        // accept-set) must pass validate. The pair jointly pins the
25294        // accessor + validate-gate composition: any future silent
25295        // detour that had the accessor return a fresh
25296        // `Duration::from_millis(1)` on the zero arm (a
25297        // `.window().max(Duration::from_millis(1))` collapse) would
25298        // silently absorb the `PolicyBreakerZeroWindow` refusal at the
25299        // accessor boundary and the validate gate would accept a
25300        // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
25301        // — the composition pin catches that at caixa-core build time.
25302        //
25303        // Peer of the sibling per-`CircuitBreaker`
25304        // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
25305        // pin on the peer required-scalar `:max-failures` axis — same
25306        // "the validate / shape-gate predicate must route through the
25307        // substrate-primitive typed dispatch" discipline extended onto
25308        // the peer per-`CircuitBreaker` required-`Duration` composition
25309        // axis.
25310        let mut spec = three_member_spec();
25311        spec.politicas = MeshPolicy {
25312            circuit_breaker: Some(CircuitBreaker {
25313                max_failures: 5,
25314                window: Duration::ZERO,
25315            }),
25316            ..MeshPolicy::default()
25317        };
25318        assert!(
25319            matches!(
25320                spec.validate(),
25321                Err(AplicacaoError::PolicyBreakerZeroWindow)
25322            ),
25323            "validate_politicas must reject window == Duration::ZERO \
25324             with PolicyBreakerZeroWindow — the accessor and the \
25325             validate gate must route through the same substrate-\
25326             primitive typed dispatch on the :window zero-floor arm",
25327        );
25328        spec.politicas = MeshPolicy {
25329            circuit_breaker: Some(CircuitBreaker {
25330                max_failures: 5,
25331                window: Duration::from_millis(1),
25332            }),
25333            ..MeshPolicy::default()
25334        };
25335        assert!(
25336            spec.validate().is_ok(),
25337            "validate_politicas must accept window == \
25338             Duration::from_millis(1) (the lower boundary of the \
25339             1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
25340        );
25341    }
25342
25343    #[test]
25344    fn circuit_breaker_window_projects_duration_by_copy() {
25345        // The by-copy pin: [`CircuitBreaker::window`] returns
25346        // `Duration` by copy — `Duration` is `Copy` and the accessor
25347        // must return by value, not by reference. Peer of the sibling
25348        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
25349        // (3a74062) by-copy pin on the peer required-scalar
25350        // `:max-failures` axis, extended onto the peer
25351        // per-`CircuitBreaker` required-`Duration` copy-invariant shape
25352        // — the accessor's returned `Duration` must outlive `&self`
25353        // (multiple calls must return equal values from a
25354        // dropped-`&self` copy, since the returned scalar carries no
25355        // borrow), and calling the accessor twice on the same
25356        // CircuitBreaker must yield the same `Duration` verbatim
25357        // (idempotent, no side effects on `&self`).
25358        //
25359        // Pins against a future silent detour that returned
25360        // `&Duration` (which would type-check but silently break every
25361        // downstream `Duration`-by-value consumer —
25362        // [`crate::render::require_positive_canonical_bounded_duration`]'s
25363        // first parameter is `Duration`, and `&Duration` would fold to
25364        // a detached copy at the call site with a `*` deref the sibling
25365        // accessors don't need), an accidental `.window + Duration::ZERO`
25366        // detour that returned a fresh copy through an arithmetic
25367        // no-op (breaking a future `const fn` regression), or a
25368        // one-arm-only accessor that returned a saturating value on
25369        // some sentinel input (breaking the pass-through invariant the
25370        // sibling required-scalar accessors carry).
25371        for window in [
25372            Duration::from_millis(1),
25373            POLICY_BREAKER_WINDOW_MAX,
25374            Duration::ZERO,
25375            Duration::from_secs(86_400),
25376        ] {
25377            let cb = CircuitBreaker {
25378                max_failures: 5,
25379                window,
25380            };
25381            let first = cb.window();
25382            let second = cb.window();
25383            assert_eq!(
25384                first, second,
25385                "CircuitBreaker::window must be idempotent — two \
25386                 successive calls on the same &self must return the \
25387                 same Duration",
25388            );
25389            assert_eq!(
25390                first, window,
25391                "CircuitBreaker::window must return :politicas \
25392                 :circuit-breaker :window verbatim by copy — \
25393                 got {first:?}, expected {window:?}",
25394            );
25395        }
25396    }
25397
25398    #[test]
25399    fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
25400        // Apex-identity pair-invariant pin composing both substrate-
25401        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
25402        // and [`WitContract::destination`] — at the emit-side call shape
25403        // every per-`(:de, :para)` CNP L4 port reader now takes. The
25404        // invariant, evaluated per-edge:
25405        //
25406        //   spec.port_for_destination(c.destination()) == expected_port
25407        //
25408        // where `expected_port` is `entrada.port` when
25409        // `c.destination() == entrada.destination()` and
25410        // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
25411        // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
25412        // pin on the per-`:entrada` axis — that pin encodes the apex
25413        // ingress L4 identity via `entrada.destination()`; this pin
25414        // encodes the per-edge L4 identity via `c.destination()`, and
25415        // both compose on the same substrate-primitive resolver so a
25416        // future refactor that silently split either accessor's apex
25417        // behavior surfaces at caixa-core build time.
25418        let mut spec = three_member_spec();
25419        if let Some(e) = spec.entrada.as_mut() {
25420            e.para = "cart".into();
25421            e.port = 8443;
25422        }
25423        let apex_contract = WitContract {
25424            de: "checkout".into(),
25425            para: "cart".into(),
25426            wit: "wasi:http/proxy".into(),
25427            endpoint: Some("/hello".into()),
25428            subject: None,
25429            slot: None,
25430        };
25431        assert_eq!(
25432            spec.port_for_destination(apex_contract.destination()),
25433            8443,
25434            "`spec.port_for_destination(c.destination())` must equal \
25435             `entrada.port` when the contract callee names the ingress \
25436             apex — the CNP per-edge L4 port and the HTTPRoute apex \
25437             backendRef port share this substrate-primitive resolver.",
25438        );
25439        let non_apex_contract = WitContract {
25440            de: "cart".into(),
25441            para: "payment".into(),
25442            wit: "wasi:http/proxy".into(),
25443            endpoint: Some("/charge".into()),
25444            subject: None,
25445            slot: None,
25446        };
25447        assert_eq!(
25448            spec.port_for_destination(non_apex_contract.destination()),
25449            DEFAULT_SERVICO_PORT,
25450            "`spec.port_for_destination(c.destination())` must fall back \
25451             to the substrate-canonical port floor when the contract \
25452             callee is not the ingress apex — the resolver's non-apex \
25453             arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
25454        );
25455    }
25456
25457    #[test]
25458    fn membro_key_consts_are_lower_camel_case_shape() {
25459        // Shape-pin: every `MEMBRO_KEY_*` const must be a
25460        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
25461        // `kebab-case` hyphens, no leading colon, no `PascalCase`
25462        // leading capital, no whitespace / dots) — the canonical shape
25463        // the `#[serde(rename_all = "camelCase")]` derive produces on
25464        // [`Membro`]. A future flip to a non-camelCase attribute at
25465        // the derive surfaces both here (this test fails on the
25466        // stale-constant shape) and at
25467        // `membro_serde_keys_match_lifted_membro_key_consts` (that test
25468        // fails on the mismatch between const and derive). Peer with
25469        // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
25470        // on the sibling `SupervisorSpec` top-level axis.
25471        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
25472            assert!(
25473                !key.is_empty(),
25474                "MEMBRO_KEY_* must be non-empty (got {key:?})"
25475            );
25476            let first = key.chars().next().unwrap();
25477            assert!(
25478                first.is_ascii_lowercase(),
25479                "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
25480                 (got {key:?}, leads with {first:?})",
25481            );
25482            assert!(
25483                key.chars().all(|c| c.is_ascii_alphanumeric()),
25484                "MEMBRO_KEY_* must be ASCII-alphanumeric only \
25485                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
25486            );
25487        }
25488    }
25489
25490    // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
25491
25492    #[test]
25493    fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
25494        // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
25495        // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
25496        // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
25497        // keys the `#[serde(rename_all = "camelCase")]` attribute on
25498        // [`WitContract`] emits for the required-triad. The three
25499        // sibling payload-arm keys already pin under
25500        // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
25501        // `STORE_FIELD_NAME` — pin all six alongside so a future
25502        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
25503        // verbatim-field-name flip at the derive attribute (any of which
25504        // would silently break every downstream JSON consumer that
25505        // reaches for one of the six via `Value::get(...)`) surfaces
25506        // here as a build-time test failure at `aplicacao.rs`, not as an
25507        // apply-time `.get(<stale-canonical-const>)` returning `None`
25508        // far from the derive-attr drift's commit. Peer with the sibling
25509        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
25510        // pin on the M3 `:membros` per-entry axis — same discipline the
25511        // `Membro` per-entry lift established, extended here to the
25512        // sibling M3 `WitContract` per-`:contratos` entry axis, the last
25513        // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
25514        // axis on the Aplicacao surface without a lifted serde-key peer.
25515        let c = WitContract {
25516            de: "cart".into(),
25517            para: "catalog".into(),
25518            wit: "wasi:http/proxy".into(),
25519            endpoint: Some("/lookup".into()),
25520            subject: None,
25521            slot: None,
25522        };
25523        let json = serde_json::to_string(&c).unwrap();
25524        for key in [
25525            crate::CONTRATO_KEY_DE,
25526            crate::CONTRATO_KEY_PARA,
25527            crate::CONTRATO_KEY_WIT,
25528            WitTarget::HTTP_FIELD_NAME,
25529        ] {
25530            let quoted = format!("\"{key}\"");
25531            assert!(
25532                json.contains(&quoted),
25533                "serialized WitContract must carry the lifted \
25534                 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
25535                 {quoted} verbatim in the JSON emission (got: {json})",
25536            );
25537        }
25538
25539        // Pin the two remaining payload-arm keys by round-tripping a
25540        // `WitContract` under each payload-shape (pub-sub, store) — the
25541        // required-triad appears on every emission but the payload arms
25542        // only surface when their `Option<String>` field is `Some`.
25543        let pubsub = WitContract {
25544            de: "cart".into(),
25545            para: "events".into(),
25546            wit: "nats:pub-sub".into(),
25547            endpoint: None,
25548            subject: Some("orders.placed".into()),
25549            slot: None,
25550        };
25551        let pubsub_json = serde_json::to_string(&pubsub).unwrap();
25552        let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
25553        assert!(
25554            pubsub_json.contains(&pubsub_quoted),
25555            "serialized pub-sub WitContract must carry the lifted \
25556             WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
25557             verbatim in the JSON emission (got: {pubsub_json})",
25558        );
25559        let store = WitContract {
25560            de: "cart".into(),
25561            para: "sessions".into(),
25562            wit: "wasi:keyvalue/store".into(),
25563            endpoint: None,
25564            subject: None,
25565            slot: Some("cart/$id".into()),
25566        };
25567        let store_json = serde_json::to_string(&store).unwrap();
25568        let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
25569        assert!(
25570            store_json.contains(&store_quoted),
25571            "serialized store WitContract must carry the lifted \
25572             WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
25573             verbatim in the JSON emission (got: {store_json})",
25574        );
25575    }
25576
25577    #[test]
25578    fn contrato_key_consts_are_pairwise_distinct() {
25579        // Cross-axis drift-detection pin: a future collapse of the six
25580        // canonical [`WitContract`] per-entry byte-strings onto the same
25581        // value (e.g. an accidental copy-paste flip of
25582        // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
25583        // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
25584        // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
25585        // every downstream probe on one axis onto the sibling axis's
25586        // overlay entry and pass every propagation-probe test that
25587        // expected only the stale axis's value. Peer of the sibling
25588        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
25589        // widened here to the six-way axis the `WitContract`
25590        // required-triad + `WitTarget` payload-triad jointly cover.
25591        let all = [
25592            crate::CONTRATO_KEY_DE,
25593            crate::CONTRATO_KEY_PARA,
25594            crate::CONTRATO_KEY_WIT,
25595            WitTarget::HTTP_FIELD_NAME,
25596            WitTarget::PUBSUB_FIELD_NAME,
25597            WitTarget::STORE_FIELD_NAME,
25598        ];
25599        for (i, a) in all.iter().enumerate() {
25600            for b in all.iter().skip(i + 1) {
25601                assert_ne!(
25602                    a, b,
25603                    "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
25604                     must be pairwise-distinct canonical byte-sequences \
25605                     — got `{a}` == `{b}`",
25606                );
25607            }
25608        }
25609    }
25610
25611    #[test]
25612    fn contrato_key_consts_are_lower_camel_case_shape() {
25613        // Shape-pin: every `CONTRATO_KEY_*` (and every peer
25614        // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
25615        // byte-sequence (no `snake_case` underscores, no `kebab-case`
25616        // hyphens, no leading colon, no `PascalCase` leading capital, no
25617        // whitespace / dots) — the canonical shape the
25618        // `#[serde(rename_all = "camelCase")]` derive produces on
25619        // [`WitContract`]. A future flip to a non-camelCase attribute at
25620        // the derive surfaces both here (this test fails on the
25621        // stale-constant shape) and at
25622        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
25623        // (that test fails on the mismatch between const and derive).
25624        // Peer with `membro_key_consts_are_lower_camel_case_shape`
25625        // (ce80ca0) on the sibling `Membro` per-entry axis.
25626        for key in [
25627            crate::CONTRATO_KEY_DE,
25628            crate::CONTRATO_KEY_PARA,
25629            crate::CONTRATO_KEY_WIT,
25630            WitTarget::HTTP_FIELD_NAME,
25631            WitTarget::PUBSUB_FIELD_NAME,
25632            WitTarget::STORE_FIELD_NAME,
25633        ] {
25634            assert!(
25635                !key.is_empty(),
25636                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
25637                 non-empty (got {key:?})"
25638            );
25639            let first = key.chars().next().unwrap();
25640            assert!(
25641                first.is_ascii_lowercase(),
25642                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
25643                 with an ASCII-lowercase byte (got {key:?}, leads with \
25644                 {first:?})",
25645            );
25646            assert!(
25647                key.chars().all(|c| c.is_ascii_alphanumeric()),
25648                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
25649                 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
25650                 whitespace (got {key:?})",
25651            );
25652        }
25653    }
25654
25655    // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
25656
25657    #[test]
25658    fn entrada_serde_keys_match_lifted_entrada_key_consts() {
25659        // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
25660        // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
25661        // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
25662        // name the exact camelCase JSON keys the
25663        // `#[serde(rename_all = "camelCase")]` attribute on
25664        // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
25665        // pin that each canonical byte-sequence appears verbatim in the
25666        // JSON — a future accidental `rename_all = "snake_case"` /
25667        // `"kebab-case"` / verbatim-field-name flip at the derive
25668        // attribute (any of which would silently break every downstream
25669        // JSON consumer that reaches for one of the four consts via
25670        // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
25671        // emitter's per-Aplicacao hostname/paths/port projection, the
25672        // future `app-operator` reconciler's per-Aplicacao ingress
25673        // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
25674        // materializer's admission-time cross-check) surfaces here as
25675        // a build-time test failure at `aplicacao.rs`, not as an
25676        // apply-time `.get(<stale-canonical-const>)` returning `None`
25677        // far from the derive-attr drift's commit. Peer with the
25678        // sibling
25679        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
25680        // (ca463a4) and
25681        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
25682        // pins on the M3 collection-slot atom axes — same discipline
25683        // both collection-slot lifts established, extended here to the
25684        // singleton `:entrada` mesh-slot atom axis, the last M3
25685        // typed-struct top-level `#[serde(rename_all = "camelCase")]`
25686        // axis on the Aplicacao surface without a lifted serde-key
25687        // peer.
25688        let e = Entrada {
25689            host: "checkout.quero.cloud".into(),
25690            para: "cart".into(),
25691            paths: vec!["/cart".into()],
25692            port: 8080,
25693        };
25694        let json = serde_json::to_string(&e).unwrap();
25695        for key in [
25696            crate::ENTRADA_KEY_HOST,
25697            crate::ENTRADA_KEY_PARA,
25698            crate::ENTRADA_KEY_PATHS,
25699            crate::ENTRADA_KEY_PORT,
25700        ] {
25701            let quoted = format!("\"{key}\"");
25702            assert!(
25703                json.contains(&quoted),
25704                "serialized Entrada must carry the lifted ENTRADA_KEY_* \
25705                 byte-sequence {quoted} verbatim in the JSON emission \
25706                 (got: {json})",
25707            );
25708        }
25709    }
25710
25711    #[test]
25712    fn entrada_key_consts_are_pairwise_distinct() {
25713        // Cross-axis drift-detection pin: a future collapse of the four
25714        // canonical [`Entrada`] singleton byte-strings onto the same
25715        // value (e.g. an accidental copy-paste flip of
25716        // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
25717        // silently reroute every downstream probe on one axis onto the
25718        // sibling axis's overlay entry and pass every propagation-probe
25719        // test that expected only the stale axis's value — the
25720        // Gateway/HTTPRoute emitter would read the hostname string
25721        // where the destination-Servico name was expected (or vice
25722        // versa), the admission-webhook cross-check would compare the
25723        // wrong pair of values, and the resulting Gateway resource
25724        // would either be admitted with garbage or rejected at the
25725        // controller far from the rebrand commit's source. Peer of the
25726        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
25727        // tetrad (40cc4e5), the two-way distinct pin on the
25728        // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
25729        // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
25730        // triad (ca463a4).
25731        let all = [
25732            crate::ENTRADA_KEY_HOST,
25733            crate::ENTRADA_KEY_PARA,
25734            crate::ENTRADA_KEY_PATHS,
25735            crate::ENTRADA_KEY_PORT,
25736        ];
25737        for (i, a) in all.iter().enumerate() {
25738            for b in all.iter().skip(i + 1) {
25739                assert_ne!(
25740                    a, b,
25741                    "ENTRADA_KEY_* consts must be pairwise-distinct \
25742                     canonical byte-sequences — got `{a}` == `{b}`",
25743                );
25744            }
25745        }
25746    }
25747
25748    #[test]
25749    fn entrada_key_consts_are_lower_camel_case_shape() {
25750        // Shape-pin: every `ENTRADA_KEY_*` const must be a
25751        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
25752        // `kebab-case` hyphens, no leading colon, no `PascalCase`
25753        // leading capital, no whitespace / dots) — the canonical shape
25754        // the `#[serde(rename_all = "camelCase")]` derive produces on
25755        // [`Entrada`]. A future flip to a non-camelCase attribute at
25756        // the derive surfaces both here (this test fails on the
25757        // stale-constant shape) and at
25758        // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
25759        // test fails on the mismatch between const and derive). Peer
25760        // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
25761        // and `contrato_key_consts_are_lower_camel_case_shape`
25762        // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
25763        // entry axes.
25764        for key in [
25765            crate::ENTRADA_KEY_HOST,
25766            crate::ENTRADA_KEY_PARA,
25767            crate::ENTRADA_KEY_PATHS,
25768            crate::ENTRADA_KEY_PORT,
25769        ] {
25770            assert!(
25771                !key.is_empty(),
25772                "ENTRADA_KEY_* must be non-empty (got {key:?})"
25773            );
25774            let first = key.chars().next().unwrap();
25775            assert!(
25776                first.is_ascii_lowercase(),
25777                "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
25778                 (got {key:?}, leads with {first:?})",
25779            );
25780            assert!(
25781                key.chars().all(|c| c.is_ascii_alphanumeric()),
25782                "ENTRADA_KEY_* must be ASCII-alphanumeric only \
25783                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
25784            );
25785        }
25786    }
25787
25788    // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
25789
25790    #[test]
25791    fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
25792        // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
25793        // ([`crate::POLITICAS_KEY_TIMEOUT`] /
25794        // [`crate::POLITICAS_KEY_RETRIES`] /
25795        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
25796        // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
25797        // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
25798        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
25799        // on [`MeshPolicy`] emits. Three of the five axes
25800        // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
25801        // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
25802        // camelCase transforms — the derive-attribute is load-bearing
25803        // on those, unlike the sibling `Entrada` / `Membro` /
25804        // `WitContract` structs whose fields are all lowercase-single-
25805        // word and where the derive is a no-op on every axis.
25806        // Serialize a fully-populated [`MeshPolicy`] (every axis
25807        // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
25808        // on none of the five slots) and pin that each canonical
25809        // byte-sequence appears verbatim in the JSON — a future
25810        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
25811        // verbatim-field-name flip at the derive attribute (any of
25812        // which would silently break every downstream JSON consumer
25813        // that reaches for one of the five consts via
25814        // `Value::get(...)` — the future M4 per-edge `:politicas`
25815        // overlay projection onto Cilium `L7Rules` and Gateway API
25816        // `HTTPRoute` backend timeouts, the future
25817        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
25818        // admission-time mesh-policy cross-check, the future
25819        // `feira lint` per-`:politicas` bound-check gate) surfaces here
25820        // as a build-time test failure at `aplicacao.rs`, not as an
25821        // apply-time `.get(<stale-canonical-const>)` returning `None`
25822        // far from the derive-attr drift's commit. Peer with the
25823        // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
25824        // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
25825        // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
25826        // (ce80ca0) pins on the M3 collection-slot / singleton-slot
25827        // atom axes — same discipline every M3 sibling lift
25828        // established, extended here to the singleton `:politicas`
25829        // mesh-slot atom axis, closing the last M3 typed-struct
25830        // top-level `#[serde(rename_all = "camelCase")]` axis on the
25831        // Aplicacao surface without a lifted serde-key peer.
25832        let p = MeshPolicy {
25833            timeout: Some(Duration::from_secs(30)),
25834            retries: Some(3),
25835            circuit_breaker: Some(CircuitBreaker {
25836                max_failures: 5,
25837                window: Duration::from_secs(60),
25838            }),
25839            mtls_required: Some(true),
25840            rate_limit: Some(RateLimit {
25841                rate: 100,
25842                window: Duration::from_secs(1),
25843            }),
25844        };
25845        let json = serde_json::to_string(&p).unwrap();
25846        for key in [
25847            crate::POLITICAS_KEY_TIMEOUT,
25848            crate::POLITICAS_KEY_RETRIES,
25849            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
25850            crate::POLITICAS_KEY_MTLS_REQUIRED,
25851            crate::POLITICAS_KEY_RATE_LIMIT,
25852        ] {
25853            let quoted = format!("\"{key}\"");
25854            assert!(
25855                json.contains(&quoted),
25856                "serialized MeshPolicy must carry the lifted \
25857                 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
25858                 JSON emission (got: {json})",
25859            );
25860        }
25861    }
25862
25863    #[test]
25864    fn politicas_key_consts_are_pairwise_distinct() {
25865        // Cross-axis drift-detection pin: a future collapse of the five
25866        // canonical [`MeshPolicy`] singleton byte-strings onto the same
25867        // value (e.g. an accidental copy-paste flip of
25868        // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
25869        // would silently reroute every downstream probe on one axis
25870        // onto the sibling axis's overlay entry and pass every
25871        // propagation-probe test that expected only the stale axis's
25872        // value — the M4 per-edge `:politicas` overlay projection would
25873        // read the retry-count string where the timeout duration was
25874        // expected (or vice versa), the CR materializer's admission
25875        // cross-check would compare the wrong pair of values, and the
25876        // resulting mesh reconciler would either bind the wrong axis
25877        // or reject the resource at reconcile far from the rebrand
25878        // commit's source. Peer of the sibling four-way distinct pin
25879        // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
25880        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
25881        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
25882        // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
25883        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
25884        let all = [
25885            crate::POLITICAS_KEY_TIMEOUT,
25886            crate::POLITICAS_KEY_RETRIES,
25887            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
25888            crate::POLITICAS_KEY_MTLS_REQUIRED,
25889            crate::POLITICAS_KEY_RATE_LIMIT,
25890        ];
25891        for (i, a) in all.iter().enumerate() {
25892            for b in all.iter().skip(i + 1) {
25893                assert_ne!(
25894                    a, b,
25895                    "POLITICAS_KEY_* consts must be pairwise-distinct \
25896                     canonical byte-sequences — got `{a}` == `{b}`",
25897                );
25898            }
25899        }
25900    }
25901
25902    #[test]
25903    fn politicas_key_consts_are_lower_camel_case_shape() {
25904        // Shape-pin: every `POLITICAS_KEY_*` const must be a
25905        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
25906        // `kebab-case` hyphens, no leading colon, no `PascalCase`
25907        // leading capital, no whitespace / dots) — the canonical shape
25908        // the `#[serde(rename_all = "camelCase")]` derive produces on
25909        // [`MeshPolicy`]. A future flip to a non-camelCase attribute
25910        // at the derive surfaces both here (this test fails on the
25911        // stale-constant shape) and at
25912        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
25913        // (that test fails on the mismatch between const and derive).
25914        // Peer with `entrada_key_consts_are_lower_camel_case_shape`
25915        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
25916        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
25917        // (ca463a4) on the sibling M3 typed-struct axes.
25918        for key in [
25919            crate::POLITICAS_KEY_TIMEOUT,
25920            crate::POLITICAS_KEY_RETRIES,
25921            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
25922            crate::POLITICAS_KEY_MTLS_REQUIRED,
25923            crate::POLITICAS_KEY_RATE_LIMIT,
25924        ] {
25925            assert!(
25926                !key.is_empty(),
25927                "POLITICAS_KEY_* must be non-empty (got {key:?})"
25928            );
25929            let first = key.chars().next().unwrap();
25930            assert!(
25931                first.is_ascii_lowercase(),
25932                "POLITICAS_KEY_* must lead with an ASCII-lowercase \
25933                 byte (got {key:?}, leads with {first:?})",
25934            );
25935            assert!(
25936                key.chars().all(|c| c.is_ascii_alphanumeric()),
25937                "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
25938                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
25939            );
25940        }
25941    }
25942
25943    // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
25944
25945    #[test]
25946    fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
25947        // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
25948        // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
25949        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
25950        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
25951        // [`CircuitBreaker`] emits inside the
25952        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
25953        // two axes (`max_failures` → `maxFailures`) is a non-trivial
25954        // camelCase transform — the derive-attribute is load-bearing on
25955        // that axis, unlike the sibling `window` field where the derive
25956        // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
25957        // pin that each canonical byte-sequence appears verbatim in the
25958        // JSON — a future accidental `rename_all = "snake_case"` /
25959        // `"kebab-case"` / verbatim-field-name flip at the derive
25960        // attribute (any of which would silently break every downstream
25961        // JSON consumer that reaches for one of the two consts via
25962        // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
25963        // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
25964        // per-edge `:politicas` overlay projection onto the mesh's
25965        // per-backend consecutive-failure-counter tripping threshold, the
25966        // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
25967        // admission-time breaker cross-check, the future `feira lint`
25968        // per-`:politicas :circuit-breaker` bound-check gate) surfaces
25969        // here as a build-time test failure at `aplicacao.rs`, not as an
25970        // apply-time `.get(<stale-canonical-const>)` returning `None`
25971        // far from the derive-attr drift's commit. Peer with the sibling
25972        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
25973        // (b55cca7) parent-axis pin — that test pins the outer
25974        // sub-block key the derive on [`MeshPolicy`] emits, this test
25975        // pins the inner keys the derive on the payload type emits, so
25976        // the two together lock the whole [`MeshPolicy`] breaker-tuning
25977        // shape end-to-end at build time.
25978        let cb = CircuitBreaker {
25979            max_failures: 5,
25980            window: Duration::from_secs(60),
25981        };
25982        let json = serde_json::to_string(&cb).unwrap();
25983        for key in [
25984            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
25985            crate::CIRCUIT_BREAKER_KEY_WINDOW,
25986        ] {
25987            let quoted = format!("\"{key}\"");
25988            assert!(
25989                json.contains(&quoted),
25990                "serialized CircuitBreaker must carry the lifted \
25991                 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
25992                 in the JSON emission (got: {json})",
25993            );
25994        }
25995    }
25996
25997    #[test]
25998    fn circuit_breaker_key_consts_are_pairwise_distinct() {
25999        // Cross-axis drift-detection pin: a future collapse of the two
26000        // canonical [`CircuitBreaker`] sub-block byte-strings onto the
26001        // same value (e.g. an accidental copy-paste flip of
26002        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
26003        // `"maxFailures"`) would silently reroute every downstream
26004        // probe on one axis onto the sibling axis's overlay entry and
26005        // pass every propagation-probe test that expected only the
26006        // stale axis's value — the M4 per-edge `:politicas` overlay
26007        // projection would read the failure-count where the window
26008        // duration was expected (or vice versa), the CR materializer's
26009        // admission cross-check would compare the wrong pair of values,
26010        // and the resulting mesh reconciler would either bind the wrong
26011        // axis or reject the resource at reconcile far from the rebrand
26012        // commit's source. Peer of the sibling five-way distinct pin on
26013        // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
26014        // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
26015        // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
26016        // six-way distinct pin on the `CONTRATO_KEY_*` triad +
26017        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
26018        let all = [
26019            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
26020            crate::CIRCUIT_BREAKER_KEY_WINDOW,
26021        ];
26022        for (i, a) in all.iter().enumerate() {
26023            for b in all.iter().skip(i + 1) {
26024                assert_ne!(
26025                    a, b,
26026                    "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
26027                     canonical byte-sequences — got `{a}` == `{b}`",
26028                );
26029            }
26030        }
26031    }
26032
26033    #[test]
26034    fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
26035        // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
26036        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26037        // `kebab-case` hyphens, no leading colon, no `PascalCase`
26038        // leading capital, no whitespace / dots) — the canonical shape
26039        // the `#[serde(rename_all = "camelCase")]` derive produces on
26040        // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
26041        // at the derive surfaces both here (this test fails on the
26042        // stale-constant shape) and at
26043        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
26044        // (that test fails on the mismatch between const and derive).
26045        // Peer with `politicas_key_consts_are_lower_camel_case_shape`
26046        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
26047        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
26048        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
26049        // (ca463a4) on the sibling M3 typed-struct axes.
26050        for key in [
26051            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
26052            crate::CIRCUIT_BREAKER_KEY_WINDOW,
26053        ] {
26054            assert!(
26055                !key.is_empty(),
26056                "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
26057            );
26058            let first = key.chars().next().unwrap();
26059            assert!(
26060                first.is_ascii_lowercase(),
26061                "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
26062                 byte (got {key:?}, leads with {first:?})",
26063            );
26064            assert!(
26065                key.chars().all(|c| c.is_ascii_alphanumeric()),
26066                "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
26067                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26068            );
26069        }
26070    }
26071
26072    // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
26073
26074    #[test]
26075    fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
26076        // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
26077        // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
26078        // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
26079        // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
26080        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
26081        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
26082        // [`Placement`] emits. One of the four axes (`shard_key` →
26083        // `shardKey`) is a non-trivial camelCase transform — the
26084        // derive-attribute is load-bearing on that axis, unlike the
26085        // sibling `estrategia` / `clusters` / `affinity` axes whose
26086        // source-side field names carry no `_` and where the derive is a
26087        // no-op. Serialize a fully-populated [`Placement`] (both
26088        // `Option`-carrying axes `Some(_)` so
26089        // `skip_serializing_if = "Option::is_none"` fires on neither of
26090        // the two optional slots) and pin that each canonical
26091        // byte-sequence appears verbatim in the JSON — a future
26092        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
26093        // verbatim-field-name flip at the derive attribute (any of which
26094        // would silently break every downstream consumer that reaches
26095        // for one of the four consts via
26096        // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
26097        // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
26098        // aggregator's per-cluster fanout filter keying off
26099        // `placement.clusters`, the M3 shard-pool dispatch materializer
26100        // keying off `placement.shardKey`, the M3 Adaptive compression
26101        // pass weighting off `placement.affinity`, every downstream
26102        // dispatcher branching on `placement.estrategia`, the future
26103        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
26104        // admission-time placement cross-check, the future `feira lint`
26105        // per-`:placement` bound-check gate) surfaces here as a
26106        // build-time test failure at `aplicacao.rs`, not as an
26107        // apply-time `.get(<stale-canonical-const>)` returning `None`
26108        // far from the derive-attr drift's commit. Peer with the sibling
26109        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
26110        // (b55cca7),
26111        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
26112        // (468e959),
26113        // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
26114        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26115        // (ca463a4), and
26116        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
26117        // pins on the M3 collection-slot / singleton-slot atom axes —
26118        // closes the last M3 typed-struct top-level
26119        // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
26120        // surface without a drift-detection pin.
26121        let p = Placement {
26122            estrategia: PlacementStrategy::Sharded,
26123            clusters: vec!["rio".into(), "mar".into()],
26124            affinity: Some("data-locality".into()),
26125            shard_key: Some("$tenantId".into()),
26126        };
26127        let json = serde_json::to_string(&p).unwrap();
26128        for key in [
26129            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
26130            crate::M3_PLACEMENT_KEY_CLUSTERS,
26131            crate::M3_PLACEMENT_KEY_AFFINITY,
26132            crate::M3_PLACEMENT_KEY_SHARD_KEY,
26133        ] {
26134            let quoted = format!("\"{key}\"");
26135            assert!(
26136                json.contains(&quoted),
26137                "serialized Placement must carry the lifted \
26138                 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
26139                 the JSON emission (got: {json})",
26140            );
26141        }
26142    }
26143
26144    #[test]
26145    fn m3_placement_key_consts_are_pairwise_distinct() {
26146        // Cross-axis drift-detection pin: a future collapse of the four
26147        // canonical [`Placement`] sub-block byte-strings onto the same
26148        // value (e.g. an accidental copy-paste flip of
26149        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
26150        // `"affinity"`) would silently reroute every downstream probe on
26151        // one axis onto the sibling axis's overlay entry and pass every
26152        // propagation-probe test that expected only the stale axis's
26153        // value — the M3 shard-pool dispatch materializer would read the
26154        // affinity placement-hint where the shard-selection template was
26155        // expected (or vice versa), the M3 Adaptive compression pass's
26156        // cross-check would compare the wrong pair of values, and the
26157        // resulting placement engine would either bind the wrong axis or
26158        // reject the resource at reconcile far from the rebrand commit's
26159        // source. Peer of the sibling two-way distinct pin on the
26160        // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
26161        // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
26162        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
26163        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
26164        // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
26165        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
26166        let all = [
26167            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
26168            crate::M3_PLACEMENT_KEY_CLUSTERS,
26169            crate::M3_PLACEMENT_KEY_AFFINITY,
26170            crate::M3_PLACEMENT_KEY_SHARD_KEY,
26171        ];
26172        for (i, a) in all.iter().enumerate() {
26173            for b in all.iter().skip(i + 1) {
26174                assert_ne!(
26175                    a, b,
26176                    "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
26177                     canonical byte-sequences — got `{a}` == `{b}`",
26178                );
26179            }
26180        }
26181    }
26182
26183    #[test]
26184    fn m3_placement_key_consts_are_lower_camel_case_shape() {
26185        // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
26186        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26187        // `kebab-case` hyphens, no leading colon, no `PascalCase`
26188        // leading capital, no whitespace / dots) — the canonical shape
26189        // the `#[serde(rename_all = "camelCase")]` derive produces on
26190        // [`Placement`]. A future flip to a non-camelCase attribute at
26191        // the derive surfaces both here (this test fails on the stale-
26192        // constant shape) and at
26193        // `placement_serde_keys_match_lifted_m3_placement_key_consts`
26194        // (that test fails on the mismatch between const and derive).
26195        // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
26196        // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
26197        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
26198        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
26199        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
26200        // (ca463a4) on the sibling M3 typed-struct axes.
26201        for key in [
26202            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
26203            crate::M3_PLACEMENT_KEY_CLUSTERS,
26204            crate::M3_PLACEMENT_KEY_AFFINITY,
26205            crate::M3_PLACEMENT_KEY_SHARD_KEY,
26206        ] {
26207            assert!(
26208                !key.is_empty(),
26209                "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
26210            );
26211            let first = key.chars().next().unwrap();
26212            assert!(
26213                first.is_ascii_lowercase(),
26214                "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
26215                 byte (got {key:?}, leads with {first:?})",
26216            );
26217            assert!(
26218                key.chars().all(|c| c.is_ascii_alphanumeric()),
26219                "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
26220                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26221            );
26222        }
26223    }
26224
26225    // ── AplicacaoSpec::port_for_destination — the substrate-canonical
26226    //    destination-facing L4 port resolver every per-Aplicacao renderer
26227    //    reaching for a per-destination Servico TCP port axis routes
26228    //    through. The four pin tests below fix the four-way accept-set
26229    //    the resolver must always honor: (:entrada-para-matches,
26230    //    :entrada-para-mismatches, :entrada-none-so-fallback,
26231    //    :entrada-port-non-default-honored) — drift on any arm surfaces
26232    //    at caixa-core build time rather than at cluster-apply time.
26233
26234    #[test]
26235    fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
26236        // The typed `:entrada` block's `:para "cart"` matches the
26237        // queried destination, so the resolver returns the author-
26238        // declared `:port` scalar verbatim — the canonical "the
26239        // destination Servico IS the ingress apex, honor the typed
26240        // listener port" arm of the port-resolution dispatch.
26241        let mut spec = three_member_spec();
26242        if let Some(e) = spec.entrada.as_mut() {
26243            e.para = "cart".into();
26244            e.port = 9090;
26245        }
26246        assert_eq!(
26247            spec.port_for_destination("cart"),
26248            9090,
26249            "port_for_destination(entrada.para) must return entrada.port \
26250             verbatim, not the DEFAULT_SERVICO_PORT fallback"
26251        );
26252    }
26253
26254    #[test]
26255    fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
26256        // The typed `:entrada` block names `:para "cart"`, but the
26257        // queried destination is `"payment"` — a Servico that
26258        // participates in the mesh graph but is not the ingress apex.
26259        // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
26260        // canonical port floor, closing the "non-apex destination reads
26261        // the substrate default" arm. Same fixture the peer
26262        // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
26263        // pin at caixa-mesh exercises through the CNP emit-side path;
26264        // this pin exercises the shared underlying resolver directly.
26265        let spec = three_member_spec();
26266        assert_eq!(
26267            spec.port_for_destination("payment"),
26268            DEFAULT_SERVICO_PORT,
26269            "port_for_destination(non-apex-destination) must route \
26270             through the lifted DEFAULT_SERVICO_PORT canonical port floor"
26271        );
26272    }
26273
26274    #[test]
26275    fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
26276        // Internal-only Aplicacao — no `:entrada` block declared. Every
26277        // per-destination port query falls back to the lifted
26278        // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
26279        // the Aplicacao surface admits `:entrada None` (internal mesh
26280        // with no external gateway); every downstream renderer's per-
26281        // destination port axis must still resolve to a well-defined
26282        // scalar even without an ingress apex.
26283        let mut spec = three_member_spec();
26284        spec.entrada = None;
26285        assert_eq!(
26286            spec.port_for_destination("cart"),
26287            DEFAULT_SERVICO_PORT,
26288            "port_for_destination on an internal-only Aplicacao must \
26289             fall back to the lifted DEFAULT_SERVICO_PORT floor for \
26290             every destination"
26291        );
26292        assert_eq!(
26293            spec.port_for_destination("payment"),
26294            DEFAULT_SERVICO_PORT,
26295            "port_for_destination on an internal-only Aplicacao must \
26296             fall back uniformly across every destination — the fallback \
26297             is not entrada-shape-conditional"
26298        );
26299    }
26300
26301    #[test]
26302    fn port_for_destination_honors_non_default_entrada_port_verbatim() {
26303        // Structural pin against a hypothetical future refactor that
26304        // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
26305        // the resolver (a "normalize to the default when the author's
26306        // port matches the substrate default" collapse) — that would
26307        // break renderer sites that carry meaning on the emitted port
26308        // value beyond bare equality (a future per-cluster listener-
26309        // audit that keys off the author-declared port, not the
26310        // resolved-with-fallback port). Pin that a non-default
26311        // entrada.port is returned verbatim so drift here surfaces at
26312        // caixa-core build time.
26313        let mut spec = three_member_spec();
26314        if let Some(e) = spec.entrada.as_mut() {
26315            e.para = "cart".into();
26316            e.port = 8443;
26317        }
26318        assert_ne!(
26319            8443, DEFAULT_SERVICO_PORT,
26320            "test fixture must probe a port distinct from \
26321             DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
26322        );
26323        assert_eq!(
26324            spec.port_for_destination("cart"),
26325            8443,
26326            "port_for_destination(entrada.para) must return entrada.port \
26327             verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
26328        );
26329    }
26330
26331    #[test]
26332    fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
26333        // Apex-identity pair-invariant pin composing both substrate-
26334        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
26335        // and [`Entrada::destination`] — at the emit-side call shape
26336        // every per-Aplicacao renderer's ingress-apex L4 port reader
26337        // now takes. The invariant:
26338        //
26339        //   spec.port_for_destination(entrada.destination()) == entrada.port
26340        //
26341        // holds by construction under today's single-destination
26342        // `:entrada` slot (`destination()` returns `entrada.para`, and
26343        // the resolver's apex arm matches `para == destination` and
26344        // returns `entrada.port`), and every downstream consumer that
26345        // composes the two accessors at the ingress apex — the
26346        // `caixa_mesh::gateway_routes` HTTPRoute per-rule
26347        // `backendRefs[0].port` emit-site path, the peer future M4 CR
26348        // materializer's admission-webhook that promotes the scalar to
26349        // a per-CR override overlay, every future per-Aplicacao snapshot
26350        // renderer's apex-facing L4 port reader — reaches through the
26351        // same composition. Pin the identity across four permutations
26352        // (`:para` × `:port` including a non-default port to exercise
26353        // the honor-verbatim arm and a non-cart `:para` to exercise
26354        // destination-agnostic identity) so a future refactor that
26355        // silently split either accessor's apex behavior surfaces at
26356        // caixa-core build time — a subtle `destination()` renaming
26357        // that returned `entrada.host.as_str()` instead of
26358        // `entrada.para.as_str()` would blow this pin loudly, closing
26359        // the last quiet failure mode the two lifts admit in composition.
26360        //
26361        // Peer discipline with the sibling caixa-mesh cross-crate pin
26362        // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
26363        // on the two-renderer pair-invariant axis; this pin encodes the
26364        // same two-consumer coherence rule at the substrate-primitive
26365        // level so the invariant survives even if every renderer is
26366        // deleted.
26367        for (para, port) in [
26368            ("cart", DEFAULT_SERVICO_PORT),
26369            ("cart", 8443u16),
26370            ("payment", 9090u16),
26371            ("catalog", 443u16),
26372        ] {
26373            let mut spec = three_member_spec();
26374            if let Some(e) = spec.entrada.as_mut() {
26375                e.para = para.into();
26376                e.port = port;
26377            }
26378            let expected_port = spec
26379                .entrada()
26380                .expect("three_member_spec carries a typed `:entrada` block")
26381                .port();
26382            let composed_port = {
26383                let entrada = spec.entrada().expect("entrada present");
26384                spec.port_for_destination(entrada.destination())
26385            };
26386            assert_eq!(
26387                composed_port, expected_port,
26388                "`spec.port_for_destination(entrada.destination())` must \
26389                 equal `entrada.port` under today's single-destination \
26390                 `:entrada` slot — this is the apex-identity contract \
26391                 every downstream ingress-apex L4 port reader relies on. \
26392                 Input :entrada :para: {para:?}, :entrada :port: {port}"
26393            );
26394        }
26395    }
26396
26397    #[test]
26398    fn port_for_destination_apex_arm_routes_through_destination_accessor() {
26399        // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
26400        // per-`:entrada` apex-arm membership probe must key off
26401        // [`Entrada::destination`], not the raw `.para` field access.
26402        // Structurally: setting ONLY the `:entrada :para` field to a
26403        // fresh non-cart destination on an otherwise-well-formed
26404        // Aplicacao must (1) leave `e.destination()` byte-equal to
26405        // `e.para.as_str()` (the accessor is byte-projective by
26406        // definition), and (2) cause the resolver's apex arm to fire
26407        // and return `entrada.port` at exactly that new destination
26408        // while every other destination string falls through to
26409        // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
26410        // membership check. Pins against a future silent detour that
26411        // (a) re-derived the apex-arm membership probe off
26412        // `e.para == destination` in `port_for_destination` instead of
26413        // `e.destination() == destination`, silently disagreeing with
26414        // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
26415        // consumers (`entrada.destination()` at
26416        // caixa-mesh/src/lib.rs:3173, `c.destination()` at
26417        // caixa-mesh/src/lib.rs:2739) that already reach through the
26418        // accessor, (b) accessor-side introduced a per-tenant alias
26419        // arm the caller was unaware of, silently rewriting an
26420        // author-declared `:para "cart"` value to a canary-aliased
26421        // form — the raw-field-access resolver would fall through to
26422        // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
26423        // while the peer emit-site consumers landed on the aliased
26424        // destination, splitting the ingress-apex L4 port at
26425        // cluster-apply time.
26426        //
26427        // Peer of the sibling
26428        // [`validate_membros_empty_gate_routes_through_nome_accessor`]
26429        // (d0de220) composition pin on the per-`:membros` refusal-arm
26430        // axis — same "the shape-gate predicate must route through the
26431        // substrate-primitive typed dispatch" discipline extended onto
26432        // the per-`:entrada` apex-arm membership-probe axis. Closes
26433        // the last unlifted `.para` production-code read site on
26434        // `Entrada` in `caixa-core` — after this converge every
26435        // `caixa-core` `.para` field access outside the accessor's own
26436        // body and outside the `WitContract` per-`:contratos` sibling
26437        // axis is either a test-side field-setter or a doc-comment
26438        // reference.
26439        for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
26440            let mut spec = three_member_spec();
26441            if let Some(e) = spec.entrada.as_mut() {
26442                e.para = para.into();
26443                e.port = port;
26444            }
26445            let e = spec
26446                .entrada
26447                .as_ref()
26448                .expect("three_member_spec carries a typed `:entrada` block");
26449            assert_eq!(
26450                e.destination(),
26451                e.para.as_str(),
26452                "Entrada::destination must byte-equal the .para field \
26453                 access — an accessor-side detour that no longer \
26454                 projects the raw field would silently split this \
26455                 drift-detection test from the port_for_destination \
26456                 apex-arm membership probe",
26457            );
26458            assert_eq!(
26459                spec.port_for_destination(para),
26460                port,
26461                "port_for_destination must key off the accessor-projected \
26462                 destination and return `entrada.port` on the apex arm — \
26463                 input :entrada :para: {para:?}, :entrada :port: {port}",
26464            );
26465            assert_eq!(
26466                spec.port_for_destination("ghost-destination-never-a-member"),
26467                DEFAULT_SERVICO_PORT,
26468                "port_for_destination must fall through to \
26469                 DEFAULT_SERVICO_PORT on a non-matching destination \
26470                 under the accessor-projected membership check — input \
26471                 :entrada :para: {para:?}, :entrada :port: {port}",
26472            );
26473        }
26474    }
26475
26476    #[test]
26477    fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
26478        // The canonical per-`:politicas :rate-limit` `:rate`
26479        // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
26480        // [`RateLimit::rate`] must return the `:politicas :rate-limit`
26481        // typed `u32` verbatim, byte-equal to the raw field access
26482        // across every representative value in the accept-set — `1` (the
26483        // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
26484        // the surrounding [`AplicacaoSpec::validate_politicas`] gate
26485        // carves out on the sibling `PolicyRateLimitZero` refusal),
26486        // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
26487        // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
26488        // `0` (a past-the-guard sentinel that pins the accessor doesn't
26489        // perform a silent bounds-collapse into `1` on the zero arm —
26490        // validate rejects zero but the accessor must ship the raw slot
26491        // verbatim so a validate-time gate regression surfaces at the
26492        // emit boundary rather than being silently absorbed), `u32::MAX`
26493        // (a past-the-guard sentinel that pins the accessor doesn't
26494        // perform a silent bounds-collapse through
26495        // `POLICY_RATE_LIMIT_MAX` at the return path).
26496        //
26497        // First sub-struct required-scalar accessor pin on the
26498        // `RateLimit` axis — sibling in shape to the peer
26499        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
26500        // required-`u32` accessor pin on the peer per-sub-struct
26501        // required-axis. Pins against a future silent detour that
26502        // re-derived the token capacity from a peer axis (an accidental
26503        // `self.window.as_secs() as u32` collapse that read the
26504        // rate-limit window duration as a token count), a `0 → 1`
26505        // cluster-default projection (which would silently absorb the
26506        // `PolicyRateLimitZero` refusal case at the accessor boundary),
26507        // or a bounds-collapsing accessor that clamped the return
26508        // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
26509        // gate owns the bounds; the accessor must ship the raw slot
26510        // verbatim).
26511        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
26512            let rl = RateLimit {
26513                rate,
26514                window: Duration::from_secs(1),
26515            };
26516            assert_eq!(
26517                rl.rate(),
26518                rate,
26519                "RateLimit::rate must return :politicas :rate-limit :rate \
26520                 verbatim (got {}, expected {rate})",
26521                rl.rate(),
26522            );
26523            assert_eq!(
26524                rl.rate(),
26525                rl.rate,
26526                "RateLimit::rate must byte-equal the raw .rate field \
26527                 access across every value in the u32 accept-set",
26528            );
26529        }
26530    }
26531
26532    #[test]
26533    fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
26534        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26535        // `:rate-limit :rate` zero-floor arm must key off
26536        // [`RateLimit::rate`], not the raw `.rate` field access.
26537        // Structurally: a `RateLimit { rate: 0, window:
26538        // Duration::from_secs(1) }` embedded in a `:politicas
26539        // :rate-limit` slot must surface the `PolicyRateLimitZero`
26540        // refusal exactly, and a `RateLimit { rate: 1, window:
26541        // Duration::from_secs(1) }` (the lower boundary of the
26542        // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
26543        // The pair jointly pins the accessor + validate-gate composition:
26544        // any future silent detour that had the accessor return a fresh
26545        // `1` on the zero arm (a `.rate().max(1)` collapse) would
26546        // silently absorb the `PolicyRateLimitZero` refusal at the
26547        // accessor boundary and the validate gate would accept a
26548        // struct-literal `RateLimit { rate: 0, .. }` — the composition
26549        // pin catches that at caixa-core build time.
26550        //
26551        // Peer of the sibling per-`CircuitBreaker`
26552        // [`CircuitBreaker::max_failures`] (3a74062) /
26553        // [`CircuitBreaker::window`] (373957f) accessor-composition
26554        // pins on the peer required-scalar axes — same "the validate /
26555        // shape-gate predicate must route through the substrate-primitive
26556        // typed dispatch" discipline extended onto the peer
26557        // per-`RateLimit` required-`u32` composition axis.
26558        let mut spec = three_member_spec();
26559        spec.politicas = MeshPolicy {
26560            rate_limit: Some(RateLimit {
26561                rate: 0,
26562                window: Duration::from_secs(1),
26563            }),
26564            ..MeshPolicy::default()
26565        };
26566        assert!(
26567            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
26568            "validate_politicas must reject rate == 0 with \
26569             PolicyRateLimitZero — the accessor and the validate gate \
26570             must route through the same substrate-primitive typed \
26571             dispatch on the :rate zero-floor arm",
26572        );
26573        spec.politicas = MeshPolicy {
26574            rate_limit: Some(RateLimit {
26575                rate: 1,
26576                window: Duration::from_secs(1),
26577            }),
26578            ..MeshPolicy::default()
26579        };
26580        assert!(
26581            spec.validate().is_ok(),
26582            "validate_politicas must accept rate == 1 (the lower \
26583             boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
26584        );
26585    }
26586
26587    #[test]
26588    fn rate_limit_rate_projects_u32_by_copy() {
26589        // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
26590        // `u32` is `Copy` and the accessor must return by value, not by
26591        // reference. Peer of the sibling per-`CircuitBreaker`
26592        // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
26593        // peer required-scalar `:max-failures` axis, extended onto the
26594        // peer per-`RateLimit` required-`u32` copy-invariant shape —
26595        // the accessor's returned `u32` must outlive `&self` (multiple
26596        // calls must return equal values from a dropped-`&self` copy,
26597        // since the returned scalar carries no borrow), and calling the
26598        // accessor twice on the same RateLimit must yield the same
26599        // `u32` verbatim (idempotent, no side effects on `&self`).
26600        //
26601        // Pins against a future silent detour that returned `&u32`
26602        // (which would type-check but silently break every downstream
26603        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
26604        // first parameter is `u32`, and `&u32` would fold to a detached
26605        // copy at the call site with a `*` deref the sibling accessors
26606        // don't need), an accidental `.rate.wrapping_add(0)` detour that
26607        // returned a fresh copy through an arithmetic no-op (breaking a
26608        // future `const fn` regression), or a one-arm-only accessor
26609        // that returned a saturating value on some sentinel input
26610        // (breaking the pass-through invariant the sibling required-
26611        // scalar accessors carry).
26612        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
26613            let rl = RateLimit {
26614                rate,
26615                window: Duration::from_secs(1),
26616            };
26617            let first = rl.rate();
26618            let second = rl.rate();
26619            assert_eq!(
26620                first, second,
26621                "RateLimit::rate must be idempotent — two successive \
26622                 calls on the same &self must return the same u32",
26623            );
26624            assert_eq!(
26625                first, rate,
26626                "RateLimit::rate must return :politicas :rate-limit :rate \
26627                 verbatim by copy — got {first}, expected {rate}",
26628            );
26629        }
26630    }
26631
26632    #[test]
26633    fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
26634        // The canonical per-`:politicas :rate-limit` `:window`
26635        // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
26636        // pin: [`RateLimit::window`] must return the
26637        // `:politicas :rate-limit :window` typed `Duration` verbatim,
26638        // byte-equal to the raw field access across every
26639        // representative value in the accept-set — `Duration::from_secs(1)`
26640        // (the `"s"` canonical window, the lower row of
26641        // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
26642        // [`AplicacaoSpec::validate_politicas`] gate accepts via
26643        // [`is_canonical_rate_limit_window`]),
26644        // `Duration::from_secs(60)` (the `"m"` canonical window, the
26645        // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
26646        // window, the upper row), `Duration::ZERO` (a past-the-guard
26647        // sentinel that pins the accessor doesn't perform a silent
26648        // bounds-collapse into `Duration::from_secs(1)` on the zero
26649        // arm — validate rejects an off-set window through
26650        // `PolicyRateLimitWindowNotCanonical` but the accessor must
26651        // ship the raw slot verbatim so a validate-time gate
26652        // regression surfaces at the emit boundary rather than being
26653        // silently absorbed), `Duration::from_millis(500)` (a
26654        // sub-canonical past-the-guard sentinel that pins the accessor
26655        // doesn't silently normalize a non-canonical fractional
26656        // magnitude onto the nearest canonical row).
26657        //
26658        // Second sub-struct required-scalar accessor pin on the
26659        // `RateLimit` axis — sibling in shape to the just-landed
26660        // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
26661        // accessor pin on the peer per-sub-struct required-axis,
26662        // extended onto the per-`RateLimit` required-`Duration` axis.
26663        // Pins against a future silent detour that re-derived the
26664        // refill period from a peer axis (an accidental
26665        // `Duration::from_secs(self.rate as u64)` collapse that read
26666        // the rate-limit token capacity as a refill-interval
26667        // duration), a `Duration::ZERO → Duration::from_secs(1)`
26668        // canonical-default projection (which would silently absorb
26669        // the `PolicyRateLimitWindowNotCanonical` refusal case at the
26670        // accessor boundary), or a canonical-set-collapsing accessor
26671        // that clamped the return through [`rate_limit_window_unit`]
26672        // (the `AplicacaoSpec::validate` gate owns the canonical-set
26673        // membership; the accessor must ship the raw slot verbatim).
26674        for window in [
26675            Duration::from_secs(1),
26676            Duration::from_secs(60),
26677            Duration::from_secs(3600),
26678            Duration::ZERO,
26679            Duration::from_millis(500),
26680        ] {
26681            let rl = RateLimit { rate: 100, window };
26682            assert_eq!(
26683                rl.window(),
26684                window,
26685                "RateLimit::window must return :politicas :rate-limit :window \
26686                 verbatim (got {:?}, expected {window:?})",
26687                rl.window(),
26688            );
26689            assert_eq!(
26690                rl.window(),
26691                rl.window,
26692                "RateLimit::window must byte-equal the raw .window field \
26693                 access across every value in the Duration accept-set",
26694            );
26695        }
26696    }
26697
26698    #[test]
26699    fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
26700        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26701        // `:rate-limit :window` canonical-set arm must key off
26702        // [`RateLimit::window`], not the raw `.window` field access.
26703        // Structurally: a `RateLimit { window: Duration::from_millis(500),
26704        // .. }` embedded in a `:politicas :rate-limit` slot must
26705        // surface the `PolicyRateLimitWindowNotCanonical` refusal
26706        // exactly (with the sub-canonical `Duration::from_millis(500)`
26707        // magnitude carried through verbatim), and a `RateLimit
26708        // { window: Duration::from_secs(1), .. }` (the lower row of
26709        // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
26710        // The pair jointly pins the accessor + validate-gate
26711        // composition: any future silent detour that had the accessor
26712        // normalize the off-set window to the nearest canonical row
26713        // (a `.window().max(Duration::from_secs(1))` collapse, or a
26714        // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
26715        // collapse) would silently absorb the
26716        // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
26717        // boundary — including a drift in the error's `window` payload
26718        // (the emit-side diagnostic reader keys off the offending
26719        // magnitude verbatim, so a normalization at the accessor
26720        // boundary would silently pin the wrong magnitude in the
26721        // refusal). The composition pin catches that at caixa-core
26722        // build time.
26723        //
26724        // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
26725        // (7f81a60) accessor-composition pin on the peer required-
26726        // scalar `:rate` axis — same "the validate / shape-gate
26727        // predicate must route through the substrate-primitive typed
26728        // dispatch, and the error payload must project through the
26729        // same accessor" discipline extended onto the peer
26730        // per-`RateLimit` required-`Duration` composition axis.
26731        let mut spec = three_member_spec();
26732        spec.politicas = MeshPolicy {
26733            rate_limit: Some(RateLimit {
26734                rate: 100,
26735                window: Duration::from_millis(500),
26736            }),
26737            ..MeshPolicy::default()
26738        };
26739        match spec.validate() {
26740            Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
26741                assert_eq!(
26742                    window,
26743                    Duration::from_millis(500),
26744                    "PolicyRateLimitWindowNotCanonical must carry the \
26745                     offending :window magnitude verbatim through the \
26746                     accessor — got {window:?}, expected 500ms",
26747                );
26748            }
26749            other => panic!(
26750                "validate_politicas must reject non-canonical :window \
26751                 with PolicyRateLimitWindowNotCanonical — the accessor \
26752                 and the validate gate must route through the same \
26753                 substrate-primitive typed dispatch on the :window \
26754                 canonical-set arm; got {other:?}",
26755            ),
26756        }
26757        spec.politicas = MeshPolicy {
26758            rate_limit: Some(RateLimit {
26759                rate: 100,
26760                window: Duration::from_secs(1),
26761            }),
26762            ..MeshPolicy::default()
26763        };
26764        assert!(
26765            spec.validate().is_ok(),
26766            "validate_politicas must accept window == Duration::from_secs(1) \
26767             (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
26768        );
26769    }
26770
26771    #[test]
26772    fn rate_limit_window_projects_duration_by_copy() {
26773        // The by-copy pin: [`RateLimit::window`] returns `Duration`
26774        // by copy — `Duration` is `Copy` and the accessor must return
26775        // by value, not by reference. Peer of the sibling per-`RateLimit`
26776        // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
26777        // required-scalar `:rate` axis, extended onto the peer
26778        // per-`RateLimit` required-`Duration` copy-invariant shape —
26779        // the accessor's returned `Duration` must outlive `&self`
26780        // (multiple calls must return equal values from a
26781        // dropped-`&self` copy, since the returned scalar carries no
26782        // borrow), and calling the accessor twice on the same
26783        // RateLimit must yield the same `Duration` verbatim
26784        // (idempotent, no side effects on `&self`).
26785        //
26786        // Pins against a future silent detour that returned
26787        // `&Duration` (which would type-check but silently break every
26788        // downstream `Duration`-by-value consumer —
26789        // [`is_canonical_rate_limit_window`]'s first parameter is
26790        // `Duration`, and `&Duration` would fold to a detached copy at
26791        // the call site with a `*` deref the sibling accessors don't
26792        // need), an accidental `.window + Duration::ZERO` detour that
26793        // returned a fresh copy through an arithmetic no-op (breaking
26794        // a future `const fn` regression), or a one-arm-only accessor
26795        // that returned a canonical fallback on some sentinel input
26796        // (breaking the pass-through invariant the sibling required-
26797        // scalar accessors carry).
26798        for window in [
26799            Duration::from_secs(1),
26800            Duration::from_secs(60),
26801            Duration::from_secs(3600),
26802            Duration::ZERO,
26803            Duration::from_millis(500),
26804        ] {
26805            let rl = RateLimit { rate: 100, window };
26806            let first = rl.window();
26807            let second = rl.window();
26808            assert_eq!(
26809                first, second,
26810                "RateLimit::window must be idempotent — two successive \
26811                 calls on the same &self must return the same Duration",
26812            );
26813            assert_eq!(
26814                first, window,
26815                "RateLimit::window must return :politicas :rate-limit :window \
26816                 verbatim by copy — got {first:?}, expected {window:?}",
26817            );
26818        }
26819    }
26820
26821    #[test]
26822    fn placement_estrategia_default_pins_m3_canonical_value() {
26823        // Pin [`PLACEMENT_ESTRATEGIA_DEFAULT`] at
26824        // [`PlacementStrategy::Replicated`] — MESH-COMPOSITION §II.2's
26825        // active-active-across-every-named-cluster arm, the closest
26826        // canonical M3 production reference the substrate carries and
26827        // the arm the caixa-mesh `programs.yaml` fan-out already keys off
26828        // for every un-`:placement`-declared Aplicacao. Pinning the arm
26829        // here surfaces a future rebrand of the M3-canonical
26830        // distribution default (a widening to `Sharded` once the
26831        // substrate discovers hash-keyed distribution as the more
26832        // common production shape, a tightening to `SingleNode` for
26833        // stateful Erlang/OTP distributed-app-takeover semantics
26834        // MESH-COMPOSITION §II.1 names, a per-cluster overlay the
26835        // operator pins through a future `:placement-overrides` slot)
26836        // as a deliberate test edit, not a silent contract migration.
26837        // Peer of the sibling M2 per-supervisor value pins
26838        // [`crate::supervisor::tests::supervisor_estrategia_default_pins_otp_canonical_value`]
26839        // /
26840        // [`crate::supervisor::tests::supervisor_child_restart_default_pins_otp_canonical_value`]
26841        // extended onto the M3 mesh-primitive-defining `:placement
26842        // :estrategia` axis.
26843        assert_eq!(PLACEMENT_ESTRATEGIA_DEFAULT, PlacementStrategy::Replicated);
26844    }
26845
26846    #[test]
26847    fn placement_strategy_default_routes_through_lifted_default() {
26848        // Composition pin: the [`Default for PlacementStrategy`] impl's
26849        // return arm must route through the substrate-canonical
26850        // [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
26851        // a raw `Self::Replicated` arm. Prior to the lift the impl
26852        // carried an inline `Self::Replicated` arm with no compile-time
26853        // link back to the shared M3-canonical `Replicated` arm the
26854        // paired [`Default for Placement`] impl's struct-literal
26855        // `estrategia` field, the serde-side `#[serde(default)]` on
26856        // [`Placement::estrategia`] that resolves an author-omitted
26857        // wire-form `:placement :estrategia` scalar through the impl,
26858        // and the [`crate::manifest::Caixa::aplicacao_view`] fold's
26859        // `.unwrap_or_default()` `Option<Placement>` collapse arm (which
26860        // routes through [`Placement::default`] which routes through the
26861        // strategy default) all key off — so a future rebrand of the
26862        // M3-canonical distribution default would have had to be threaded
26863        // through the `Default` impl and the three peer routes in
26864        // lockstep or the four consumers would silently split. Byte-
26865        // parity against the lifted constant closes the split. Peer of
26866        // the sibling
26867        // [`crate::supervisor::tests::restart_strategy_default_routes_through_lifted_default`]
26868        // /
26869        // [`crate::supervisor::tests::restart_policy_default_routes_through_lifted_default`]
26870        // composition pins on the M2 per-supervisor axes.
26871        assert_eq!(PlacementStrategy::default(), PLACEMENT_ESTRATEGIA_DEFAULT);
26872    }
26873
26874    #[test]
26875    fn placement_default_estrategia_routes_through_lifted_default() {
26876        // Composition pin: the [`Default for Placement`] impl's
26877        // struct-literal `estrategia` field must route through the
26878        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
26879        // `pub const` (either directly, or via the [`PlacementStrategy::default`]
26880        // impl that the sibling
26881        // `placement_strategy_default_routes_through_lifted_default` pin
26882        // already routes onto the constant). Structurally: every
26883        // `Placement::default()` call must yield an `estrategia` field
26884        // byte-equal to the lifted constant so the two paired defaults —
26885        // the [`Default for PlacementStrategy`] impl arm and the
26886        // struct-literal default arm here — cannot silently split on any
26887        // future M3-canonical distribution-default rebrand. Peer of the
26888        // sibling M2
26889        // [`crate::supervisor::tests::supervisor_spec_default_estrategia_routes_through_lifted_default`]
26890        // byte-parity pin on the [`Default for SupervisorSpec`]
26891        // struct-literal `estrategia` field extended onto the M3
26892        // mesh-primitive-defining slot family.
26893        assert_eq!(
26894            Placement::default().estrategia,
26895            PLACEMENT_ESTRATEGIA_DEFAULT,
26896        );
26897    }
26898
26899    #[test]
26900    fn placement_serde_default_estrategia_routes_through_lifted_default() {
26901        // Composition pin: the serde-side `#[serde(default)]` on
26902        // [`Placement::estrategia`] — the wire-format author-omitted
26903        // `:placement :estrategia` arm — must resolve onto the substrate-
26904        // canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const`
26905        // (via the [`Default for PlacementStrategy`] impl the sibling
26906        // `placement_strategy_default_routes_through_lifted_default` pin
26907        // already routes onto the constant). Structurally: a `Placement`
26908        // deserialized from a payload that omits the `estrategia` key
26909        // must yield an `estrategia` field byte-equal to the lifted
26910        // constant, so the wire-format author-omitted arm and the
26911        // [`PlacementStrategy::default`] impl arm cannot silently split
26912        // on any future M3-canonical distribution-default rebrand. Peer
26913        // of the sibling M2
26914        // [`crate::supervisor::tests::child_spec_serde_default_restart_routes_through_lifted_default`]
26915        // byte-parity pin on the wire-format author-omitted `:children
26916        // :restart` scalar extended onto the M3 mesh-primitive-defining
26917        // slot family.
26918        let omitted: Placement = serde_json::from_str("{}")
26919            .expect("Placement must deserialize with the estrategia key omitted");
26920        assert_eq!(
26921            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
26922            "an author-omitted :placement :estrategia slot must degrade onto \
26923             the PLACEMENT_ESTRATEGIA_DEFAULT typed pub const (got \
26924             {:?}, expected {:?})",
26925            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
26926        );
26927    }
26928}