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
181impl WitContract {
182    /// Substrate-canonical per-`:contratos` caller-Servico scalar
183    /// accessor every consumer that reads the edge's source endpoint
184    /// keys off — returns the author-declared `:contratos :de`
185    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
186    /// own [`String`] storage.
187    ///
188    /// The `:contratos :de` slot names the caller-side member Servico
189    /// on a typed inter-Servico edge (validated by
190    /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
191    /// Aplicacao declares — a stray `:de` that doesn't name a member is
192    /// [`AplicacaoError::ContratoMemberMissing`], not a silent
193    /// caller-attachment miss at cluster-apply time). Peer of the
194    /// sibling [`WitContract::destination`] accessor on the same
195    /// per-`:contratos` entry — the pair `( source(), destination() )`
196    /// jointly names the typed edge every renderer that fans on the
197    /// caller-callee identity keys off (the
198    /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)`
199    /// grouping, the [`AplicacaoSpec::detect_sync_cycles`] adjacency
200    /// map, the per-edge dedup key, the per-edge membership-lookup
201    /// diagnostic).
202    ///
203    /// Prior to this lift the `.de` byte-string was accessed inline at
204    /// four caixa-core sites (the two validate-side membership lookups
205    /// at `!names.contains(c.de.as_str())`, the per-edge dedup-key
206    /// tuple's caller-arm at
207    /// `(c.de.as_str(), c.para.as_str(), c.wit.as_str(), ...)`, the
208    /// `detect_sync_cycles` adjacency `adj.entry(c.de.as_str())`) and
209    /// one caixa-mesh site (the per-`(:de, :para)` CNP grouping's
210    /// caller-arm at `groups.entry((c.de.as_str(), c.para.as_str()))`)
211    /// — five open-coded `.de.as_str()` field-accesses that expressed
212    /// no compile-time link back to the typed slot. A future extension
213    /// of the `:contratos :de` axis to a richer author surface (a
214    /// multi-caller weighted-fan-in overlay per MESH-COMPOSITION §III.2
215    /// canary flow, a per-cluster caller-alias table the operator pins
216    /// through a future `:placement`-scoped slot, the M4
217    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
218    /// admission-webhook that promotes the scalar to a caller-set
219    /// projection) would have had to be threaded through every
220    /// open-coded copy in lockstep or one consumer would silently
221    /// disagree with the peers on which caller Servico a given edge
222    /// resolves to. Lifting the resolution rule to a typed method on
223    /// the substrate primitive means every downstream caller-facing
224    /// consumer reaches for one typed dispatch — the resolver's
225    /// accept-set migrates as a unit on any future axis addition.
226    ///
227    /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
228    /// (6db982c) accessor on the analogous per-ingress-Servico scalar
229    /// axis — same "one typed dispatch on the substrate primitive,
230    /// thin projections at each consumer" discipline extended onto the
231    /// per-`:contratos` caller-Servico byte-string axis.
232    #[must_use]
233    pub fn source(&self) -> &str {
234        self.de.as_str()
235    }
236
237    /// Substrate-canonical per-`:contratos` callee-Servico scalar
238    /// accessor every consumer that reads the edge's destination
239    /// endpoint keys off — returns the author-declared
240    /// `:contratos :para` byte-string verbatim as a `&str`, borrowed
241    /// from the typed slot's own [`String`] storage.
242    ///
243    /// The `:contratos :para` slot names the callee-side member Servico
244    /// on a typed inter-Servico edge (validated by
245    /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
246    /// Aplicacao declares — a stray `:para` that doesn't name a member
247    /// is [`AplicacaoError::ContratoMemberMissing`], not a silent
248    /// callee-attachment miss at cluster-apply time). Callee-side twin
249    /// of the sibling [`WitContract::source`] accessor — the pair
250    /// jointly names the typed edge every renderer that fans on the
251    /// caller-callee identity keys off, and this accessor is also the
252    /// per-`(:de, :para)` L4 port resolver's canonical destination arg:
253    /// under today's typed surface [`AplicacaoSpec::port_for_destination`]
254    /// composes with `destination()` at every emit site that projects a
255    /// per-edge destination Servico's L4 listener port.
256    ///
257    /// Prior to this lift the `.para` byte-string was accessed inline
258    /// at five sites — four caixa-core (the validate-side membership
259    /// lookup at `!names.contains(c.para.as_str())`, the per-edge
260    /// dedup-key tuple's callee-arm, the `detect_sync_cycles`
261    /// adjacency `.insert(c.para.as_str())`, the CNP grouping's
262    /// callee-arm) and one caixa-mesh (the per-`(:de, :para)` CNP L4
263    /// port resolver's destination arg `spec.port_for_destination(&c.para)`)
264    /// — with no compile-time link back to the typed slot. A future
265    /// extension of the `:contratos :para` axis to a richer author
266    /// surface (a multi-callee weighted-fan-out overlay for canary /
267    /// blue-green routing on typed edges, a per-cluster callee-alias
268    /// table the operator pins through a future `:placement`-scoped
269    /// slot, the M4 CR materializer's per-CR admission-webhook that
270    /// promotes the scalar to a callee-set projection) would have had
271    /// to be threaded through every open-coded copy in lockstep or one
272    /// consumer would silently disagree on which callee Servico a given
273    /// edge resolves to (a per-CNP `endpointSelector` that names a
274    /// different destination than its L4 port resolver reads for, a
275    /// dedup-key that treats `(cart, catalog-v2)` and `(cart, catalog)`
276    /// as distinct while the adjacency map collapses them, or vice
277    /// versa). Lifting to a typed method on the substrate primitive
278    /// means every downstream callee-facing consumer reaches for one
279    /// typed dispatch.
280    ///
281    /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
282    /// (6db982c) accessor — both name the "destination-Servico
283    /// byte-string" concept on their respective mesh-slot atoms (per-
284    /// ingress apex vs. per-typed-edge callee), and both extend the
285    /// substrate-primitive-owns-the-resolver discipline onto the
286    /// per-slot destination-Servico scalar axis. Composes with
287    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) at every
288    /// emit-side per-edge L4 port reader — the composition
289    /// `spec.port_for_destination(c.destination())` pins the CNP per-
290    /// `(:de, :para)` L4 port axis to the same typed dispatch the peer
291    /// `HTTPRoute` `backendRefs[0].port` axis reaches through with
292    /// `spec.port_for_destination(entrada.destination())`.
293    #[must_use]
294    pub fn destination(&self) -> &str {
295        self.para.as_str()
296    }
297
298    /// Substrate-canonical per-`:contratos` WIT-world-reference scalar
299    /// accessor every consumer that reads the edge's WIT world
300    /// discriminator keys off — returns the author-declared
301    /// `:contratos :wit` byte-string verbatim as a `&str`, borrowed from
302    /// the typed slot's own [`String`] storage.
303    ///
304    /// The `:contratos :wit` slot names the WIT world the typed edge
305    /// carries (e.g. `"wasi:http/proxy"`, `"nats:pub-sub"`,
306    /// `"wasi:keyvalue/store"`); validated by [`WitContract::target`] to
307    /// be a well-shaped WIT world reference via
308    /// [`crate::render::is_wit_world_ref`] and by
309    /// [`AplicacaoSpec::validate`] to be non-empty via the narrower
310    /// [`AplicacaoError::EmptyWit`] variant. Peer of the sibling
311    /// [`WitContract::source`] / [`WitContract::destination`] accessors
312    /// on the same per-`:contratos` entry — the triple
313    /// `( source(), destination(), world_ref() )` jointly names the
314    /// typed edge every renderer that fans on the caller-callee-shape
315    /// identity keys off (the per-edge dedup key at
316    /// [`AplicacaoSpec::validate`]'s duplicate-`:contratos` gate, the
317    /// per-`(:de, :para)` CNP grouping's shape-arm classifier at
318    /// [`caixa_mesh::cilium_network_policies`], the
319    /// [`WitContract::is_http`] / [`is_pubsub`][WitContract::is_pubsub]
320    /// / [`is_store`][WitContract::is_store] shape-dispatch predicates,
321    /// the [`feira app graph`][fag] per-edge printer's WIT-shape label).
322    ///
323    /// Prior to this lift the `.wit` byte-string was accessed inline at
324    /// five sites — three caixa-core (the `WitContract::is_*` shape-
325    /// dispatch predicates' `&self.wit` arg, the validate-side empty
326    /// check at `if c.wit.is_empty()`, the per-edge dedup-key tuple's
327    /// shape arm at `c.wit.as_str()`) and one caixa-feira (the app-graph
328    /// printer's `{}` format-slot at `c.wit`) — five open-coded
329    /// `.wit` field-accesses that expressed no compile-time link back to
330    /// the typed slot. A future extension of the `:contratos :wit` axis
331    /// to a richer author surface (an M4 promotion from `String` to a
332    /// typed WIT-world enum once the WIT registry stabilizes in tatara-
333    /// lisp per this struct's own `:wit` field docstring, a per-cluster
334    /// WIT-alias table the operator pins through a future
335    /// `:placement`-scoped slot, a canonicalization pass that lowercases
336    /// `wasi:*` prefixes) would have had to be threaded through every
337    /// open-coded copy in lockstep or one consumer would silently
338    /// disagree with the peers on which WIT shape a given edge resolves
339    /// to (a per-CNP L7 emission that read `wasi:http/proxy` while the
340    /// dedup key read the pre-canonicalized `WASI:HTTP/proxy`, an
341    /// empty-check that missed a whitespace-only string a peer accessor
342    /// stripped, or vice versa). Lifting to a typed method on the
343    /// substrate primitive means every downstream WIT-shape-facing
344    /// consumer reaches for one typed dispatch — the resolver's
345    /// accept-set migrates as a unit on any future axis addition.
346    ///
347    /// Sibling of the peer per-`:contratos` [`WitContract::source`] /
348    /// [`WitContract::destination`] (7f0fd43), per-`:entrada`
349    /// [`Entrada::hostname`] / [`Entrada::destination`] (11f3dfe /
350    /// 6db982c), per-`:membros` [`Membro::nome`] /
351    /// [`Membro::versao_requirement`] (4a32abf / a40b0e3) accessors on
352    /// the mesh-slot-atom scalar-value axes — same "one typed dispatch
353    /// on the substrate primitive, thin projections at each consumer"
354    /// discipline extended onto the last unlifted per-`:contratos`
355    /// scalar (the WIT-world-reference arm).
356    ///
357    /// [fag]: caixa-feira/src/cmd/app.rs
358    #[must_use]
359    pub fn world_ref(&self) -> &str {
360        self.wit.as_str()
361    }
362
363    /// Substrate-canonical per-`:contratos` `:endpoint` HTTP-shaped
364    /// payload-target scalar accessor every consumer that reads the
365    /// edge's L7 HTTP request path payload keys off — returns the
366    /// author-declared `:contratos :endpoint` byte-string verbatim as
367    /// an `Option<&str>`, borrowed from the typed slot's own
368    /// `Option<String>` storage; `None` when the slot is absent (the
369    /// canonical shape of a non-HTTP-`:wit`-world edge — pub-sub
370    /// `nats:*`/`kafka:*` carries `:subject` instead, key/value
371    /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
372    /// [`WitTarget::Capability`] edge carries none of the three).
373    ///
374    /// The `:contratos :endpoint` slot carries the HTTP request path
375    /// payload (Cilium L7 `path:` + Gateway API v1 `PathPrefix` grammar
376    /// — same shape required of `:entrada :paths`, gated by the shared
377    /// [`crate::render::is_gateway_api_http_path`] predicate) that
378    /// [`WitContract::target`] projects onto the [`WitTarget::Http`]
379    /// arm's `endpoint: &'a str` payload when the edge's `:wit` world
380    /// matches the [`WIT_HTTP_SHAPE_PREFIXES`] accept-set. Every
381    /// downstream consumer that reads the payload keys off this scalar
382    /// (the [`WitContract::target`] Http-arm payload extraction that
383    /// materializes [`WitTarget::Http { endpoint }`] under the paired
384    /// [`WitTarget::HTTP_FIELD_NAME`] label, the
385    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
386    /// key's endpoint arm that pins the payload as part of the six-tuple
387    /// dedup key alongside the sibling `:subject`/`:slot` arms, the
388    /// future M4 per-edge WIT registry resolver's HTTP-arm materializer,
389    /// the future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
390    /// per-edge L7 admission webhook, the future caixa-mesh L7 CNP
391    /// emission path that lands the payload verbatim as a Cilium L7
392    /// `path:` rule).
393    ///
394    /// Prior to this lift the `.endpoint` field was accessed inline at
395    /// two production sites in `caixa-core/src/aplicacao.rs` — the
396    /// [`WitContract::target`] payload-shape dispatch's `let endpoint =
397    /// self.endpoint.as_deref();` binding at the top of the method, and
398    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
399    /// tuple's `c.endpoint.as_deref()` HTTP-arm slot — two open-coded
400    /// field-accesses that expressed no compile-time link back to the
401    /// typed slot. A future extension of the `:contratos :endpoint`
402    /// axis to a richer author surface (an M4 promotion from
403    /// `Option<String>` to a typed HTTP path-template enum once the
404    /// WIT registry stabilizes path-parameter shapes in tatara-lisp per
405    /// this struct's own `:wit` field docstring, a per-cluster endpoint-
406    /// alias table the operator pins through a future `:placement`-
407    /// scoped slot, a canonicalization pass that percent-encodes non-
408    /// ASCII path segments, a per-CR fully-qualified rewrite the M4 CR
409    /// materializer applies per-tenant) would have had to be threaded
410    /// through both open-coded copies in lockstep or the two consumers
411    /// would silently disagree on which HTTP path a given edge resolves
412    /// to — the [`WitContract::target`] payload-extraction reading
413    /// `"/lookup"` while the [`AplicacaoSpec::validate`] dedup key read
414    /// the operator-resolved `"/tenant-a/lookup"` would silently split
415    /// the [`WitTarget::Http`]-arm rendered payload from the actual
416    /// dedup-key uniqueness axis, a two-consumer split at the validator
417    /// far from the source `caixa.lisp` with no field naming the
418    /// payload-drift root cause. Lifting the resolution rule to a typed
419    /// method on the substrate primitive means every downstream
420    /// HTTP-payload-facing consumer of the Aplicacao's per-`:contratos`
421    /// L7-payload surface reaches for exactly one typed dispatch — the
422    /// resolver's accept-set migrates as a unit on any future axis
423    /// addition.
424    ///
425    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
426    /// (7cd2a28) / [`Placement::affinity`] (74ec2d3) `Option<&str>`
427    /// accessors on the M3 mesh-slot family — same "one typed dispatch
428    /// on the substrate primitive, thin projections at each consumer"
429    /// discipline extended onto the per-`:contratos` HTTP-shaped
430    /// payload-carrier `Option<String>` optional-scalar axis. First
431    /// `Option<&str>`-return accessor on the per-`:contratos` mesh-slot
432    /// atom — opens the "optional per-slot payload-carrier scalar"
433    /// projection pattern the sibling per-`:contratos` `:subject` /
434    /// `:slot` future lifts fold on, matching the closed
435    /// per-`:contratos` scalar-value accessor family
436    /// ([`WitContract::source`] / [`WitContract::destination`] /
437    /// [`WitContract::world_ref`]) already lifted onto the mandatory-
438    /// scalar `String` axes. Named `endpoint()` to match the storage
439    /// field's name and the paired [`WitTarget::HTTP_FIELD_NAME`]
440    /// author-facing label const; the accessor's identity name maps
441    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
442    /// docstring already carries.
443    #[must_use]
444    pub fn endpoint(&self) -> Option<&str> {
445        self.endpoint.as_deref()
446    }
447
448    /// Substrate-canonical per-`:contratos` `:subject` pub-sub-shaped
449    /// payload-target scalar accessor every consumer that reads the
450    /// edge's NATS / Kafka publish subject payload keys off — returns
451    /// the author-declared `:contratos :subject` byte-string verbatim
452    /// as an `Option<&str>`, borrowed from the typed slot's own
453    /// `Option<String>` storage; `None` when the slot is absent (the
454    /// canonical shape of a non-pub-sub-`:wit`-world edge — HTTP
455    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, key/value
456    /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
457    /// [`WitTarget::Capability`] edge carries none of the three).
458    ///
459    /// The `:contratos :subject` slot carries the NATS / Kafka publish
460    /// subject payload (the [`WIT_PUBSUB_SHAPE_PREFIXES`] dispatch arm's
461    /// per-edge target selector — `orders.paid`, `events.>`, whatever
462    /// subject namespace the author names on the pub-sub edge) that
463    /// [`WitContract::target`] projects onto the [`WitTarget::PubSub`]
464    /// arm's `subject: &'a str` payload when the edge's `:wit` world
465    /// matches the [`WIT_PUBSUB_SHAPE_PREFIXES`] accept-set. Every
466    /// downstream consumer that reads the payload keys off this scalar
467    /// (the [`WitContract::target`] PubSub-arm payload extraction that
468    /// materializes [`WitTarget::PubSub { subject }`] under the paired
469    /// [`WitTarget::PUBSUB_FIELD_NAME`] label, the
470    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
471    /// key's subject arm that pins the payload as part of the six-tuple
472    /// dedup key alongside the sibling `:endpoint`/`:slot` arms, the
473    /// future M4 per-edge WIT registry resolver's pub-sub-arm
474    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
475    /// materializer's per-edge NATS admission webhook, the future
476    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
477    /// as a NATS subject the operator pins per-CR).
478    ///
479    /// Prior to this lift the `.subject` field was accessed inline at
480    /// two production sites in `caixa-core/src/aplicacao.rs` — the
481    /// [`WitContract::target`] payload-shape dispatch's `let subject =
482    /// self.subject.as_deref();` binding at the top of the method, and
483    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
484    /// tuple's `c.subject.as_deref()` pub-sub-arm slot — two open-coded
485    /// field-accesses that expressed no compile-time link back to the
486    /// typed slot. A future extension of the `:contratos :subject` axis
487    /// to a richer author surface (an M4 promotion from `Option<String>`
488    /// to a typed NATS-subject-template enum once the WIT registry
489    /// stabilizes wildcard / hierarchy shapes in tatara-lisp per this
490    /// struct's own `:wit` field docstring, a per-cluster subject-alias
491    /// table the operator pins through a future `:placement`-scoped
492    /// slot, a canonicalization pass that lowercases / dedupes wildcard
493    /// segments, a per-CR fully-qualified rewrite the M4 CR materializer
494    /// applies per-tenant) would have had to be threaded through both
495    /// open-coded copies in lockstep or the two consumers would silently
496    /// disagree on which NATS subject a given edge resolves to — the
497    /// [`WitContract::target`] payload-extraction reading `"orders.paid"`
498    /// while the [`AplicacaoSpec::validate`] dedup key read the operator-
499    /// resolved `"tenant-a.orders.paid"` would silently split the
500    /// [`WitTarget::PubSub`]-arm rendered payload from the actual dedup-
501    /// key uniqueness axis, a two-consumer split at the validator far
502    /// from the source `caixa.lisp` with no field naming the payload-
503    /// drift root cause. Lifting the resolution rule to a typed method
504    /// on the substrate primitive means every downstream pub-sub-payload-
505    /// facing consumer of the Aplicacao's per-`:contratos` L4-payload
506    /// surface reaches for exactly one typed dispatch — the resolver's
507    /// accept-set migrates as a unit on any future axis addition.
508    ///
509    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
510    /// (7020470) `Option<&str>` accessor on the M3 mesh-slot payload-
511    /// carrier axis — second `Option<&str>`-return accessor on the
512    /// per-`:contratos` mesh-slot atom, extending the "optional per-slot
513    /// payload-carrier scalar" projection pattern the [`WitContract::endpoint`]
514    /// HTTP-arm lift opened onto the pub-sub arm; leaves the [`WitContract::slot`]
515    /// key/value-store arm as the last unlifted per-`:contratos`
516    /// `Option<String>` axis. Named `subject()` to match the storage
517    /// field's name and the paired [`WitTarget::PUBSUB_FIELD_NAME`]
518    /// author-facing label const; the accessor's identity name maps
519    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
520    /// docstring already carries.
521    #[must_use]
522    pub fn subject(&self) -> Option<&str> {
523        self.subject.as_deref()
524    }
525
526    /// Substrate-canonical per-`:contratos` `:slot` key/value-store-
527    /// shaped payload-target scalar accessor every consumer that reads
528    /// the edge's `wasi:keyvalue/*` / `kv:*` key-template payload keys
529    /// off — returns the author-declared `:contratos :slot` byte-string
530    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
531    /// own `Option<String>` storage; `None` when the slot is absent
532    /// (the canonical shape of a non-store-`:wit`-world edge — HTTP
533    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, pub-sub
534    /// `nats:*`/`kafka:*` carries `:subject` instead, and a plain
535    /// [`WitTarget::Capability`] edge carries none of the three).
536    ///
537    /// The `:contratos :slot` slot carries the key/value store
538    /// key-template payload (the [`WIT_STORE_SHAPE_PREFIXES`] dispatch
539    /// arm's per-edge target selector — `carts/{cart_id}`,
540    /// `sessions/{tenant}/{sid}`, whatever key-template the author
541    /// names on the store edge) that [`WitContract::target`] projects
542    /// onto the [`WitTarget::Store`] arm's `slot: &'a str` payload when
543    /// the edge's `:wit` world matches the [`WIT_STORE_SHAPE_PREFIXES`]
544    /// accept-set. Every downstream consumer that reads the payload
545    /// keys off this scalar (the [`WitContract::target`] Store-arm
546    /// payload extraction that materializes [`WitTarget::Store { slot }`]
547    /// under the paired [`WitTarget::STORE_FIELD_NAME`] label, the
548    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
549    /// key's store arm that pins the payload as part of the six-tuple
550    /// dedup key alongside the sibling `:endpoint`/`:subject` arms,
551    /// the future M4 per-edge WIT registry resolver's store-arm
552    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
553    /// materializer's per-edge key/value admission webhook, the future
554    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
555    /// as a key-template the operator pins per-CR).
556    ///
557    /// Prior to this lift the `.slot` field was accessed inline at two
558    /// production sites in `caixa-core/src/aplicacao.rs` — the
559    /// [`WitContract::target`] payload-shape dispatch's `let slot =
560    /// self.slot.as_deref();` binding at the top of the method, and
561    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
562    /// tuple's `c.slot.as_deref()` store-arm slot — two open-coded
563    /// field-accesses that expressed no compile-time link back to the
564    /// typed slot. A future extension of the `:contratos :slot` axis
565    /// to a richer author surface (an M4 promotion from `Option<String>`
566    /// to a typed key-template enum once the WIT registry stabilizes
567    /// key-template parameter shapes in tatara-lisp per this struct's
568    /// own `:wit` field docstring, a per-cluster slot-alias table the
569    /// operator pins through a future `:placement`-scoped slot, a
570    /// canonicalization pass that lowercases the bucket prefix, a
571    /// per-CR fully-qualified rewrite the M4 CR materializer applies
572    /// per-tenant) would have had to be threaded through both
573    /// open-coded copies in lockstep or the two consumers would
574    /// silently disagree on which key-template a given edge resolves
575    /// to — the [`WitContract::target`] payload-extraction reading
576    /// `"carts/{cart_id}"` while the [`AplicacaoSpec::validate`] dedup
577    /// key read the operator-resolved `"tenant-a/carts/{cart_id}"`
578    /// would silently split the [`WitTarget::Store`]-arm rendered
579    /// payload from the actual dedup-key uniqueness axis, a
580    /// two-consumer split at the validator far from the source
581    /// `caixa.lisp` with no field naming the payload-drift root cause.
582    /// Lifting the resolution rule to a typed method on the substrate
583    /// primitive means every downstream store-payload-facing consumer
584    /// of the Aplicacao's per-`:contratos` payload surface reaches for
585    /// exactly one typed dispatch — the resolver's accept-set migrates
586    /// as a unit on any future axis addition.
587    ///
588    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
589    /// (7020470) / [`WitContract::subject`] (90de675) `Option<&str>`
590    /// accessors on the M3 mesh-slot payload-carrier axis — third and
591    /// final `Option<&str>`-return accessor on the per-`:contratos`
592    /// mesh-slot atom, closes the last unlifted per-`:contratos`
593    /// `Option<String>` axis and completes the "optional per-slot
594    /// payload-carrier scalar" projection pattern the peer HTTP /
595    /// pub-sub arms established across the three payload-shape
596    /// dispatch arms. Named `slot()` to match the storage field's
597    /// name and the paired [`WitTarget::STORE_FIELD_NAME`]
598    /// author-facing label const; the accessor's identity name maps
599    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
600    /// docstring already carries.
601    #[must_use]
602    pub fn slot(&self) -> Option<&str> {
603        self.slot.as_deref()
604    }
605
606    /// Substrate-canonical per-`:contratos` `(caller, callee)` owned-form
607    /// caller-callee-pair accessor every consumer that constructs an
608    /// [`AplicacaoError`] variant carrying the per-edge `(de, para)`
609    /// caller-callee pair keys off — returns the author-declared
610    /// `:contratos :de` / `:contratos :para` byte-strings verbatim as an
611    /// owned `(String, String)` tuple, projected through the lifted
612    /// [`WitContract::source`] / [`WitContract::destination`] scalar
613    /// accessors so any future rebrand on the caller-arm / callee-arm
614    /// projection axis (an M4 per-cluster caller-alias table the
615    /// operator pins through a future `:placement`-scoped slot, a
616    /// namespace-qualified rewrite the M4 CR materializer applies per-CR,
617    /// a per-`:membros` alias overlay from the future `:membros
618    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
619    /// acknowledges) reaches every diagnostic-construction site by
620    /// construction.
621    ///
622    /// The `(de, para)` pair is the "typed-edge caller-callee identity in
623    /// owned form" primitive every per-`:contratos` diagnostic variant on
624    /// [`AplicacaoError`] carries alongside its payload-shape arm — the
625    /// nine variants [`AplicacaoError::EmptyWit`],
626    /// [`AplicacaoError::ContratoEndpointEmpty`],
627    /// [`AplicacaoError::ContratoEndpointNotAbsolute`],
628    /// [`AplicacaoError::ContratoEndpointInvalid`],
629    /// [`AplicacaoError::ContratoSubjectEmpty`],
630    /// [`AplicacaoError::ContratoSubjectInvalid`],
631    /// [`AplicacaoError::ContratoSlotEmpty`],
632    /// [`AplicacaoError::ContratoSlotInvalid`], and
633    /// [`AplicacaoError::ContratoDuplicate`] each carry a `de: String,
634    /// para: String` field pair the constructor site reads verbatim off
635    /// the [`WitContract`] the diagnostic points at, so a diagnostic
636    /// whose `de:` and `para:` labels silently drift off the source
637    /// caller/callee — a per-cluster caller-alias rewrite that landed on
638    /// one variant's inline `de: c.de.clone()` field access but not on
639    /// its sibling variant's, an accidental swap of the `de:` and `para:`
640    /// arms in a copy-paste of the constructor block — would emit a
641    /// build-time error whose "which caixa is at fault" question the
642    /// operator answers wrongly, far from the source `caixa.lisp`.
643    ///
644    /// Prior to this lift the `(self.de.clone(), self.para.clone())`
645    /// pair was inlined at seven [`WitContract::target`] error-
646    /// construction sites (the [`AplicacaoError::ContratoEndpointEmpty`]
647    /// / [`AplicacaoError::ContratoEndpointNotAbsolute`] /
648    /// [`AplicacaoError::ContratoEndpointInvalid`] HTTP-arm variants,
649    /// the [`AplicacaoError::ContratoSubjectEmpty`] /
650    /// [`AplicacaoError::ContratoSubjectInvalid`] pub-sub-arm variants,
651    /// the [`AplicacaoError::ContratoSlotEmpty`] /
652    /// [`AplicacaoError::ContratoSlotInvalid`] store-arm variants) and
653    /// two [`AplicacaoSpec::validate`] error-construction sites (the
654    /// [`AplicacaoError::EmptyWit`] empty-`:wit` gate, the
655    /// [`AplicacaoError::ContratoDuplicate`] duplicate-`:contratos`
656    /// insert-first-seen closure) — nine open-coded `.de.clone() +
657    /// .para.clone()` pairs that expressed no compile-time contract that
658    /// the caller-arm and callee-arm arms of the same diagnostic
659    /// construction reach for the same [`WitContract`] instance or that
660    /// the `de:` and `para:` label pair binds to the fields the author
661    /// declared. Any future rebrand on the axis — an M4 per-cluster
662    /// caller/callee-alias rewrite the operator pins through a future
663    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
664    /// per-CR fully-qualified namespace prefix the M4
665    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
666    /// per-tenant, a canonicalization pass that lowercases the caller +
667    /// callee identifiers post-parse — would have had to be threaded
668    /// through every open-coded copy in lockstep or one variant's
669    /// diagnostic would silently name a different caller/callee pair
670    /// than its peer, silently degrading the "which caixa is at fault"
671    /// self-locating signal every operator-facing typed diagnostic
672    /// exists to carry. Lifting the pair to a typed method on the
673    /// substrate primitive means every downstream diagnostic-construction
674    /// site reaches for exactly one typed dispatch — the resolver's
675    /// projection migrates as a unit on any future axis addition.
676    ///
677    /// Peer of the sibling per-`:contratos` scalar accessor family
678    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43)
679    /// / [`WitContract::world_ref`] (6226bf4) on the mesh-slot-atom
680    /// scalar-value axes — first composite-projection accessor on the
681    /// per-`:contratos` mesh-slot atom, folds the two open-coded owned-
682    /// form `.clone()` field-accesses that pair the sibling
683    /// caller/callee accessors' `&str`-return borrowed-form outputs onto
684    /// one typed dispatch. Named `edge_pair()` to reflect the identity
685    /// name of the projected tuple (the typed-edge caller-callee pair,
686    /// distinct from the sibling triple-projection
687    /// [`WitContract::edge_triple`] accessor that folds the local `edge`
688    /// closure in [`WitContract::target`] + the paired
689    /// [`AplicacaoError::ContratoDuplicate`] diagnostic constructor
690    /// site's `(de, para, wit)` triple onto one typed dispatch).
691    #[must_use]
692    pub fn edge_pair(&self) -> (String, String) {
693        (self.source().to_string(), self.destination().to_string())
694    }
695
696    /// Owned form of the `(:contratos :de, :contratos :para, :contratos
697    /// :wit)` triple every per-edge diagnostic constructor that names
698    /// all three axes threads verbatim into its `de:` / `para:` /
699    /// `wit:` fields — the [`WitTarget::target`] dispatch's wrong-target
700    /// / missing-target / invalid-wit / capability-with-payload arms
701    /// (eight sites all shape `let (de, para, wit) = edge();
702    /// AplicacaoError::Contrato* { de, para, wit, .. }` before this
703    /// accessor landed) and the sibling
704    /// [`AplicacaoError::ContratoDuplicate`] duplicate-gate diagnostic
705    /// constructor (which paired `edge_pair()` for the `(de, para)`
706    /// prefix with a raw `c.wit.clone()` for the `wit:` tail — a mixed
707    /// typed-dispatch + raw-field-access shape the sibling accessor
708    /// family already flagged as a drift risk). Nine total call sites
709    /// collapse onto this helper.
710    ///
711    /// Lifted with the same one-source-of-truth discipline
712    /// [`WitContract::edge_pair`] carries on the paired
713    /// caller-callee-only axis: the returned tuple's `.0` / `.1` / `.2`
714    /// arms compose through the lifted [`WitContract::source`] /
715    /// [`WitContract::destination`] / [`WitContract::world_ref`]
716    /// scalar accessors byte-for-byte (pinned by the paired
717    /// [`tests::wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`]
718    /// composition-pin), so any future rebrand on the per-`:contratos`
719    /// caller / callee / world-ref axis (an M4 per-cluster
720    /// caller/callee-alias rewrite the operator pins through a future
721    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
722    /// per-CR fully-qualified namespace prefix the M4
723    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
724    /// per-tenant, an M4-typed-caller-enum `Display` re-canonicalization
725    /// on `source()` / `destination()`, a per-CR canonicalization pass
726    /// that lowercases the WIT world ref post-parse) migrates as a
727    /// single caixa-core edit rather than a coordinated rewrite of
728    /// nine open-coded triple-constructors.
729    ///
730    /// Peer of the sibling per-`:contratos` composite-projection
731    /// [`WitContract::edge_pair`] accessor on the mesh-slot-atom
732    /// composite-value axes — closes the last unlifted owned-form
733    /// composite-tuple axis on the per-`:contratos` diagnostic-
734    /// construction surface. Named `edge_triple()` to reflect the
735    /// identity name of the projected tuple (the typed-edge
736    /// caller-callee-wit triple, sibling to the caller-callee-only
737    /// pair `edge_pair()` returns).
738    #[must_use]
739    pub fn edge_triple(&self) -> (String, String, String) {
740        (
741            self.source().to_string(),
742            self.destination().to_string(),
743            self.world_ref().to_string(),
744        )
745    }
746
747    /// Borrowed [`ContratoIdentity`] six-tuple every consumer that
748    /// dedups typed edges keys off — routes through the lifted
749    /// [`WitContract::source`] / [`WitContract::destination`] /
750    /// [`WitContract::world_ref`] / [`WitContract::endpoint`] /
751    /// [`WitContract::subject`] / [`WitContract::slot`] scalar
752    /// accessors so the tuple's six arms and the [`ContratoIdentity`]
753    /// type alias's six axes migrate as a unit on any future axis
754    /// addition (adding a seventh field to [`WitContract`] is one
755    /// [`ContratoIdentity`] alias edit + one accessor addition + one
756    /// arm here, not a coordinated rewrite of every open-coded
757    /// six-tuple builder that dedups on the identity axis).
758    ///
759    /// Sibling of [`WitContract::edge_pair`] /
760    /// [`WitContract::edge_triple`] on the composite-projection axis:
761    /// the pair projects the caller-callee axes, the triple extends it
762    /// with the world-ref, this method extends it with the three
763    /// payload-carrier axes. Every projection returns the same six
764    /// scalar accessors' outputs; the three methods differ only in
765    /// which arms they surface.
766    #[must_use]
767    pub fn identity(&self) -> ContratoIdentity<'_> {
768        (
769            self.source(),
770            self.destination(),
771            self.world_ref(),
772            self.endpoint(),
773            self.subject(),
774            self.slot(),
775        )
776    }
777
778    /// True when this contract targets an HTTP-shaped WIT world.
779    #[must_use]
780    pub fn is_http(&self) -> bool {
781        wit_shape_is_http(self.world_ref())
782    }
783
784    /// True when this contract targets a pub-sub-shaped WIT world.
785    #[must_use]
786    pub fn is_pubsub(&self) -> bool {
787        wit_shape_is_pubsub(self.world_ref())
788    }
789
790    /// True when this contract targets a key/value-shaped WIT world.
791    #[must_use]
792    pub fn is_store(&self) -> bool {
793        wit_shape_is_store(self.world_ref())
794    }
795
796    /// True when this contract's caller equals its callee — a
797    /// structurally degenerate typed edge that no `:contratos` entry can
798    /// legitimately carry (MESH-COMPOSITION §III.1 — "Servico A calls
799    /// Servico B" is an *inter*-Servico contract between two distinct
800    /// graph nodes). A Servico contracting with itself resolves to an
801    /// in-process call the wasm-engine never routes through the mesh at
802    /// all, so no rendered `CiliumNetworkPolicy` / `HTTPRoute` /
803    /// per-edge policy can express the intended shape — the pub-sub
804    /// path silently rendered a self-allow rule that is a no-op (intra-
805    /// pod traffic bypasses the mesh entirely), and the synchronous
806    /// paths surfaced as a misleading `ContratoCycle` whose path was
807    /// `["cart", "cart"]` — framing a self-edge as a multi-node
808    /// deadlock. Every downstream consumer that must reject the shape
809    /// (the [`AplicacaoSpec::validate`] per-`:contratos` self-loop
810    /// gate at caixa-core/src/aplicacao.rs:5559, every future
811    /// per-`:contratos`-edge policy resolver on the M4 CR materializer
812    /// axis, every future adjacency-graph builder that must skip self-
813    /// edges rather than fold them into an incidental cycle) now keys
814    /// off exactly one typed dispatch on the substrate primitive, so
815    /// any future rebrand on the axis (an M4-typed-caller enum whose
816    /// identity comparison rule the accessor could route through, an
817    /// operator-side per-cluster caller/callee-alias table the
818    /// materializer resolves per-CR before the equality probe, a
819    /// promotion of the pointwise `==` to a set-membership check once
820    /// SimpleOneForOne-shaped dynamic replicas come into typed scope
821    /// so a per-replica self-edge is rejected under the same predicate)
822    /// migrates as a single caixa-core edit rather than a coordinated
823    /// rewrite of every downstream self-edge consumer. Composes
824    /// byte-for-byte through the lifted [`Self::source`] /
825    /// [`Self::destination`] scalar accessors — the accessor pair every
826    /// per-`:contratos` scalar-value axis already routes through — so
827    /// any future rebrand of the underlying `:de` / `:para` storage
828    /// (a lift from `String` to a typed `ServicoName(String)` newtype,
829    /// a per-Aplicacao interning arena the M4 CR materializer authors,
830    /// a `smol_str::SmolStr` inline-buffer swap) flows through the
831    /// same one body without a coordinated per-consumer rewrite.
832    ///
833    /// Sibling in shape to the peer per-`:contratos` shape-predicate
834    /// family [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
835    /// on the `:wit` world-ref axis — extended onto the per-edge
836    /// endpoint-equality axis: `is_http` / `is_pubsub` / `is_store`
837    /// partition the WIT-shape-space; `is_self_loop` partitions the
838    /// caller-callee identity-space. Named `is_self_loop()` to reflect
839    /// the graph-theoretic identity of the shape (a loop from a graph
840    /// node to itself, distinct from the sibling multi-node
841    /// `ContratoCycle` shape [`Self::detect_sync_cycles`] rejects) and
842    /// to match the [`AplicacaoError::ContratoSelfLoop`] diagnostic
843    /// variant already carrying the term.
844    #[must_use]
845    pub fn is_self_loop(&self) -> bool {
846        self.source() == self.destination()
847    }
848
849    /// Typed view of the contract's payload target. Enforces that the
850    /// `:wit` shape and the carried `:endpoint`/`:subject`/`:slot`
851    /// fields agree, and that each carried value is itself
852    /// value-shape valid:
853    ///
854    ///   - HTTP world (`wasi:http/*`, `http:*`) ⇒ exactly `:endpoint`,
855    ///     non-empty, leading-`/` (Cilium L7 `path` + Gateway API
856    ///     `PathPrefix` invariant — same shape required of `:entrada
857    ///     :paths`)
858    ///   - `PubSub` world (`nats:*`, `kafka:*`) ⇒ exactly `:subject`,
859    ///     non-empty (NATS / Kafka publish without a subject is a
860    ///     no-op subscribe, never the author's intent)
861    ///   - Store world (`wasi:keyvalue/*`, `kv:*`) ⇒ exactly `:slot`,
862    ///     non-empty (an empty slot template addresses the bucket
863    ///     root, defeating the per-key isolation the slot exists for)
864    ///   - Anything else ⇒ none of the three; the contract is a pure
865    ///     typed capability edge with no payload selector.
866    ///
867    /// Translates the Apollo Federation discipline ("conflicts are
868    /// errors at compile time, not warnings at runtime";
869    /// MESH-COMPOSITION §II.3) onto pleme-io's typed Aplicacao surface:
870    /// a contract whose WIT shape disagrees with its target field, or
871    /// whose target field carries a value-shape-invalid string, is a
872    /// build error — not a silent renderer drop. The returned
873    /// [`WitTarget`] view's `&str` payload is therefore guaranteed
874    /// non-empty (and absolute, for `Http`); every downstream consumer
875    /// (caixa-mesh's L7 emission, the M3 Gateway/HTTPRoute renderer,
876    /// the M4 per-edge policy resolver) can rely on that without
877    /// re-checking.
878    pub fn target(&self) -> Result<WitTarget<'_>, AplicacaoError> {
879        // Route the HTTP-shaped payload-target extraction through the
880        // lifted [`WitContract::endpoint`] accessor rather than the raw
881        // `self.endpoint.as_deref()` field access — the two production
882        // consumers of the per-`:contratos :endpoint` HTTP-shaped
883        // payload-carrier scalar (this method's Http-arm payload
884        // extraction, the [`AplicacaoSpec::validate`] duplicate-
885        // `:contratos` [`ContratoIdentity`] dedup-key HTTP arm) now key
886        // off exactly one typed dispatch on the substrate primitive, so
887        // any future rebrand on the axis (an M4 per-cluster endpoint-
888        // alias rewrite, a per-CR fully-qualified path prefix the M4
889        // materializer applies per-tenant, an M4 promotion from
890        // `Option<String>` to a typed HTTP path-template enum) migrates
891        // as a single caixa-core edit rather than a coordinated rewrite
892        // of the two call sites — peer of the sibling M3 per-`:placement`
893        // [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
894        // (74ec2d3) `Option<&str>` typed-dispatch discipline extended
895        // onto the per-`:contratos` HTTP-shaped payload-carrier axis.
896        let endpoint = self.endpoint();
897        let subject = self.subject();
898        // Route the store-arm payload-carrier scalar through the
899        // lifted [`WitContract::slot`] accessor rather than the raw
900        // `self.slot.as_deref()` field access — the two production
901        // consumers of the per-`:contratos :slot` key/value-store-
902        // shaped payload-carrier scalar (this method's Store-arm
903        // payload extraction, the [`AplicacaoSpec::validate`]
904        // duplicate-`:contratos` [`ContratoIdentity`] dedup-key store
905        // arm) now key off exactly one typed dispatch on the substrate
906        // primitive. Closes the last unlifted per-`:contratos`
907        // `Option<String>` axis, completing the payload-carrier
908        // accessor family peer of the sibling per-`:contratos`
909        // [`WitContract::endpoint`] (7020470) / [`WitContract::subject`]
910        // (90de675) lifts across the HTTP / pub-sub arms.
911        let slot = self.slot();
912        // Route the local `(de, para, wit)` triple-projection closure
913        // through the lifted [`WitContract::edge_triple`] typed accessor
914        // rather than re-inlining `(self.de.clone(), self.para.clone(),
915        // self.wit.clone())` — the eight [`AplicacaoError::Contrato*`]
916        // triple-carrying diagnostic constructors below (wrong-target /
917        // missing-target on all three payload arms + capability-with-
918        // payload + invalid-wit) now key off exactly one typed dispatch
919        // on the substrate-primitive composite projection, sibling to
920        // the peer [`WitContract::edge_pair`]-routed
921        // [`AplicacaoError::Empty*`]/`ContratoEndpointEmpty`/
922        // `ContratoSubjectEmpty`/`ContratoSlotEmpty` pair-carrying
923        // diagnostic constructors on the same per-`:contratos`
924        // diagnostic-construction surface.
925        let edge = || self.edge_triple();
926
927        // The `:wit` value drives every downstream dispatch — the
928        // is_http/is_pubsub/is_store prefix matchers below, the
929        // caixa-mesh L7-vs-L4 emission, the cycle-detector's pub-sub
930        // exclusion. Until this gate landed `target()` accepted any
931        // non-empty string and silently demoted unrecognized shapes to
932        // a capability-only edge (`:wit "WASI:HTTP/proxy"` — uppercase
933        // typo, `:wit "wasi-http/proxy"` — hyphen-instead-of-colon typo,
934        // `:wit "wasi:http proxy"` — whitespace, `:wit "wasi:"` — empty
935        // package, the paste-from-binary footgun a multi-line blob
936        // accidentally landing in the slot, the un-percent-encoded
937        // non-ASCII byte) — the canonical "I thought I had L7 HTTP
938        // routing, got L4-only" footgun. Empty is still pre-checked at
939        // the [`AplicacaoSpec::validate`] call site via the narrower
940        // [`AplicacaoError::EmptyWit`] variant (and fires first at the
941        // validate layer); the value-shape gate here picks up the
942        // structurally-invalid non-empty cases the empty check misses,
943        // and remains correct under direct `target()` calls outside
944        // validate (the predicate's defensive empty arm returns a
945        // parser-shaped reason rather than silently falling through to
946        // the Capability arm). Same trajectory as c4213a4 (WitContract
947        // endpoint/subject/slot value-shape gates lifted into
948        // `target()`) on the peer payload axes.
949        if let Err(reason) = crate::render::is_wit_world_ref(&self.wit) {
950            let (de, para, wit) = edge();
951            return Err(AplicacaoError::ContratoWitInvalid {
952                de,
953                para,
954                wit,
955                reason,
956            });
957        }
958
959        if self.is_http() {
960            if subject.is_some() || slot.is_some() {
961                let (de, para, wit) = edge();
962                return Err(AplicacaoError::ContratoWrongTarget {
963                    de,
964                    para,
965                    wit,
966                    expected: WitTarget::HTTP_FIELD_NAME,
967                });
968            }
969            let ep = endpoint.ok_or_else(|| {
970                let (de, para, wit) = edge();
971                AplicacaoError::ContratoMissingTarget {
972                    de,
973                    para,
974                    wit,
975                    expected: WitTarget::HTTP_FIELD_NAME,
976                }
977            })?;
978            if ep.is_empty() {
979                let (de, para) = self.edge_pair();
980                return Err(AplicacaoError::ContratoEndpointEmpty { de, para });
981            }
982            if !ep.starts_with('/') {
983                let (de, para) = self.edge_pair();
984                return Err(AplicacaoError::ContratoEndpointNotAbsolute {
985                    de,
986                    para,
987                    endpoint: ep.to_string(),
988                });
989            }
990            // The `:endpoint` lands verbatim as a Cilium L7 `path:` rule
991            // (caixa-mesh/src/lib.rs:311) and shares the K8s Gateway
992            // API v1 HTTPPathMatch.value admission grammar with the
993            // sibling `:entrada :paths` axis. Until this gate landed
994            // `target()` only refused the empty string + the missing-
995            // leading-`/` form; a structurally invalid endpoint
996            // (`"/charge?token=X"` — query in path slot, `"/foo bar"` —
997            // un-percent-encoded whitespace, `"/api/café"` — non-ASCII,
998            // `"/api//bar"` — consecutive slash, `"/api/../etc"` —
999            // path-traversal segment, the >1024-byte slug) silently
1000            // passed validate and the failure surfaced at apply time
1001            // as a Cilium policy rejection / silent traffic drop, far
1002            // from the source caixa.lisp. Same Gateway API HTTPPathMatch
1003            // grammar `:entrada :paths` already gates (55410e4), now
1004            // shared with `:contratos :endpoint` through the lifted
1005            // `crate::render::is_gateway_api_http_path` predicate.
1006            if let Err(reason) = crate::render::is_gateway_api_http_path(ep) {
1007                let (de, para) = self.edge_pair();
1008                return Err(AplicacaoError::ContratoEndpointInvalid {
1009                    de,
1010                    para,
1011                    endpoint: ep.to_string(),
1012                    reason,
1013                });
1014            }
1015            return Ok(WitTarget::Http { endpoint: ep });
1016        }
1017        if self.is_pubsub() {
1018            if endpoint.is_some() || slot.is_some() {
1019                let (de, para, wit) = edge();
1020                return Err(AplicacaoError::ContratoWrongTarget {
1021                    de,
1022                    para,
1023                    wit,
1024                    expected: WitTarget::PUBSUB_FIELD_NAME,
1025                });
1026            }
1027            let s = subject.ok_or_else(|| {
1028                let (de, para, wit) = edge();
1029                AplicacaoError::ContratoMissingTarget {
1030                    de,
1031                    para,
1032                    wit,
1033                    expected: WitTarget::PUBSUB_FIELD_NAME,
1034                }
1035            })?;
1036            if s.is_empty() {
1037                let (de, para) = self.edge_pair();
1038                return Err(AplicacaoError::ContratoSubjectEmpty { de, para });
1039            }
1040            // The `:subject` lands at runtime as the NATS subject the
1041            // producer publishes to and the consumer subscribes from.
1042            // Until this gate landed `target()` only refused the
1043            // empty string; a structurally invalid subject
1044            // (`"foo..bar"` — empty token between separators,
1045            // `"foo.>.bar"` — non-trailing `>` wildcard the NATS
1046            // server's subject parser rejects, `"foo bar"` —
1047            // un-percent-encoded whitespace, `"foo.café"` —
1048            // un-percent-encoded non-ASCII, `".foo"` / `"foo."` —
1049            // empty leading/trailing tokens, the >256-byte
1050            // paste-from-binary slug) silently passed validate and
1051            // the failure surfaced at runtime as a NATS server-side
1052            // `-ERR 'Invalid Subject'` on publish / subscribe, or as
1053            // a silent message drop, far from the source caixa.lisp.
1054            // Same Gateway API HTTPPathMatch / WIT-IDL grammar
1055            // trajectory `:contratos :endpoint` (4f0390b) and
1056            // `:contratos :wit` (6226bf4) already gate, now shared
1057            // with `:contratos :subject` through the lifted
1058            // `crate::render::is_nats_subject` predicate.
1059            if let Err(reason) = crate::render::is_nats_subject(s) {
1060                let (de, para) = self.edge_pair();
1061                return Err(AplicacaoError::ContratoSubjectInvalid {
1062                    de,
1063                    para,
1064                    subject: s.to_string(),
1065                    reason,
1066                });
1067            }
1068            return Ok(WitTarget::PubSub { subject: s });
1069        }
1070        if self.is_store() {
1071            if endpoint.is_some() || subject.is_some() {
1072                let (de, para, wit) = edge();
1073                return Err(AplicacaoError::ContratoWrongTarget {
1074                    de,
1075                    para,
1076                    wit,
1077                    expected: WitTarget::STORE_FIELD_NAME,
1078                });
1079            }
1080            let sl = slot.ok_or_else(|| {
1081                let (de, para, wit) = edge();
1082                AplicacaoError::ContratoMissingTarget {
1083                    de,
1084                    para,
1085                    wit,
1086                    expected: WitTarget::STORE_FIELD_NAME,
1087                }
1088            })?;
1089            if sl.is_empty() {
1090                let (de, para) = self.edge_pair();
1091                return Err(AplicacaoError::ContratoSlotEmpty { de, para });
1092            }
1093            // Value-shape gate on the third (and last) typed payload
1094            // axis the `WitContract::target` dispatch carries — the
1095            // peer of [`crate::render::is_gateway_api_http_path`] for
1096            // `:endpoint` (4f0390b) and [`crate::render::is_nats_subject`]
1097            // for `:subject` (63e18a0). Until this gate landed
1098            // `target()` only refused the empty string; a structurally
1099            // invalid slot (`"check out/$order"` — un-percent-encoded
1100            // whitespace whose runtime behavior varies unpredictably
1101            // across kv backends, `"checkout/\x01order"` — control
1102            // character that Redis admits but corrupts on next read
1103            // and DynamoDB rejects outright, `"chéckout/$order"` —
1104            // un-percent-encoded non-ASCII byte each backend re-encodes
1105            // differently, `"checkout\n/$order"` — embedded newline,
1106            // the 513-byte paste-from-binary slug) silently passed
1107            // validate and surfaced at runtime as a per-backend kv
1108            // write rejection (DynamoDB / etcd) or as a silent
1109            // next-read corruption (Redis-via-RESP3), far from the
1110            // source caixa.lisp with no field naming which `:contratos`
1111            // edge carried the typo. The lifted predicate makes the
1112            // kv-backend intersection-floor a substrate-level
1113            // invariant at validate time, not a runtime "this passed
1114            // validate but the kv backend rejected on first write"
1115            // surprise — closes the typed payload-axis value-shape
1116            // trajectory across all three legs of the four
1117            // [`WitTarget`] arms (HTTP / PubSub / Store / Capability)
1118            // that caixa-mesh + the future kv emitters land in.
1119            if let Err(reason) = crate::render::is_wasi_keyvalue_slot(sl) {
1120                let (de, para) = self.edge_pair();
1121                return Err(AplicacaoError::ContratoSlotInvalid {
1122                    de,
1123                    para,
1124                    slot: sl.to_string(),
1125                    reason,
1126                });
1127            }
1128            return Ok(WitTarget::Store { slot: sl });
1129        }
1130
1131        // Unrecognized WIT world — must not carry any payload target.
1132        if endpoint.is_some() || subject.is_some() || slot.is_some() {
1133            let (de, para, wit) = edge();
1134            return Err(AplicacaoError::ContratoWrongTarget {
1135                de,
1136                para,
1137                wit,
1138                expected: WitTarget::CAPABILITY_EXPECTED,
1139            });
1140        }
1141        Ok(WitTarget::Capability)
1142    }
1143}
1144
1145/// Borrowed identity key for the typed-graph duplicate-`:contratos`
1146/// gate (see [`AplicacaoSpec::validate`]): every field that
1147/// distinguishes one contract from another, in declaration order
1148/// (`(de, para, wit, endpoint, subject, slot)`). Two [`WitContract`]s
1149/// with equal [`ContratoIdentity`]s are the same typed edge declared
1150/// twice — the graph-edge analogue of duplicate `:membros` /
1151/// `:placement :clusters` / `:entrada :paths` entries. Lifted as a
1152/// type alias so the duplicate-gate's `HashSet<…>` type doesn't trip
1153/// clippy's `type_complexity` lint (and so a future axis added to
1154/// `WitContract` is one alias edit, not a coordinated rewrite of
1155/// every set instantiation).
1156pub type ContratoIdentity<'a> = (
1157    &'a str,
1158    &'a str,
1159    &'a str,
1160    Option<&'a str>,
1161    Option<&'a str>,
1162    Option<&'a str>,
1163);
1164
1165/// Typed view of a [`WitContract`]'s payload target. Each variant
1166/// carries the field its WIT shape requires; constructing a `Http`
1167/// view without an endpoint is impossible by the type system.
1168///
1169/// Renderers (caixa-mesh L7 rules, feira app graph) match on this
1170/// instead of probing `Option<String>` fields one by one — the
1171/// "which payload field is set?" question is answered once, at
1172/// validation time.
1173#[derive(Debug, Clone, Copy, PartialEq, Eq, gen_platform::IsVariant)]
1174pub enum WitTarget<'a> {
1175    /// HTTP-shaped WIT world. Carries the configured request path.
1176    Http { endpoint: &'a str },
1177    /// Pub-sub-shaped WIT world. Carries the event-stream subject.
1178    ///
1179    /// The `IsVariant` derive would auto-name the predicate `is_pub_sub`
1180    /// (`discriminant_to_snake("PubSub") == "pub_sub"`); the explicit
1181    /// `#[is_variant(name = "pubsub")]` override keeps the emitted
1182    /// method name byte-identical to the sibling
1183    /// [`WitContract::is_pubsub`] predicate (the paired shape-side
1184    /// arm-discriminator that routes through
1185    /// [`wit_shape_is_pubsub`] on the wit-world-ref scalar rather than
1186    /// through `matches!` on the variant), so the two arm-discriminator
1187    /// axes — target-side variant-arm and shape-side ref-prefix — reach
1188    /// every downstream consumer through the same `is_pubsub()` name.
1189    #[is_variant(name = "pubsub")]
1190    PubSub { subject: &'a str },
1191    /// Key-value-shaped WIT world. Carries the slot template.
1192    Store { slot: &'a str },
1193    /// A typed capability edge with no payload selector — the WIT
1194    /// world stands on its own (rare; reserved for plain capability
1195    /// imports or M4-and-later WIT worlds we haven't shaped yet).
1196    Capability,
1197}
1198
1199impl<'a> WitTarget<'a> {
1200    /// Canonical author-facing `:contratos` payload field name for the
1201    /// HTTP-shaped arm — the `expected: &'static str` scalar the
1202    /// [`AplicacaoError::ContratoMissingTarget`] /
1203    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1204    /// through, the `:endpoint "…"` keyword the [`WitTarget::label`]
1205    /// duplicate-edge diagnostic emits, and the `endpoint=…` prefix
1206    /// the `feira app graph` verb prints. Peer of
1207    /// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
1208    /// on the payload-field-name axis; declared as a peer const next
1209    /// to the [`WitTarget::Http`] variant so a future rename on the
1210    /// author-surface `(defcaixa … :contratos ((:de … :para … :wit …
1211    /// :endpoint …)))` field lands in exactly one place, not scattered
1212    /// across the [`WitContract::target`] gate's six `expected:`
1213    /// literals, the label template, and every downstream consumer
1214    /// that prints a per-arm prefix. Same trajectory as the peer
1215    /// [`WitTarget::label`] lift (174e96a): a single source of truth
1216    /// for the arm's shape, next to the variant declaration.
1217    pub const HTTP_FIELD_NAME: &'static str = "endpoint";
1218    /// Canonical author-facing `:contratos` payload field name for the
1219    /// pub-sub-shaped arm. Peer of [`WitTarget::HTTP_FIELD_NAME`] /
1220    /// [`WitTarget::STORE_FIELD_NAME`] on the payload-field-name axis;
1221    /// see [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1222    pub const PUBSUB_FIELD_NAME: &'static str = "subject";
1223    /// Canonical author-facing `:contratos` payload field name for the
1224    /// key/value-store-shaped arm. Peer of
1225    /// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`]
1226    /// on the payload-field-name axis; see
1227    /// [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1228    pub const STORE_FIELD_NAME: &'static str = "slot";
1229
1230    /// Canonical stable human-readable label the payload-less
1231    /// [`WitTarget::Capability`] arm renders as under [`Self::label`] —
1232    /// the byte-string every consumer that formats a payload-less
1233    /// typed capability edge as text lands on (the
1234    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` diagnostic
1235    /// naming which identical edge was declared twice, the future
1236    /// `feira app graph` verb's per-arm prefix, the future M4 per-edge
1237    /// policy resolver's audit view, the operator's mesh-graph audit).
1238    /// Peer of the payload-arm [`Self::HTTP_FIELD_NAME`] /
1239    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`]
1240    /// author-facing label-scalar consts — the same
1241    /// "one canonical declaration per arm, next to the variant, so a
1242    /// future rename lands in one place" discipline extended to the
1243    /// payload-less arm. Until this lift landed the byte-string sat
1244    /// twice — once inline in [`Self::label`]'s [`WitTarget::Capability`]
1245    /// match arm, once in the pin test asserting the label's
1246    /// [`WitTarget::Capability`] output — with no compile-time link
1247    /// between the two: a rebrand on either side (an operator-facing
1248    /// vocabulary shift, a per-consumer disambiguation like
1249    /// `"(capability — no payload; typed edge only)"`) would silently
1250    /// desynchronize until a downstream consumer surfaced the drift at
1251    /// runtime.
1252    pub const CAPABILITY_LABEL: &'static str = "(capability — no payload)";
1253
1254    /// Canonical `expected:` scalar the
1255    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1256    /// through for the payload-less [`WitTarget::Capability`] arm — the
1257    /// byte-string authors read as "this WIT world's shape is not one
1258    /// of {`HTTP`, `PubSub`, `Store`}, so it must not carry
1259    /// `:endpoint` / `:subject` / `:slot`". Peer of the payload-arm
1260    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1261    /// [`Self::STORE_FIELD_NAME`] consts on the
1262    /// `ContratoWrongTarget::expected` axis — the fourth arm of the
1263    /// same "which payload field name goes in the diagnostic" dispatch
1264    /// the three payload-arm consts cover, extended to the payload-less
1265    /// arm. Until this lift landed the byte-string sat twice — once
1266    /// inline in the [`Self::target`] Capability-arm rejection at the
1267    /// production dispatch, once in the pin test asserting the
1268    /// diagnostic's `expected:` scalar carries `"none"` verbatim — with
1269    /// no compile-time link between the two: a rebrand on either side
1270    /// (an author-facing vocabulary shift to `"capability"` /
1271    /// `"(none)"` / `"no-payload"` as the WIT registry's shape
1272    /// vocabulary sharpens, a per-consumer disambiguation as M4 splits
1273    /// [`WitTarget::Capability`] into per-shape peers) would silently
1274    /// desynchronize until a downstream consumer surfaced the drift at
1275    /// runtime. Same "one canonical declaration per arm, next to the
1276    /// variant, so a future rename lands in one place" discipline the
1277    /// peer [`Self::CAPABILITY_LABEL`] lift (7ed03a3-era) already
1278    /// established for the payload-less arm's human-readable label
1279    /// axis; this lift extends it onto the peer diagnostic-scalar axis
1280    /// so both halves of the "how does the Capability arm surface at
1281    /// its two consumer axes (human-readable label, wrong-target
1282    /// diagnostic)" pipeline route through peer consts declared next
1283    /// to the variant.
1284    ///
1285    /// Pairwise-distinctness against the three payload-arm scalars
1286    /// ([`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1287    /// [`Self::STORE_FIELD_NAME`]) is pinned by the sibling
1288    /// `wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`
1289    /// test — the 4-way closure of the 3-way
1290    /// `wit_target_field_names_are_pairwise_distinct` sibling pin onto
1291    /// the `ContratoWrongTarget::expected` axis, matching the peer
1292    /// `m3_placement_estrategia_consts_are_pairwise_distinct` closed-set
1293    /// scalar-value distinctness discipline the sibling M3 typed-enum
1294    /// discriminator axis already carries.
1295    pub const CAPABILITY_EXPECTED: &'static str = "none";
1296
1297    /// The `(author-facing field name, payload)` pair this typed target
1298    /// arm carries — `Some((HTTP_FIELD_NAME, endpoint))` for
1299    /// [`Self::Http`], `Some((PUBSUB_FIELD_NAME, subject))` for
1300    /// [`Self::PubSub`], `Some((STORE_FIELD_NAME, slot))` for
1301    /// [`Self::Store`], `None` for the payload-less
1302    /// [`Self::Capability`] arm.
1303    ///
1304    /// Lifted as the single 4-arm dispatch that both [`Self::label`]
1305    /// (formats `":{field} {payload:?}"` on `Some`, falls to
1306    /// [`Self::CAPABILITY_LABEL`] on `None`) and [`Self::field_name`]
1307    /// (returns the first component) route through, so a future
1308    /// [`WitTarget`] variant addition — the M4-and-later per-edge WIT
1309    /// registry may split [`Self::Http`] into `Rest` / `Grpc` peers,
1310    /// or extend [`Self::Store`] with a `Queue`-shaped peer — becomes
1311    /// exactly one new match-arm here (a compile-time exhaustiveness
1312    /// error otherwise), not a coordinated three-way rewrite of the
1313    /// prior [`Self::label`] template + [`Self::field_name`] dispatch
1314    /// + every downstream consumer that reaches for the pair.
1315    ///
1316    /// Until this lift landed the three payload arms sat in
1317    /// [`Self::label`] as three near-identical `format!(":{} {…:?}", …)`
1318    /// invocations (one per variant, each hand-quoting the paired
1319    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1320    /// [`Self::STORE_FIELD_NAME`] const) — the canonical
1321    /// "same shape, written N times" duplication THEORY.md §I.3.5
1322    /// ("Generation first, composition second, hand-authoring last;
1323    /// the duplication budget is zero") promotes to a build-time
1324    /// concern, with each per-arm site paired to its own const with no
1325    /// compile-time link between the format template and the arm's
1326    /// payload extraction.
1327    #[must_use]
1328    pub const fn payload_pair(&self) -> Option<(&'static str, &'a str)> {
1329        match *self {
1330            WitTarget::Http { endpoint } => Some((Self::HTTP_FIELD_NAME, endpoint)),
1331            WitTarget::PubSub { subject } => Some((Self::PUBSUB_FIELD_NAME, subject)),
1332            WitTarget::Store { slot } => Some((Self::STORE_FIELD_NAME, slot)),
1333            WitTarget::Capability => None,
1334        }
1335    }
1336
1337    /// The canonical author-facing `:contratos` payload field name
1338    /// this typed target arm carries (`Http` → `Some("endpoint")`,
1339    /// `PubSub` → `Some("subject")`, `Store` → `Some("slot")`), or
1340    /// `None` for the payload-less `Capability` arm.
1341    ///
1342    /// Routes through [`Self::payload_pair`] — the single 4-arm
1343    /// dispatch [`Self::label`] also reads — so a future variant
1344    /// addition is one match-arm edit at [`Self::payload_pair`], not a
1345    /// per-consumer rewrite. Same "exhaustive-match at one canonical
1346    /// dispatch, thin projections at each consumer" trajectory the
1347    /// peer [`PlacementStrategy::as_str`] / [`std::fmt::Display`]
1348    /// pair (0a2f653) landed on the sibling M3 typed-enum axis.
1349    #[must_use]
1350    pub const fn field_name(&self) -> Option<&'static str> {
1351        match self.payload_pair() {
1352            Some((f, _)) => Some(f),
1353            None => None,
1354        }
1355    }
1356
1357    /// Render this typed target as a stable human-readable label
1358    /// (`:endpoint "/charge"`, `:subject "events.x"`,
1359    /// `:slot "checkout/$order"`, or `(capability — no payload)` when
1360    /// the WIT world is a pure capability edge).
1361    ///
1362    /// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
1363    /// gate so the diagnostic names *which* identical edge was
1364    /// declared twice (not just which `(de, para, wit)` triple).
1365    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
1366    /// on the payload-carrying arms (`Some((field, payload)) →
1367    /// format!(":{field} {payload:?}")`) and through the lifted
1368    /// [`Self::CAPABILITY_LABEL`] const on the payload-less
1369    /// [`Self::Capability`] arm — so a future variant addition (the
1370    /// M4-and-later per-edge WIT registry may split [`Self::Http`]
1371    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
1372    /// `Queue`-shaped peer) becomes a single new match-arm on
1373    /// [`Self::payload_pair`] rather than a rewrite of this template
1374    /// (and every downstream consumer that reaches for the label
1375    /// shape: the per-edge policy resolver in M4, the `feira app
1376    /// graph` view, the operator's mesh-graph audit). Until this
1377    /// lift landed the three payload arms carried three near-identical
1378    /// per-arm `format!(":{} {…:?}", …)` invocations, and the
1379    /// [`Self::Capability`] arm carried the payload-less byte-string
1380    /// twice (once inline here, once in the pin test) — closing the
1381    /// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
1382    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
1383    /// / 4a1e490) peer-const lifts already established for the
1384    /// payload-carrying arms.
1385    #[must_use]
1386    pub fn label(&self) -> String {
1387        match self.payload_pair() {
1388            Some((field, payload)) => format!(":{field} {payload:?}"),
1389            None => Self::CAPABILITY_LABEL.to_string(),
1390        }
1391    }
1392}
1393
1394/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
1395/// pretty-printed byte-string every consumer that formats a typed
1396/// payload target as user-facing text lands on (the
1397/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
1398/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
1399/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
1400/// graph` per-`:contratos`-edge payload column that reaches the graph
1401/// verb through `format!("{target}")`, the future M4 per-edge policy
1402/// resolver's per-edge audit-log line, the operator's mesh-graph
1403/// per-edge inspection view) reaches for the same lifted
1404/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
1405/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
1406/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
1407/// routes through — extending the three-path-convergence
1408/// (`Debug` for structural inspection, `Display` for user-facing text,
1409/// per-arm typed accessor for the canonical byte-string) discipline the
1410/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
1411/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
1412/// onto the fourth (and only remaining) typed-shape-discriminator axis
1413/// on the caixa surface.
1414///
1415/// Pre-lift the two paths were structurally independent — every consumer
1416/// reaching for a payload byte-string past the [`WitTarget::label`]
1417/// helper had to pick between three paths ([`WitTarget::label`],
1418/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
1419/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
1420/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
1421/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
1422/// that reached for `format!("{target}")` — the canonical shape every
1423/// user-facing pretty-print site on the sibling typed-enum axes already
1424/// uses — would silently land on the `Debug` derive's structural output
1425/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
1426/// than the `label()` helper's stable byte-string (`:endpoint
1427/// "/charge"` — the author-facing `:contratos` keyword form) the
1428/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
1429/// already threads through. The two spellings would diverge silently in
1430/// every downstream diagnostic / graph / audit line reached through
1431/// `format!` rather than through the `label()` helper. Routing
1432/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
1433/// path: every `format!("{v}")` call reaches the same
1434/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
1435/// and the duplicate-`:contratos` gate already route through, so a
1436/// future variant addition (the M4-and-later per-edge WIT registry may
1437/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
1438/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
1439/// consumer at exactly one place — the [`WitTarget::payload_pair`]
1440/// match — rather than fanning out through hand-rolled per-arm
1441/// [`std::fmt::Display`] arms.
1442///
1443/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
1444/// is the typed view returned by [`WitContract::target`], not a
1445/// closed-set discriminator enum with a gen-platform Discriminant
1446/// registration, so the `Debug` derive's structural output (which every
1447/// `{v:?}` consumer still reaches) stays distinct from the `Display`
1448/// helper's stable pretty-printed byte-string. `Debug` reveals variant
1449/// shape for structural inspection; `Display` (via `label`) reveals the
1450/// stable author-facing payload projection.
1451///
1452/// Pin tests
1453/// [`tests::wit_target_display_routes_through_label_helper`] and
1454/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
1455/// assert the two paths agree byte-for-byte on every variant, so a
1456/// future variant addition or `label()` reimplementation that hand-rolls
1457/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
1458/// build error visible at caixa-core test time, not a silent
1459/// per-consumer dispatch miss at diagnostic / audit / graph time.
1460impl std::fmt::Display for WitTarget<'_> {
1461    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1462        f.write_str(&self.label())
1463    }
1464}
1465
1466// ── one Aplicacao member ─────────────────────────────────────────────
1467
1468/// A Servico participating in the Aplicacao. Same shape as
1469/// `crate::supervisor::ChildSpec` but without a restart policy —
1470/// supervision is per-Servico (each member has its own
1471/// `:supervisor`), the Aplicacao orchestrates *placement*.
1472#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1473#[serde(rename_all = "camelCase")]
1474pub struct Membro {
1475    /// Member caixa's `:nome`. Resolves through the same dep
1476    /// resolution path as `crate::dep::Dep`.
1477    pub caixa: String,
1478
1479    /// Semver constraint.
1480    pub versao: String,
1481}
1482
1483impl Membro {
1484    /// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
1485    /// accessor every consumer that reads the member's Servico identity
1486    /// keys off — returns the author-declared `:membros :caixa`
1487    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
1488    /// own [`String`] storage.
1489    ///
1490    /// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
1491    /// participating in the Aplicacao — validated by
1492    /// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
1493    /// (via [`validate_membro_caixa`]), unique across the Aplicacao's
1494    /// `:membros` list, distinct from the Aplicacao's own `:nome` (via
1495    /// [`validate_no_self_membership`]) — and every downstream consumer
1496    /// that fans on the member's identity keys off this scalar (the
1497    /// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
1498    /// lookup, the per-`:membros` duplicate gate's dedup key, the
1499    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
1500    /// identity, the self-membership gate, the
1501    /// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
1502    /// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
1503    /// CR materializer's per-member resolver).
1504    ///
1505    /// Prior to this lift the `.caixa` byte-string was read inline at
1506    /// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
1507    /// set collector at
1508    /// `self.membros.iter().map(|m| m.caixa.as_str())`, the
1509    /// [`validate_membros`] validation-side member-caixa gate at
1510    /// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
1511    /// per-member duplicate-gate dedup key at
1512    /// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
1513    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
1514    /// `adj.entry(m.caixa.as_str()).or_default()`, and the
1515    /// [`validate_no_self_membership`] self-loop gate at
1516    /// `m.caixa == parent_nome`) — five open-coded field-accesses that
1517    /// expressed no compile-time link back to the typed slot. Every
1518    /// caixa-mesh `metadata.name` derived from a `:membros :caixa`
1519    /// value flows through the [`caixa_mesh::fleet_programs`] per-entry
1520    /// `name:` axis, so a future extension of the `:membros :caixa`
1521    /// axis to a richer author surface — a per-cluster alias table the
1522    /// operator pins through a future `:placement`-scoped slot, a
1523    /// namespace-qualified rewrite the M4 CR materializer applies
1524    /// per-CR, a per-member overlay from the future `:membros
1525    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
1526    /// acknowledges — would have had to be threaded through every
1527    /// open-coded copy in lockstep or one consumer would silently
1528    /// disagree with the peers on which caixa a given member resolves
1529    /// to. A member-set lookup that treated the name as `"cart"` while
1530    /// the peer adjacency map treated it as `"tenant-a/cart"` would
1531    /// silently split the `:contratos` membership-lookup diagnostic from
1532    /// the cycle-detector's node identity — a two-consumer split at the
1533    /// validator far from the source `caixa.lisp` with no field naming
1534    /// the identity-drift root cause. Lifting the resolution rule to a
1535    /// typed method on the substrate primitive means every downstream
1536    /// consumer of the Aplicacao's per-`:membros` identity surface
1537    /// reaches for exactly one typed dispatch — the resolver's
1538    /// accept-set migrates as a unit on any future axis addition.
1539    ///
1540    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
1541    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
1542    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
1543    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
1544    /// destination-Servico scalar accessors — same "one typed dispatch
1545    /// on the substrate primitive, thin projections at each consumer"
1546    /// discipline extended onto the per-`:membros` member-caixa `:nome`
1547    /// byte-string axis. Named `nome()` to match the tatara-lisp
1548    /// author-surface term the field's docstring already reaches for
1549    /// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
1550    /// [`crate::dep::Dep::nome`] field-name discipline the substrate
1551    /// already carries — the accessor's name maps directly onto the
1552    /// canonical caixa-identity vocabulary rather than shadowing the
1553    /// field's storage-side `caixa` label.
1554    #[must_use]
1555    pub fn nome(&self) -> &str {
1556        self.caixa.as_str()
1557    }
1558
1559    /// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
1560    /// requirement scalar accessor every consumer that reads the
1561    /// member's version pin keys off — returns the author-declared
1562    /// `:membros :versao` byte-string verbatim as a `&str`, borrowed
1563    /// from the typed slot's own [`String`] storage.
1564    ///
1565    /// The `:membros :versao` slot carries the Cargo-shaped semver
1566    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
1567    /// pins which release of the member-caixa the Aplicacao composes
1568    /// against — the same requirement grammar the peer `:deps :versao`
1569    /// / `:children :versao` axes carry, resolved through the shared
1570    /// [`crate::render::require_valid_versao_requirement`] cascade and
1571    /// the shared [`crate::version::parse_requirement`] parser. Every
1572    /// downstream consumer that fans on the member's version pin keys
1573    /// off this scalar (the [`validate_membros`] per-member requirement
1574    /// gate at `require_valid_versao_requirement(m.versao_requirement(),
1575    /// …)`, the [`feira app graph`] per-member `println!("    - {} {}",
1576    /// m.nome(), m.versao_requirement())` line, every future per-cluster
1577    /// version-lock overlay the operator pins through a future
1578    /// `:placement`-scoped slot, the future
1579    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
1580    /// version resolver, the future `feira app deploy` pipeline's
1581    /// per-member lacre BLAKE3-closure lookup).
1582    ///
1583    /// Prior to this lift the `.versao` byte-string was accessed inline
1584    /// at two `&str`-shaped sites — the [`validate_membros`]
1585    /// requirement-gate call `require_valid_versao_requirement(&m.versao,
1586    /// …)` and the `feira app graph` per-member printer's `println!(
1587    /// "    - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
1588    /// prior to this lift) — two open-coded field-accesses that expressed
1589    /// no compile-time link back to the typed slot. A future extension of
1590    /// the `:membros :versao` axis to a richer author surface (a
1591    /// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
1592    /// flow, a lacre-projected concrete-version rewrite the operator
1593    /// materializes at CR-admission time, a future `:membros :versao-lock`
1594    /// per-cluster override slot) would have had to be threaded through
1595    /// every open-coded copy in lockstep or one consumer would silently
1596    /// disagree with the peers on which release constraint a given
1597    /// member resolves to. Lifting the resolution rule to a typed method
1598    /// on the substrate primitive means every downstream requirement-
1599    /// facing consumer reaches for exactly one typed dispatch — the
1600    /// resolver's accept-set migrates as a unit on any future axis
1601    /// addition.
1602    ///
1603    /// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
1604    /// member-caixa `:nome` scalar accessor — the pair
1605    /// `(nome(), versao_requirement())` jointly projects the
1606    /// `(caixa, versao)` field pair every renderer that fans on
1607    /// per-member identity + version pin keys off, closing the last
1608    /// unlifted per-`:membros` scalar axis so every downstream
1609    /// per-`:membros` reader now routes through a typed dispatch on the
1610    /// substrate primitive. Named `versao_requirement()` rather than
1611    /// `versao()` because the field's storage-side `.versao` label is
1612    /// already the author-surface term (`:versao`); the accessor's name
1613    /// carries the semantic role — the semver *requirement* string the
1614    /// shared [`crate::version::parse_requirement`] entry-point consumes
1615    /// — so a raw field access and a typed dispatch read differently at
1616    /// every consumer site.
1617    ///
1618    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
1619    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
1620    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
1621    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
1622    /// destination-Servico scalar accessors — same "one typed dispatch
1623    /// on the substrate primitive, thin projections at each consumer"
1624    /// discipline extended onto the per-`:membros` member-`:versao`
1625    /// semver-requirement byte-string axis.
1626    #[must_use]
1627    pub fn versao_requirement(&self) -> &str {
1628        self.versao.as_str()
1629    }
1630}
1631
1632// ── mesh-level policies ──────────────────────────────────────────────
1633
1634/// Mesh policies that apply to every `:contratos` edge unless
1635/// overridden per-edge in M4. V0 is a single global policy block.
1636#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
1637#[serde(rename_all = "camelCase")]
1638pub struct MeshPolicy {
1639    /// Per-call timeout. Authored as a duration string (`"30s"`).
1640    #[serde(
1641        default,
1642        skip_serializing_if = "Option::is_none",
1643        with = "supervisor::duration_codec"
1644    )]
1645    pub timeout: Option<Duration>,
1646
1647    /// Number of retries on transient failure. None = no retries.
1648    #[serde(default, skip_serializing_if = "Option::is_none")]
1649    pub retries: Option<u32>,
1650
1651    /// Circuit breaker config. Trips after N failures within W
1652    /// duration; closes after a cooldown.
1653    #[serde(default, skip_serializing_if = "Option::is_none")]
1654    pub circuit_breaker: Option<CircuitBreaker>,
1655
1656    /// Whether mTLS is required for every contrato. Default: true
1657    /// (sandboxing-by-default; explicit opt-out only).
1658    #[serde(default, skip_serializing_if = "Option::is_none")]
1659    pub mtls_required: Option<bool>,
1660
1661    /// Token-bucket rate limit. Authored as `"100/s"` or
1662    /// `"5000/m"`; stored as `(rate, window)`.
1663    #[serde(
1664        default,
1665        skip_serializing_if = "Option::is_none",
1666        with = "rate_limit_codec"
1667    )]
1668    pub rate_limit: Option<RateLimit>,
1669}
1670
1671impl MeshPolicy {
1672    /// True when no `:politicas` axis carries a value — every field is
1673    /// `None`. The same emptiness contract every other M2/M3 typed
1674    /// surface carries ([`crate::LimitsSpec::is_empty`],
1675    /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
1676    /// typed slot onto a cluster artifact key off this predicate to
1677    /// decide "emit the slot" vs "skip the slot entirely", so an
1678    /// authored-but-unset `:politicas (())` round-trips to a rendered
1679    /// artifact that's structurally identical to one that omits the
1680    /// slot. Lifted as a typed predicate (rather than per-renderer
1681    /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
1682    /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
1683    /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
1684    /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
1685    /// not a coordinated rewrite of every consumer that's reaching
1686    /// for the emptiness semantic.
1687    #[must_use]
1688    pub const fn is_empty(&self) -> bool {
1689        self.timeout().is_none()
1690            && self.retries().is_none()
1691            && self.circuit_breaker().is_none()
1692            && self.mtls_required().is_none()
1693            && self.rate_limit().is_none()
1694    }
1695
1696    /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
1697    /// per-call-deadline scalar accessor every consumer of the
1698    /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
1699    /// returns the author-declared `:politicas :timeout` typed
1700    /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
1701    /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
1702    /// is `Copy`, so the accessor returns by value; no borrow of
1703    /// `&self` past the call). `None` when the slot is absent (the
1704    /// "cluster default applies — typically the gateway class's
1705    /// implementation-side per-request wall-clock cap" arm caixa-mesh's
1706    /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
1707    /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
1708    /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
1709    /// round-trips to a rendered `HTTPRoute` structurally identical to
1710    /// one that omits the slot).
1711    ///
1712    /// The `:politicas :timeout` slot carries the "no infinite blocking"
1713    /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
1714    /// the typed slot's `Option<Duration>` accept-set (zero-floor
1715    /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
1716    /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
1717    /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
1718    /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
1719    /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
1720    /// Every downstream consumer that reads the per-call cap keys off
1721    /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
1722    /// renderers key off to decide "emit :politicas overlay" vs "skip
1723    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
1724    /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
1725    /// fans the deadline into every rule via
1726    /// [`crate::render::single_field_overlay`], the future M4 per-
1727    /// Aplicacao Gateway API reconciler materialization pass, the
1728    /// future per-`:contratos`-edge timeout-override overlay the
1729    /// MESH-COMPOSITION §III.2 roadmap acknowledges).
1730    ///
1731    /// Prior to this lift the `.timeout` field was accessed inline at
1732    /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
1733    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
1734    /// …)` call — two open-coded field-accesses that expressed no
1735    /// compile-time link back to the typed slot. A future extension of
1736    /// the `:politicas :timeout` axis to a richer author surface — a
1737    /// per-`:contratos`-edge timeout override the operator pins through
1738    /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
1739    /// roadmap acknowledges, a per-cluster timeout-default overlay the
1740    /// M4 CR materializer resolves per-CR, a split of the single
1741    /// per-call `Duration` into a richer `{request, backendRequest}`
1742    /// pair once the Gateway API's per-rule `timeouts` block grows the
1743    /// upstream-facing backendRequest arm alongside the client-facing
1744    /// request arm — would have had to be threaded through both open-
1745    /// coded copies in lockstep or the emptiness predicate and the
1746    /// caixa-mesh emit path would silently disagree on which per-call
1747    /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
1748    /// whose only axis is a `Some :timeout` would satisfy `is_empty()
1749    /// == false` while the renderer's overlay-emit path silently read
1750    /// a drifted other value, or vice versa: an author's `:timeout
1751    /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
1752    /// the emptiness predicate still classified the policy as non-
1753    /// empty, and every `kubectl -n tatara-system get httproute -o yaml
1754    /// | grep -A2 timeouts` audit would land on a route whose author's
1755    /// typed slot value silently vanished at the renderer layer).
1756    /// Lifting the resolution to a typed method on the substrate
1757    /// primitive means every downstream consumer of the Aplicacao's
1758    /// per-`:politicas` deadline surface reaches for exactly one typed
1759    /// dispatch — the resolver's accept-set migrates as a unit on any
1760    /// future axis addition.
1761    ///
1762    /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
1763    /// family (sibling of the peer per-`:politicas`
1764    /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
1765    /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
1766    /// `Option<bool>` accessor — same "one typed dispatch on the
1767    /// substrate primitive, thin projections at each consumer"
1768    /// discipline extended onto the peer per-`:politicas` typed-
1769    /// [`Duration`] optional-scalar axis; closes the "optional per-slot
1770    /// numeric-Copy-T scalar" projection pattern the sibling
1771    /// `Option<u32>` / `Option<bool>` lifts opened, since every
1772    /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
1773    /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
1774    /// than a scalar). Named `timeout()` to match the storage field's
1775    /// name; the accessor's identity maps onto the canonical MESH-
1776    /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
1777    #[must_use]
1778    pub const fn timeout(&self) -> Option<Duration> {
1779        self.timeout
1780    }
1781
1782    /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
1783    /// retry-budget scalar accessor every consumer of the Aplicacao's
1784    /// Gateway API v1.x per-rule retry-cap keys off — returns the
1785    /// author-declared `:politicas :retries` typed `u32` verbatim as an
1786    /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
1787    /// storage (`Option<u32>` is `Copy`, so the accessor returns by
1788    /// value; no borrow of `&self` past the call). `None` when the slot
1789    /// is absent (the "cluster default applies — typically 'no retries
1790    /// beyond a single dispatch attempt'" arm the caixa-mesh
1791    /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
1792    /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
1793    /// this predicate too, so an authored-but-unset `:politicas
1794    /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
1795    /// identical to one that omits the slot).
1796    ///
1797    /// The `:politicas :retries` slot carries the "transient failure
1798    /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
1799    /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
1800    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
1801    /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
1802    /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
1803    /// count scalar the caixa-mesh `retry_overlay` builder writes.
1804    /// Every downstream consumer that reads the retry cap keys off this
1805    /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
1806    /// renderers key off to decide "emit :politicas overlay" vs "skip
1807    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
1808    /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
1809    /// the value into every rule via [`crate::render::single_field_overlay`],
1810    /// the future M4 per-Aplicacao Gateway API reconciler
1811    /// materialization pass, the future per-`:contratos`-edge retry-
1812    /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
1813    /// acknowledges).
1814    ///
1815    /// Prior to this lift the `.retries` field was accessed inline at
1816    /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
1817    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
1818    /// …)` call — two open-coded field-accesses that expressed no
1819    /// compile-time link back to the typed slot. A future extension of
1820    /// the `:politicas :retries` axis to a richer author surface — a
1821    /// per-`:contratos`-edge retry override the operator pins through a
1822    /// future `:contratos :retries` slot, a per-cluster retry-default
1823    /// overlay the M4 CR materializer resolves per-CR, a promotion of
1824    /// the plain `u32` attempt-count to a richer `{attempts, codes,
1825    /// backoff}` sub-block once the Gateway API grows the peer
1826    /// `retry.codes` / `retry.backoff` axes — would have had to be
1827    /// threaded through both open-coded copies in lockstep or the
1828    /// emptiness predicate and the caixa-mesh emit path would silently
1829    /// disagree on which retry budget a given [`MeshPolicy`] resolves to
1830    /// (a `:politicas` block whose only axis is a `Some :retries` would
1831    /// satisfy `is_empty() == false` while the renderer's overlay-emit
1832    /// path silently read a drifted other value, or vice versa: an
1833    /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
1834    /// block while the emptiness predicate still classified the policy
1835    /// as non-empty). Lifting the resolution to a typed method on the
1836    /// substrate primitive means every downstream consumer of the
1837    /// Aplicacao's per-`:politicas` retry surface reaches for exactly
1838    /// one typed dispatch — the resolver's accept-set migrates as a
1839    /// unit on any future axis addition.
1840    ///
1841    /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
1842    /// family (sibling of the peer per-`:politicas`
1843    /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
1844    /// same "one typed dispatch on the substrate primitive, thin
1845    /// projections at each consumer" discipline extended onto the
1846    /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
1847    /// the "optional per-slot numeric-Copy-T scalar" projection pattern
1848    /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
1849    /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
1850    /// fold on). Named `retries()` to match the storage field's name;
1851    /// the accessor's identity maps onto the canonical MESH-COMPOSITION
1852    /// §III.2 vocabulary the slot's docstring already carries.
1853    #[must_use]
1854    pub const fn retries(&self) -> Option<u32> {
1855        self.retries
1856    }
1857
1858    /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
1859    /// enforcement-toggle scalar accessor every consumer of the
1860    /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
1861    /// — returns the author-declared `:politicas :mtls-required` typed
1862    /// bool verbatim as an `Option<bool>`, copied out of the typed
1863    /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
1864    /// the accessor returns by value; no borrow of `&self` past the
1865    /// call). `None` when the slot is absent (the "cluster default
1866    /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
1867    /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
1868    /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
1869    /// this predicate too, so an authored-but-unset `:politicas
1870    /// (:mtls-required ())` round-trips to a rendered
1871    /// `CiliumNetworkPolicy` structurally identical to one that omits
1872    /// the slot).
1873    ///
1874    /// The `:politicas :mtls-required` slot carries the "explicit opt-
1875    /// out only, sandboxing-by-default" mTLS-enforcement toggle
1876    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
1877    /// `{None, Some(true), Some(false)}` accept-set maps onto the
1878    /// Cilium `authentication.mode` bijection through
1879    /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
1880    /// handshake enforced), `Some(false) → "disabled"` (handshake
1881    /// skipped — the debug-edge opt-out), `None` → omit the block
1882    /// (cluster default applies). Every downstream consumer that
1883    /// reads the toggle keys off this scalar (the
1884    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
1885    /// off to decide "emit :politicas overlay" vs "skip entirely", the
1886    /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
1887    /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
1888    /// ingress rule via [`crate::render::single_field_overlay`], the
1889    /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
1890    /// materialization pass, the future per-`:contratos`-edge mTLS
1891    /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
1892    ///
1893    /// Prior to this lift the `.mtls_required` field was accessed
1894    /// inline at two sites — [`MeshPolicy::is_empty`]'s
1895    /// `self.mtls_required.is_none()` arm and caixa-mesh's
1896    /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
1897    /// two open-coded field-accesses that expressed no compile-time
1898    /// link back to the typed slot. A future extension of the
1899    /// `:politicas :mtls-required` axis to a richer author surface —
1900    /// a per-`:contratos`-edge mTLS override the operator pins through
1901    /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
1902    /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
1903    /// M4 CR materializer resolves per-CR, a three-valued
1904    /// `{None, Some(true), Some(false), Some(Optional)}` promotion
1905    /// once Cilium's `authentication.mode` grows an `"optional"` arm —
1906    /// would have had to be threaded through both open-coded copies in
1907    /// lockstep or the emptiness predicate and the caixa-mesh emit
1908    /// path would silently disagree on which toggle a given
1909    /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
1910    /// axis is a `Some`
1911    /// `:mtls-required` would satisfy `is_empty() == false` while the
1912    /// renderer's overlay-emit path silently read a drifted other
1913    /// value, or vice versa). Lifting the resolution to a typed method
1914    /// on the substrate primitive means every downstream consumer of
1915    /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
1916    /// for exactly one typed dispatch — the resolver's accept-set
1917    /// migrates as a unit on any future axis addition.
1918    ///
1919    /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
1920    /// family (peer of the sibling per-`:placement`
1921    /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
1922    /// same "one typed dispatch on the substrate primitive, thin
1923    /// projections at each consumer" discipline extended onto the
1924    /// peer per-`:politicas` typed-bool optional-scalar axis; opens
1925    /// the "optional per-slot Copy-T scalar" projection pattern the
1926    /// sibling per-`:politicas` `:retries` (Option<u32>) /
1927    /// `:timeout` (Option<Duration>) future lifts fold on). Named
1928    /// `mtls_required()` to match the storage field's name; the
1929    /// accessor's identity maps onto the canonical MESH-COMPOSITION
1930    /// §III.2 vocabulary the slot's docstring already carries.
1931    #[must_use]
1932    pub const fn mtls_required(&self) -> Option<bool> {
1933        self.mtls_required
1934    }
1935
1936    /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
1937    /// `local_rate_limit`-mesh token-bucket-declaration scalar
1938    /// accessor every consumer of the Aplicacao's per-`:politicas`
1939    /// per-`(rate, window)` rate-limit surface keys off — returns the
1940    /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
1941    /// verbatim as an `Option<RateLimit>`, copied out of the typed
1942    /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
1943    /// `Copy`, so the accessor returns by value; no borrow of `&self`
1944    /// past the call). `None` when the slot is absent (the "cluster
1945    /// default applies — typically 'no per-Aplicacao rate declaration,
1946    /// gateway-class per-listener default applies'" arm the future
1947    /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
1948    /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
1949    /// `rate_limit().is_none()` arm reads this predicate too, so an
1950    /// authored-but-unset `:politicas (:rate-limit ())` round-trips
1951    /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
1952    /// identical to one that omits the slot).
1953    ///
1954    /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
1955    /// token-bucket rate declaration" contract (MESH-COMPOSITION
1956    /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
1957    /// (rate lower-bounded by 1 through
1958    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
1959    /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
1960    /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
1961    /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
1962    /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
1963    /// bijection the future `CiliumClusterwideEnvoyConfig` per-
1964    /// `:politicas` overlay emits. Every downstream consumer that
1965    /// reads the rate declaration keys off this scalar (the
1966    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
1967    /// off to decide "emit :politicas overlay" vs "skip entirely", the
1968    /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
1969    /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
1970    /// `rl.window` against [`is_canonical_rate_limit_window`], the
1971    /// future M4 per-Aplicacao Envoy reconciler materialization pass,
1972    /// the future per-`:contratos`-edge rate-limit override the
1973    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
1974    ///
1975    /// Prior to this lift the `.rate_limit` field was accessed inline
1976    /// at two sites — [`MeshPolicy::is_empty`]'s
1977    /// `self.rate_limit.is_none()` arm and the `validate_politicas`
1978    /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
1979    /// field-accesses that expressed no compile-time link back to the
1980    /// typed slot. A future extension of the `:politicas :rate-limit`
1981    /// axis to a richer author surface — a per-`:contratos`-edge
1982    /// rate-limit override the operator pins through a future
1983    /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
1984    /// roadmap acknowledges, a per-cluster rate-limit-default overlay
1985    /// the M4 CR materializer resolves per-CR, a promotion of the
1986    /// plain `(rate, window)` scalar pair to a richer
1987    /// `{rate, window, burst, key}` sub-block once Envoy's
1988    /// `local_rate_limit` grows the peer `burst_size` /
1989    /// `descriptor_key` axes — would have had to be threaded through
1990    /// both open-coded copies in lockstep or the emptiness predicate
1991    /// and the validate gate would silently disagree on which rate
1992    /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
1993    /// block whose only axis is a `Some :rate-limit` would satisfy
1994    /// `is_empty() == false` while the validate path silently read a
1995    /// drifted other value, or vice versa: an author's
1996    /// `:rate-limit "100/s"` would omit the value-shape gate while the
1997    /// emptiness predicate still classified the policy as non-empty).
1998    /// Lifting the resolution to a typed method on the substrate
1999    /// primitive means every downstream consumer of the Aplicacao's
2000    /// per-`:politicas` rate-limit surface reaches for exactly one
2001    /// typed dispatch — the resolver's accept-set migrates as a unit
2002    /// on any future axis addition.
2003    ///
2004    /// First `Option<Copy-composite-T>`-return accessor on the M3
2005    /// mesh-slot family — closes the last un-lifted per-`:politicas`
2006    /// scalar-value axis. Peer of the sibling per-`:politicas`
2007    /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
2008    /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
2009    /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
2010    /// "one typed dispatch on the substrate primitive, thin
2011    /// projections at each consumer" discipline extended onto the
2012    /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
2013    /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
2014    /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
2015    /// sub-accessors rather than a top-level accessor because
2016    /// consumers reach for the axes not the aggregate). Named
2017    /// `rate_limit()` to match the storage field's name; the
2018    /// accessor's identity maps onto the canonical MESH-COMPOSITION
2019    /// §III.2 vocabulary the slot's docstring already carries.
2020    #[must_use]
2021    pub const fn rate_limit(&self) -> Option<RateLimit> {
2022        self.rate_limit
2023    }
2024
2025    /// Substrate-canonical per-`:politicas` `:circuit-breaker`
2026    /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
2027    /// declaration scalar accessor every consumer of the Aplicacao's
2028    /// per-`:politicas` breaker declaration keys off — returns the
2029    /// author-declared `:politicas :circuit-breaker` typed
2030    /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
2031    /// copied out of the typed slot's own `Option<CircuitBreaker>`
2032    /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
2033    /// by value; no borrow of `&self` past the call). `None` when the
2034    /// slot is absent (the "cluster default applies — typically 'no
2035    /// per-Aplicacao breaker declaration, gateway-class per-listener
2036    /// default applies'" arm the future caixa-mesh
2037    /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
2038    /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
2039    /// arm reads this predicate too, so an authored-but-unset
2040    /// `:politicas (:circuit-breaker ())` round-trips to a rendered
2041    /// `CiliumClusterwideEnvoyConfig` structurally identical to one
2042    /// that omits the slot).
2043    ///
2044    /// The `:politicas :circuit-breaker` slot carries the
2045    /// "per-Aplicacao consecutive-transient-failure trip declaration"
2046    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2047    /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
2048    /// zero-floor rejected through
2049    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2050    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
2051    /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
2052    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
2053    /// canonical-form pinned through
2054    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
2055    /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
2056    /// bijection the future `CiliumClusterwideEnvoyConfig`
2057    /// per-`:politicas` overlay emits. Every downstream consumer that
2058    /// reads the breaker declaration keys off this scalar (the
2059    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2060    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2061    /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
2062    /// that brackets `cb.max_failures()` against
2063    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
2064    /// [`POLICY_BREAKER_WINDOW_MAX`] via
2065    /// [`crate::render::require_positive_canonical_bounded_duration`],
2066    /// the future M4 per-Aplicacao Envoy reconciler materialization
2067    /// pass, the future per-`:contratos`-edge breaker override the
2068    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2069    ///
2070    /// Prior to this lift the `.circuit_breaker` field was accessed
2071    /// inline at two sites — [`MeshPolicy::is_empty`]'s
2072    /// `self.circuit_breaker.is_none()` arm and the
2073    /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
2074    /// bind — two open-coded field-accesses that expressed no
2075    /// compile-time link back to the typed slot. A future extension of
2076    /// the `:politicas :circuit-breaker` axis to a richer author
2077    /// surface — a per-`:contratos`-edge breaker override the operator
2078    /// pins through a future `:contratos :circuit-breaker` slot the
2079    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
2080    /// breaker-default overlay the M4 CR materializer resolves per-CR,
2081    /// a promotion of the plain `(max_failures, window)` scalar pair to
2082    /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
2083    /// sub-block once Envoy's `outlier_detection` grows the peer
2084    /// ejection-percentage / ejection-time axes — would have had to be
2085    /// threaded through both open-coded copies in lockstep or the
2086    /// emptiness predicate and the validate gate would silently
2087    /// disagree on which breaker declaration a given [`MeshPolicy`]
2088    /// resolves to (a `:politicas` block whose only axis is a
2089    /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
2090    /// the validate path silently read a drifted other value, or vice
2091    /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
2092    /// "60s"))` would omit the value-shape gate while the emptiness
2093    /// predicate still classified the policy as non-empty). Lifting
2094    /// the resolution to a typed method on the substrate primitive
2095    /// means every downstream consumer of the Aplicacao's
2096    /// per-`:politicas` breaker surface reaches for exactly one typed
2097    /// dispatch — the resolver's accept-set migrates as a unit on any
2098    /// future axis addition.
2099    ///
2100    /// Second `Option<Copy-composite-T>`-return accessor on the M3
2101    /// mesh-slot family (sibling of the peer per-`:politicas`
2102    /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
2103    /// on the same composite-Copy shape, and of the sibling per-
2104    /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
2105    /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
2106    /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
2107    /// `Option<bool>` accessors on the sibling primitive-Copy axes —
2108    /// same "one typed dispatch on the substrate primitive, thin
2109    /// projections at each consumer" discipline extended onto the last
2110    /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
2111    /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
2112    /// match the storage field's name; the accessor's identity maps
2113    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2114    /// docstring already carries. Closes the last unlifted
2115    /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
2116    /// reader now routes through a typed dispatch on the substrate
2117    /// primitive.
2118    #[must_use]
2119    pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
2120        self.circuit_breaker
2121    }
2122}
2123
2124#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2125#[serde(rename_all = "camelCase")]
2126pub struct CircuitBreaker {
2127    pub max_failures: u32,
2128    #[serde(with = "supervisor::duration_codec_required")]
2129    pub window: Duration,
2130}
2131
2132impl CircuitBreaker {
2133    /// Substrate-canonical per-`:politicas :circuit-breaker`
2134    /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
2135    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2136    /// breaker trip-count keys off — returns the author-declared
2137    /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
2138    /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
2139    /// so the accessor returns by value; no borrow of `&self` past the
2140    /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
2141    /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
2142    /// axis; a `CircuitBreaker` past pattern-match is definitionally
2143    /// present, and its `:max-failures` field carries the trip count as a
2144    /// required-axis scalar).
2145    ///
2146    /// The `:politicas :circuit-breaker :max-failures` axis carries the
2147    /// "consecutive-transient-failure trip threshold" contract
2148    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
2149    /// (zero-floor rejected through
2150    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2151    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
2152    /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
2153    /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
2154    /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
2155    /// Every downstream consumer that reads the trip threshold keys off
2156    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2157    /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
2158    /// canonical `require_positive_bounded_u32` helper, the future M4
2159    /// per-Aplicacao Envoy config reconciler materialization pass, the
2160    /// future per-`:contratos`-edge breaker-override overlay the
2161    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2162    ///
2163    /// Prior to this lift the `.max_failures` field was accessed inline
2164    /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
2165    /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
2166    /// open-coded field-access that expressed no compile-time link back
2167    /// to the typed sub-struct axis. A future extension of the
2168    /// `:max-failures` axis to a richer author surface — a
2169    /// per-`:contratos`-edge breaker override the operator pins through a
2170    /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
2171    /// #3 roadmap acknowledges, a per-cluster max-failures-default
2172    /// overlay the M4 CR materializer resolves per-CR, a promotion of the
2173    /// plain `u32` trip count to a richer
2174    /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
2175    /// tuple once Envoy's `outlier_detection` block's peer axes come into
2176    /// scope, a per-Envoy-cluster minimum-request-volume gate before the
2177    /// count arms — would have had to be threaded through every open-
2178    /// coded copy in lockstep or the validate gate and the future M4
2179    /// emit path would silently disagree on which trip threshold a given
2180    /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
2181    /// would satisfy validate while the emit path silently read a drifted
2182    /// other value, or vice versa: a validated typed slot would land at
2183    /// the emit boundary as a no-op breaker whose trip threshold is
2184    /// structurally never reached). Lifting the resolution to a typed
2185    /// method on the substrate primitive means every downstream consumer
2186    /// of the Aplicacao's per-`:politicas :circuit-breaker`
2187    /// trip-threshold surface reaches for exactly one typed dispatch —
2188    /// the resolver's accept-set migrates as a unit on any future axis
2189    /// addition.
2190    ///
2191    /// First sub-struct scalar accessor on the M3 mesh-slot family
2192    /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
2193    /// scalar" projection pattern the sibling `CircuitBreaker::window` /
2194    /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
2195    /// closes the last unlifted per-`:politicas` scalar-value axis after
2196    /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
2197    /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
2198    /// Same "one typed dispatch on the substrate primitive, thin
2199    /// projections at each consumer" discipline the peer
2200    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
2201    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
2202    /// [`Membro::versao_requirement`] (a40b0e3),
2203    /// [`Entrada::destination`] (6db982c) accessors carry on their
2204    /// respective per-mesh-slot-atom scalar-value axes, extended onto the
2205    /// per-sub-struct required-`u32` axis. Named `max_failures()` to
2206    /// match the storage field's name; the accessor's identity maps onto
2207    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2208    /// docstring already carries.
2209    #[must_use]
2210    pub const fn max_failures(&self) -> u32 {
2211        self.max_failures
2212    }
2213
2214    /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
2215    /// Envoy-outlier-detection rolling-observation-interval scalar
2216    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2217    /// breaker rolling-window duration keys off — returns the
2218    /// author-declared `:politicas :circuit-breaker :window` typed
2219    /// `Duration` verbatim, copied out of the typed slot's own
2220    /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
2221    /// by value; no borrow of `&self` past the call). Non-optional (the
2222    /// surrounding `Option<CircuitBreaker>` is the "slot present?"
2223    /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
2224    /// `CircuitBreaker` past pattern-match is definitionally present,
2225    /// and its `:window` field carries the rolling-observation interval
2226    /// as a required-axis scalar).
2227    ///
2228    /// The `:politicas :circuit-breaker :window` axis carries the
2229    /// "consecutive-transient-failure rolling-observation interval"
2230    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2231    /// `Duration` accept-set (zero-floor rejected through
2232    /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
2233    /// residue rejected through
2234    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
2235    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
2236    /// Envoy `outlier_detection.interval` per-cluster
2237    /// ejection-observation-interval scalar (equivalently the future
2238    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2239    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2240    /// consumer that reads the rolling-observation interval keys off
2241    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2242    /// integer-millisecond canonical-form + cap bracket at
2243    /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
2244    /// [`crate::render::require_positive_canonical_bounded_duration`]
2245    /// helper, the future M4 per-Aplicacao Envoy config reconciler
2246    /// materialization pass, the future per-`:contratos`-edge
2247    /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
2248    /// acknowledges).
2249    ///
2250    /// Prior to this lift the `.window` field was accessed inline at
2251    /// one production site — [`AplicacaoSpec::validate_politicas`]'s
2252    /// `require_positive_canonical_bounded_duration(cb.window, …)`
2253    /// call — one open-coded field-access that expressed no compile-
2254    /// time link back to the typed sub-struct axis. A future extension
2255    /// of the `:window` axis to a richer author surface — a
2256    /// per-`:contratos`-edge window override the operator pins through
2257    /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
2258    /// #3 roadmap acknowledges, a per-cluster window-default overlay
2259    /// the M4 CR materializer resolves per-CR, a promotion of the plain
2260    /// `Duration` observation interval to a richer
2261    /// `{interval, base_ejection_time, max_ejection_percent}` tuple
2262    /// once Envoy's `outlier_detection` block's peer axes come into
2263    /// scope, a per-Envoy-cluster minimum-request-volume gate before
2264    /// the window arms — would have had to be threaded through every
2265    /// open-coded copy in lockstep or the validate gate and the future
2266    /// M4 emit path would silently disagree on which observation
2267    /// interval a given [`CircuitBreaker`] resolves to (an author's
2268    /// `:window "60s"` would satisfy validate while the emit path
2269    /// silently read a drifted other value, or vice versa: a validated
2270    /// typed slot would land at the emit boundary as a breaker whose
2271    /// observation window is structurally so wide that no realistic
2272    /// failure-rate shape can trip it). Lifting the resolution to a
2273    /// typed method on the substrate primitive means every downstream
2274    /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
2275    /// observation-window surface reaches for exactly one typed
2276    /// dispatch — the resolver's accept-set migrates as a unit on any
2277    /// future axis addition.
2278    ///
2279    /// Second sub-struct scalar accessor on the M3 mesh-slot family —
2280    /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
2281    /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
2282    /// required-axis, extended onto the per-sub-struct required-`Duration`
2283    /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
2284    /// axis. Same "one typed dispatch on the substrate primitive, thin
2285    /// projections at each consumer" discipline the peer
2286    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
2287    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
2288    /// [`Membro::versao_requirement`] (a40b0e3),
2289    /// [`Entrada::destination`] (6db982c) accessors carry on their
2290    /// respective per-mesh-slot-atom scalar-value axes, extended onto
2291    /// the per-sub-struct required-`Duration` axis. Named `window()` to
2292    /// match the storage field's name; the accessor's identity maps onto
2293    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2294    /// docstring already carries.
2295    #[must_use]
2296    pub const fn window(&self) -> Duration {
2297        self.window
2298    }
2299}
2300
2301#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2302pub struct RateLimit {
2303    /// Requests per window.
2304    pub rate: u32,
2305    /// Window duration.
2306    pub window: Duration,
2307}
2308
2309impl RateLimit {
2310    /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
2311    /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
2312    /// every consumer of the Aplicacao's per-`:contratos`-edge
2313    /// rate-limit-bucket capacity keys off — returns the author-declared
2314    /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
2315    /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
2316    /// returns by value; no borrow of `&self` past the call). Non-optional
2317    /// (the surrounding `Option<RateLimit>` is the "slot present?"
2318    /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
2319    /// `RateLimit` past pattern-match is definitionally present, and its
2320    /// `:rate` field carries the token-bucket capacity as a required-axis
2321    /// scalar).
2322    ///
2323    /// The `:politicas :rate-limit` `:rate` axis carries the
2324    /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
2325    /// the typed slot's `u32` accept-set (zero-floor rejected through
2326    /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
2327    /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
2328    /// `local_rate_limit.token_bucket.max_tokens` per-cluster
2329    /// token-bucket-capacity scalar (equivalently the future
2330    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2331    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2332    /// consumer that reads the token-bucket capacity keys off this
2333    /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2334    /// cap bracket that gates on the canonical
2335    /// [`crate::render::require_positive_bounded_u32`] helper, the
2336    /// [`rate_limit_codec::render`] `Duration → unit` projection that
2337    /// emits the `<n>/<s|m|h>` author surface, the future M4
2338    /// per-Aplicacao Envoy config reconciler materialization pass, the
2339    /// future per-`:contratos`-edge rate-limit-override overlay the
2340    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2341    ///
2342    /// Prior to this lift the `.rate` field was accessed inline at three
2343    /// production sites — [`AplicacaoSpec::validate_politicas`]'s
2344    /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
2345    /// [`rate_limit_codec::render`] format-arm arms (canonical-window
2346    /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
2347    /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
2348    /// field-accesses that expressed no compile-time link back to the
2349    /// typed sub-struct axis. A future extension of the `:rate` axis
2350    /// to a richer author surface — a per-`:contratos`-edge rate
2351    /// override the operator pins through a future `:contratos :rate`
2352    /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
2353    /// per-cluster rate-default overlay the M4 CR materializer resolves
2354    /// per-CR, a promotion of the plain `u32` token capacity to a
2355    /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
2356    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
2357    /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
2358    /// before the token arms — would have had to be threaded through
2359    /// every open-coded copy in lockstep or the validate gate, the
2360    /// codec's render path, and the future M4 emit path would silently
2361    /// disagree on which token capacity a given [`RateLimit`] resolves
2362    /// to (an author's `:rate-limit "100/s"` would satisfy validate
2363    /// while the render / emit paths silently read a drifted other
2364    /// value, or vice versa: a validated typed slot would land at the
2365    /// emit boundary as a no-op limiter whose token capacity is
2366    /// structurally so high that no realistic per-edge traffic shape
2367    /// can drain it). Lifting the resolution to a typed method on the
2368    /// substrate primitive means every downstream consumer of the
2369    /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
2370    /// reaches for exactly one typed dispatch — the resolver's
2371    /// accept-set migrates as a unit on any future axis addition.
2372    ///
2373    /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
2374    /// in shape to the peer per-`CircuitBreaker`
2375    /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
2376    /// on the peer per-sub-struct required-axis, extended onto the
2377    /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
2378    /// required-axis scalar" projection pattern the sibling
2379    /// [`RateLimit::window`] future lift folds on. Same "one typed
2380    /// dispatch on the substrate primitive, thin projections at each
2381    /// consumer" discipline the peer [`WitContract::source`] /
2382    /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
2383    /// (0804823), [`Membro::nome`] (4a32abf),
2384    /// [`Membro::versao_requirement`] (a40b0e3),
2385    /// [`Entrada::destination`] (6db982c),
2386    /// [`CircuitBreaker::max_failures`] (3a74062),
2387    /// [`CircuitBreaker::window`] (373957f) accessors carry on their
2388    /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
2389    /// to match the storage field's name; the accessor's identity maps
2390    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2391    /// docstring already carries.
2392    #[must_use]
2393    pub const fn rate(&self) -> u32 {
2394        self.rate
2395    }
2396
2397    /// Substrate-canonical per-`:politicas :rate-limit` `:window`
2398    /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
2399    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2400    /// rate-limit-bucket refill period keys off — returns the
2401    /// author-declared `:politicas :rate-limit` typed `Duration`
2402    /// verbatim, copied out of the typed slot's own `Duration` storage
2403    /// (`Duration` is `Copy`, so the accessor returns by value; no
2404    /// borrow of `&self` past the call). Non-optional (the surrounding
2405    /// `Option<RateLimit>` is the "slot present?" projection at the
2406    /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
2407    /// pattern-match is definitionally present, and its `:window`
2408    /// field carries the token-bucket refill period as a required-axis
2409    /// scalar).
2410    ///
2411    /// The `:politicas :rate-limit` `:window` axis carries the
2412    /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
2413    /// — the typed slot's `Duration` accept-set (constrained to the
2414    /// three canonical windows `{1s, 60s, 3600s}` the
2415    /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
2416    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
2417    /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
2418    /// per-cluster token-bucket-refill-period scalar (equivalently the
2419    /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2420    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2421    /// consumer that reads the token-bucket refill period keys off
2422    /// this scalar (the [`AplicacaoSpec::validate_politicas`]
2423    /// canonical-window gate that keys off
2424    /// [`is_canonical_rate_limit_window`], the
2425    /// [`rate_limit_codec::render`] `Duration → unit` projection that
2426    /// emits the `<n>/<s|m|h>` author surface — canonical arm via
2427    /// [`rate_limit_window_unit`] and non-canonical fallback via
2428    /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
2429    /// reconciler materialization pass, the future per-`:contratos`-
2430    /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
2431    /// roadmap acknowledges).
2432    ///
2433    /// Prior to this lift the `.window` field was accessed inline at
2434    /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
2435    /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
2436    /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
2437    /// error-payload construction on refusal, and the two
2438    /// [`rate_limit_codec::render`] arms
2439    /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
2440    /// and non-canonical-window `rl.window.as_secs()` fallback). Three
2441    /// open-coded field-accesses that expressed no compile-time link
2442    /// back to the typed sub-struct axis. A future extension of the
2443    /// `:window` axis to a richer author surface — a per-`:contratos`-
2444    /// edge window override the operator pins through a future
2445    /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
2446    /// acknowledges, a per-cluster window-default overlay the M4 CR
2447    /// materializer resolves per-CR, a promotion of the plain
2448    /// `Duration` refill period to a richer
2449    /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
2450    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
2451    /// axis comes into scope, an addition of a `"d"` day suffix once
2452    /// Envoy's `rate_limit_action` grows daily-bucket support — would
2453    /// have had to be threaded through every open-coded copy in
2454    /// lockstep or the validate gate, the codec's render path, and
2455    /// the future M4 emit path would silently disagree on which
2456    /// refill period a given [`RateLimit`] resolves to (an author's
2457    /// `:rate-limit "100/s"` would satisfy validate while the render
2458    /// / emit paths silently read a drifted other value, or vice
2459    /// versa: a validated typed slot would land at the emit boundary
2460    /// as a limiter whose refill period is structurally so long that
2461    /// no realistic per-edge traffic shape stays inside the token
2462    /// budget). Lifting the resolution to a typed method on the
2463    /// substrate primitive means every downstream consumer of the
2464    /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
2465    /// reaches for exactly one typed dispatch — the resolver's
2466    /// accept-set migrates as a unit on any future axis addition.
2467    ///
2468    /// Second sub-struct scalar accessor on the `RateLimit` axis —
2469    /// sibling in shape to the just-landed [`RateLimit::rate`]
2470    /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
2471    /// required-axis, extended onto the per-sub-struct
2472    /// required-`Duration` axis; closes the last unlifted
2473    /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
2474    /// per-sub-struct accessor coverage is now complete across both
2475    /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
2476    /// the substrate primitive, thin projections at each consumer"
2477    /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
2478    /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
2479    /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
2480    /// (7f0fd43), [`WitContract::world_ref`] (0804823),
2481    /// [`Membro::nome`] (4a32abf),
2482    /// [`Membro::versao_requirement`] (a40b0e3),
2483    /// [`Entrada::destination`] (6db982c) accessors carry on their
2484    /// respective per-mesh-slot-atom scalar-value axes. Named
2485    /// `window()` to match the storage field's name; the accessor's
2486    /// identity maps onto the canonical MESH-COMPOSITION §III.2
2487    /// vocabulary the slot's docstring already carries.
2488    #[must_use]
2489    pub const fn window(&self) -> Duration {
2490        self.window
2491    }
2492
2493    /// Recognize this rate-limit's `:window` as a canonical
2494    /// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
2495    /// exactly matches one of the three closed-set arm-Durations
2496    /// (`1s` / `60s` / `3600s`), `None` when the window carries a
2497    /// non-canonical magnitude the codec's round-trip would break on
2498    /// (sub-second residue, or a second-magnitude outside the set
2499    /// [`RateLimitUnit::ALL`] enumerates).
2500    ///
2501    /// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
2502    /// returns `Some` here — the validate gate's
2503    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
2504    /// rejects every window this accessor returns `None` on. Downstream
2505    /// consumers past validate (the codec's [`rate_limit_codec::render`]
2506    /// path, the future M4 per-Aplicacao Envoy config reconciler's
2507    /// materialization pass, the future per-`:contratos`-edge rate-limit-
2508    /// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
2509    /// acknowledges) that read the typed unit off a validated slot can
2510    /// pattern-match on the returned `Some` without re-checking
2511    /// canonicality at the consumer layer — the typed enum surface is
2512    /// the load-bearing carrier of the canonicality invariant.
2513    ///
2514    /// Preferred over the free [`is_canonical_rate_limit_window`]
2515    /// module-private helper at any call site that has the typed
2516    /// [`RateLimit`] in hand (the codec's `render` arm at
2517    /// [`rate_limit_codec::render`], the validate gate's canonical-form
2518    /// arm in [`AplicacaoSpec::validate_politicas`], any future
2519    /// per-`:contratos` edge-override overlay resolver): those consumers
2520    /// reach for the typed enum without going through the
2521    /// `.window()` scalar-projection layer, and get the enum value
2522    /// directly (which the codec's render arm can then format via
2523    /// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
2524    /// "typed sub-struct scalar accessor, one dispatch on the substrate
2525    /// primitive" discipline the sibling [`RateLimit::rate`] and
2526    /// [`RateLimit::window`] accessors carry on the peer per-sub-struct
2527    /// scalar-value axes, extended onto the per-`RateLimit` typed-unit
2528    /// projection axis (the third scalar accessor on the [`RateLimit`]
2529    /// axis, first typed-enum-return projection).
2530    #[must_use]
2531    pub fn canonical_unit(&self) -> Option<RateLimitUnit> {
2532        RateLimitUnit::from_window(self.window)
2533    }
2534}
2535
2536/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
2537/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
2538/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
2539///
2540/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
2541/// the `:politicas :rate-limit` unit surface reads from
2542/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
2543/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
2544/// [`is_canonical_rate_limit_window`] predicate the
2545/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
2546/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
2547/// projection) now lives inside this typed enum's `match self` arms — a
2548/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
2549/// `rate_limit_action` grows daily-bucket support) is one new variant
2550/// plus the exhaustiveness arms on the four methods, so every consumer
2551/// picks it up by compile-time construction rather than a runtime
2552/// table-scan miss.
2553///
2554/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
2555/// scanned via `find_map` at every projection call — an untyped runtime
2556/// walk that carried no compile-time link between the parse arm's
2557/// accepted suffixes, the render arm's emitted suffixes, and the
2558/// validate gate's accepted windows. A future rate-limit-unit addition
2559/// that landed one row without threading through the other consumers
2560/// (or a copy-paste flip that collapsed two rows onto one suffix) would
2561/// silently split the accepted-set across the three consumers — the
2562/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
2563/// for a 24h window that parse can't round-trip, the validate gate
2564/// misses one canonical window. Lifting the pairs onto a typed
2565/// closed-set enum with exhaustive `match` arms makes any such
2566/// half-landed extension a caixa-core build error (the compiler enforces
2567/// arm coverage on every method), not a silent per-consumer drift
2568/// surfacing at apply time. Same "closed-set typed-enum discriminator"
2569/// discipline the sibling [`PlacementStrategy`] (cc8f749),
2570/// [`crate::supervisor::RestartStrategy`],
2571/// [`crate::supervisor::RestartPolicy`],
2572/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
2573/// closed-set typed enums carry on their respective closed-set axes —
2574/// extended onto the seventh closed-set typed-enum discriminator axis
2575/// on the caixa typed surface (the `:politicas :rate-limit :window`
2576/// canonical-unit axis).
2577#[derive(
2578    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
2579)]
2580pub enum RateLimitUnit {
2581    /// 1-second window — canonical author-surface suffix `"s"`
2582    /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
2583    /// with a 1s magnitude.
2584    Second,
2585    /// 1-minute window — canonical author-surface suffix `"m"`
2586    /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
2587    /// with a 60s magnitude.
2588    Minute,
2589    /// 1-hour window — canonical author-surface suffix `"h"`
2590    /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
2591    /// with a 3600s magnitude.
2592    Hour,
2593}
2594
2595impl RateLimitUnit {
2596    /// Exhaustive iteration surface for every consumer that reads the
2597    /// full canonical-unit set (the byte-parity witness against the
2598    /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
2599    /// webhook's accepted-suffix listing in its rejection body, any
2600    /// future round-trip fuzz harness). A future variant addition to
2601    /// [`RateLimitUnit`] extends this slice as a single edit and every
2602    /// consumer picks up the new entry by construction — the compiler-
2603    /// checked exhaustiveness on the sibling method `match` arms is the
2604    /// build-time guarantee that no arm forgets to grow.
2605    pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
2606
2607    /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
2608    /// string every `<n>/<unit>` rate-limit shape carries after its
2609    /// `/` separator. The single source of truth the codec's parse and
2610    /// render arms both dispatch on: the parse arm matches an incoming
2611    /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
2612    /// output; the render arm emits the entry's `as_suffix` verbatim
2613    /// after the rate magnitude.
2614    #[must_use]
2615    pub const fn as_suffix(self) -> &'static str {
2616        match self {
2617            Self::Second => "s",
2618            Self::Minute => "m",
2619            Self::Hour => "h",
2620        }
2621    }
2622
2623    /// Canonical `Duration` for this unit — the token-bucket refill
2624    /// period the [`RateLimit::window`] axis carries when the surrounding
2625    /// slot's `:rate-limit` author surface named this unit.
2626    #[must_use]
2627    pub const fn window(self) -> Duration {
2628        Duration::from_secs(match self {
2629            Self::Second => 1,
2630            Self::Minute => 60,
2631            Self::Hour => 3_600,
2632        })
2633    }
2634
2635    /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
2636    /// `None` when `suffix` is outside the closed-set arm-string set
2637    /// [`Self::as_suffix`] emits. The single `str → Self` projection
2638    /// [`rate_limit_codec::parse`] consumes.
2639    #[must_use]
2640    pub fn from_suffix(suffix: &str) -> Option<Self> {
2641        Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
2642    }
2643
2644    /// Recognize a canonical rate-limit `Duration` as one of the three
2645    /// arms, or `None` when `window` carries sub-second residue or a
2646    /// second-magnitude outside the closed-set arm-window set
2647    /// [`Self::window`] emits. The single `Duration → Self` projection
2648    /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
2649    /// both consume.
2650    #[must_use]
2651    pub fn from_window(window: Duration) -> Option<Self> {
2652        if window.subsec_nanos() != 0 {
2653            return None;
2654        }
2655        Self::ALL.iter().copied().find(|u| u.window() == window)
2656    }
2657}
2658
2659/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
2660/// every consumer that formats a canonical rate-limit unit as user-
2661/// facing text (future M4 admission-webhook rejection bodies naming
2662/// the accepted-suffix set, future `feira app graph` per-`:politicas`
2663/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
2664/// codec's parse arm accepts and the render arm emits. Same
2665/// as_str-through-Display convergence discipline the sibling
2666/// [`PlacementStrategy`], [`crate::CaixaKind`],
2667/// [`crate::supervisor::RestartStrategy`], and
2668/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
2669impl std::fmt::Display for RateLimitUnit {
2670    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2671        f.write_str(self.as_suffix())
2672    }
2673}
2674
2675/// Canonical rate-limit unit suffix for `window`, or `None` when
2676/// `window` isn't a [`RateLimitUnit`] arm's `Duration` (i.e. carries
2677/// sub-second residue or a second-magnitude outside the closed-set
2678/// arm-window set). Thin delegate over [`RateLimitUnit::from_window`]
2679/// composed with [`RateLimitUnit::as_suffix`] — the two consumers on
2680/// the `Duration → &'static str` axis ([`rate_limit_codec::render`] and
2681/// [`is_canonical_rate_limit_window`]) share this projection.
2682#[must_use]
2683fn rate_limit_window_unit(window: Duration) -> Option<&'static str> {
2684    RateLimitUnit::from_window(window).map(RateLimitUnit::as_suffix)
2685}
2686
2687/// Canonical rate-limit `Duration` for a unit suffix, or `None` when
2688/// the suffix isn't a [`RateLimitUnit`] arm's `as_suffix` output. Thin
2689/// delegate over [`RateLimitUnit::from_suffix`] composed with
2690/// [`RateLimitUnit::window`] — the sole consumer on the
2691/// `&'static str → Duration` axis ([`rate_limit_codec::parse`]) reads
2692/// this projection.
2693#[must_use]
2694fn rate_limit_window_from_unit(unit: &str) -> Option<Duration> {
2695    RateLimitUnit::from_suffix(unit).map(RateLimitUnit::window)
2696}
2697
2698/// True when `window` is exactly one of the three canonical rate-limit
2699/// windows the [`rate_limit_codec`] round-trips losslessly: 1 second
2700/// (`"<n>/s"`), 1 minute (`"<n>/m"`), or 1 hour (`"<n>/h"`). Routes
2701/// through [`RateLimitUnit::from_window`] — the single `Duration → Self`
2702/// projection [`rate_limit_codec::render`] also consumes — so the
2703/// canonical-window set lives in one typed enum's `match self` arms,
2704/// drift between the codec's accepted unit set and the validate gate's
2705/// accepted window set is a compiler-enforced build error at the enum,
2706/// not a silent round-trip break at the codec layer. Same shape every
2707/// other predicate-on-the-typed-slot helper carries
2708/// ([`MeshPolicy::is_empty`], [`crate::LimitsSpec::is_empty`],
2709/// [`crate::BehaviorSpec::is_empty`]).
2710#[must_use]
2711fn is_canonical_rate_limit_window(window: Duration) -> bool {
2712    RateLimitUnit::from_window(window).is_some()
2713}
2714
2715/// Upper-bound ceiling on the `:politicas :timeout` axis — every
2716/// validated [`MeshPolicy::timeout`] past
2717/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
2718/// (inclusive on both ends, integer-millisecond magnitudes by the
2719/// canonical-form gate immediately preceding).
2720///
2721/// The typed field is `Option<Duration>` (the zero-floor arm
2722/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
2723/// `Duration::ZERO`, and the canonical-form arm
2724/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
2725/// sub-millisecond residue), so a programmatic struct literal
2726/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
2727/// 24h) and the equivalent author-surface form
2728/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
2729/// integer-hour magnitude) both round-trip cleanly through serde — a
2730/// structurally unbounded `Duration` ceiling. A `:timeout` value far
2731/// above the documented production-playbook band (Envoy default `15s`,
2732/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
2733/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
2734/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
2735/// at `~3600s`) silently degenerates the mesh-policy contract: the
2736/// per-call deadline is structurally so long that no realistic
2737/// synchronous-`:contratos` traversal can reach it, so the typed slot
2738/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
2739/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
2740/// blocking" degenerates to a nominal-only contract on the
2741/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
2742/// the sibling `:politicas :retries` axis and the
2743/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
2744/// `:politicas :circuit-breaker :max-failures` axis — all three close
2745/// the "structurally unbounded ceiling on a typed `:politicas` axis"
2746/// footgun the prior zero-floor-and-canonical-form-only checks left
2747/// open.
2748///
2749/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
2750/// shared duration codec emits (`"<n>h"` for any integer-hour
2751/// magnitude) — every value in the canonical authoring form's
2752/// `<integer><unit>` grammar at or below this cap renders to a clean
2753/// canonical string. The cap sits an order of magnitude above every
2754/// documented production-playbook recommendation band (Envoy default
2755/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
2756/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
2757/// configured maximum (`proxy_read_timeout` typical max `3600s`),
2758/// below the clearly-pathological "effectively no timeout" floor
2759/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
2760/// want for a long-running synchronous workflow, but a hard wall above
2761/// which the mesh-level deadline is structurally a non-deadline.
2762/// Lifted as a typed `pub const` so the bound has exactly one source
2763/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
2764/// materializer's admission webhook and the caixa-mesh-side
2765/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2766/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
2767/// other typed upper bound in this crate carries
2768/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
2769/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2770/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2771/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2772pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
2773
2774/// Upper-bound ceiling on the `:politicas :retries` axis — every
2775/// validated [`MeshPolicy::retries`] past
2776/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
2777///
2778/// The typed slot is `Option<u32>` (`None` = no retries on transient
2779/// failure; `Some(0)` already rejected by the
2780/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
2781/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
2782/// .. }`) and the equivalent author-surface form
2783/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
2784/// serde / the codec — a structurally unbounded `u32` ceiling. The
2785/// runtime substrate that consumes the value (Envoy's
2786/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
2787/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
2788/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
2789/// admission cap is 10) translates a four-billion-retry policy into a
2790/// thundering-herd amplification vector on transient failure — the
2791/// caller's one request fans out to `retries` server-side calls per
2792/// edge per traversal, multiplying load by `(retries+1)^depth` across
2793/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
2794/// invariant "no infinite blocking" pairs with a no-runaway-amplification
2795/// invariant on the retry axis; both belong at the typed-slot layer.
2796///
2797/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
2798/// upstream mesh-policy schema that documents one) and sits above the
2799/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
2800/// every documented production playbook): a value the author can
2801/// plausibly want, but a hard wall above which the policy is
2802/// structurally a footgun. Lifted as a typed `pub const` so the bound
2803/// has exactly one source of truth — a future axis reaching for the
2804/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
2805/// materializer's admission webhook, the caixa-mesh-side
2806/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
2807/// one place. Same shape every other typed upper bound in this crate
2808/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2809/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2810/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
2811/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2812pub const POLICY_RETRIES_MAX: u32 = 10;
2813
2814/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
2815/// axis — every validated [`CircuitBreaker::max_failures`] past
2816/// [`AplicacaoSpec::validate_politicas`] lies in
2817/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
2818///
2819/// The typed field is `u32` (the zero-floor arm
2820/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
2821/// `0` — a breaker that trips on the first call), so a programmatic
2822/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
2823/// and the equivalent author-surface form
2824/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
2825/// cleanly through serde — a structurally unbounded `u32` ceiling. A
2826/// `max_failures` value far above the documented production-playbook
2827/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
2828/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
2829/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
2830/// typical 5–50) silently disables the breaker's protection role:
2831/// the threshold is structurally so high that no realistic
2832/// failures-per-`:window` traffic shape can reach it, so the breaker
2833/// never trips and the typed slot becomes a no-op carried on every
2834/// emitted Envoy / Cilium L7 overlay. Pairs with the
2835/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
2836/// axis — both close the "structurally unbounded `u32` ceiling on a
2837/// typed policy axis" footgun the prior zero-floor-only checks left
2838/// open.
2839///
2840/// The `1000` ceiling sits an order of magnitude above every
2841/// documented upstream production-playbook recommendation band (the
2842/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
2843/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
2844/// the clearly-pathological "effectively no protection"
2845/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
2846/// plausibly want at hyperscale, but a hard wall above which the
2847/// policy is structurally a no-op. Lifted as a typed `pub const` so
2848/// the bound has exactly one source of truth — the future M4
2849/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
2850/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
2851/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
2852/// one place. Same shape every other typed upper bound in this crate
2853/// carries ([`POLICY_RETRIES_MAX`],
2854/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2855/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2856/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2857pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
2858
2859/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
2860/// every validated [`CircuitBreaker::window`] past
2861/// [`AplicacaoSpec::validate_politicas`] lies in
2862/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
2863/// integer-millisecond magnitudes by the canonical-form gate
2864/// immediately preceding).
2865///
2866/// The typed field is `Duration` (the zero-floor arm
2867/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
2868/// `Duration::ZERO`, and the canonical-form arm
2869/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
2870/// sub-millisecond residue), so a programmatic struct literal
2871/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
2872/// and the equivalent author-surface form
2873/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
2874/// integer-hour magnitude) both round-trip cleanly through serde — a
2875/// structurally unbounded `Duration` ceiling. A `:window` value far
2876/// above the documented production-playbook band (Hystrix
2877/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
2878/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
2879/// Istio `outlierDetection.interval` default `10s`, Envoy
2880/// `outlier_detection.interval` default `10s`, AWS App Mesh
2881/// circuit-breaker time-window typical `30s..=300s`) degenerates the
2882/// breaker's role: a rolling-window failure counter whose window is
2883/// hours long is operationally a lifetime counter, the breaker's
2884/// "recent failures" memory is structurally so long that transient
2885/// failures are never forgotten, and the typed slot becomes a no-op
2886/// trigger that trips once and stays tripped for the lifetime of the
2887/// component carried on every emitted Envoy / Cilium L7 overlay.
2888///
2889/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
2890/// shared duration codec emits (`"<n>h"` for any integer-hour
2891/// magnitude) — every value in the canonical authoring form's
2892/// `<integer><unit>` grammar at or below this cap renders to a clean
2893/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
2894/// cap on the first typed-`Duration` `:politicas` axis: the two
2895/// duration-typed `:politicas` axes now share a single uniform top
2896/// edge so the next typed-slot wiring (the future caixa-mesh
2897/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
2898/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
2899/// admission webhook) reaches for either field knowing the value is
2900/// in `1ms..=1h` without re-validating at the renderer layer. The cap
2901/// sits two orders of magnitude above every documented upstream
2902/// production-playbook recommendation band (Hystrix / resilience4j /
2903/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
2904/// and below the clearly-pathological "rolling window degenerates to
2905/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
2906/// author can plausibly want for a very-low-traffic long-tail
2907/// failure-detection window, but a hard wall above which the breaker's
2908/// rolling-window contract is structurally a lifetime-counter contract.
2909/// Lifted as a typed `pub const` so the bound has exactly one source
2910/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
2911/// materializer's admission webhook and the caixa-mesh-side
2912/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2913/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
2914/// other typed upper bound in this crate carries
2915/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
2916/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
2917/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2918/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2919/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2920pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
2921
2922/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
2923/// every validated [`RateLimit::rate`] past
2924/// [`AplicacaoSpec::validate_politicas`] lies in
2925/// `1..=POLICY_RATE_LIMIT_MAX`.
2926///
2927/// The typed field is `u32` (the zero-floor arm
2928/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
2929/// zero-rate limit denies every request, the canonical "I forgot
2930/// that 0 means deny-everything" footgun), so a programmatic struct
2931/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
2932/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
2933/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
2934/// round-trip cleanly through serde — a structurally unbounded `u32`
2935/// ceiling. The runtime substrate consuming the value (Envoy's
2936/// `local_rate_limit.token_bucket.max_tokens`, the future
2937/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2938/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
2939/// rate-limit into a no-op rate-limiter: the bucket capacity is
2940/// structurally so high no realistic per-edge traffic shape can
2941/// drain it, the limiter never trips, and the typed slot becomes a
2942/// "rate-limit declared, no enforcement" footgun — the canonical
2943/// declared-but-inert shape every other `:politicas` cap arm
2944/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
2945/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
2946///
2947/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
2948/// above every documented upstream production-playbook recommendation
2949/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
2950/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
2951/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
2952/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
2953/// `limit_req_zone` typical `1..=1_000` RPS) and below the
2954/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
2955/// `u32::MAX`): a value the author can plausibly want at hyperscale
2956/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
2957/// /h-window arm), but a hard wall above which the policy is
2958/// structurally a no-op carried verbatim on every emitted Envoy /
2959/// Cilium L7 overlay. The cap brackets all three canonical windows
2960/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
2961/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
2962/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
2963/// per-endpoint API band). Lifted as a typed `pub const` so the bound
2964/// has exactly one source of truth — the future M4
2965/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
2966/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
2967/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
2968/// one place. Same shape every other typed upper bound in this crate
2969/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
2970/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
2971/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2972/// [`crate::LIMITS_WALL_CLOCK_MAX`],
2973/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2974/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2975pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
2976
2977// `:entrada :host` total-length and per-label cap axes route through
2978// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
2979// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
2980// pair of aplicacao-private aliases the previous `validate_entrada_host`
2981// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
2982// = 63`) were structurally the same K8s Gateway API v1 Hostname
2983// admission-schema bounds — the total-length cap on the OpenAPI
2984// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
2985// same regex — that the peer axes at the caixa-core::render level pin,
2986// so hoisting both readers onto the shared lifted constants closes the
2987// third-occurrence duplication threshold structurally: the M4
2988// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
2989// label validator, the future per-`Certificate` SAN emitter, and every
2990// other per-Gateway-API-Hostname landing site reach the same one place
2991// as the `:entrada :host` gate does — no per-axis alias drift surface
2992// between them, by construction.
2993
2994/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
2995/// extractor expression — the upper bound `validate_placement_shard_key`
2996/// enforces on every well-shaped shard-key past validate. The realistic
2997/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
2998/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
2999/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
3000/// `:placement :affinity` / `:placement :clusters` identifier-shaped
3001/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
3002/// in `:shard-key`" footgun at validate time rather than at the future
3003/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
3004const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
3005
3006/// Reject `:membros :caixa` values the K8s apiserver would refuse at
3007/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3008/// that maps the shared parser-shaped reason into the
3009/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
3010/// is self-locating (the offending `caixa:` is named verbatim) and
3011/// the author can grep their caixa.lisp for `:caixa "<name>"` and
3012/// fix it in one edit. Same diagnostic shape as
3013/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
3014/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
3015fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
3016    // Empty is already gated by `MembroCaixaEmpty` at the call site;
3017    // re-checking here keeps the predicate usable from any future
3018    // call site (the M4 CR materializer) without an empty-check
3019    // footgun. The shared
3020    // [`crate::render::require_valid_dns_1123_label`] helper brackets
3021    // the empty-first + shape cascade every peer name axis
3022    // (`:placement :clusters`, `:placement :affinity`, `:contratos
3023    // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
3024    // `:upgrade-from :module`) routes through, so drift between the
3025    // eight axes' accepted DNS-1123-label sets is structurally
3026    // impossible.
3027    crate::render::require_valid_dns_1123_label(
3028        caixa,
3029        || AplicacaoError::MembroCaixaEmpty,
3030        |reason| AplicacaoError::MembroCaixaInvalid {
3031            caixa: caixa.to_string(),
3032            reason,
3033        },
3034    )
3035}
3036
3037/// Reject `:placement :clusters` entries the K8s apiserver would refuse
3038/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3039/// that maps the shared parser-shaped reason into the
3040/// [`AplicacaoError::PlacementClusterInvalid`] variant.
3041///
3042/// Cluster names land in DNS-1123-label territory across every consumer:
3043/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
3044/// the `lareira-fleet-programs` aggregator applies to scope programs to
3045/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
3046/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
3047/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
3048/// cluster identity the M4 CR materializer round-trips. Each apiserver-
3049/// side schema enforces the DNS-1123 label rule on admission; a
3050/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
3051/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
3052/// mistaken-identity slug) silently passes the prior empty-/duplicate-
3053/// only gate and the failure surfaces as a no-match at filter time —
3054/// the workload doesn't land in the named cluster, with no diagnostic
3055/// naming the offending `:clusters` entry. Lifting the gate to caixa-
3056/// build time mirrors the `:membros :caixa` value-shape trajectory
3057/// (3f9d7a0) on the peer name axis.
3058///
3059/// The diagnostic carries the offending `cluster:` verbatim plus a
3060/// parser-shaped `reason:` naming the specific violation, so the
3061/// author can grep their caixa.lisp for `:clusters` and fix it in
3062/// one edit. Same diagnostic shape as
3063/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
3064fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
3065    // Empty is already gated by `PlacementClusterEmpty` at the call
3066    // site; re-checking here keeps the predicate usable from any
3067    // future call site (the M4 CR materializer's per-cluster validator)
3068    // without an empty-check footgun. Routes through the shared
3069    // [`crate::render::require_valid_dns_1123_label`] gate the peer
3070    // name axes each land on.
3071    crate::render::require_valid_dns_1123_label(
3072        cluster,
3073        || AplicacaoError::PlacementClusterEmpty,
3074        |reason| AplicacaoError::PlacementClusterInvalid {
3075            cluster: cluster.to_string(),
3076            reason,
3077        },
3078    )
3079}
3080
3081/// Reject `:placement :affinity` hints whose shape can never legitimately
3082/// land in any downstream selector or label-keyed routing axis. Thin
3083/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
3084/// shared parser-shaped reason into the
3085/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
3086/// diagnostic is self-locating (the offending `:affinity` is named
3087/// verbatim) and the author can grep their caixa.lisp for
3088/// `:affinity "<hint>"` and fix it in one edit.
3089///
3090/// The `:affinity` slot carries a placement-engine hint — canonical
3091/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
3092/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
3093/// compression overlay and the future M4 placement-engine's per-hint
3094/// routing axis. Each downstream consumer (caixa-mesh's
3095/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
3096/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3097/// `spec.placement.affinity` admission rule, the future M4 per-hint
3098/// node-affinity / pod-affinity rule generator keying off the same
3099/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
3100/// selector) requires the value to be a DNS-1123 label — K8s label
3101/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
3102/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
3103/// admission rule the apiserver enforces.
3104///
3105/// Until this gate landed an `:affinity "DataLocality"` (the canonical
3106/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
3107/// Python-module-name leak), `:affinity "data.locality"` (the
3108/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
3109/// `:affinity "data-locality-"` (boundary-hyphen violation),
3110/// `:affinity "data locality"` (paste-from-doc whitespace),
3111/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
3112/// 64-byte over-cap slug silently passed the empty-only check and the
3113/// failure surfaced as a no-match at the M3 Adaptive compression
3114/// overlay's filter time (`placement.affinity` carried a malformed
3115/// value, no node matched, the workload landed on the default
3116/// heuristic) — the canonical "declared-but-inert" footgun mirroring
3117/// the empty-:affinity / empty-shard-key / zero-:politicas /
3118/// empty-:contratos-target gates already close on every other
3119/// declare-but-no-opinion axis. Lifting the rejection to a build-time
3120/// gate closes the fifth typed slot on the Aplicacao surface to land
3121/// on the canonical DNS-1123 label floor (after the four Servico-name
3122/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
3123/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
3124/// b0e8748).
3125///
3126/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
3127/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
3128/// validated values are guaranteed-accepted by the apiserver without
3129/// re-validation at any downstream renderer or admission layer.
3130fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
3131    // Empty is gated separately at the call site for a self-locating
3132    // diagnostic; re-checking here keeps the predicate usable from any
3133    // future call site (the M4 CR materializer's per-affinity
3134    // validator) without an empty-check footgun. Routes through the
3135    // shared [`crate::render::require_valid_dns_1123_label`] gate the
3136    // peer name axes each land on.
3137    crate::render::require_valid_dns_1123_label(
3138        affinity,
3139        || AplicacaoError::PlacementAffinityEmpty,
3140        |reason| AplicacaoError::PlacementAffinityInvalid {
3141            affinity: affinity.to_string(),
3142            reason,
3143        },
3144    )
3145}
3146
3147/// Reject `:placement :shard-key` extractor expressions whose shape can
3148/// never legitimately drive the future M4 Akka-style cluster-sharding
3149/// reconciler's hash-extractor pass. Maps the per-byte / length checks
3150/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
3151/// diagnostic is self-locating (the offending `:shard-key` value is
3152/// named verbatim alongside the parser-shaped reason) and the author can
3153/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
3154/// edit.
3155///
3156/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
3157/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
3158/// expression naming the message property to hash on. The realistic
3159/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
3160/// property name; `$tenantId` — Akka entity-id placeholder;
3161/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
3162/// `${tenant}` — interpolation-style template) all sit in the printable
3163/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
3164/// multi-line blob landing in `:shard-key`, an embedded space from a
3165/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
3166/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
3167/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
3168/// check and the failure surfaces at the future M4 reconciler's hash
3169/// pass as a runtime extractor-evaluation error far from the source
3170/// `caixa.lisp`, with no field naming which member's `:shard-key`
3171/// carried the offending value.
3172///
3173/// The contract — the printable ASCII single-token intersection-floor
3174/// every Akka-style entity-id extractor implementation admits:
3175///
3176///   - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
3177///     peer DNS-1123-label-shaped `:placement :affinity` /
3178///     `:placement :clusters` identifier axes; realistic shard-keys sit
3179///     well under 32 bytes, the cap surfaces paste-from-doc multi-line
3180///     blob footguns at validate time;
3181///   - every byte in the printable ASCII range `0x21..=0x7E` —
3182///     rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
3183///     `"$tenantId\n"` from paste-from-aligned-doc /
3184///     paste-from-shell-heredoc), control characters (`\x00..\x1F`,
3185///     `\x7F` — the canonical "embedded null from a copy-paste-binary
3186///     footgun"), and non-ASCII bytes (`"$tenàntId"` —
3187///     un-Punycode-encoded IDN that round-trips inconsistently across
3188///     NFC/NFD normalization).
3189///
3190/// The accepted set is broader than the DNS-1123 label floor the peer
3191/// `:placement :clusters` / `:placement :affinity` axes use because the
3192/// `:shard-key` value is not a K8s `metadata.name` / label-selector
3193/// landing site; it's an extractor expression the future Akka-style
3194/// reconciler reads as a property reference. The realistic forms
3195/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
3196/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
3197/// but every Akka-style entity-id extractor parses. The
3198/// printable-ASCII-token floor accepts every shape any such extractor
3199/// would accept while rejecting the cross-implementation footguns
3200/// (whitespace breaks token boundaries; non-ASCII round-trips
3201/// inconsistently across YAML emitters and NFC/NFD normalization;
3202/// control characters silently corrupt the next read).
3203///
3204/// Until this gate landed `validate_placement` only refused the
3205/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
3206/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
3207/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
3208/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
3209/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
3210/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
3211/// control character from paste-from-binary, the 64-byte over-cap
3212/// paste-from-doc multi-line slug) silently passed validate. The future
3213/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
3214/// would then surface the malformed value either as a runtime
3215/// extractor-evaluation error (whitespace breaks the extractor's token
3216/// boundary, no match) or as a silently-different shard assignment
3217/// across YAML emitters (non-ASCII normalizes differently between the
3218/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
3219/// parser, the same entity ID maps to two distinct shards on a
3220/// re-render). Lifting the shape gate to caixa-build time makes the
3221/// extractor-floor invariant a structural property of every validated
3222/// `Placement`: every `Sharded` placement past `validate_placement` has
3223/// a `:shard-key` the future M4 reconciler can hash without
3224/// re-validating at the runtime layer.
3225///
3226/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
3227/// [`AplicacaoError::ContratoSubjectInvalid`] /
3228/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
3229/// on the peer `:contratos` payload axes — each lifts the
3230/// runtime-side parser's intersection-floor to a caixa-build-time gate,
3231/// closing the canonical "this passed validate but the runtime parser
3232/// rejected it" surprise.
3233fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
3234    // Empty is gated separately at the call site via the more
3235    // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
3236    // re-checking here keeps the predicate usable from any future call
3237    // site (the M4 CR materializer's per-shard-key validator) without
3238    // an empty-check footgun.
3239    if key.is_empty() {
3240        return Err(AplicacaoError::ShardedKeyEmpty);
3241    }
3242    if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
3243        return Err(AplicacaoError::ShardKeyInvalid {
3244            shard_key: key.to_string(),
3245            reason: format!(
3246                "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
3247                 (got {} bytes; realistic Akka-style entity-id extractor expressions \
3248                 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
3249                 well under 32 bytes, this length suggests a paste-from-doc \
3250                 multi-line blob landed in `:shard-key` instead of a single-token \
3251                 extractor expression)",
3252                key.len()
3253            ),
3254        });
3255    }
3256    for &b in key.as_bytes() {
3257        if (0x21..=0x7E).contains(&b) {
3258            continue;
3259        }
3260        let reason = if b == b' ' {
3261            "contains a space (Akka-style entity-id extractor expressions are \
3262             single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
3263             whitespace breaks the extractor's token boundary at the runtime layer, \
3264             and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
3265             a multi-token blob in one `:shard-key` slot)"
3266                .to_string()
3267        } else if b == b'\t' {
3268            "contains a tab character (paste-from-aligned-doc footgun; the \
3269             Akka-style entity-id extractor reads `:shard-key` as a single-token \
3270             reference, embedded whitespace breaks the token boundary at the \
3271             runtime hash-extractor pass)"
3272                .to_string()
3273        } else if b == b'\n' || b == b'\r' {
3274            format!(
3275                "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
3276                 paste-from-multiline-doc footgun; the Akka-style entity-id \
3277                 extractor reads `:shard-key` as a single-token reference, embedded \
3278                 newlines either truncate the value at the YAML emitter layer or \
3279                 break the token boundary at the runtime hash-extractor pass)"
3280            )
3281        } else if b < 0x20 || b == 0x7F {
3282            format!(
3283                "contains control character 0x{b:02x} (the canonical \
3284                 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
3285                 control characters silently corrupt round-trip serialization \
3286                 across YAML emitters and break the runtime hash-extractor's \
3287                 single-token parser)"
3288            )
3289        } else {
3290            format!(
3291                "contains non-ASCII byte 0x{b:02x} (the canonical \
3292                 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
3293                 inconsistently across NFC/NFD normalization on APFS / ext4 / \
3294                 across YAML emitter implementations — the same entity ID can \
3295                 silently map to two distinct shards on a re-render. Use a \
3296                 printable-ASCII extractor expression like `tenantId`, \
3297                 `$tenantId`, or `metadata.tenantId`)"
3298            )
3299        };
3300        return Err(AplicacaoError::ShardKeyInvalid {
3301            shard_key: key.to_string(),
3302            reason,
3303        });
3304    }
3305    Ok(())
3306}
3307
3308/// Reject `:contratos :de` / `:contratos :para` values whose shape
3309/// can never legitimately match a validated `:membros :caixa`. Thin
3310/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
3311/// shared parser-shaped reason into the
3312/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
3313/// diagnostic is self-locating (which slot — `:de` or `:para` — and
3314/// the offending value verbatim) and the author can grep their
3315/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
3316/// one edit.
3317///
3318/// Until this gate landed an empty or DNS-1123-malformed `:de` /
3319/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
3320/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
3321/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
3322/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
3323/// un-Punycode-encoded IDN) silently passed the per-axis check and
3324/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
3325/// membership lookup — diagnostic-framed as "this caixa is not in
3326/// `:membros`" when the root cause is "this `:de` value is not a
3327/// well-shaped Servico-name identifier and could never legitimately
3328/// match any validated member". Because every `:membros :caixa` is
3329/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
3330/// `names` HashSet structurally never contains an empty / malformed
3331/// string, so the membership lookup arm misframes every empty /
3332/// malformed input. Lifting the shape arm ahead of the lookup
3333/// preserves the legitimate `ContratoMemberMissing` arm (a
3334/// well-shaped `:de` that simply isn't in `:membros` — a phantom
3335/// reference) while routing every structurally-impossible-to-match
3336/// input through the narrower self-locating shape diagnostic.
3337///
3338/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
3339/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
3340/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
3341/// to land on the canonical [`crate::render::is_dns_1123_label`]
3342/// floor. The `slot: &'static str` field carries the kebab-case
3343/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
3344/// per-callback-slot diagnostic shape and the
3345/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
3346/// (85f102c) cross-list-tag pattern.
3347fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
3348    // Routes through the shared
3349    // [`crate::render::require_valid_dns_1123_label`] gate the peer
3350    // name axes each land on. The `slot: &'static str` field flows
3351    // through both error variants so the diagnostic names which
3352    // per-edge axis (`:de` vs `:para`) the offending value came from.
3353    crate::render::require_valid_dns_1123_label(
3354        caixa,
3355        || AplicacaoError::ContratoCaixaEmpty { slot },
3356        |reason| AplicacaoError::ContratoCaixaInvalid {
3357            slot,
3358            caixa: caixa.to_string(),
3359            reason,
3360        },
3361    )
3362}
3363
3364/// Reject `:entrada :para` values whose shape can never legitimately
3365/// match a validated `:membros :caixa`. Thin wrapper around
3366/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
3367/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
3368/// variant, so the diagnostic is self-locating (the offending
3369/// `:entrada :para` value is named verbatim) and the author can grep
3370/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
3371///
3372/// Until this gate landed an empty or DNS-1123-malformed `:entrada
3373/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
3374/// ADR typo, `:para "my_cart"` the Python-module-name leak,
3375/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
3376/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
3377/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
3378/// silently passed the per-axis check and surfaced as
3379/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
3380/// — diagnostic-framed as "this caixa is not in `:membros`" when the
3381/// root cause is "this `:entrada :para` value is not a well-shaped
3382/// Servico-name identifier and could never legitimately match any
3383/// validated member". Because every `:membros :caixa` is shape-
3384/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
3385/// `HashSet` structurally never contains an empty / malformed string,
3386/// so the membership lookup arm misframes every empty / malformed
3387/// input. Lifting the shape arm ahead of the lookup preserves the
3388/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
3389/// simply isn't in `:membros` — a phantom reference) while routing
3390/// every structurally-impossible-to-match input through the narrower
3391/// self-locating shape diagnostic.
3392///
3393/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
3394/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
3395/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
3396/// fourth and last Aplicacao-level Servico-name reference axis to
3397/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
3398/// No `slot: &'static str` field because there is only one axis
3399/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
3400/// the simpler shape mirrors [`validate_membro_caixa`] and
3401/// [`validate_placement_cluster`].
3402fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
3403    // Empty is gated separately at the call site for a self-locating
3404    // diagnostic; re-checking here keeps the predicate usable from any
3405    // future call site (the M4 CR materializer's per-`:entrada`
3406    // validator) without an empty-check footgun. Routes through the
3407    // shared [`crate::render::require_valid_dns_1123_label`] gate the
3408    // peer name axes each land on.
3409    crate::render::require_valid_dns_1123_label(
3410        para,
3411        || AplicacaoError::EntradaParaEmpty,
3412        |reason| AplicacaoError::EntradaParaInvalid {
3413            para: para.to_string(),
3414            reason,
3415        },
3416    )
3417}
3418
3419/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
3420/// would refuse at admission time. The contract — exactly the regex
3421/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
3422/// and `HTTPRoute.spec.hostnames[]`,
3423/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
3424/// (max length 253; per-label max length 63):
3425///
3426///   - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
3427///     uppercase, no underscore, no Unicode/IDN — IDN must be
3428///     pre-encoded as Punycode `xn--…` by the author);
3429///   - exactly one optional leading wildcard label (`*.`); a wildcard
3430///     in any non-leading label position is rejected;
3431///   - each `.`-separated label is 1..=63 bytes, with non-hyphen
3432///     alphanumeric at both boundaries (no `-foo`, no `foo-`);
3433///   - total length 1..=253 bytes;
3434///   - no IPv4 literal (Gateway API forbids IP literals);
3435///   - no scheme (`https://`, `http://`), no port (`:8080`), no
3436///     whitespace, no path (`/`).
3437///
3438/// Lifted as a typed gate (rather than an inline cascade in
3439/// `validate()`) so the contract lives in one place — every future
3440/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3441/// materializer's host validator, the future per-`:entrada` SAN
3442/// emission for cert-manager Certificates, the multi-`:entrada`
3443/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
3444/// for the same predicate, not its own. Same compounding shape as
3445/// `is_canonical_rate_limit_window` (808017c) and
3446/// [`WitTarget::label`] (previously the free `contrato_target_label`
3447/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
3448/// per-variant label match is compiler-checked-exhaustive).
3449///
3450/// The diagnostic carries the offending `host:` verbatim plus a
3451/// parser-shaped `reason:` naming the specific violation, so the
3452/// author can grep their caixa.lisp for `:host "<host>"` and fix it
3453/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
3454/// (9888b13).
3455fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
3456    // Empty is already gated by `EmptyEntradaHost` at the call site;
3457    // re-checking here keeps the predicate usable from any future
3458    // call site (M4 CR materializer) without an empty-check footgun.
3459    if host.is_empty() {
3460        return Err(AplicacaoError::EmptyEntradaHost);
3461    }
3462    if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
3463        return Err(AplicacaoError::EntradaHostInvalid {
3464            host: host.to_string(),
3465            reason: format!(
3466                "exceeds Gateway API v1 Hostname max length of {cap} bytes \
3467                 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
3468                host.len(),
3469                cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
3470            ),
3471        });
3472    }
3473    if host.contains("://") {
3474        return Err(AplicacaoError::EntradaHostInvalid {
3475            host: host.to_string(),
3476            reason: "must not carry a scheme (drop the `https://` or `http://` prefix; \
3477                     Gateway API takes the bare hostname)"
3478                .to_string(),
3479        });
3480    }
3481    if host.contains('/') {
3482        return Err(AplicacaoError::EntradaHostInvalid {
3483            host: host.to_string(),
3484            reason: "must not carry a path (drop the `/…` suffix; Gateway API path \
3485                     matching is in `:entrada :paths`)"
3486                .to_string(),
3487        });
3488    }
3489    // After the `://` scheme-prefix and `/` path arms have ruled out the
3490    // two `:`-bearing shapes the Gateway API actively rejects with
3491    // location-shaped diagnostics, any remaining `:` in the host body is
3492    // either the canonical "I put the port in the `:host` slot"
3493    // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
3494    // slot lives one axis away on the same `:entrada` block) or an
3495    // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
3496    // Hostname forbids identically to the IPv4-literal arm below. Both
3497    // shapes silently fell through the `://` and `/` arms before this
3498    // lift and surfaced as a deep `label "<rest>:<port>" contains
3499    // invalid character ':'` diagnostic from the per-byte loop near the
3500    // bottom of this predicate, which named the offending byte but not
3501    // the canonical authoring fix — for the port case the author has to
3502    // know the `:entrada` block carries a separate `:port u16` slot
3503    // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
3504    // move the value over; for the IPv6 case the author has to know
3505    // Gateway API v1 forbids IP literals across the board. The contract
3506    // doc-comment above already promises "no port (`:8080`)" verbatim
3507    // in the rejected-shape enumeration but the predicate's
3508    // implementation refused the `:` only as a side-effect of the
3509    // per-label `[a-z0-9-]` character-class loop; this arm brings the
3510    // implementation in line with the documented contract by surfacing
3511    // the canonical fix at the top-level shape gate, peer with how the
3512    // `://` arm names the scheme prefix and the `/` arm names the
3513    // `:entrada :paths` axis. Same compounding trajectory the recent
3514    // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
3515    // — the typed slot's rejected set matches the apiserver's rejected
3516    // set, structurally, with a self-locating diagnostic at the
3517    // offending axis instead of a deep parser-shape leak.
3518    if host.contains(':') {
3519        return Err(AplicacaoError::EntradaHostInvalid {
3520            host: host.to_string(),
3521            reason: "must not contain `:` (the port belongs in the `:entrada :port` \
3522                     slot — a separate `u16` axis on the same `:entrada` block, \
3523                     defaulting to 8080 — not in the host body; drop the `:<port>` \
3524                     suffix and author the bare hostname. If you intended an IPv6 \
3525                     literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
3526                     Hostname forbids IP literals identically to the IPv4-literal \
3527                     arm — use a DNS name)"
3528                .to_string(),
3529        });
3530    }
3531    // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
3532    // predicate — the same single source of truth every peer
3533    // ASCII-whitespace scan in caixa-core flows through: the four
3534    // typed-magnitude codec sites (`limits::parse_byte_size` backing
3535    // `:limits :memory`, `limits::parse_duration` backing `:limits
3536    // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
3537    // `aplicacao::rate_limit_codec::parse` backing `:politicas
3538    // :rate-limit`) and the shared duration codec
3539    // (`supervisor::duration_codec::parse`) backing `:supervisor
3540    // :restart-window` / `:politicas :timeout` / `:politicas
3541    // :circuit-breaker :window`. This landing closes the last string-typed
3542    // slot in caixa-core still calling `.bytes().any(|b|
3543    // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
3544    // across every typed slot now shares one predicate, so a future
3545    // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
3546    // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
3547    // deliberately excluded from the peer non-ASCII predicate) can
3548    // extend at this shared site in one edit rather than seven
3549    // independent scans diverging over time. Naming the offending byte
3550    // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
3551    // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
3552    // the offending byte verbatim" discipline every peer codec site
3553    // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
3554    // / `supervisor.rs:823` / `aplicacao.rs:1640`).
3555    if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
3556        return Err(AplicacaoError::EntradaHostInvalid {
3557            host: host.to_string(),
3558            reason: format!(
3559                "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
3560                 Hostname is a single-token DNS name — leading, trailing, \
3561                 or embedded whitespace breaks the K8s apiserver's Hostname \
3562                 regex at admission time; the paste-from-aligned-doc / \
3563                 paste-from-shell-history / paste-from-CSV footgun silently \
3564                 lands a multi-token blob in `:entrada :host`. Strip every \
3565                 whitespace byte and author the bare hostname — space \
3566                 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
3567                 refuse identically)"
3568            ),
3569        });
3570    }
3571    // Peer of the ASCII-whitespace scan above: route the non-ASCII
3572    // subset of Unicode `White_Space` through the shared
3573    // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
3574    // single source of truth every peer non-ASCII-whitespace scan in
3575    // caixa-core flows through: `limits::parse_byte_size` (`:limits
3576    // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
3577    // `limits::parse_millicores` (`:limits :cpu`),
3578    // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
3579    // and `supervisor::duration_codec::parse` (`:supervisor
3580    // :restart-window` / `:politicas :timeout` / `:politicas
3581    // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
3582    // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
3583    // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
3584    // paste-from-web-doc), or an EM-SPACE-split host
3585    // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
3586    // survived this predicate's ASCII byte-scan (none of the UTF-8
3587    // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
3588    // `u8::is_ascii_whitespace`), then landed on the per-label
3589    // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
3590    // predicate with the generic `label "…" must start and end with an
3591    // alphanumeric` diagnostic — a "far from source at build-time"
3592    // leak that names the label-shape violation but not the
3593    // paste-from-typography origin the author actually needs to fix.
3594    // Peer with the four codec sites the 1b75b38 landing pinned: the
3595    // typed slot's diagnostic axis names the offending codepoint
3596    // (`U+XXXX`) verbatim rather than laundering the value through a
3597    // downstream label-shape arm, so the author can grep their
3598    // caixa.lisp for the invisible codepoint at the surfaced position
3599    // rather than eyeball a multi-byte host for embedded NBSP / LINE
3600    // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
3601    // discipline the peer ASCII-whitespace arm (720ac3b) carries:
3602    // drift between any two typed-slot sites' non-ASCII-whitespace
3603    // rejection set becomes a single-edit fix at the shared predicate
3604    // rather than N independent inline scans diverging over time, and
3605    // a future stricter classification (BOM `\u{FEFF}` / ZWSP
3606    // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
3607    // `char::is_whitespace`" class the peer non-ASCII predicate's
3608    // doc-comment names as the follow-up trajectory) extends at the
3609    // shared predicate in one edit rather than seven.
3610    if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
3611        return Err(AplicacaoError::EntradaHostInvalid {
3612            host: host.to_string(),
3613            reason: format!(
3614                "contains non-ASCII Unicode whitespace character {ch:?} \
3615                 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
3616                 single-token DNS name limited to `[a-z0-9-]` labels; \
3617                 the paste-from-typography footgun silently lands an \
3618                 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
3619                 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
3620                 `U+3000`, and every other member of the Unicode \
3621                 `White_Space` property outside the ASCII byte range) \
3622                 in `:entrada :host`, which the K8s apiserver's \
3623                 Hostname regex refuses at admission time far from the \
3624                 caixa.lisp source line. Strip every non-ASCII \
3625                 whitespace character and author the bare hostname \
3626                 with only ASCII bytes (write \"checkout.quero.cloud\" \
3627                 verbatim)",
3628                codepoint = ch as u32,
3629            ),
3630        });
3631    }
3632
3633    // Strip the optional single leading wildcard label *before* the
3634    // trailing-dot check so the bare `"*."` form surfaces the more
3635    // self-locating "wildcard without domain" diagnostic instead of
3636    // the generic "trailing dot" one.
3637    let (had_wildcard, rest) = match host.strip_prefix("*.") {
3638        Some(r) => (true, r),
3639        None => (false, host),
3640    };
3641    if had_wildcard && rest.is_empty() {
3642        return Err(AplicacaoError::EntradaHostInvalid {
3643            host: host.to_string(),
3644            reason: "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)".to_string(),
3645        });
3646    }
3647    if rest.contains('*') {
3648        return Err(AplicacaoError::EntradaHostInvalid {
3649            host: host.to_string(),
3650            reason: "wildcard `*` is allowed only as the first label (`*.example.com`); \
3651                     no inner or trailing `*` labels"
3652                .to_string(),
3653        });
3654    }
3655    if rest.ends_with('.') {
3656        return Err(AplicacaoError::EntradaHostInvalid {
3657            host: host.to_string(),
3658            reason: "must not have a trailing `.` (Gateway API hostnames are not \
3659                     fully-qualified with a root dot; the apiserver regex rejects \
3660                     trailing dots)"
3661                .to_string(),
3662        });
3663    }
3664
3665    // Reject pure IPv4 literals: four dot-separated labels, every
3666    // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
3667    // literals as Hostnames.
3668    let labels: Vec<&str> = rest.split('.').collect();
3669    if labels.len() == 4
3670        && labels
3671            .iter()
3672            .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
3673    {
3674        return Err(AplicacaoError::EntradaHostInvalid {
3675            host: host.to_string(),
3676            reason: "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
3677                     literals; use a DNS name)"
3678                .to_string(),
3679        });
3680    }
3681
3682    // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
3683    // hyphen, with non-hyphen at both boundaries.
3684    for label in &labels {
3685        if label.is_empty() {
3686            return Err(AplicacaoError::EntradaHostInvalid {
3687                host: host.to_string(),
3688                reason: "has an empty label (consecutive `..` or a leading `.`)".to_string(),
3689            });
3690        }
3691        if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
3692            return Err(AplicacaoError::EntradaHostInvalid {
3693                host: host.to_string(),
3694                reason: format!(
3695                    "label {label:?} exceeds DNS-1123 label max length of \
3696                     {cap} bytes (got {} bytes)",
3697                    label.len(),
3698                    cap = crate::render::DNS_1123_LABEL_MAX_LEN,
3699                ),
3700            });
3701        }
3702        let bytes = label.as_bytes();
3703        if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
3704            return Err(AplicacaoError::EntradaHostInvalid {
3705                host: host.to_string(),
3706                reason: format!(
3707                    "label {label:?} must start and end with an alphanumeric \
3708                     (no leading or trailing `-`)"
3709                ),
3710            });
3711        }
3712        for &b in bytes {
3713            let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
3714            if !valid {
3715                let msg = if b.is_ascii_uppercase() {
3716                    format!(
3717                        "label {label:?} contains uppercase character {ch:?} \
3718                         (Gateway API hostnames are lowercase-only; use {lower:?})",
3719                        ch = b as char,
3720                        lower = label.to_ascii_lowercase()
3721                    )
3722                } else if b == b'_' {
3723                    format!(
3724                        "label {label:?} contains `_` (Gateway API hostnames \
3725                         allow only `[a-z0-9-]`; use `-` instead)"
3726                    )
3727                } else {
3728                    format!(
3729                        "label {label:?} contains invalid character {ch:?} \
3730                         (Gateway API hostnames allow only `[a-z0-9-]`)",
3731                        ch = b as char
3732                    )
3733                };
3734                return Err(AplicacaoError::EntradaHostInvalid {
3735                    host: host.to_string(),
3736                    reason: msg,
3737                });
3738            }
3739        }
3740    }
3741    Ok(())
3742}
3743
3744/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
3745/// would refuse at admission time. Thin wrapper around
3746/// [`crate::render::is_gateway_api_http_path`] that maps the shared
3747/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
3748/// variant, preserving the more self-locating
3749/// [`AplicacaoError::EntradaPathEmpty`] /
3750/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
3751/// path fails those narrower invariants first.
3752///
3753/// The contract is the canonical HTTP-path grammar — `1..=
3754/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
3755/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
3756/// whitespace/control/non-ASCII bytes — shared with the
3757/// `:contratos :endpoint` axis through the lifted predicate so drift
3758/// between either landing site and the K8s apiserver-side
3759/// HTTPPathMatch.value OpenAPI schema is a build error visible at
3760/// the predicate, not a per-renderer "this passed validate but failed
3761/// admission" surprise. The diagnostic carries the offending `path:`
3762/// verbatim plus a parser-shaped `reason:` naming the specific
3763/// violation, so the author can grep their caixa.lisp for `:paths`
3764/// and fix it in one edit. Same diagnostic shape as
3765/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
3766/// axis.
3767fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
3768    // Empty and missing-leading-`/` are already gated at the call
3769    // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
3770    // checking here keeps the per-axis narrower diagnostics in force
3771    // when the predicate is reached directly (and `is_gateway_api_http_path`
3772    // itself defends against `bytes[0]`-style indexing on empty
3773    // input).
3774    if path.is_empty() {
3775        return Err(AplicacaoError::EntradaPathEmpty);
3776    }
3777    if !path.starts_with('/') {
3778        return Err(AplicacaoError::EntradaPathNotAbsolute {
3779            path: path.to_string(),
3780        });
3781    }
3782    crate::render::is_gateway_api_http_path(path).map_err(|reason| {
3783        AplicacaoError::EntradaPathInvalid {
3784            path: path.to_string(),
3785            reason,
3786        }
3787    })
3788}
3789
3790mod rate_limit_codec {
3791    // `Duration` is no longer named here — the codec routes through
3792    // the module-scope [`super::rate_limit_window_from_unit`] /
3793    // [`super::rate_limit_window_unit`] projections that carry the
3794    // canonical typed `Duration` unit-table axis on their signatures.
3795    use super::RateLimit;
3796    use serde::{Deserialize, Deserializer, Serializer};
3797
3798    pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
3799        match v {
3800            Some(rl) => s.serialize_str(&render(*rl)),
3801            None => s.serialize_none(),
3802        }
3803    }
3804
3805    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
3806        let opt: Option<String> = Option::deserialize(d)?;
3807        match opt {
3808            None => Ok(None),
3809            Some(s) => parse(&s).map(Some).map_err(serde::de::Error::custom),
3810        }
3811    }
3812
3813    fn parse(s: &str) -> Result<RateLimit, String> {
3814        // Whitespace-rejection arm — peer with the leading-`+`
3815        // (`"+100/s"`) and leading-zero (`"0100/s"`) arms below on the
3816        // same canonical-form render-determinism axis. Until this gate
3817        // landed the parser silently tolerated leading / trailing /
3818        // internal whitespace via the top-level `s.trim()` and the
3819        // per-part `rate_str.trim()` / `unit.trim()` calls, so every
3820        // whitespace-carrying shape (`" 100/s"`, `"100/s "`,
3821        // `"100 /s"`, `"100/ s"`, `"100 / s"`, `"100/s\n"`,
3822        // `"\t100/s"`) parsed to the same `RateLimit { 100, 1s }` and
3823        // serde silently round-tripped to `"100/s"` on the next emit
3824        // (a *different* canonical string) — breaking the THEORY.md
3825        // Part V render-determinism contract on the same
3826        // canonical-form-drift axis the leading-`+` arm below (the
3827        // 4eeae98 predecessor) and the leading-zero arm below (the
3828        // 4f46830 predecessor) already close.
3829        //
3830        // The canonical author shape is `<integer>/<s|m|h>` with no
3831        // whitespace bytes anywhere — every string [`render`] emits
3832        // carries none, so the parser's accepted set must match for
3833        // serialize / deserialize to round-trip losslessly. This gate
3834        // makes the pre-existing `s.trim()` / `rate_str.trim()` /
3835        // `unit.trim()` calls below strict no-ops on the accepted set
3836        // (every byte-position match they would perform is now already
3837        // trimmed away by the accepted set itself), while the arm
3838        // surfaces every rejected whitespace-carrying shape with a
3839        // self-locating diagnostic naming the offending byte and the
3840        // canonical form the author intended, peer with every prior
3841        // canonical-form-drift arm on this codec.
3842        //
3843        // Routed through the lifted
3844        // [`crate::render::find_ascii_whitespace_byte`] predicate — the
3845        // same source of truth the four peer typed-magnitude codec
3846        // sites (`limits::parse_byte_size`, `limits::parse_duration`,
3847        // `limits::parse_millicores`, `supervisor::duration_codec`)
3848        // share. `u8::is_ascii_whitespace()` at the predicate covers
3849        // the five WhatWG-conformant ASCII whitespace bytes (space,
3850        // tab, LF, FF, CR); the "single lifted predicate" discipline
3851        // the peer non-ASCII arm below carries on the strictly-
3852        // complementary Unicode `White_Space` class extends here to
3853        // the ASCII byte set as well.
3854        if let Some(b) = crate::render::find_ascii_whitespace_byte(s) {
3855            return Err(format!(
3856                "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
3857                 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
3858                 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
3859                 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
3860                 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
3861                 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
3862                 on first serialize — breaking the THEORY.md Part V render-determinism \
3863                 contract every typed slot carries. Strip every whitespace byte (write \
3864                 `\"100/s\"` verbatim)"
3865            ));
3866        }
3867        // Non-ASCII Unicode `White_Space` arm — the strictly-
3868        // complementary class the ASCII arm above cannot see.
3869        // `str::trim` at the top of every peer codec uses
3870        // `char::is_whitespace` (Unicode `White_Space`, strictly
3871        // wider than the ASCII byte set), so an NBSP (`\u{00A0}`) /
3872        // LINE SEPARATOR (`\u{2028}`) / EM-SPACE (`\u{2003}`)
3873        // survives the byte-scan (its UTF-8 bytes are not in
3874        // `is_ascii_whitespace`), gets silently stripped by the
3875        // top-level `s.trim()` below, and the value round-trips
3876        // through `render` to a *different* canonical form
3877        // (`\"100/s\"`) on next emit — breaking the THEORY.md Part V
3878        // render-determinism contract every typed slot carries.
3879        // Closed here (`:politicas :rate-limit`) and at the three
3880        // peer codec sites (`limits::parse_byte_size`,
3881        // `limits::parse_duration`, `supervisor::duration_codec`)
3882        // through the shared
3883        // [`crate::render::find_non_ascii_whitespace_char`] predicate
3884        // — the "single lifted predicate across all four codec sites
3885        // in one follow-up run" the 24a8ad4 commit body's `Forward
3886        // compounding` bullet named as the next compounding step.
3887        if let Some(ch) = crate::render::find_non_ascii_whitespace_char(s) {
3888            return Err(format!(
3889                "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
3890                 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
3891                 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
3892                 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
3893                 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
3894                 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
3895                 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
3896                 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
3897                 silently strips it at parse entry, and the value round-trips through \
3898                 `render` to a *different* canonical form (`\"100/s\"`) on first \
3899                 serialize — breaking the THEORY.md Part V render-determinism contract \
3900                 every typed slot carries. Strip every non-ASCII whitespace character \
3901                 (write `\"100/s\"` verbatim with only ASCII bytes)",
3902                cp = ch as u32
3903            ));
3904        }
3905        let s = s.trim();
3906        let (rate_str, unit) = s
3907            .split_once('/')
3908            .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
3909        let rate_trim = rate_str.trim();
3910        // The canonical authoring form for `:politicas :rate-limit` is
3911        // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
3912        // non-negative integer with no decimal point and no leading
3913        // sign, so the parser's accepted set must match for
3914        // serialize/deserialize to round-trip without canonical-form
3915        // drift. Until this gate landed the parser accepted any
3916        // `u32::from_str`-shaped magnitude — and current Rust
3917        // `u32::from_str` permissively accepts a leading `+` (`"+100"`
3918        // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
3919        // serde silently round-tripped to `"100/s"` on the next emit
3920        // (a *different* canonical string) — breaking the THEORY.md
3921        // Part V render-determinism contract on the fifth typed-codec
3922        // surface in caixa-core (peer with the four duration codecs the
3923        // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
3924        // already covered: `supervisor::duration_codec` backing three
3925        // typed-duration slots, `limits::parse_duration` backing
3926        // `:limits :wall-clock`, `limits::parse_byte_size` backing
3927        // `:limits :memory`). The fractional / decimal-shaped sibling
3928        // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
3929        // existing rejection arm, but the diagnostic is value-laundered
3930        // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
3931        // doesn't name the canonical-form remediation or the round-trip
3932        // drift the next emit would produce); this gate lifts the
3933        // fractional arm onto the same canonical-form diagnostic the
3934        // peer codecs carry.
3935        //
3936        // Strict canonical form: every byte of the magnitude is an
3937        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
3938        // inputs the gate distinguishes "non-canonical-but-numeric"
3939        // (parses as f64 or i64 — surfaced with a self-locating
3940        // diagnostic naming the canonical authoring form and the
3941        // round-trip drift the rejected shape would produce on first
3942        // serialize) from "garbage" (parses as neither — surfaced with
3943        // the existing narrower `"not a u32"` wording so its
3944        // diagnostic shape remains stable for the parser-shape footgun
3945        // case).
3946        //
3947        // Routed through the lifted
3948        // [`crate::render::is_digit_only_magnitude`] predicate — the
3949        // same source of truth the four peer typed-magnitude codec
3950        // sites share.
3951        let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
3952        if !digit_only {
3953            let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
3954            if numeric {
3955                return Err(format!(
3956                    "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
3957                     canonical authoring form for `:politicas :rate-limit` is \
3958                     `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
3959                     with no decimal point and no leading `+` / `-` sign. A fractional / \
3960                     signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
3961                     through `render` to a *different* canonical form (`\"1/s\"`, \
3962                     `\"100/s\"`, parser-reject) on first serialize — breaking the \
3963                     THEORY.md Part V render-determinism contract every typed slot \
3964                     carries. Pick an integer rate that fits the desired window \
3965                     (write `\"6000/m\"` instead of `\"1.66/s\"`)"
3966                ));
3967            }
3968            return Err(format!("rate-limit rate {rate_str:?} not a u32"));
3969        }
3970        // Leading-zero arm — peer with the prior `"+100/s"` arm above
3971        // (4eeae98's predecessor) on the same canonical-form
3972        // render-determinism axis. The digit-only gate accepts
3973        // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
3974        // them losslessly (= 100, 0, 7), but `render` emits the
3975        // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
3976        // a *different* canonical string on the next emit, breaking
3977        // the THEORY.md Part V render-determinism contract the same
3978        // way `"+100/s"` did before the leading-`+` arm landed. The
3979        // single-byte magnitude `"0"` itself round-trips losslessly
3980        // through `render` (`render(0)` emits `"0/s"`) — the
3981        // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
3982        // what refuses rate-zero authoring, so `"0/s"` stays in the
3983        // accepted set at this codec layer and the diagnostic
3984        // partitioning between canonical-form drift (this arm) and
3985        // semantic-zero (the downstream gate) remains stable.
3986        // Peer with the future leading-zero arms on the three peer
3987        // typed-magnitude codecs the trajectory acknowledges:
3988        // `supervisor::duration_codec`, `limits::parse_duration`,
3989        // `limits::parse_byte_size` — each carries the same
3990        // canonical-form-drift class today; this gate lands the
3991        // discipline on the fourth typed-magnitude codec in
3992        // caixa-core first because the peer `"+100/s"` arm above is
3993        // the closest predecessor on the trajectory.
3994        //
3995        // Routed through the lifted
3996        // [`crate::render::is_leading_zero_padded_magnitude`]
3997        // predicate — the same source of truth the four peer
3998        // typed-magnitude codec sites share.
3999        if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
4000            return Err(format!(
4001                "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
4002                 canonical authoring form for `:politicas :rate-limit` is \
4003                 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4004                 with no leading-zero padding on the magnitude. A leading-zero magnitude \
4005                 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
4006                 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
4007                 first serialize — breaking the THEORY.md Part V render-determinism \
4008                 contract every typed slot carries. Strip the leading zeros (write \
4009                 `\"100/s\"` instead of `\"0100/s\"`)"
4010            ));
4011        }
4012        // The digit-only gate guarantees every byte is `[0-9]`, and
4013        // the leading-zero arm above guarantees the magnitude is
4014        // either the single byte `"0"` or starts with `[1-9]`, so
4015        // the only way `u32::from_str` can fail here is overflow
4016        // (the magnitude exceeds `u32::MAX`). Surface that with an
4017        // overflow-shaped wording so the diagnostic names the
4018        // offending magnitude verbatim rather than collapsing onto
4019        // the non-canonical arm. Same shape
4020        // `supervisor::duration_codec` (1c55a2a) carries on the peer
4021        // duration-codec axis.
4022        let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
4023            format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
4024        })?;
4025        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
4026        // module scope as the lifted [`super::RATE_LIMIT_UNIT_TABLE`]
4027        // const; this parse arm now consumes only the `unit → Duration`
4028        // projection [`super::rate_limit_window_from_unit`], so a future
4029        // rate-limit-unit addition (a `"d"` day suffix once Envoy's
4030        // `rate_limit_action` grows daily-bucket support) is one row
4031        // appended to the table — parse, render, and
4032        // `is_canonical_rate_limit_window` all pick it up by construction.
4033        let unit = unit.trim();
4034        let window = super::rate_limit_window_from_unit(unit)
4035            .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
4036        Ok(RateLimit { rate, window })
4037    }
4038
4039    fn render(rl: RateLimit) -> String {
4040        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
4041        // module scope as the lifted [`super::RATE_LIMIT_UNIT_TABLE`]
4042        // const; this render arm now consumes only the `Duration → unit`
4043        // projection [`super::rate_limit_window_unit`], which returns
4044        // `None` on every non-canonical window (the sub-second /
4045        // non-`{1, 60, 3600}` shapes the validate gate rejects). Same
4046        // helper the sibling [`super::is_canonical_rate_limit_window`]
4047        // predicate reads — so a future rate-limit-unit addition
4048        // (a `"d"` day suffix once Envoy's `rate_limit_action` grows
4049        // daily-bucket support) is one row appended to the table and
4050        // both consumers pick it up by construction.
4051        if let Some(unit) = super::rate_limit_window_unit(rl.window()) {
4052            format!("{}/{unit}", rl.rate())
4053        } else {
4054            // Defensive fallback for non-canonical windows. Note:
4055            // [`AplicacaoSpec::validate_politicas`] rejects any
4056            // non-canonical `:rate-limit :window` via
4057            // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
4058            // a validated `RateLimit` never reaches this branch. The
4059            // emitted `<n>/<k>s` form is *not* round-trippable through
4060            // [`parse`] (which accepts only the [`super::RATE_LIMIT_UNIT_TABLE`]
4061            // suffixes, not `<k>s` with an explicit count) — the
4062            // validate gate is what makes the round-trip a structural
4063            // property; this branch exists only so a programmatic
4064            // non-validated serialize doesn't panic.
4065            format!("{}/{}s", rl.rate(), rl.window().as_secs())
4066        }
4067    }
4068}
4069
4070// ── placement strategy ───────────────────────────────────────────────
4071
4072/// How the Aplicacao distributes across clusters. Three options:
4073///
4074/// - `SingleNode` — one cluster runs the app at a time; takeover on
4075///   death (Erlang/OTP distributed-app semantics).
4076/// - `Replicated` — every named cluster runs an instance (active-active).
4077/// - `Sharded` — entities distribute by hash key across clusters
4078///   (Akka cluster sharding).
4079#[derive(
4080    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
4081)]
4082pub enum PlacementStrategy {
4083    SingleNode,
4084    Replicated,
4085    Sharded,
4086}
4087
4088impl Default for PlacementStrategy {
4089    fn default() -> Self {
4090        Self::Replicated
4091    }
4092}
4093
4094impl PlacementStrategy {
4095    /// Canonical camelCase-schema discriminator scalar this variant
4096    /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
4097    /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
4098    /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4099    /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
4100    /// every substrate consumer that dispatches on the strategy (the
4101    /// `lareira-fleet-programs` aggregator, the future `app-operator`
4102    /// reconciler, the M3 Adaptive compression pass) reads the same
4103    /// byte-string the `Serialize` derive emits — the pin test in
4104    /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
4105    /// asserts the two paths agree.
4106    #[must_use]
4107    pub const fn as_str(self) -> &'static str {
4108        match self {
4109            Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
4110            Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
4111            Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
4112        }
4113    }
4114}
4115
4116/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
4117/// the pretty-printed byte-string every consumer that formats the strategy
4118/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
4119/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
4120/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
4121/// per-Aplicacao strategy line, the future M4 CR materializer's per-
4122/// admission-webhook rejection body) reaches for the same lifted
4123/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
4124/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4125/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
4126/// `Serialize` derive already emits under
4127/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
4128/// [`PlacementStrategy::as_str`] helper already returns.
4129///
4130/// Until this lift landed the sibling OTP-shape typed enums —
4131/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
4132/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
4133/// so [`std::fmt::Display`] routes through the same discriminant string
4134/// the wire format emits) — carried a stable [`std::fmt::Display`]
4135/// surface but [`PlacementStrategy`] did not; every consumer reaching
4136/// for a strategy byte-string past the wire format had to pick between
4137/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
4138/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
4139/// derive), any two of which a future variant rename or
4140/// `#[serde(rename_all = "kebab-case")]` attribute would silently
4141/// desynchronize — with the failure surfacing as a downstream renderer /
4142/// operator's per-strategy dispatch reading one spelling while the wire
4143/// format emitted another, far from the source rebrand commit and with
4144/// no field naming the drift. Routing `Display` through
4145/// [`PlacementStrategy::as_str`] makes the three paths
4146/// (`Debug` for structural inspection, `Display` for user-facing text,
4147/// `Serialize` for the wire format) converge on the same lifted
4148/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
4149/// the diagnostic byte-string, and the pretty-printed byte-string move
4150/// as a single unit through one canonical declaration each, by
4151/// construction. Same trajectory as [`PlacementStrategy::as_str`]
4152/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
4153/// closes the third path.
4154///
4155/// Pin tests
4156/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
4157/// and
4158/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
4159/// assert the three paths agree byte-for-byte on every variant, so a
4160/// future variant rename or per-arm serde attribute drift is a build
4161/// error visible at caixa-core test time, not a silent per-consumer
4162/// dispatch miss at apply / reconcile time.
4163impl std::fmt::Display for PlacementStrategy {
4164    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4165        f.write_str(self.as_str())
4166    }
4167}
4168
4169/// Where the Aplicacao runs.
4170#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
4171#[serde(rename_all = "camelCase")]
4172pub struct Placement {
4173    /// Distribution strategy.
4174    #[serde(default)]
4175    pub estrategia: PlacementStrategy,
4176
4177    /// Named clusters that host this Aplicacao. Required for
4178    /// `Replicated` and `SingleNode`; for `Sharded` declares the
4179    /// shard pool.
4180    #[serde(default)]
4181    pub clusters: Vec<String>,
4182
4183    /// Optional hint to the placement engine: `"data-locality"`,
4184    /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
4185    #[serde(default, skip_serializing_if = "Option::is_none")]
4186    pub affinity: Option<String>,
4187
4188    /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
4189    #[serde(default, skip_serializing_if = "Option::is_none")]
4190    pub shard_key: Option<String>,
4191}
4192
4193impl Placement {
4194    /// Substrate-canonical per-`:placement` Akka-cluster-sharding
4195    /// `:shard-key` extractor-expression scalar accessor every consumer
4196    /// of the Aplicacao's hash-keyed distribution routing keys off —
4197    /// returns the author-declared `:placement :shard-key` byte-string
4198    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
4199    /// own `Option<String>` storage; `None` when the slot is absent
4200    /// (the canonical shape under `:estrategia Replicated` /
4201    /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
4202    /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
4203    /// partition — `validate` refuses any `Placement` past this call
4204    /// that lands `Some` on a non-`Sharded` strategy or `None` on
4205    /// `Sharded`).
4206    ///
4207    /// The `:placement :shard-key` slot carries the Akka-style
4208    /// cluster-sharding entity-id extractor expression
4209    /// (MESH-COMPOSITION §II.4) — validated by
4210    /// [`validate_placement_shard_key`] to be a non-empty printable-
4211    /// ASCII single-token reference (`tenantId`, `$tenantId`,
4212    /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
4213    /// future M4 Akka-style cluster-sharding reconciler hashes without
4214    /// re-validating at the runtime layer), and every downstream
4215    /// consumer that reads the key keys off this scalar (the
4216    /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
4217    /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
4218    /// declared-but-inert refusal diagnostic, the caixa-mesh
4219    /// per-Aplicacao `placement.shardKey` emit path the substrate
4220    /// operator's per-entity hash-routing reader consumes, the future
4221    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4222    /// per-shard-key resolver).
4223    ///
4224    /// Prior to this lift the `.shard_key` field was accessed inline at
4225    /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
4226    /// `Sharded` arm's `match &self.placement.shard_key { None => …,
4227    /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
4228    /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
4229    /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
4230    /// — two open-coded field-accesses that expressed no compile-time
4231    /// link back to the typed slot. A future extension of the
4232    /// `:placement :shard-key` axis to a richer author surface — a
4233    /// per-cluster override the operator pins through a future
4234    /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
4235    /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
4236    /// alias table the M4 CR materializer resolves per-CR, a
4237    /// per-Aplicacao dynamic `:shard-key` derivation the future
4238    /// adaptive placement engine computes from `:affinity` weights —
4239    /// would have had to be threaded through both open-coded copies in
4240    /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
4241    /// arm refusal would silently disagree on which extractor
4242    /// expression a given Placement resolves to. Lifting the resolution
4243    /// rule to a typed method on the substrate primitive means every
4244    /// downstream consumer of the Aplicacao's per-`:placement`
4245    /// hash-key surface reaches for exactly one typed dispatch — the
4246    /// resolver's accept-set migrates as a unit on any future axis
4247    /// addition.
4248    ///
4249    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
4250    /// [`WitContract::destination`] / [`WitContract::world_ref`]
4251    /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
4252    /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
4253    /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
4254    /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
4255    /// typed dispatch on the substrate primitive, thin projections at
4256    /// each consumer" discipline extended onto the per-`:placement`
4257    /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
4258    /// First `Option<&str>`-return accessor on the M3 mesh-slot family
4259    /// — opens the "optional per-slot scalar" projection pattern the
4260    /// sibling per-`:placement` `:affinity`, per-`:politicas`
4261    /// `:rate-limit` future lifts fold on. Named `shard_key()` to
4262    /// match the storage field's name; the accessor's identity name
4263    /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
4264    /// slot's docstring already carries.
4265    #[must_use]
4266    pub fn shard_key(&self) -> Option<&str> {
4267        self.shard_key.as_deref()
4268    }
4269
4270    /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
4271    /// compression-hint scalar accessor every weighting-consumer of the
4272    /// Aplicacao's per-hint routing surface keys off — returns the
4273    /// author-declared `:placement :affinity` byte-string verbatim as
4274    /// an `Option<&str>`, borrowed from the typed slot's own
4275    /// `Option<String>` storage; `None` when the slot is absent (the
4276    /// canonical shape of an Aplicacao that leaves the compression
4277    /// weighting up to the placement engine's cluster-default arm — no
4278    /// author-authored `data-locality` / `low-latency` / etc. hint
4279    /// biases the routing).
4280    ///
4281    /// The `:placement :affinity` slot carries the M3 Adaptive-
4282    /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
4283    /// by [`validate_placement_affinity`] to be a DNS-1123 label
4284    /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
4285    /// K8s-conformant label-selector shape every apiserver-side pod-
4286    /// affinity / node-affinity materializer already gates on
4287    /// admission), and every downstream consumer that reads the hint
4288    /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
4289    /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
4290    /// `placement.affinity` overlay emit path the substrate operator's
4291    /// per-hint weighting-consumer reads, the future M4
4292    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
4293    /// pod-affinity / node-affinity selector resolver).
4294    ///
4295    /// Prior to this lift the `.affinity` field was accessed inline at
4296    /// the sole caixa-core site — the
4297    /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
4298    /// `if let Some(a) = &self.placement.affinity { …
4299    /// validate_placement_affinity(a)? … }` cascade — one open-coded
4300    /// field-access that expressed no compile-time link back to the
4301    /// typed slot. A future extension of the `:placement :affinity`
4302    /// axis to a richer author surface — a per-cluster override the
4303    /// operator pins through a future `:placement :affinity-overrides`
4304    /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
4305    /// tenant hint alias table the M4 CR materializer resolves per-CR,
4306    /// a per-Aplicacao dynamic `:affinity` derivation the future
4307    /// adaptive placement engine computes from `:clusters` topology —
4308    /// would have had to be threaded through the open-coded copy in
4309    /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
4310    /// materializer reader that landed on the axis, or the per-hint
4311    /// value-shape gate and its downstream weighting consumers would
4312    /// silently disagree on which hint a given Placement resolves to.
4313    /// Lifting the resolution rule to a typed method on the substrate
4314    /// primitive means every downstream consumer of the Aplicacao's
4315    /// per-`:placement` compression-hint surface reaches for exactly
4316    /// one typed dispatch — the resolver's accept-set migrates as a
4317    /// unit on any future axis addition.
4318    ///
4319    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
4320    /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
4321    /// optional-scalar axis — same "one typed dispatch on the substrate
4322    /// primitive, thin projections at each consumer" discipline extended
4323    /// onto the per-`:placement` M3-Adaptive-compression-hint
4324    /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
4325    /// return accessor on the M3 mesh-slot family; closes the last
4326    /// un-lifted per-`:placement` `Option<String>` axis. Named
4327    /// `affinity()` to match the storage field's name; the accessor's
4328    /// identity name maps onto the canonical MESH-COMPOSITION §II.4
4329    /// vocabulary the slot's docstring already carries.
4330    #[must_use]
4331    pub fn affinity(&self) -> Option<&str> {
4332        self.affinity.as_deref()
4333    }
4334
4335    /// Substrate-canonical per-`:placement` `:estrategia` distribution-
4336    /// strategy scalar accessor every consumer that dispatches on the
4337    /// Aplicacao's per-cluster distribution shape keys off — returns the
4338    /// author-declared `:placement :estrategia` variant verbatim as a
4339    /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
4340    /// `PlacementStrategy` storage.
4341    ///
4342    /// The `:placement :estrategia` slot carries the closed-set
4343    /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
4344    /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
4345    /// `Replicated` — active-active across every named cluster; `Sharded`
4346    /// — Akka-style hash-keyed entity distribution across the cluster pool
4347    /// per §II.4) that every downstream consumer of the Aplicacao's
4348    /// per-cluster fan-out shape keys off. Validated by
4349    /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
4350    /// the sibling `:shard-key` axis (`shard_key.is_some() ==
4351    /// matches!(estrategia, Sharded)` — the cross-slot partition the
4352    /// [`Placement::shard_key`] accessor's docstring pins), and every
4353    /// downstream consumer that reads the strategy keys off this scalar
4354    /// (the [`AplicacaoSpec::validate_placement`]
4355    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
4356    /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
4357    /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
4358    /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
4359    /// declared-but-inert refusal's
4360    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
4361    /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
4362    /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
4363    /// emit path the substrate operator's per-strategy fan-out reader
4364    /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4365    /// materializer's per-strategy admission-webhook resolver).
4366    ///
4367    /// Prior to this lift the `.estrategia` field was accessed inline at
4368    /// four sites — the [`AplicacaoSpec::validate_placement`]
4369    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
4370    /// `estrategia: self.placement.estrategia`, the same method's
4371    /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
4372    /// partition dispatch, the non-`Sharded`-arm
4373    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
4374    /// `estrategia: self.placement.estrategia`, and the `feira app graph`
4375    /// per-Aplicacao strategy print line at
4376    /// `println!("… {} …", spec.placement.estrategia, …)`
4377    /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
4378    /// expressed no compile-time link back to the typed slot. A future
4379    /// extension of the `:placement :estrategia` axis to a richer author
4380    /// surface (a per-cluster override the operator pins through a future
4381    /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
4382    /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
4383    /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
4384    /// derivation the future adaptive placement engine computes from
4385    /// `:affinity` + `:clusters` topology) would have had to be threaded
4386    /// through every open-coded copy in lockstep — one consumer reading
4387    /// the raw variant while a peer read the operator-resolved variant
4388    /// would silently split the `PlacementWithoutClusters` /
4389    /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
4390    /// partition-dispatch input, a two-consumer split at the validator
4391    /// far from the source `caixa.lisp` with no field naming the
4392    /// strategy-drift root cause. Lifting the resolution rule to a typed
4393    /// method on the substrate primitive means every downstream consumer
4394    /// of the Aplicacao's per-`:placement` distribution-strategy surface
4395    /// reaches for exactly one typed dispatch — the resolver's accept-set
4396    /// migrates as a unit on any future axis addition.
4397    ///
4398    /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
4399    /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
4400    /// same "one typed dispatch on the substrate primitive, thin
4401    /// projections at each consumer" discipline extended onto the
4402    /// per-`:placement` distribution-strategy `Copy`-composite-enum
4403    /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
4404    /// family; first `Copy`-return accessor on the M3 mesh-slot
4405    /// `Placement` type — companion to the sibling per-`:placement`
4406    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
4407    /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
4408    /// optional-scalar axes, closing the last unlifted per-`:placement`
4409    /// scalar-value axis (the closed-set `PlacementStrategy`
4410    /// distribution-strategy discriminator) so every downstream
4411    /// per-`:placement` reader now routes through a typed dispatch on
4412    /// the substrate primitive. Named `estrategia()` to match the storage
4413    /// field's name; the accessor's identity name maps onto the
4414    /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
4415    /// already carries.
4416    #[must_use]
4417    pub fn estrategia(&self) -> PlacementStrategy {
4418        self.estrategia
4419    }
4420
4421    /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
4422    /// per-cluster distribution-target slice accessor every consumer that
4423    /// walks the Aplicacao's declared cluster-pool keys off — returns the
4424    /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
4425    /// `&[String]` slice-view, borrowed from the typed slot's own
4426    /// `Vec<String>` storage (a zero-copy slice-view over the same
4427    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
4428    /// through). Non-optional: the empty slice is the load-bearing
4429    /// pre-validation sentinel every downstream consumer of the paired
4430    /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
4431    /// off — every strategy in the closed
4432    /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
4433    /// requires a non-empty list (`SingleNode` / `Replicated` use the
4434    /// list as hosting / takeover candidates per Erlang/OTP distributed-
4435    /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
4436    /// shard pool per Akka cluster-sharding convention, §II.4), so the
4437    /// `.is_empty()` probe is the shared pre-condition every
4438    /// [`AplicacaoSpec::validate_placement`] arm heads on.
4439    ///
4440    /// The `:placement :clusters` slot carries the K8s-conformant DNS-
4441    /// 1123-label per-cluster distribution-target list — the same
4442    /// set-not-multiset shape the sibling `:membros :caixa` /
4443    /// `:children :caixa` axes carry (`validate_placement`'s per-entry
4444    /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
4445    /// pins the shape). Every downstream consumer that fans on the list
4446    /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
4447    /// pre-flight `.is_empty()` probe that trips
4448    /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
4449    /// per-cluster value-shape + duplicate-detection fan-out loop, the
4450    /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
4451    /// that materializes the list verbatim onto every
4452    /// programs.yaml entry the substrate operator's per-cluster
4453    /// `placement.clusters | contains .Values.cluster` filter reads,
4454    /// the `feira app graph` per-Aplicacao cluster print line, the
4455    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4456    /// per-cluster admission-webhook fan-out, the future M5 adaptive-
4457    /// placement engine's cluster-topology reader).
4458    ///
4459    /// Prior to this lift the `.clusters` `Vec<String>` was accessed
4460    /// inline at three production sites — the
4461    /// [`AplicacaoSpec::validate_placement`] pre-flight
4462    /// `self.placement.clusters.is_empty()` refusal probe, the same
4463    /// method's per-cluster validate loop's
4464    /// `for c in &self.placement.clusters` traversal head, and the
4465    /// `feira app graph` per-Aplicacao print line's
4466    /// `spec.placement.clusters` `{:?}` formatter argument
4467    /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
4468    /// that expressed no compile-time link back to the typed slot. A
4469    /// future extension of the `:placement :clusters` axis to a richer
4470    /// author surface (a per-tenant cluster-pool overlay the operator
4471    /// pins through a future `:placement :clusters-overrides` slot the
4472    /// MESH-COMPOSITION §V cross-cluster-federation roadmap
4473    /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
4474    /// the future M5 adaptive-placement engine computes from
4475    /// `:affinity` weights + live cluster-topology probes, a promotion
4476    /// of the plain `Vec<String>` to a richer `{static, dynamic}`
4477    /// partition once the substrate operator's cluster-membership
4478    /// reconciler comes into typed scope) would have had to be threaded
4479    /// through all three open-coded copies in lockstep or one consumer
4480    /// would silently disagree with the peers on which cluster-pool a
4481    /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
4482    /// reading the raw slot while the peer per-cluster validate loop
4483    /// read an operator-resolved slot would silently split the paired
4484    /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
4485    /// `PlacementClusterDuplicate` refusal cascade's actual traversal
4486    /// input from the pre-flight input, a three-consumer split at the
4487    /// validator and formatter far from the source `caixa.lisp` with
4488    /// no field naming the cluster-pool-drift root cause. Lifting the
4489    /// resolution rule to a typed method on the substrate primitive
4490    /// means every downstream consumer of the Aplicacao's
4491    /// per-`:placement` cluster-pool surface reaches for exactly one
4492    /// typed dispatch — the resolver's accept-set migrates as a unit
4493    /// on any future axis addition.
4494    ///
4495    /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
4496    /// slot — sibling to the seed M2
4497    /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
4498    /// slice-return accessor on the peer per-`:supervisor` static-
4499    /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
4500    /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
4501    /// primitive, thin projections at each consumer" discipline. The
4502    /// three peer `Vec`-carry axes still unlifted at the time of this
4503    /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
4504    /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
4505    /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
4506    /// [`crate::UpgradeFromEntry::instructions`]
4507    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
4508    /// — inherit this accessor's discipline as future compounding runs
4509    /// migrate their consumers onto the shared slice-return shape.
4510    /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
4511    /// type, sibling to the two `Option<&str>`-return
4512    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
4513    /// (74ec2d3) accessors and the `Copy`-return
4514    /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
4515    /// unlifted per-`:placement` field axis (the `Vec<String>`
4516    /// distribution-target-list carrier) so every downstream
4517    /// per-`:placement` reader now routes through a typed dispatch on
4518    /// the substrate primitive. Named `clusters()` to match the storage
4519    /// field's name verbatim and the tatara-lisp author-surface term
4520    /// (`:clusters`) the field's own docstring already carries; the
4521    /// accessor's identity maps onto the canonical MESH-COMPOSITION
4522    /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
4523    /// for. Returns `&[String]` (not `&Vec<String>`) because every
4524    /// downstream consumer of the cluster list treats it as a read-only
4525    /// sequence — the slice-view is the narrowest borrow that supports
4526    /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
4527    /// `.len()`) without leaking the backing `Vec`'s
4528    /// grow/push/reserve surface that no consumer of the typed view
4529    /// reaches for (the storage-side `Vec` remains reachable through
4530    /// the `pub clusters` field for the mutation-carrying serde
4531    /// round-trip and per-test fixture-mutation paths).
4532    #[must_use]
4533    pub fn clusters(&self) -> &[String] {
4534        self.clusters.as_slice()
4535    }
4536}
4537
4538impl Default for Placement {
4539    fn default() -> Self {
4540        Self {
4541            estrategia: PlacementStrategy::default(),
4542            clusters: Vec::new(),
4543            affinity: None,
4544            shard_key: None,
4545        }
4546    }
4547}
4548
4549// ── external entry point ─────────────────────────────────────────────
4550
4551/// External entry point — what an outside caller sees. Renders to a
4552/// Gateway / Ingress + a route to the named member Servico.
4553#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
4554#[serde(rename_all = "camelCase")]
4555pub struct Entrada {
4556    /// Public hostname (e.g. `"checkout.quero.cloud"`).
4557    pub host: String,
4558
4559    /// Member Servico the gateway routes to. Must be in `:membros`.
4560    pub para: String,
4561
4562    /// Optional path filter — if set, only matching paths route to
4563    /// this Aplicacao (the rest fall through to other route rules).
4564    #[serde(default)]
4565    pub paths: Vec<String>,
4566
4567    /// Default port on the destination Servico (the trigger.service.port).
4568    #[serde(default = "default_port")]
4569    pub port: u16,
4570}
4571
4572impl Entrada {
4573    /// Substrate-canonical per-`:entrada` URL-path fallback resolver
4574    /// every HTTPRoute-aware renderer keys off — returns the author-
4575    /// declared `:entrada :paths` list verbatim when non-empty, and the
4576    /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
4577    /// all fallback otherwise (so an Aplicacao author who declares an
4578    /// external `:entrada` block but no per-path rule surface still
4579    /// gets a route whose sole `HTTPPathMatch` matches every incoming
4580    /// request under the paired
4581    /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
4582    ///
4583    /// Prior to this lift the "if `:entrada :paths` is empty use the
4584    /// substrate catch-all; else return each declared path verbatim"
4585    /// cascade lived inline at
4586    /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
4587    /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
4588    /// per-Aplicacao HTTPRoute per-rule path-list emit site the
4589    /// substrate ships today, with no typed method on the substrate
4590    /// primitive that named the rule. A future path-resolution axis
4591    /// addition — a per-cluster `:entrada :default-path` override the
4592    /// operator pins through a future `:placement`-scoped slot, an
4593    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
4594    /// admission-webhook floor that materializes the catch-all before
4595    /// the CR lands, a future per-`:entrada :paths` overlay from a
4596    /// per-cluster policy the future `feira app deploy` pipeline
4597    /// consumes — would have to be threaded through every renderer's
4598    /// inline copy of the cascade in lockstep or one consumer would
4599    /// silently disagree with the peers on which path list a given
4600    /// `:entrada` block resolves to. Lifting the rule to a typed
4601    /// method on the substrate primitive means every downstream
4602    /// HTTPRoute-aware consumer (the M4 CR materializer, the future
4603    /// per-cluster overlay resolver, every future per-Aplicacao
4604    /// snapshot renderer) reaches for exactly one typed dispatch —
4605    /// the resolver's accept-set moves as a unit on any future axis
4606    /// addition.
4607    ///
4608    /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
4609    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
4610    /// per-`:entrada` scalar-value axes — extends the "one typed
4611    /// dispatch on the substrate primitive, thin projections at each
4612    /// consumer" discipline onto the per-`:entrada` path-list
4613    /// resolution axis every HTTPRoute-aware renderer consumes. Same
4614    /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
4615    /// sibling `:politicas` primitive — one typed method on the
4616    /// substrate primitive that names the cascade every renderer
4617    /// otherwise re-inlines.
4618    #[must_use]
4619    pub fn resolved_paths(&self) -> Vec<&str> {
4620        // Route the internal cascade-head + per-entry projection reads
4621        // through the lifted [`Self::paths`] slice accessor rather than
4622        // the raw `self.paths` field access — the substrate-primitive
4623        // per-`:entrada` path-list resolver's two internal reads now
4624        // key off the canonical raw-slot surface every downstream
4625        // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
4626        // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
4627        // entrada summary line's `{:?}` Debug print) routes through, so
4628        // any future rebrand on the typed slot's raw-slot reader lands
4629        // at exactly one place. Same two-consumer coherence discipline
4630        // the sibling `Placement::clusters` (a6e18d7) accessor pins on
4631        // the peer M3 mesh-slot `Vec<String>`-carry axis.
4632        if self.paths().is_empty() {
4633            vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
4634        } else {
4635            self.paths().iter().map(String::as_str).collect()
4636        }
4637    }
4638
4639    /// Substrate-canonical per-`:entrada` DNS-hostname singular
4640    /// accessor every Gateway-API `Listener.hostname` reader keys off
4641    /// — returns the author-declared `:entrada :host` byte-string
4642    /// verbatim as a `&str`, borrowed from the typed slot's own
4643    /// [`String`] storage.
4644    ///
4645    /// Named the "singular" half of the DNS-hostname resolver pair on
4646    /// the substrate primitive: the parent-Gateway per-listener
4647    /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
4648    /// (`Listener.hostname: Option<PreciseHostname>` — at most one
4649    /// hostname per listener), and this accessor is the typed dispatch
4650    /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
4651    /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
4652    /// the per-HTTPRoute `spec.hostnames[]` list axis the same
4653    /// per-Aplicacao ingress-hostname surface projects onto.
4654    ///
4655    /// Prior to this lift the `entrada.host.clone()` byte-string was
4656    /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
4657    /// per-listener singular `hostname:` axis
4658    /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
4659    /// per-HTTPRoute plural `spec.hostnames[]` axis
4660    /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
4661    /// consumers read the same `entrada.host` field but the two-site
4662    /// duplication expressed no compile-time contract that the singular
4663    /// Gateway-listener filter and the plural `HTTPRoute` filter list
4664    /// stay in lockstep on future extensions of the `:entrada` slot to
4665    /// a multi-hostname author surface (an `:entrada :alt-hosts` list
4666    /// overlay, a per-cluster SNI fan-out the operator pins through a
4667    /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
4668    /// Aplicacao` CR materializer's per-listener virtual-host filter
4669    /// admission-webhook overlay). Any such extension would have to be
4670    /// threaded through every renderer's inline copy of the resolution
4671    /// in lockstep or the Gateway listener's `hostname:` filter would
4672    /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
4673    /// — a Gateway-API-conformance divergence whose apply-time symptom
4674    /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
4675    /// `NoMatchingParent` — the API server rejects the route because
4676    /// its `hostnames[]` filter doesn't intersect the parent listener's
4677    /// `hostname` filter) is far from the source `caixa.lisp` and never
4678    /// surfaces in the emitted YAML. Lifting the singular and plural
4679    /// resolvers to typed methods on the substrate primitive means
4680    /// every consumer of the Aplicacao's ingress-hostname surface
4681    /// reaches for exactly one typed dispatch, and the pair-invariant
4682    /// `hostnames() == vec![hostname()]` pinned by the sibling
4683    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
4684    /// keeps the two axes in lockstep by construction.
4685    ///
4686    /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
4687    /// (1449891) path-list resolver on the per-HTTPRoute per-rule
4688    /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
4689    /// the substrate primitive, thin projections at each consumer"
4690    /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
4691    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
4692    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
4693    /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
4694    /// `:entrada` scalar-value + list-value axes.
4695    #[must_use]
4696    pub fn hostname(&self) -> &str {
4697        self.host.as_str()
4698    }
4699
4700    /// Substrate-canonical per-`:entrada` DNS-hostname plural
4701    /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
4702    /// keys off — returns the singleton `[hostname()]` list under
4703    /// today's single-hostname-per-Aplicacao author surface, and the
4704    /// authoritative multi-hostname list under a future
4705    /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
4706    ///
4707    /// Plural half of the DNS-hostname resolver pair — see the
4708    /// companion [`Entrada::hostname`] docstring for the two-consumer
4709    /// lift + pair-invariant discipline (`hostnames() ==
4710    /// vec![hostname()]`, pinned load-bearing by the sibling
4711    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
4712    /// test).
4713    ///
4714    /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
4715    /// per-`:entrada` plural-list resolver on the per-HTTPRoute
4716    /// per-rule path-list axis — same `Vec<&str>` shape, same
4717    /// substrate-primitive-owns-the-resolver discipline extended to
4718    /// the per-HTTPRoute virtual-host filter-list axis.
4719    #[must_use]
4720    pub fn hostnames(&self) -> Vec<&str> {
4721        vec![self.hostname()]
4722    }
4723
4724    /// Substrate-canonical per-`:entrada` destination-Servico scalar
4725    /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
4726    /// the author-declared `:entrada :para` byte-string verbatim as a
4727    /// `&str`, borrowed from the typed slot's own [`String`] storage.
4728    ///
4729    /// The `:entrada :para` slot names the single member Servico the
4730    /// external Gateway routes to (validated by
4731    /// [`AplicacaoSpec::validate`] to be a
4732    /// [`Membro::caixa`] the Aplicacao declares — a stray
4733    /// `:para` that doesn't name a member is
4734    /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
4735    /// backend-attachment miss at cluster-apply time). Under today's
4736    /// single-destination author surface `:entrada :para` is the ingress
4737    /// apex Servico's canonical identity; under a hypothetical
4738    /// future multi-backend author surface (a `:entrada
4739    /// :split :backends` weighted-fan-out overlay for canary /
4740    /// blue-green traffic-split rollouts, per-path override for
4741    /// path-based per-Servico routing beyond the single-apex model,
4742    /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4743    /// per-CR admission-webhook that promotes the scalar to a
4744    /// weighted list) this accessor is the substrate primitive's typed
4745    /// dispatch every downstream `HTTPRoute`-aware consumer routes
4746    /// through, so the resolution shape migrates as a unit on one
4747    /// caixa-core edit rather than a coordinated rewrite across every
4748    /// renderer's inline field-access.
4749    ///
4750    /// Prior to this lift the `entrada.para` byte-string was accessed
4751    /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
4752    /// `metadata.name` composer's per-destination discriminator arg
4753    /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
4754    /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
4755    /// per-HTTPRoute per-rule `backendRefs[0].name` axis
4756    /// (`entrada.para.clone()`,
4757    /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
4758    /// consumers read the same `entrada.para` field but the two-site
4759    /// duplication expressed no compile-time contract that the HTTPRoute
4760    /// name-discriminator and the per-rule backend name stay in
4761    /// lockstep on future extensions of the `:entrada` slot to a
4762    /// multi-destination author surface. Any such extension would have
4763    /// to be threaded through every renderer's inline copy of the
4764    /// destination projection in lockstep or the HTTPRoute
4765    /// `metadata.name` would silently reference a different destination
4766    /// than its own `backendRefs[]` — an operator-side
4767    /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
4768    /// grep-by-name lookup would land on a route whose `backendRefs[]`
4769    /// silently point at a peer Servico, dropping every external
4770    /// `:entrada` flow at the gateway with the destination-drift root
4771    /// cause invisible in the emitted YAML.
4772    ///
4773    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
4774    /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
4775    /// the per-listener singular / per-HTTPRoute plural filter axes and
4776    /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
4777    /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
4778    /// typed dispatch on the substrate primitive, thin projections at
4779    /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
4780    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
4781    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
4782    /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
4783    /// sibling per-`:entrada` scalar-value + list-value axes — this
4784    /// accessor closes the last unlifted per-`:entrada` scalar axis
4785    /// (the destination-Servico byte-string) so every downstream
4786    /// per-`:entrada` reader now routes through a typed dispatch on
4787    /// the substrate primitive.
4788    #[must_use]
4789    pub fn destination(&self) -> &str {
4790        self.para.as_str()
4791    }
4792
4793    /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
4794    /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
4795    /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
4796    /// reader keys off — returns the author-declared `:entrada :port`
4797    /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
4798    /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
4799    /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
4800    /// [`AplicacaoError::EntradaPortZero`], not a silent
4801    /// admission-webhook rejection at cluster-apply time).
4802    ///
4803    /// The `:entrada :port` slot carries the destination Servico's
4804    /// canonical in-cluster L4 listener port (`trigger.service.port` on
4805    /// the `pleme-computeunit` library chart), and every downstream
4806    /// consumer that reads the port keys off this scalar (the
4807    /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
4808    /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
4809    /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
4810    /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
4811    /// CR materializer's per-Aplicacao gateway port resolver).
4812    ///
4813    /// Prior to this lift the `.port` field was accessed inline at two
4814    /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
4815    /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
4816    /// the [`AplicacaoSpec::port_for_destination`] resolver's
4817    /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
4818    /// open-coded field-accesses that expressed no compile-time link
4819    /// back to the typed slot. A future extension of the `:entrada :port`
4820    /// axis to a richer author surface — a per-cluster override the
4821    /// operator pins through a future `:placement :default-port` slot the
4822    /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
4823    /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
4824    /// heterogeneous listener ports, an M4
4825    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
4826    /// admission-webhook floor that promotes the scalar to a
4827    /// per-destination map — would have had to be threaded through both
4828    /// open-coded copies in lockstep or the structural-floor validator
4829    /// and the [`AplicacaoSpec::port_for_destination`] resolver would
4830    /// silently disagree on which port a given [`Entrada`] resolves to.
4831    /// Lifting the resolution rule to a typed method on the substrate
4832    /// primitive means every downstream consumer of the Aplicacao's
4833    /// per-`:entrada` L4-port surface reaches for exactly one typed
4834    /// dispatch — the resolver's accept-set migrates as a unit on any
4835    /// future axis addition.
4836    ///
4837    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
4838    /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
4839    /// accessors on the per-`:entrada` scalar-value axis — same "one
4840    /// typed dispatch on the substrate primitive, thin projections at
4841    /// each consumer" discipline extended onto the per-`:entrada`
4842    /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
4843    /// the M3 mesh-slot `Entrada` type — closes the last unlifted
4844    /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
4845    /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
4846    /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
4847    /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
4848    /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
4849    /// storage field's name; the accessor's identity name maps onto the
4850    /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
4851    /// already carries.
4852    #[must_use]
4853    pub fn port(&self) -> u16 {
4854        self.port
4855    }
4856
4857    /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
4858    /// slice accessor every HTTPRoute-aware renderer keys off when it
4859    /// wants the raw author-declared path-list (not the fallback-
4860    /// applied projection [`Self::resolved_paths`] returns) — returns
4861    /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
4862    /// borrowed from the typed slot's own [`Vec<String>`] storage.
4863    ///
4864    /// Named the "raw slot" half of the per-`:entrada` path-list resolver
4865    /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
4866    /// (1449891) closes the fallback-applying arm every per-Aplicacao
4867    /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
4868    /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
4869    /// catch-all; non-empty slot → per-entry verbatim projection); this
4870    /// accessor closes the raw-slot arm every consumer that must see the
4871    /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
4872    /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
4873    /// not `Err(EntradaPathEmpty)`, so it cannot route through the
4874    /// fallback-applying sibling; the `feira app graph` per-Aplicacao
4875    /// external-gateway summary line's `{:?}` Debug print — which must
4876    /// name the author's declaration, not the substrate's fallback, so
4877    /// an author reading their graph output can grep their caixa.lisp
4878    /// for the exact list they authored) routes through.
4879    ///
4880    /// Prior to this lift the `.paths` field was accessed inline at four
4881    /// production sites: the two internal reads in [`Self::resolved_paths`]
4882    /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
4883    /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
4884    /// value-shape gate's `for p in &e.paths` traversal head, and the
4885    /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
4886    /// Debug print — four open-coded field-accesses that expressed no
4887    /// compile-time link back to the typed slot. A future extension of
4888    /// the `:entrada :paths` axis to a richer author surface — a
4889    /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
4890    /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
4891    /// spec supports through `matches[].method`), a per-path per-header
4892    /// filter overlay (`matches[].headers[]`), a per-cluster override
4893    /// the operator pins through a future `:placement :path-overlay`
4894    /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4895    /// per-CR admission-webhook that normalized the list at admission
4896    /// time — would have had to be threaded through every open-coded
4897    /// copy in lockstep or the validator's per-entry gate would silently
4898    /// disagree with the renderer's per-entry emit on which list a given
4899    /// `:entrada` block resolves to. Lifting the resolution to a typed
4900    /// method on the substrate primitive means every downstream consumer
4901    /// of the Aplicacao's per-`:entrada` path-list surface reaches for
4902    /// exactly one typed dispatch — the resolver's accept-set migrates
4903    /// as a unit on any future axis addition.
4904    ///
4905    /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
4906    /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
4907    /// carry axis — same "one typed dispatch on the substrate primitive,
4908    /// thin projections at each consumer" discipline extended onto the
4909    /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
4910    /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
4911    /// carrier) so every downstream per-`:entrada` reader now routes
4912    /// through a typed dispatch on the substrate primitive. Returns
4913    /// `&[String]` (not `&Vec<String>`) because every downstream consumer
4914    /// treats the list as a read-only sequence — the slice-view is the
4915    /// narrowest borrow that supports every present + roadmapped consumer
4916    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
4917    /// `Vec`'s grow/push/reserve surface that no consumer of the typed
4918    /// view reaches for (the storage-side `Vec` remains reachable through
4919    /// the `pub paths` field for the mutation-carrying serde round-trip
4920    /// and per-test fixture-mutation paths).
4921    #[must_use]
4922    pub fn paths(&self) -> &[String] {
4923        self.paths.as_slice()
4924    }
4925}
4926
4927/// Canonical default L4 port every typed Servico exposes on its
4928/// in-cluster K8s Service (the `trigger.service.port` axis the
4929/// `pleme-computeunit` library chart emits, the `:entrada :port` author
4930/// surface defaults to when the author omits the slot, and the
4931/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
4932/// `:entrada` block matches the per-`:contratos` destination Servico).
4933/// The single source of truth all three typed-port consumers reach for:
4934///
4935///   - [`Entrada::port`]'s serde default (via the
4936///     [`default_port`] helper this constant feeds); the author surface
4937///     `(:entrada (:host … :para …))` without an explicit `:port` slot
4938///     reads back as a typed [`Entrada`] carrying this exact value;
4939///   - the
4940///     [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
4941///     emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
4942///     fallback, fired when the typed `:entrada` block doesn't name
4943///     the per-`:contratos` destination Servico — the typed
4944///     `:contratos` graph carries no per-destination port axis (the
4945///     destination port is the destination Servico's
4946///     `lareira-<nome>` chart's `trigger.service.port`, which the
4947///     Aplicacao-level renderer has no visibility into without a
4948///     resolver round-trip), so the renderer falls back to the
4949///     substrate's canonical Servico-port assumption — by
4950///     construction the same value the destination's own
4951///     `pleme-computeunit` chart emits, the same value the
4952///     destination's own typed `:entrada :port` slot defaults to;
4953///   - every future per-Servico renderer the absorption-roadmap
4954///     acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
4955///     CR materializer's per-edge port resolver, the future
4956///     per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
4957///     emitter's per-route bucket key, the future caixa-otel
4958///     collector-pipeline emitter's per-Servico scrape port).
4959///
4960/// Until this lift landed the value `8080` lived at two production-code
4961/// call-sites: the [`default_port`] helper at
4962/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
4963/// and the `.unwrap_or(8080)` literal at
4964/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
4965/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
4966/// resolver). A future Servico-port rebrand — the substrate moving the
4967/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
4968/// gateway grows direct `:80` listeners, to `8443` once the substrate
4969/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
4970/// override the operator pins through a future
4971/// `:placement :default-port` slot — without a coordinated edit on
4972/// both sides would silently emit Servicos listening on one port and
4973/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
4974/// The CNP's apply-time symptom (the policy is admitted but every L4
4975/// flow on the destination Servico's actual port silently drops because
4976/// it doesn't match the whitelisted port) is far from the rebrand
4977/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
4978/// in hubble traces, not in `kubectl describe`. Lifting the literal to
4979/// a shared constant closes the drift footgun structurally — both
4980/// consumers read from the same `u16`, so any rebrand reaches both
4981/// sites by construction.
4982///
4983/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
4984/// per-renderer canonical-K8s-axis constant — the namespace string
4985/// and the canonical Servico port both lived as duplicated literals
4986/// across caixa-core / caixa-mesh / caixa-flux before their respective
4987/// lifts. Same "the typed constant lives in one place" discipline the
4988/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
4989/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
4990/// shared-string axes.
4991///
4992/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
4993pub const DEFAULT_SERVICO_PORT: u16 = 8080;
4994
4995/// Structural floor for the typed `:entrada :port` axis — every
4996/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
4997/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
4998///
4999/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
5000/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
5001/// interprets as "let the kernel pick a free port at bind time", not a
5002/// well-defined destination the substrate's per-`:entrada` Gateway API
5003/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
5004/// carrying `port: 0` degenerates to a nominal-only routing target: the
5005/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
5006/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
5007/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
5008/// at build time rather than at `kubectl apply` time), and the
5009/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
5010/// (caixa-mesh/src/lib.rs:2657 through
5011/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
5012/// [`Entrada::port`] typed value — silently emits a policy whose
5013/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
5014/// actual listener, dropping every L4 flow at the eBPF data plane far
5015/// from the source caixa.lisp with no field naming the port-zero-drift
5016/// root cause.
5017///
5018/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
5019/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
5020/// on the top edge (unlike the peer capped-`u32` `:politicas` /
5021/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
5022/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
5023/// well below `u32::MAX` and therefore need explicit typed caps).
5024///
5025/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
5026/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
5027/// scalar every `(:entrada (:host … :para …))` slot without an explicit
5028/// `:port` inherits through the serde default hook; this constant names
5029/// the accept-set floor every declared port must satisfy. The pair is
5030/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
5031/// substrate's default must satisfy its own accept-set floor by
5032/// construction) — a future rebrand that accidentally moved
5033/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
5034/// negative-cast typo, a per-cluster override the operator pins through
5035/// a future `:placement :default-port` slot that lands out-of-range)
5036/// would silently invalidate the serde-default emission at every
5037/// author-side `(:entrada (:host … :para …))` slot — the compile-time
5038/// invariant pin
5039/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
5040/// closes the drift footgun at caixa-core build time.
5041///
5042/// Lifted as a typed `pub const` (rather than an inline `0` literal at
5043/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
5044/// has exactly one source of truth — the future M4
5045/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
5046/// gateway resolver, the future per-Servico
5047/// `computeunit.trigger.service.port` renderer's per-CR port-value
5048/// validator, and every downstream test-fixture navigator asserting
5049/// the accept-set floor all read from one place. Same shape every
5050/// other typed bracket-floor / bracket-ceiling in this crate carries
5051/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
5052/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
5053/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
5054/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
5055/// [`POLICY_RATE_LIMIT_MAX`]).
5056pub const SERVICO_PORT_MIN: u16 = 1;
5057
5058const fn default_port() -> u16 {
5059    DEFAULT_SERVICO_PORT
5060}
5061
5062// ── the typed view ───────────────────────────────────────────────────
5063
5064/// Typed composition view of the flat Aplicacao slots on
5065/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
5066/// validation + downstream renderer consumption.
5067#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5068#[serde(rename_all = "camelCase")]
5069pub struct AplicacaoSpec {
5070    pub membros: Vec<Membro>,
5071    pub contratos: Vec<WitContract>,
5072    pub politicas: MeshPolicy,
5073    pub placement: Placement,
5074    pub entrada: Option<Entrada>,
5075}
5076
5077impl AplicacaoSpec {
5078    /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
5079    /// per-Aplicacao member-list slice-return accessor every
5080    /// per-Aplicacao member-list reader keys off — returns the author-
5081    /// declared `:membros` list verbatim as a `&[Membro]` slice-view
5082    /// over the same backing buffer the raw `self.membros.as_slice()`
5083    /// field access borrows from.
5084    ///
5085    /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
5086    /// member list — the load-bearing identity of the application graph
5087    /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
5088    /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
5089    /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
5090    /// accessor) with a `:versao` semver-requirement string (through
5091    /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
5092    /// and every downstream consumer that fans on the member-set keys
5093    /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
5094    /// membership-lookup `HashSet<&str>` seed's collect input, the
5095    /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
5096    /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
5097    /// per-member DNS-1123 / semver-requirement / duplicate-detection
5098    /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
5099    /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
5100    /// programs.yaml per-`:membros` fan-out emitter's per-entry
5101    /// mapping-composition loop, the `feira app graph` per-Aplicacao
5102    /// member-count print line and per-member tree traversal,
5103    /// every future wasm-operator (M4) per-Aplicacao CR materializer's
5104    /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
5105    /// placement engine's per-member weight-topology reader).
5106    ///
5107    /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
5108    /// inline at six production sites — the [`AplicacaoSpec::validate`]
5109    /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
5110    /// [`AplicacaoSpec::validate_membros`]'s pre-flight
5111    /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
5112    /// probe, the same method's per-member `for m in &self.membros`
5113    /// validate-loop traversal head, the
5114    /// [`AplicacaoSpec::detect_sync_cycles`]'s
5115    /// `for m in &self.membros` adjacency-list seed, the
5116    /// [`caixa_mesh::programs_for_aplicacao`] emitter's
5117    /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
5118    /// paired with the peer `for m in &spec.membros` per-entry fan-out
5119    /// loop, and the `feira app graph` per-Aplicacao print line's
5120    /// `spec.membros.len()` count formatter argument paired with the
5121    /// peer `for m in &spec.membros` per-member tree traversal — six
5122    /// open-coded field-accesses that expressed no compile-time link
5123    /// back to the typed slot. A future extension of the `:membros`
5124    /// axis to a richer author surface (a per-cluster member-set
5125    /// overlay the operator pins through a future
5126    /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
5127    /// roadmap acknowledges, a per-tenant member-alias table the M4
5128    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
5129    /// CR at admission time, a per-Aplicacao dynamic member-set
5130    /// derivation the future adaptive-placement engine computes from
5131    /// weighted membership topology, a promotion of the plain
5132    /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
5133    /// Orleans-style virtual-actor dynamic-membership comes into typed
5134    /// scope) would have had to be threaded through all six open-coded
5135    /// copies in lockstep or one consumer would silently disagree with
5136    /// the peers on which member-set a given Aplicacao resolves to —
5137    /// the `HashSet<&str>` name-set seed reading the raw slot while
5138    /// the peer `.is_empty()` refusal probe read an operator-resolved
5139    /// slot would silently split the `:contratos` membership-lookup
5140    /// input from the pre-flight-refusal input, a six-consumer split
5141    /// at the validator + programs.yaml emitter + graph printer far
5142    /// from the source `caixa.lisp` with no field naming the member-
5143    /// set-drift root cause. Lifting the resolution rule to a typed
5144    /// method on the substrate primitive means every downstream
5145    /// consumer of the Aplicacao's per-`:membros` member-list surface
5146    /// reaches for exactly one typed dispatch — the resolver's accept-
5147    /// set migrates as a unit on any future axis addition.
5148    ///
5149    /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
5150    /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
5151    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
5152    /// static-child-list `Vec`-carry axis, and to the M3
5153    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
5154    /// on the peer per-`:placement` distribution-target-list `Vec`-
5155    /// carry axis. Same "one typed dispatch on the substrate primitive,
5156    /// thin projections at each consumer" discipline. The two peer
5157    /// `Vec`-carry axes still unlifted at the time of this lift —
5158    /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
5159    /// WIT-typed edge list) and
5160    /// [`crate::UpgradeFromEntry::instructions`]
5161    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
5162    /// — inherit this accessor's discipline as future compounding runs
5163    /// migrate their consumers onto the shared slice-return shape.
5164    /// First `&[T]`-return accessor on the top-level M3 mesh-slot
5165    /// `AplicacaoSpec` type itself, extending the discipline beyond
5166    /// the inner per-slot types ([`crate::Placement`],
5167    /// [`crate::SupervisorSpec`]) onto the outermost typed composition
5168    /// view every renderer consumes. Named `membros()` to match the
5169    /// storage field's name verbatim and the tatara-lisp author-
5170    /// surface term (`:membros`) the field's own docstring already
5171    /// carries; the accessor's identity maps onto the canonical
5172    /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
5173    /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
5174    /// every downstream consumer of the member list treats it as a
5175    /// read-only sequence — the slice-view is the narrowest borrow
5176    /// that supports every present + roadmapped consumer
5177    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
5178    /// backing `Vec`'s grow/push/reserve surface that no consumer of
5179    /// the typed view reaches for (the storage-side `Vec` remains
5180    /// reachable through the `pub membros` field for the mutation-
5181    /// carrying serde round-trip and per-test fixture-mutation paths).
5182    #[must_use]
5183    pub fn membros(&self) -> &[Membro] {
5184        self.membros.as_slice()
5185    }
5186
5187    /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
5188    /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
5189    /// accessor every per-Aplicacao contract-list reader keys off —
5190    /// returns the author-declared `:contratos` list verbatim as a
5191    /// `&[WitContract]` slice-view over the same backing buffer the raw
5192    /// `self.contratos.as_slice()` field access borrows from.
5193    ///
5194    /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
5195    /// WIT-typed edge list — the load-bearing set of directed edges
5196    /// on the application graph whose nodes are the `:membros` entries
5197    /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
5198    /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
5199    /// six-tuple is the edge identity every downstream duplicate gate
5200    /// keys off). Every per-`:contratos` entry pairs a `:de` source-
5201    /// Servico caller name + a `:para` destination-Servico callee name
5202    /// (through the lifted [`WitContract::source`] +
5203    /// [`WitContract::destination`] (7f0fd43) accessor pair on the
5204    /// caller/callee-Servico axis) with a `:wit` world-reference
5205    /// (through the lifted [`WitContract::world_ref`] (0804823)
5206    /// accessor) and the target-shape-appropriate payload-carrier
5207    /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
5208    /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
5209    /// (ed22b66) accessor on the per-target-shape payload-carrier
5210    /// axis). Every downstream consumer that fans on the edge-set
5211    /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
5212    /// name-set / self-edge / target-shape / dedup fan-out loop, the
5213    /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
5214    /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
5215    /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
5216    /// grouping loop, the `feira app graph` per-Aplicacao contract-
5217    /// count print line and per-contract tree traversal, every future
5218    /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
5219    /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
5220    /// mesh-policy overlay resolver's per-contract typed-edge weight
5221    /// reader).
5222    ///
5223    /// Prior to this lift the `.contratos` `Vec<WitContract>` was
5224    /// accessed inline at four production sites — the
5225    /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
5226    /// per-edge validate-loop traversal head (which drives every
5227    /// per-edge name-set membership lookup, self-edge check,
5228    /// target-shape dispatch, and dedup `HashSet` insert), the
5229    /// [`AplicacaoSpec::detect_sync_cycles`]'s
5230    /// `for c in &self.contratos` adjacency-list seed head (which
5231    /// drives every per-edge sync-vs-pub-sub partition and per-edge
5232    /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
5233    /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
5234    /// `BTreeMap` grouping loop head (which drives every per-CNP
5235    /// fan-out emit), and the `feira app graph` per-Aplicacao print
5236    /// line's `spec.contratos.len()` count formatter argument paired
5237    /// with the peer `for c in &spec.contratos` per-contract tree
5238    /// traversal — four open-coded field-accesses that expressed no
5239    /// compile-time link back to the typed slot. A future extension
5240    /// of the `:contratos` axis to a richer author surface (a
5241    /// per-cluster contract overlay the operator pins through a
5242    /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
5243    /// federation roadmap acknowledges, a per-tenant edge-policy
5244    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5245    /// materializer resolves per-CR at admission time, a per-edge
5246    /// weight scalar the future adaptive-placement engine reads to
5247    /// bias sync-subgraph routing, a promotion of the plain
5248    /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
5249    /// once virtual-actor-style dynamic-edge composition comes into
5250    /// typed scope) would have had to be threaded through all four
5251    /// open-coded copies in lockstep or one consumer would silently
5252    /// disagree with the peers on which edge-set a given Aplicacao
5253    /// resolves to — the validator's per-edge dedup `HashSet` seed
5254    /// reading the raw slot while the peer sync-cycle adjacency-list
5255    /// seed read an operator-resolved slot would silently split the
5256    /// build-time edge-set gate from the runtime deadlock-detection
5257    /// gate, a four-consumer split at the validator, the cycle
5258    /// detector, the CNP emitter, and the graph printer far from
5259    /// the source `caixa.lisp` with no field naming the edge-set-
5260    /// drift root cause. Lifting the resolution rule to a typed method on the
5261    /// substrate primitive means every downstream consumer of the
5262    /// Aplicacao's per-`:contratos` edge-list surface reaches for
5263    /// exactly one typed dispatch — the resolver's accept-set
5264    /// migrates as a unit on any future axis addition.
5265    ///
5266    /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
5267    /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
5268    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
5269    /// static-child-list `Vec`-carry axis, to the M3
5270    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
5271    /// on the peer per-`:placement` distribution-target-list `Vec`-
5272    /// carry axis, and to the immediately-adjacent sibling M3
5273    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
5274    /// the peer per-`:membros` node-list `Vec`-carry axis — the
5275    /// per-`:contratos` edge-list accessor is the natural pair of
5276    /// the per-`:membros` node-list accessor (graph edges over graph
5277    /// nodes; every graph-shaped consumer reads both). Same "one
5278    /// typed dispatch on the substrate primitive, thin projections
5279    /// at each consumer" discipline. The last remaining `Vec`-carry
5280    /// axis still unlifted at the time of this lift —
5281    /// [`crate::UpgradeFromEntry::instructions`]
5282    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
5283    /// list) — inherits this accessor's discipline as future
5284    /// compounding runs migrate its consumers onto the shared slice-
5285    /// return shape. Second `&[T]`-return accessor on the top-level
5286    /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
5287    /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
5288    /// `:contratos` are the two `Vec` fields on the outer typed
5289    /// composition view — `:politicas`, `:placement`, `:entrada` are
5290    /// scalar/option-shaped and already route through their per-slot
5291    /// accessor families). Named `contratos()` to match the storage
5292    /// field's name verbatim and the tatara-lisp author-surface term
5293    /// (`:contratos`) the field's own docstring already carries; the
5294    /// accessor's identity maps onto the canonical MESH-COMPOSITION
5295    /// §III.1 vocabulary the slot's docstring already reaches for.
5296    /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
5297    /// every downstream consumer of the contract list treats it as a
5298    /// read-only sequence — the slice-view is the narrowest borrow
5299    /// that supports every present + roadmapped consumer
5300    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
5301    /// backing `Vec`'s grow/push/reserve surface that no consumer of
5302    /// the typed view reaches for (the storage-side `Vec` remains
5303    /// reachable through the `pub contratos` field for the mutation-
5304    /// carrying serde round-trip and per-test fixture-mutation paths).
5305    #[must_use]
5306    pub fn contratos(&self) -> &[WitContract] {
5307        self.contratos.as_slice()
5308    }
5309
5310    /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
5311    /// per-Aplicacao mesh-policy composite-reference accessor every
5312    /// per-Aplicacao policy-block reader keys off — returns the author-
5313    /// declared `:politicas` composite verbatim as a `&MeshPolicy`
5314    /// reference over the same backing storage the raw `&self.politicas`
5315    /// field access borrows from.
5316    ///
5317    /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
5318    /// mesh-policy composite — the load-bearing container of every
5319    /// mesh-level operational-policy axis every downstream mesh-artifact
5320    /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
5321    /// mesh-policy overlay is the single typed surface a
5322    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
5323    /// from). Every per-`:politicas` axis threads through a lifted
5324    /// per-slot accessor on the [`MeshPolicy`] type: the
5325    /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
5326    /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
5327    /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
5328    /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
5329    /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
5330    /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
5331    /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
5332    /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
5333    /// accessor. Every downstream consumer that reaches for a policy
5334    /// axis first passes through this outer accessor onto the composite
5335    /// and then dispatches onto the per-axis accessor — the two-level
5336    /// dispatch means every per-`:politicas` reader now routes through
5337    /// a typed dispatch on the substrate primitive at both altitudes.
5338    ///
5339    /// Prior to this lift the `.politicas` `MeshPolicy` composite was
5340    /// accessed inline at four production sites — the
5341    /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
5342    /// &self.politicas;` traversal seed (which drives every per-axis
5343    /// zero-floor + upper-cap + canonical-form bracket dispatch through
5344    /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
5345    /// `p.rate_limit()` on the axis-level lifted accessors), the
5346    /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
5347    /// emitter's `spec.politicas.mtls_required()` field-then-accessor
5348    /// chain (which drives every per-`(:de, :para)` CNP
5349    /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
5350    /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
5351    /// timeout + retry overlay emitter's paired
5352    /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
5353    /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
5354    /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
5355    /// open-coded outer-field accesses that expressed no compile-time
5356    /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
5357    /// future extension of the `:politicas` outer axis to a richer
5358    /// author surface (a per-cluster policy overlay the operator pins
5359    /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
5360    /// §V federation roadmap acknowledges, a per-tenant policy-alias
5361    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
5362    /// resolves per-CR at admission time, a per-Aplicacao dynamic
5363    /// policy-composite derivation the future adaptive-placement engine
5364    /// computes from a per-cluster load-topology reader, a promotion of
5365    /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
5366    /// partition once virtual-actor-style dynamic-mesh-policy
5367    /// composition comes into typed scope) would have had to be threaded
5368    /// through all four open-coded copies in lockstep or one consumer
5369    /// would silently disagree with the peers on which mesh-policy
5370    /// composite a given Aplicacao resolves to — the validator's
5371    /// per-axis bracket-dispatch seed reading the raw slot while the
5372    /// peer CNP mTLS-overlay emitter read an operator-resolved slot
5373    /// would silently split the build-time policy-shape gate from the
5374    /// runtime CNP-emission gate, a four-consumer split at the
5375    /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
5376    /// the source `caixa.lisp` with no field naming the policy-drift
5377    /// root cause. Lifting the resolution rule to a typed method on the
5378    /// substrate primitive means every downstream consumer of the
5379    /// Aplicacao's per-`:politicas` mesh-policy composite surface
5380    /// reaches for exactly one typed dispatch — the resolver's accept-
5381    /// set migrates as a unit on any future axis addition.
5382    ///
5383    /// First `&Composite`-return accessor on the top-level M3 mesh-slot
5384    /// `AplicacaoSpec` type itself — sibling to the seed slice-return
5385    /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
5386    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
5387    /// close the two `Vec`-carry axes on the outer typed composition
5388    /// view; the outer `:politicas` composite-reference axis is the
5389    /// natural pair to the paired outer `Vec`-carry accessors on the
5390    /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
5391    /// emitter reads all four axes as one unit (graph nodes + graph
5392    /// edges + mesh policy + placement pool). Peer to the same
5393    /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
5394    /// slot: every M2 `SupervisorSpec`-scoped composite reader
5395    /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
5396    /// `restart_window`, `children`) already routes through the M2
5397    /// `SupervisorSpec` accessor family — this lift extends the same
5398    /// "one typed dispatch on the substrate primitive at the outer
5399    /// composition altitude" discipline to the M3 mesh-slot
5400    /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
5401    /// remaining peer outer-composite axes still unlifted at the time
5402    /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
5403    /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
5404    /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
5405    /// inherit this accessor's discipline as future compounding runs
5406    /// migrate their consumers onto the shared reference-return shape.
5407    /// Named `politicas()` to match the storage field's name verbatim
5408    /// and the tatara-lisp author-surface term (`:politicas`) the
5409    /// field's own docstring already carries; the accessor's identity
5410    /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
5411    /// slot's docstring already reaches for. Returns `&MeshPolicy`
5412    /// (not the owning composite by copy or clone) because every
5413    /// downstream consumer of the mesh-policy composite treats it as a
5414    /// read-only per-axis dispatch source — the reference-view is the
5415    /// narrowest borrow that supports every present + roadmapped
5416    /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
5417    /// emptiness probe) without cloning the composite through every
5418    /// consumer's fast path.
5419    #[must_use]
5420    pub fn politicas(&self) -> &MeshPolicy {
5421        &self.politicas
5422    }
5423
5424    /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
5425    /// per-Aplicacao distribution-composite composite-reference accessor
5426    /// every per-Aplicacao placement-block reader keys off — returns the
5427    /// author-declared `:placement` composite verbatim as a `&Placement`
5428    /// reference over the same backing storage the raw `&self.placement`
5429    /// field access borrows from.
5430    ///
5431    /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
5432    /// distribution composite — the load-bearing container of every
5433    /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
5434    /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
5435    /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
5436    /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
5437    /// hosting-pool identity, §V for the `M3-Adaptive`-compression
5438    /// `:affinity` hint). Every per-`:placement` axis threads through a
5439    /// lifted per-slot accessor on the [`Placement`] type: the
5440    /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
5441    /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
5442    /// per-cluster distribution-target slice-return accessor, the
5443    /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
5444    /// optional-scalar accessor, and the [`Placement::shard_key`]
5445    /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
5446    /// downstream consumer that reaches for a placement axis first passes
5447    /// through this outer accessor onto the composite and then dispatches
5448    /// onto the per-axis accessor — the two-level dispatch means every
5449    /// per-`:placement` reader now routes through a typed dispatch on the
5450    /// substrate primitive at both altitudes.
5451    ///
5452    /// Prior to this lift the `.placement` `Placement` composite was
5453    /// accessed inline at three production sites — the
5454    /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
5455    /// seed (six `self.placement.<axis>()` field-then-inner-accessor
5456    /// chains: the pre-flight `.clusters().is_empty()` refusal probe
5457    /// paired with the `.estrategia()` diagnostic-carry copy, the per-
5458    /// cluster `.clusters()` validate-loop traversal head, the per-
5459    /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
5460    /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
5461    /// paired with the shape-gate cascade's `.shard_key()` /
5462    /// `.estrategia()` diagnostic-carry pair), the
5463    /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
5464    /// per-entry placement-block emitter's outer
5465    /// `serde_yaml::to_value(&spec.placement)` composite-serialization
5466    /// seed (which fans onto every per-cluster `programs[]` entry as a
5467    /// self-describing distribution overlay the aggregator filters by),
5468    /// and the `feira app graph` per-Aplicacao print line's paired
5469    /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
5470    /// then-inner-accessor chains (which drive the human-readable
5471    /// distribution summary of the typed Aplicacao view) — three open-
5472    /// coded outer-field accesses that expressed no compile-time link
5473    /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
5474    /// extension of the `:placement` outer axis to a richer author surface
5475    /// (a per-cluster placement overlay the operator pins through a
5476    /// future `:placement-overrides` slot the MESH-COMPOSITION §V
5477    /// federation roadmap acknowledges, a per-tenant placement-alias
5478    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
5479    /// resolves per-CR at admission time, a per-Aplicacao dynamic
5480    /// placement-composite derivation the future M5 adaptive-placement
5481    /// engine computes from a per-cluster load-topology reader, a
5482    /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
5483    /// partition once Orleans-style virtual-actor dynamic-placement comes
5484    /// into typed scope) would have had to be threaded through all three
5485    /// open-coded copies in lockstep or one consumer would silently
5486    /// disagree with the peers on which placement composite a given
5487    /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
5488    /// seed reading the raw slot while the peer
5489    /// `programs_for_aplicacao` emitter read an operator-resolved slot
5490    /// would silently split the build-time distribution-shape gate from
5491    /// the runtime programs.yaml distribution-annotation gate, a three-
5492    /// consumer split at the validator, the programs.yaml emitter, and
5493    /// the `feira app graph` printer far from the source `caixa.lisp`
5494    /// with no field naming the placement-drift root cause. Lifting the
5495    /// resolution rule to a typed method on the substrate primitive
5496    /// means every downstream consumer of the Aplicacao's per-
5497    /// `:placement` distribution composite surface reaches for exactly
5498    /// one typed dispatch — the resolver's accept-set migrates as a unit
5499    /// on any future axis addition.
5500    ///
5501    /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
5502    /// `AplicacaoSpec` type itself — sibling to the seed
5503    /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
5504    /// composite-reference accessor on the peer per-`:politicas` outer-
5505    /// composite axis, and to the paired slice-return accessors
5506    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
5507    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
5508    /// the two `Vec`-carry axes on the outer typed composition view; the
5509    /// outer `:placement` composite-reference axis is the natural pair
5510    /// to the peer `:politicas` composite-reference axis on the two
5511    /// operationally-symmetric M3 mesh slots (`:politicas` carries the
5512    /// how-to-run policy overlay, `:placement` carries the where-to-run
5513    /// distribution composite — every whole-Aplicacao mesh-artifact
5514    /// emitter reads both as one unit). Same "one typed dispatch on the
5515    /// substrate primitive, thin projections at each consumer"
5516    /// discipline the peer per-`:politicas` composite-reference axis
5517    /// already routes through. The one remaining outer-composite axis
5518    /// still unlifted at the time of this lift —
5519    /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
5520    /// external-gateway composite) — inherits this accessor's discipline
5521    /// as the next compounding run migrates its consumers onto the shared
5522    /// reference-return shape, closing the outer-composite altitude on
5523    /// every M3 mesh-slot axis. Named `placement()` to match the storage
5524    /// field's name verbatim and the tatara-lisp author-surface term
5525    /// (`:placement`) the field's own docstring already carries; the
5526    /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
5527    /// vocabulary the slot's docstring already reaches for. Returns
5528    /// `&Placement` (not the owning composite by copy or clone) because
5529    /// every downstream consumer of the placement composite treats it as
5530    /// a read-only per-axis dispatch source — the reference-view is the
5531    /// narrowest borrow that supports every present + roadmapped consumer
5532    /// (per-axis accessor dispatch, serde composite-serialization) without
5533    /// cloning the composite through every consumer's fast path.
5534    #[must_use]
5535    pub fn placement(&self) -> &Placement {
5536        &self.placement
5537    }
5538
5539    /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
5540    /// per-Aplicacao external-gateway composite optional-composite-
5541    /// reference accessor every per-Aplicacao gateway-block reader
5542    /// keys off — returns the author-declared `:entrada` composite
5543    /// verbatim as an `Option<&Entrada>` reference over the same
5544    /// backing storage the raw `self.entrada.as_ref()` field access
5545    /// borrows from, with `None` naming the internal-only mesh shape
5546    /// (the author-omitted `:entrada` slot the K8s Gateway API v1
5547    /// gateway_routes emitter treats as "emit nothing" and the peer
5548    /// `feira app graph` printer treats as "internal-only mesh").
5549    ///
5550    /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
5551    /// external-gateway composite — the load-bearing container of
5552    /// every does-this-Aplicacao-expose-a-public-endpoint axis every
5553    /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
5554    /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
5555    /// hostname axis, §III.4 for the `:para` destination-Servico
5556    /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
5557    /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
5558    /// axis threads through a lifted per-slot accessor on the
5559    /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
5560    /// Gateway-API `Listener.hostname` scalar accessor, the paired
5561    /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
5562    /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
5563    /// backendRefs destination-Servico scalar accessor, the
5564    /// [`Entrada::resolved_paths`] path-fallback resolver, and the
5565    /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
5566    /// scalar accessor. Every downstream consumer that reaches for
5567    /// an entrada axis first passes through this outer accessor onto
5568    /// the composite and then dispatches onto the per-axis accessor
5569    /// — the two-level dispatch means every per-`:entrada` reader
5570    /// now routes through a typed dispatch on the substrate primitive
5571    /// at both altitudes.
5572    ///
5573    /// Prior to this lift the `.entrada` `Option<Entrada>` composite
5574    /// was accessed inline at four production sites — the
5575    /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
5576    /// gate's `if let Some(e) = &self.entrada { … }` traversal head
5577    /// (which drives every per-axis refusal on the composite: the
5578    /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
5579    /// `EntradaMemberMissing` membership lookup against the
5580    /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
5581    /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
5582    /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
5583    /// per-path shape gate on each entry of `e.paths`), the
5584    /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
5585    /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
5586    /// composite-projection seed (which drives the destination-
5587    /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
5588    /// backendRefs port emitter fans on), the
5589    /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
5590    /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
5591    /// early-return seed (which drives the "no `:entrada` ⇒ no
5592    /// external artifacts" partition on the whole-Aplicacao Gateway-
5593    /// API emitter's fan-out), and the `feira app graph` per-
5594    /// Aplicacao print line's `if let Some(e) = &spec.entrada`
5595    /// external-gateway summary emitter (which drives the human-
5596    /// readable `entrada: host → para (paths=…, port=…)` /
5597    /// `entrada: (internal-only mesh)` partition on the typed
5598    /// Aplicacao view) — four open-coded outer-field accesses that
5599    /// expressed no compile-time link back to the typed slot at the
5600    /// [`AplicacaoSpec`] altitude. A future extension of the
5601    /// `:entrada` outer axis to a richer author surface (a
5602    /// multi-`:entrada` list the M4 CR materializer resolves per-CR
5603    /// at admission time so an Aplicacao can expose a public-web +
5604    /// admin-web pair, a per-cluster `:entrada-overrides` slot the
5605    /// MESH-COMPOSITION §V federation roadmap acknowledges so an
5606    /// operator can pin a per-cluster hostname override without
5607    /// re-authoring the `caixa.lisp`, a promotion of the plain
5608    /// `Option<Entrada>` to a richer `{single, multi}` partition once
5609    /// the multi-`:entrada` roadmap lands) would have had to be
5610    /// threaded through all four open-coded copies in lockstep or one
5611    /// consumer would silently disagree with the peers on which
5612    /// entrada composite a given Aplicacao resolves to — the
5613    /// validator's per-axis bracket-dispatch seed reading the raw
5614    /// slot while the peer `gateway_routes` emitter read an
5615    /// operator-resolved slot would silently split the build-time
5616    /// gateway-shape gate from the runtime Gateway + HTTPRoute
5617    /// emission gate, a four-consumer split at the validator, the
5618    /// `port_for_destination` L4-port resolver, the `gateway_routes`
5619    /// emitter, and the `feira app graph` printer far from the
5620    /// source `caixa.lisp` with no field naming the entrada-drift
5621    /// root cause. Lifting the resolution rule to a typed method on
5622    /// the substrate primitive means every downstream consumer of
5623    /// the Aplicacao's per-`:entrada` external-gateway composite
5624    /// surface reaches for exactly one typed dispatch — the
5625    /// resolver's accept-set migrates as a unit on any future axis
5626    /// addition.
5627    ///
5628    /// Third and final `&Composite`-return accessor on the top-level
5629    /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
5630    /// unlifted outer-composite axis on the outer typed composition
5631    /// view, sibling to the seed [`AplicacaoSpec::politicas`]
5632    /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
5633    /// accessor on the per-`:politicas` outer-composite axis and to
5634    /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
5635    /// distribution-composite composite-reference accessor on the
5636    /// per-`:placement` outer-composite axis; extends the outer-
5637    /// composite reference-return discipline the two peers already
5638    /// route through onto the last unlifted per-`AplicacaoSpec`
5639    /// outer-composite axis. The `:entrada` outer-composite axis is
5640    /// the natural pair to the two peer outer-composite axes on the
5641    /// three operationally-symmetric M3 mesh-slot outer composites
5642    /// (`:politicas` carries the how-to-run policy overlay,
5643    /// `:placement` carries the where-to-run distribution composite,
5644    /// `:entrada` carries the who-can-reach-it external-gateway
5645    /// composite — every whole-Aplicacao mesh-artifact emitter reads
5646    /// all three as one unit). Same "one typed dispatch on the
5647    /// substrate primitive, thin projections at each consumer"
5648    /// discipline the peer outer-composite axes already route through.
5649    /// Named `entrada()` to match the storage field's name verbatim
5650    /// and the tatara-lisp author-surface term (`:entrada`) the
5651    /// field's own docstring already carries; the accessor's
5652    /// identity maps onto the canonical MESH-COMPOSITION §III.4
5653    /// vocabulary the slot's docstring already reaches for. Returns
5654    /// `Option<&Entrada>` (not the owning composite by copy or
5655    /// clone) because every downstream consumer of the entrada
5656    /// composite treats it as a read-only per-axis dispatch source
5657    /// — the reference-view is the narrowest borrow that supports
5658    /// every present + roadmapped consumer (per-axis accessor
5659    /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
5660    /// port-fallback projection, early-return partition on the
5661    /// `None` arm) without cloning the composite through every
5662    /// consumer's fast path. The `Option` half of the return-type
5663    /// preserves the load-bearing "author-omitted `:entrada` ⇒
5664    /// internal-only mesh" partition (not a default composite the
5665    /// downstream must reject on emptiness) — the accessor projects
5666    /// the raw `Option<Entrada>` slot's presence bit through the
5667    /// reference-return unchanged.
5668    #[must_use]
5669    pub fn entrada(&self) -> Option<&Entrada> {
5670        self.entrada.as_ref()
5671    }
5672
5673    /// Validate the typed shape:
5674    ///   - `:membros` is non-empty; every entry has a non-empty `:caixa`
5675    ///     and a non-empty `:versao`; no two entries share the same
5676    ///     `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
5677    ///     not a multiset)
5678    ///   - every `:contratos` :de + :para must be in `:membros`
5679    ///   - no `:contratos` edge is a self-edge (`:de == :para`) — a
5680    ///     contract is an inter-Servico edge, so a Servico contracting
5681    ///     with itself is a build error under every WIT shape
5682    ///     (MESH-COMPOSITION §III.1)
5683    ///   - no two `:contratos` entries agree on
5684    ///     `(de, para, wit, endpoint, subject, slot)` — the typed-graph
5685    ///     edges are a set, not a multiset (peer of the `:membros` /
5686    ///     `:placement :clusters` / `:entrada :paths` duplicate gates)
5687    ///   - `:entrada :para` must be in `:membros`
5688    ///   - `:placement Sharded` must declare `:shard-key` (non-empty);
5689    ///     `:placement Replicated`/`SingleNode` must NOT declare
5690    ///     `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
5691    ///     consumes it (MESH-COMPOSITION §II.4), and the typed partition
5692    ///     between strategy and shard-key is symmetric: every validated
5693    ///     `Placement` has `shard_key.is_some()` iff `estrategia ==
5694    ///     Sharded`
5695    ///   - every `:placement` strategy must declare ≥1 `:clusters` entry —
5696    ///     `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
5697    ///     the shard pool (MESH-COMPOSITION §III.1)
5698    ///   - every `:clusters` entry is non-empty and unique
5699    ///   - `:placement :affinity`, when set, is non-empty
5700    ///   - the synchronous-`:contratos` subgraph is acyclic
5701    ///     (MESH-COMPOSITION §III.3)
5702    ///   - every declared `:politicas` value is operationally meaningful
5703    ///     (zero timeout, zero retries, zero breaker thresholds, zero rate
5704    ///     limit are all build errors — MESH-COMPOSITION §V CSE invariants;
5705    ///     omit the field instead to express "no policy on this axis")
5706    pub fn validate(&self) -> Result<(), AplicacaoError> {
5707        self.validate_membros()?;
5708        let names: std::collections::HashSet<&str> =
5709            self.membros().iter().map(Membro::nome).collect();
5710
5711        // Identity key for the typed-edge duplicate gate below: every
5712        // field that distinguishes one contract from another. Two
5713        // entries that agree on all six are *the same edge declared
5714        // twice*, the typed-graph analogue of duplicate `:membros` /
5715        // `:placement :clusters` / `:entrada :paths` entries (which
5716        // are already build errors at this layer). Rejecting it at the
5717        // validate gate closes a renderer-side footgun: caixa-mesh's
5718        // `cilium_network_policies` keys each emitted policy by
5719        // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
5720        // (de, para) and identical payload would land as two K8s
5721        // objects with colliding `metadata.name`, rejected at apply
5722        // time far from the source caixa.lisp.
5723        let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
5724            std::collections::HashSet::new();
5725        for c in self.contratos() {
5726            // Per-axis value-shape gate on every `:contratos` name
5727            // reference, before any graph-membership lookup. Empty +
5728            // DNS-1123-malformed `:de`/`:para` values silently fell
5729            // through to `ContratoMemberMissing` at the lookup arm
5730            // because every `:membros :caixa` is shape-validated
5731            // (3f9d7a0), so the `names` set structurally cannot contain
5732            // an empty / malformed string and the membership-lookup
5733            // diagnostic always misframed the root cause as
5734            // "this caixa is not in `:membros`". The shape gate runs
5735            // ahead of the lookup so structurally-impossible-to-match
5736            // inputs route through the narrower self-locating
5737            // diagnostic, preserving the legitimate "well-shaped
5738            // phantom reference" arm. `:de` runs before `:para` per
5739            // the canonical edge-direction order the existing
5740            // membership lookup, self-edge check, target dispatch,
5741            // and diagnostic strings already use.
5742            // Route the per-`:contratos` per-arm DNS-1123 shape-gate arg
5743            // + the paired [`AplicacaoError::ContratoMemberMissing`]
5744            // diagnostic's `caixa:` carrier through the lifted
5745            // [`WitContract::source`] / [`WitContract::destination`]
5746            // scalar accessors rather than the raw `&c.de` / `&c.para`
5747            // `&String`-borrow arg site + the raw `c.de.clone()` /
5748            // `c.para.clone()` field-access `String`-carry sites — the
5749            // last unlifted per-`:contratos` raw-field-access sites in
5750            // the M3 mesh-slot validator's per-edge per-arm shape-gate
5751            // arg + phantom-name diagnostic wrap-envelope emit surface.
5752            // `c.source()` is byte-identical to `&c.de` (pinned by the
5753            // sibling `wit_contract_source_returns_de_byte_equal_across_permutations`
5754            // + `wit_contract_source_borrows_from_de_storage` accessor
5755            // tests) and `c.destination()` is byte-identical to `&c.para`
5756            // (pinned by the sibling
5757            // `wit_contract_destination_returns_para_byte_equal_across_permutations`
5758            // + `wit_contract_destination_borrows_from_para_storage`
5759            // accessor tests) — so a future rebrand of either underlying
5760            // storage flows through the accessor's one body without a
5761            // coordinated per-consumer rewrite across the M3 mesh
5762            // validator's per-edge shape-gate + phantom-name refusal
5763            // arms. Peer of the sibling per-`:contratos` self-loop
5764            // arm's `.source().to_string()` / `.world_ref().to_string()`
5765            // `String`-carry sites the earlier convergence lifted onto
5766            // the same accessor pair.
5767            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
5768            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
5769            if !names.contains(c.source()) {
5770                return Err(AplicacaoError::ContratoMemberMissing {
5771                    caixa: c.source().to_string(),
5772                });
5773            }
5774            if !names.contains(c.destination()) {
5775                return Err(AplicacaoError::ContratoMemberMissing {
5776                    caixa: c.destination().to_string(),
5777                });
5778            }
5779            // A `:contratos` entry is an *inter*-Servico contract
5780            // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
5781            // typed edge between two distinct graph nodes. An edge whose
5782            // `:de` equals its `:para` is a Servico contracting with
5783            // itself — a degenerate edge under every WIT shape. The
5784            // synchronous shapes were caught only incidentally, and with
5785            // a misleading diagnostic: `detect_sync_cycles` reported
5786            // `cart → cart` as a `ContratoCycle` whose path is
5787            // `["cart", "cart"]` — framing a self-edge as a multi-node
5788            // deadlock. The pub-sub shape slipped through entirely
5789            // (`detect_sync_cycles` excludes `WitTarget::PubSub`, so a
5790            // `nats:pub-sub` edge from a member to itself silently
5791            // validated, then rendered a `CiliumNetworkPolicy` whose
5792            // endpointSelector and fromEndpoints both name the same
5793            // program — a self-allow rule that is a no-op, since
5794            // intra-pod traffic never traverses the mesh). A self-edge's
5795            // runtime meaning is an in-process call, which doesn't go
5796            // through the mesh at all, so no `:contratos` edge can carry
5797            // it. Firing the gate before the `:wit`/`target()` shape
5798            // checks means the structural "this edge can't exist" error
5799            // precedes the narrower payload-shape diagnostics, and shape-
5800            // agnostically covers all four `WitTarget` arms (HTTP / Store
5801            // / Capability / PubSub) at one point — closing the pub-sub
5802            // hole and replacing the misleading cycle diagnostic in one
5803            // gate. Peer of the duplicate-`:contratos` / duplicate-
5804            // `:membros` set gates: both reject a structurally
5805            // ill-formed graph at the typed surface, before the renderer
5806            // emits a K8s object that fails or no-ops far from the source
5807            // caixa.lisp.
5808            // Route the per-`:contratos` structural self-edge probe
5809            // through the lifted [`WitContract::is_self_loop`] typed
5810            // predicate rather than the raw `c.de == c.para` field-
5811            // equality check — the one production consumer of the per-
5812            // `:contratos` caller-equals-callee endpoint-equality axis
5813            // now keys off exactly one typed dispatch on the substrate
5814            // primitive, so any future rebrand of the axis (an M4-typed-
5815            // caller enum whose identity comparison rule the predicate
5816            // could route through, a per-cluster caller/callee-alias
5817            // table the M4 CR materializer resolves per-CR before the
5818            // equality probe) migrates as a single caixa-core edit
5819            // rather than a coordinated rewrite of the gate + every
5820            // downstream self-edge consumer. Peer of the sibling
5821            // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
5822            // [`WitContract::is_store`] shape-predicate routing on the
5823            // `:wit` world-ref axis, extended onto the per-edge
5824            // endpoint-equality axis.
5825            //
5826            // Route the paired [`AplicacaoError::ContratoSelfLoop`]
5827            // diagnostic's `caixa:` / `wit:` carriers through the
5828            // lifted [`WitContract::source`] / [`WitContract::world_ref`]
5829            // scalar accessors rather than the raw `c.de.clone()` /
5830            // `c.wit.clone()` field-access `String`-carry sites — the
5831            // last unlifted per-`:contratos` raw-field-access
5832            // `.clone()` sites in the M3 mesh-slot validator's self-
5833            // edge refusal arm. `.source().to_string()` is byte-
5834            // identical to `.de.clone()` (pinned by the sibling
5835            // `source_returns_de_byte_equal_across_permutations` accessor
5836            // test), and `.world_ref().to_string()` is byte-identical
5837            // to `.wit.clone()` (pinned by the sibling
5838            // `world_ref_returns_wit_byte_equal_across_permutations`
5839            // accessor test) — so a future rebrand of either underlying
5840            // storage flows through the accessor's one body without a
5841            // coordinated per-consumer rewrite across the M3 mesh
5842            // validator.
5843            if c.is_self_loop() {
5844                return Err(AplicacaoError::ContratoSelfLoop {
5845                    caixa: c.source().to_string(),
5846                    wit: c.world_ref().to_string(),
5847                });
5848            }
5849            if c.world_ref().is_empty() {
5850                let (de, para) = c.edge_pair();
5851                return Err(AplicacaoError::EmptyWit { de, para });
5852            }
5853            // Shape ↔ target consistency — surfaces "HTTP wit without
5854            // :endpoint", "NATS wit with :endpoint set", etc. as named
5855            // build errors instead of silent renderer drops. Threaded
5856            // through the duplicate-edge diagnostic below (via
5857            // [`WitTarget::label`]) so the "which typed target arm did
5858            // the duplicate carry" question is answered by the typed
5859            // enum's variant discriminator, not by re-probing the raw
5860            // `Option<String>` payload fields.
5861            let target_view = c.target()?;
5862            // Contract identity: (de, para, wit, endpoint, subject, slot).
5863            // Two contracts that match on all six are the same typed edge
5864            // declared twice — author error, not a legitimate variant of
5865            // "same caller-callee pair, different payload" (e.g.
5866            // cart→catalog at /products vs /search), which keeps distinct
5867            // identity keys via the differing endpoint payloads.
5868            //
5869            // Route the six-axis dedup key through the lifted
5870            // [`WitContract::identity`] composite-projection accessor
5871            // rather than the inline six-tuple builder — the two
5872            // substrate primitives on the per-`:contratos` identity axis
5873            // (the [`ContratoIdentity`] type alias's six axes, this
5874            // dedup-key's six tuple arms) now migrate as a unit on any
5875            // future axis addition. Peer of the sibling per-`:contratos`
5876            // composite-projection [`WitContract::edge_pair`] /
5877            // [`WitContract::edge_triple`] accessors on the
5878            // caller-callee / caller-callee-wit prefix axes; extends
5879            // the discipline onto the full-identity axis that carries
5880            // the three payload-shape arms too.
5881            let key = c.identity();
5882            crate::render::insert_first_seen(&mut seen_contracts, key, || {
5883                // Route the per-`:contratos` duplicate-gate diagnostic's
5884                // `(de, para, wit)` triple through the lifted
5885                // [`WitContract::edge_triple`] typed accessor rather
5886                // than pairing `edge_pair()` for the `(de, para)` prefix
5887                // with a raw `c.wit.clone()` for the `wit:` tail — the
5888                // paired-with-raw-field-access shape was the last
5889                // per-`:contratos` diagnostic constructor bypassing the
5890                // substrate-primitive composite projection, sibling to
5891                // the eight [`AplicacaoError::Contrato*`] triple-
5892                // carrying constructors [`WitContract::target`]'s edge
5893                // closure feeds through the same accessor.
5894                let (de, para, wit) = c.edge_triple();
5895                AplicacaoError::ContratoDuplicate {
5896                    de,
5897                    para,
5898                    wit,
5899                    target: target_view.label(),
5900                }
5901            })?;
5902        }
5903
5904        // Cycles in the synchronous-edge subgraph are build errors
5905        // (MESH-COMPOSITION §III.3). Pub-sub edges are excluded — they
5906        // are "acyclic by construction" because the publisher fires
5907        // and forgets, so no caller blocks on a downstream that loops
5908        // back to it.
5909        self.detect_sync_cycles()?;
5910
5911        if let Some(e) = self.entrada() {
5912            // Route the per-`:entrada` composite-reference read
5913            // through the lifted [`AplicacaoSpec::entrada`] accessor
5914            // rather than the raw `&self.entrada` field access — the
5915            // shape-and-membership gate's traversal head is now the
5916            // canonical read-side surface every per-Aplicacao entrada
5917            // consumer routes through, closing the fourth of four
5918            // open-coded outer-field accesses on the per-`:entrada`
5919            // outer-composite axis.
5920            //
5921            // Shape gate on `:entrada :para` runs ahead of the
5922            // membership lookup. Every `:membros :caixa` past
5923            // `validate_membro_caixa` is a valid DNS-1123 label
5924            // (3f9d7a0), so the `names` set structurally cannot
5925            // contain an empty / malformed string and the membership-
5926            // lookup diagnostic always misframed the root cause as
5927            // "this caixa is not in `:membros`". The shape gate
5928            // routes structurally-impossible-to-match inputs through
5929            // the narrower self-locating diagnostic, preserving the
5930            // legitimate "well-shaped phantom reference" arm — the
5931            // same trajectory the peer `:membros :caixa` (3f9d7a0),
5932            // `:placement :clusters` (6c8c00b), and `:contratos :de`
5933            // / `:para` (8d5af6b) axes already follow. This closes
5934            // the fourth and last Aplicacao-level Servico-name
5935            // reference axis on the canonical DNS-1123 floor.
5936            // Route the per-`:entrada :para` byte-string reads through
5937            // the lifted [`Entrada::destination`] accessor rather than
5938            // the raw `e.para` field access — the three
5939            // per-`AplicacaoSpec::validate` `:entrada :para` consumers
5940            // (shape-gate `validate_entrada_para` arg, membership
5941            // lookup, `EntradaMemberMissing` diagnostic carry) now key
5942            // off exactly one typed dispatch on the substrate
5943            // primitive, closing the last unlifted per-`:entrada :para`
5944            // raw-field-access axis on the M3 mesh-slot validator.
5945            // The `.destination().to_string()` at the diagnostic site
5946            // is byte-identical to `.para.clone()` — pinned by the
5947            // sibling `destination_returns_entrada_para_byte_equal` +
5948            // `destination_borrows_from_entrada_para_storage` accessor
5949            // tests — so a future rebrand of the underlying `:para`
5950            // storage (a lift from `String` to a typed
5951            // `ServicoName(String)` newtype, a per-Aplicacao interning
5952            // arena the M4 CR materializer authors, a
5953            // `smol_str::SmolStr` inline-buffer swap) flows through
5954            // the accessor's one body without a coordinated
5955            // per-consumer rewrite across the M3 mesh validator.
5956            validate_entrada_para(e.destination())?;
5957            if !names.contains(e.destination()) {
5958                return Err(AplicacaoError::EntradaMemberMissing {
5959                    para: e.destination().to_string(),
5960                });
5961            }
5962            // Route the per-`:entrada :host` byte-string reads through
5963            // the lifted [`Entrada::hostname`] accessor rather than
5964            // the raw `e.host` field access — the emptiness gate and
5965            // the shape-gate `validate_entrada_host` arg now key off
5966            // exactly one typed dispatch on the substrate primitive,
5967            // closing the last unlifted per-`:entrada :host` raw-
5968            // field-access axis on the M3 mesh-slot validator. Peer
5969            // of the sibling per-`:entrada :para` convergence above
5970            // and pinned by the existing
5971            // `hostname_returns_entrada_host_byte_equal` +
5972            // `hostnames_returns_singleton_of_hostname_accessor`
5973            // accessor tests, so any future
5974            // Gateway-API-shaped host renormalization (a wildcard-
5975            // label lift, a trailing-`.` FQDN substitution, an IDNA
5976            // Punycode round-trip the SNI fan-out overlay authors)
5977            // flows through the accessor's one body without a
5978            // coordinated per-consumer rewrite across the M3 mesh
5979            // validator.
5980            if e.hostname().is_empty() {
5981                return Err(AplicacaoError::EmptyEntradaHost);
5982            }
5983            // The `:host` lands verbatim as a K8s Gateway API v1
5984            // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
5985            // both apiserver-validated against the same restrictive
5986            // pattern: lowercase RFC 1123 DNS subdomain, optional
5987            // single leading wildcard label (`*.`), max length 253,
5988            // per-label max length 63, no IP literals, no scheme,
5989            // no port. Until this gate landed `validate()` only
5990            // refused the empty string (`EmptyEntradaHost`); a
5991            // structurally invalid hostname (`"https://example.com"`,
5992            // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
5993            // `"_underscored.example.com"`, `"FOO.example.com"`,
5994            // `"checkout.quero.cloud."`) silently passed validate
5995            // and the apiserver `field is invalid` error surfaced at
5996            // `kubectl apply` time, far from the source caixa.lisp.
5997            // Lifting the gate to caixa-build time mirrors the
5998            // `:entrada :paths` value-shape trajectory (eb3456d) and
5999            // closes the last unstructured `:entrada` axis.
6000            validate_entrada_host(e.hostname())?;
6001            // Structural-floor gate on `:entrada :port`: every
6002            // validated `Entrada::port` past this gate lies in
6003            // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
6004            // type-inferred ceiling closes the top edge, so no companion
6005            // upper-cap arm is needed here — unlike the peer capped-
6006            // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
6007            // `require_positive_bounded_u32` bracket covers both edges).
6008            // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
6009            // accept-set-floor const rather than the prior inline
6010            // `if e.port == 0` byte-check so a future rebrand of the
6011            // accept-set floor (a hypothetical unprivileged-only
6012            // migration lifting the floor to `1024`, a per-cluster
6013            // scoping the operator pins through a future
6014            // `:placement :port-floor` slot as the M4 typed-slot
6015            // trajectory adds it, the future
6016            // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6017            // per-Aplicacao gateway resolver reaching for the same
6018            // floor) is a one-line edit on the canonical
6019            // [`SERVICO_PORT_MIN`] declaration, not a coordinated
6020            // rewrite across the emit site + the pin test + every
6021            // future per-target renderer the substrate adds.
6022            if e.port() < SERVICO_PORT_MIN {
6023                return Err(AplicacaoError::EntradaPortZero);
6024            }
6025            // Each `:entrada :paths` entry becomes a K8s Gateway API
6026            // HTTPRoute `matches[].path.value`. The Gateway API rejects
6027            // values that don't start with `/` for `type: PathPrefix`,
6028            // and an empty value is meaningless. Surface those as build
6029            // errors (MESH-COMPOSITION §III.3) rather than apply-time
6030            // failures. Empty `:paths` itself is fine — caixa-mesh
6031            // falls back to a single `/` catch-all.
6032            let mut seen = std::collections::HashSet::new();
6033            // Route the per-entry value-shape gate's traversal head
6034            // through the lifted [`Entrada::paths`] slice accessor
6035            // rather than the raw `&e.paths` field access — the
6036            // per-Aplicacao `:entrada :paths` validate loop now keys
6037            // off the canonical raw-slot surface every downstream
6038            // per-`:entrada` path-list consumer (the sibling
6039            // [`Entrada::resolved_paths`] fallback-applying resolver
6040            // internal reads, `feira app graph`'s per-Aplicacao entrada
6041            // summary line's `{:?}` Debug print) routes through, so any
6042            // future rebrand on the typed slot's raw-slot reader lands
6043            // at exactly one place. Same convergence discipline as the
6044            // sibling [`Placement::clusters`] (a6e18d7) reader-site
6045            // convergences on the peer M3 mesh-slot `Vec<String>`-carry
6046            // axis.
6047            for p in e.paths() {
6048                if p.is_empty() {
6049                    return Err(AplicacaoError::EntradaPathEmpty);
6050                }
6051                if !p.starts_with('/') {
6052                    return Err(AplicacaoError::EntradaPathNotAbsolute { path: p.clone() });
6053                }
6054                // Per-entry value-shape gate: the path lands verbatim
6055                // as a K8s Gateway API HTTPRoute `matches[].path.value`
6056                // (caixa-mesh/src/lib.rs:498), apiserver-validated
6057                // against `maxLength: 1024` + the Gateway API webhook's
6058                // path-grammar rules (no `//`, no `/./`, no `/../`, no
6059                // query/fragment separators, no whitespace, no control
6060                // characters, no non-ASCII bytes). Until this gate
6061                // landed `validate` only refused the empty string and
6062                // missing-leading-slash (eb3456d); a structurally
6063                // invalid path (`"/api?q=1"`, `"/api#frag"`,
6064                // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
6065                // 1025-byte URL-shaped slug) silently passed validate
6066                // and the failure surfaced at `kubectl apply` time as
6067                // a Gateway API webhook rejection, far from the source
6068                // caixa.lisp, with no field naming the offending
6069                // `:paths` entry. Lifting the gate to caixa-build time
6070                // mirrors the `:entrada :host` value-shape trajectory
6071                // (c7d05ec) on the sibling axis — every author surface
6072                // that emits a Gateway API field now matches the
6073                // apiserver's accepted set at validate time.
6074                validate_entrada_path(p)?;
6075                crate::render::insert_first_seen(&mut seen, p.as_str(), || {
6076                    AplicacaoError::EntradaPathDuplicate { path: p.clone() }
6077                })?;
6078            }
6079        }
6080
6081        self.validate_placement()?;
6082
6083        self.validate_politicas()?;
6084
6085        Ok(())
6086    }
6087
6088    /// Reject `:membros` values that are operationally meaningless. The
6089    /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
6090    /// every entry names a Servico that participates in the Aplicacao,
6091    /// and the rendered programs.yaml fan-out emits one entry per
6092    /// `:membros`. Three authoring footguns are closed here:
6093    ///
6094    ///   - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
6095    ///     a `programs:` entry whose `name:` is the empty string, which
6096    ///     downstream `lareira-fleet-programs` rejects at template time
6097    ///     with a non-localized error;
6098    ///   - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
6099    ///     an empty semver constraint, so the failure surfaces far from
6100    ///     the source caixa.lisp;
6101    ///   - duplicate `:caixa` names — two entries with the same name
6102    ///     produce duplicate programs.yaml entries (one silently
6103    ///     overwrites the other in the cluster's HelmRelease values), and
6104    ///     contract membership lookups against `:contratos` collapse the
6105    ///     two onto one node, masking authoring mistakes.
6106    ///
6107    /// Same value-shape discipline as `:placement :clusters` (where empty
6108    /// + duplicate cluster names are rejected) and `:entrada :paths`
6109    /// (where empty + duplicate path entries are rejected). Lifting these
6110    /// invariants to the typed surface mirrors the MESH-COMPOSITION
6111    /// §III.3 promise that the `:membros` set — the load-bearing identity
6112    /// of the application graph — is well-formed by construction.
6113    fn validate_membros(&self) -> Result<(), AplicacaoError> {
6114        if self.membros().is_empty() {
6115            return Err(AplicacaoError::NoMembros);
6116        }
6117        let mut seen = std::collections::HashSet::new();
6118        for m in self.membros() {
6119            // Route the `MembroCaixaEmpty` refusal-arm's per-member
6120            // empty-`:caixa` shape-gate through the typed
6121            // [`Membro::nome`] accessor rather than the raw `.caixa`
6122            // field access — the last un-lifted `.caixa` production-
6123            // code read site on the per-`:membros` member-caixa `:nome`
6124            // axis, sibling to the six caixa-core validator read sites
6125            // (member-set collector, per-member value-shape gate,
6126            // duplicate dedup key, cycle-detector adjacency-map seed,
6127            // self-loop gate) the 4a32abf lift already routed through
6128            // the accessor and the peer 54bf2f3 caixa-mesh emit-side
6129            // per-`programs[]` entry-`name:` `String`-carry converge.
6130            // Prior to this converge the `MembroCaixaEmpty` refusal
6131            // arm was the solitary consumer bypassing the typed
6132            // dispatch — the same-loop iteration's very next call
6133            // `validate_membro_caixa(m.nome())` already routed through
6134            // the accessor, so an author landing an empty-`:caixa`
6135            // entry hit the accessor on the shape-gate line but
6136            // bypassed it on the emptiness line one line above. A
6137            // future extension of the `:membros :caixa` axis to a
6138            // richer author surface (a per-cluster alias table pinned
6139            // through a future `:placement`-scoped slot, a namespace-
6140            // qualified rewrite the M4 CR materializer applies per-CR,
6141            // a per-member overlay from the future `:membros
6142            // :nome-suffix` slot MESH-COMPOSITION §III.2 acknowledges)
6143            // that lands on the accessor would silently disagree
6144            // between the emptiness gate and every peer consumer —
6145            // an author-declared `:caixa "checkout"` value the
6146            // accessor rewrote to `""` under a future alias arm would
6147            // pass the raw `.is_empty()` gate here while the peer
6148            // `validate_membro_caixa(m.nome())` call one line below
6149            // (and every downstream emit-side consumer routing through
6150            // the accessor) tripped on the empty-value shape far from
6151            // this diagnostic. Pinned by the drift-detection test
6152            // [`validate_membros_empty_gate_routes_through_nome_accessor`]
6153            // below.
6154            if m.nome().is_empty() {
6155                return Err(AplicacaoError::MembroCaixaEmpty);
6156            }
6157            // Every emitted cluster artifact's `metadata.name` derives
6158            // from a `:membros :caixa` value verbatim — the rendered
6159            // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
6160            // the [`crate::LABEL_PROGRAM`] label value on every CNP
6161            // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
6162            // 272), the composed `CiliumNetworkPolicy` `metadata.name`
6163            // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
6164            // `metadata.name` when the member is the `:entrada :para`
6165            // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
6166            // schema enforces the DNS-1123 label rule on admission;
6167            // a structurally invalid member name (`"Cart"`, `"my_cart"`,
6168            // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
6169            // mistaken-identity slug) silently passes the prior empty-/
6170            // duplicate-only gate and the failure surfaces at `kubectl
6171            // apply` time as a `metadata.name: Invalid value` rejection,
6172            // far from the source caixa.lisp, with no field naming the
6173            // offending `:membros` entry. Lifting the gate to caixa-build
6174            // time mirrors the `:entrada :host` value-shape trajectory
6175            // (c7d05ec) on the peer axis — every author surface that
6176            // emits a K8s name now matches the apiserver's accepted set
6177            // at validate time.
6178            validate_membro_caixa(m.nome())?;
6179            // The author surface for `:versao` is the same Cargo-shaped
6180            // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
6181            // `"*"`) every `:deps` entry carries — and the lacre pipeline
6182            // resolves both axes through the same
6183            // [`crate::version::parse_requirement`] entry-point. The
6184            // shared [`crate::render::require_valid_versao_requirement`]
6185            // helper brackets the empty-first + parse cascade both peer
6186            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
6187            // [`crate::SupervisorSpec::validate`] on `:children :versao`)
6188            // route through, so drift between the three axes' accepted
6189            // requirement sets is structurally impossible and the parse-
6190            // side no-op the empty-first arm closes (semver's empty
6191            // parse yields an implicit `*`) lives in exactly one
6192            // predicate.
6193            crate::render::require_valid_versao_requirement(
6194                m.versao_requirement(),
6195                || AplicacaoError::MembroVersaoEmpty {
6196                    caixa: m.nome().to_string(),
6197                },
6198                |reason| AplicacaoError::MembroVersaoInvalid {
6199                    caixa: m.nome().to_string(),
6200                    versao: m.versao_requirement().to_string(),
6201                    reason,
6202                },
6203            )?;
6204            crate::render::insert_first_seen(&mut seen, m.nome(), || {
6205                AplicacaoError::MembroDuplicate {
6206                    caixa: m.nome().to_string(),
6207                }
6208            })?;
6209        }
6210        Ok(())
6211    }
6212
6213    /// Reject `:placement` values that are operationally meaningless or
6214    /// internally contradictory. Each strategy variant has the same
6215    /// invariants on `:clusters` (non-empty list, non-empty unique
6216    /// entries) — the §III.1 author surface is uniform on this axis,
6217    /// even though the *meaning* of the list differs by strategy
6218    /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
6219    /// shard pool).
6220    ///
6221    /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
6222    /// are the same authoring footgun closed for `:politicas` zero
6223    /// values and `:entrada` empty paths: the field is *declared* but
6224    /// carries no meaning, so downstream renderers either skip it
6225    /// silently (cluster-fanout drops the empty entry, no diagnostic)
6226    /// or apply it literally and fail at admission time. Lifting both
6227    /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
6228    /// violation is a build error" promise.
6229    ///
6230    /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
6231    /// is required exactly when `:estrategia Sharded` (hash-keyed
6232    /// distribution, Akka cluster-sharding convention, §II.4) and
6233    /// refused on `:estrategia Replicated`/`SingleNode` (where no
6234    /// hash-keyed routing axis consumes it). The partition closes the
6235    /// "I think I configured sharding" footgun where an author writes
6236    /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
6237    /// the typed slot's value silently vanishes at the renderer layer
6238    /// — every validated `Placement` past this call satisfies
6239    /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
6240    fn validate_placement(&self) -> Result<(), AplicacaoError> {
6241        // Every strategy needs at least one named cluster: `Replicated`
6242        // and `SingleNode` use the list as hosting/takeover candidates
6243        // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
6244        // §II.1), while `Sharded` uses it as the shard pool
6245        // (Akka cluster-sharding convention — §II.4). An empty list is
6246        // meaningless under any of the three.
6247        //
6248        // Route the paired pre-flight `.is_empty()` refusal probe and
6249        // the per-cluster validate loop's traversal head through the
6250        // lifted [`Placement::clusters`] slice-return accessor rather
6251        // than the raw `self.placement.clusters` field access — the
6252        // two production consumers of the per-`:placement` cluster-
6253        // pool `Vec`-carry now key off exactly one typed dispatch on
6254        // the substrate primitive, so any future rebrand on the axis
6255        // (a per-tenant cluster-pool overlay the operator pins through
6256        // a future `:placement :clusters-overrides` slot, a per-
6257        // Aplicacao dynamic cluster-pool derivation the future M5
6258        // adaptive-placement engine computes from `:affinity` weights)
6259        // migrates as a single caixa-core edit rather than a
6260        // coordinated rewrite of the paired arms — sibling of the
6261        // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
6262        // arm migration on the per-`:supervisor` static-child-list
6263        // `Vec`-carry axis.
6264        //
6265        // Route the per-`:placement` outer-composite reference read
6266        // through the lifted [`AplicacaoSpec::placement`] outer accessor
6267        // rather than the raw `&self.placement` field access — the
6268        // per-axis bracket-dispatch fan-out below (`p.clusters()`,
6269        // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
6270        // axis-level lifted accessor family) now routes through the
6271        // substrate-primitive typed dispatch at the outer composition
6272        // altitude, the same shape the peer caixa-mesh
6273        // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
6274        // and the sibling `feira app graph` per-Aplicacao print line
6275        // now key off after this accessor lift.
6276        let p = self.placement();
6277        if p.clusters().is_empty() {
6278            return Err(AplicacaoError::PlacementWithoutClusters {
6279                estrategia: p.estrategia(),
6280            });
6281        }
6282        let mut seen = std::collections::HashSet::new();
6283        for c in p.clusters() {
6284            // Per-entry value-shape gate: the cluster name lands in
6285            // every K8s context / `lareira-fleet-programs` aggregator
6286            // filter / future M4 CR materializer's per-cluster axis
6287            // a validated `:clusters` entry passes through, each
6288            // enforcing the DNS-1123 label rule on admission. Same
6289            // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
6290            // on the peer name axis — both axes' validated values
6291            // are guaranteed-accepted by the apiserver without
6292            // re-validation at any downstream renderer or admission
6293            // layer.
6294            validate_placement_cluster(c)?;
6295            crate::render::insert_first_seen(&mut seen, c.as_str(), || {
6296                AplicacaoError::PlacementClusterDuplicate { cluster: c.clone() }
6297            })?;
6298        }
6299        // Route the per-`:placement :affinity` per-hint value-shape
6300        // gate through the typed [`Placement::affinity`] accessor rather
6301        // than the raw `&self.placement.affinity` field access — the
6302        // sole open-coded field-access site on the per-`:placement`
6303        // M3-Adaptive-compression-hint axis the accessor lift now owns.
6304        // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
6305        // the accessor's `Option<&str>` return type;
6306        // [`validate_placement_affinity`]'s `&str` parameter accepts
6307        // the narrower borrow without a re-allocation, so the routing
6308        // change is byte-for-byte in the pass arm and remains
6309        // byte-for-byte in every failure diagnostic
6310        // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
6311        // String` field is populated inside
6312        // [`validate_placement_affinity`] via the peer `.to_string()`
6313        // path on the same borrowed slice). Peer of the sibling
6314        // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
6315        // routing through [`Placement::shard_key`] at the caixa-core
6316        // site above — extends the "read `:placement` optional-scalars
6317        // through the typed accessor" discipline to the second
6318        // `Option<String>`-shape slot on the M3 mesh-slot family.
6319        //
6320        // Per-hint value-shape gate: the `:affinity` value lands
6321        // verbatim in the M3 Adaptive compression overlay
6322        // (caixa-mesh's `placement.affinity` emission) and every
6323        // future M4 placement-engine routing axis keying off the
6324        // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
6325        // selector — each enforces the DNS-1123 label rule on
6326        // admission. Same typed-shape trajectory as `:placement
6327        // :clusters` (6c8c00b) on the sibling slot and the four
6328        // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
6329        // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
6330        // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
6331        // on the Aplicacao surface to land on the canonical
6332        // [`crate::render::is_dns_1123_label`] floor.
6333        if let Some(a) = p.affinity() {
6334            validate_placement_affinity(a)?;
6335        }
6336        match p.estrategia() {
6337            // Route the `Sharded`-arm shape-gate cascade through the
6338            // typed [`Placement::shard_key`] accessor rather than the
6339            // raw `&self.placement.shard_key` field access — one of the
6340            // two open-coded field-access sites on the per-`:placement`
6341            // Akka-cluster-sharding-key axis the accessor lift now
6342            // owns. The `Some(k)`-bound `k` narrows from `&String` to
6343            // `&str` under the accessor's `Option<&str>` return type;
6344            // `str::is_empty` and [`validate_placement_shard_key`]'s
6345            // `&str` parameter both accept the narrower borrow without
6346            // a re-allocation.
6347            PlacementStrategy::Sharded => match p.shard_key() {
6348                None => return Err(AplicacaoError::ShardedWithoutKey),
6349                Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
6350                // Per-axis value-shape gate on the Akka-cluster-sharding
6351                // `:shard-key` extractor expression. The shape gate runs
6352                // after the more self-locating `ShardedKeyEmpty` arm so
6353                // a `:shard-key ""` surfaces the narrower empty
6354                // diagnostic first; every non-empty `:shard-key` past
6355                // this call is guaranteed to be a printable-ASCII
6356                // single-token reference the future M4 Akka-style
6357                // cluster-sharding reconciler can hash without
6358                // re-validating at the runtime layer. Mirrors the
6359                // payload-axis shape gates on the peer `:contratos`
6360                // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
6361                // 63e18a0 / c4213a4) — each lifts the runtime parser's
6362                // intersection-floor to a caixa-build-time gate.
6363                Some(k) => validate_placement_shard_key(k)?,
6364            },
6365            // `:shard-key` is the Akka-cluster-sharding axis
6366            // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
6367            // across the cluster pool. `Replicated` (active-active across
6368            // every named cluster) and `SingleNode` (Erlang/OTP
6369            // distributed-app takeover/failover, §II.1) have no hash-keyed
6370            // routing axis to consume the slot; downstream renderers
6371            // (caixa-mesh's `placement.shardKey` overlay at
6372            // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
6373            // sharding reconciler) ignore `:shard-key` outside the
6374            // `Sharded` arm by construction. Until this gate landed an
6375            // author who wrote `:placement (:estrategia Replicated
6376            // :shard-key "tenantId")` (an off-by-one strategy typo, a
6377            // copy-paste from a Sharded sibling caixa, the "I think I
6378            // configured sharding" footgun) silently passed validate and
6379            // the typed slot's value vanished at the renderer layer with
6380            // no diagnostic — the canonical "declared-but-inert" footgun
6381            // the empty-:affinity / empty-shard-key / zero-:politicas /
6382            // empty-:contratos-target gates already close on every other
6383            // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
6384            // Lifting the rejection to a build-time gate closes the
6385            // Sharded ↔ non-Sharded partition over the typed
6386            // `:placement` slot: every validated `Placement` past this
6387            // call has `shard_key.is_some()` iff `estrategia ==
6388            // Sharded`, structurally — the future Akka reconciler can
6389            // reach for `placement.shard_key` knowing it's `Some` exactly
6390            // when the strategy consumes it, without re-deriving the
6391            // partition from inline strategy probes.
6392            PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
6393                // Route the non-`Sharded`-arm declared-but-inert refusal
6394                // through the typed [`Placement::shard_key`] accessor —
6395                // the second of the two open-coded field-access sites the
6396                // accessor lift now owns. The `Some(k)`-bound `k` narrows
6397                // from `&String` to `&str`; the `AplicacaoError::
6398                // ShardKeyOnNonSharded { shard_key: String }` diagnostic
6399                // materializes the owned `String` via `k.to_string()`
6400                // (peer to the sibling per-Membro `String`-carry sites
6401                // 4127bb6 routed through `m.nome().to_string()` /
6402                // `m.versao_requirement().to_string()`), so the whole
6403                // `Sharded` ↔ non-`Sharded` partition on the
6404                // `:shard-key` axis now flows through the same typed
6405                // dispatch as the sibling `Sharded`-arm shape gate.
6406                if let Some(k) = p.shard_key() {
6407                    return Err(AplicacaoError::ShardKeyOnNonSharded {
6408                        estrategia: p.estrategia(),
6409                        shard_key: k.to_string(),
6410                    });
6411                }
6412            }
6413        }
6414        Ok(())
6415    }
6416
6417    /// Reject `:politicas` values that are operationally meaningless.
6418    /// Each axis is optional — omitting it expresses "no policy on this
6419    /// axis". Carrying a *zero* value for a declared axis is the bug
6420    /// this function rejects: zero is either
6421    ///
6422    ///   - re-interpreted as "infinite" by downstream proxies (Envoy's
6423    ///     `RouteAction.timeout = 0s` disables the timeout entirely),
6424    ///     directly contradicting MESH-COMPOSITION §V CSE invariant
6425    ///     "every Aplicacao declares :politicas :timeout (no infinite
6426    ///     blocking)", or
6427    ///   - a renderer footgun (a 0-failure circuit breaker trips on the
6428    ///     first call; a 0-rate rate-limit denies every request).
6429    ///
6430    /// Lifting these "0 means the opposite of what you think" idioms to
6431    /// the typed Aplicacao surface as build errors mirrors the §III.3
6432    /// promise that contract drift, capability leaks, and cycles are all
6433    /// build errors — not runtime surprises.
6434    fn validate_politicas(&self) -> Result<(), AplicacaoError> {
6435        // Route the per-`:politicas` composite-reference read through
6436        // the lifted [`AplicacaoSpec::politicas`] outer accessor rather
6437        // than the raw `&self.politicas` field access — the per-axis
6438        // bracket-dispatch fan-out below (`p.timeout()`, `p.retries()`,
6439        // `p.circuit_breaker()`, `p.rate_limit()`) now routes through
6440        // the substrate-primitive typed dispatch at the outer
6441        // composition altitude AND at every per-axis altitude, matching
6442        // the peer caixa-mesh CNP mTLS-overlay + HTTPRoute
6443        // timeout/retry-overlay emitters that already key off the same
6444        // per-axis accessor family. The four-axis fan-out is now
6445        // uniformly `p.<axis>()` — the last two raw `p.timeout` /
6446        // `p.retries` field-access sites (co-resident with the peer
6447        // `p.circuit_breaker()` / `p.rate_limit()` accessor sites that
6448        // b0e741a / 21a6c3b already lifted) now route through
6449        // [`MeshPolicy::timeout`] / [`MeshPolicy::retries`], closing
6450        // the per-`:politicas` bracket-dispatch fan-out's raw-field-
6451        // access axis on the M3 mesh-slot family.
6452        let p = self.politicas();
6453        if let Some(t) = p.timeout() {
6454            // Zero-floor + integer-millisecond canonical-form +
6455            // upper-cap bracket on the typed `:timeout` axis. See
6456            // [`crate::render::require_positive_canonical_bounded_duration`]
6457            // for the full three-arm ordering discipline (zero-floor
6458            // strictly precedes the canonical-form arm so
6459            // `Duration::ZERO` surfaces the self-locating
6460            // `PolicyTimeoutZero` diagnostic naming the omit-axis
6461            // remediation; canonical-form strictly precedes the cap
6462            // arm so a sub-millisecond above-cap `Duration` surfaces
6463            // the more fundamental round-trip-shape diagnostic first)
6464            // and the four peer typed-`Duration` sites that now share
6465            // this canonical bracket. Every validated value lies in
6466            // `1ms..=POLICY_TIMEOUT_MAX` (1ms..=1h), integer-millisecond
6467            // granularity — the same top-and-bottom-edge discipline
6468            // [`POLICY_RETRIES_MAX`] and
6469            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] apply on the sibling
6470            // capped-`u32` `:politicas` axes.
6471            crate::render::require_positive_canonical_bounded_duration(
6472                t,
6473                POLICY_TIMEOUT_MAX,
6474                || AplicacaoError::PolicyTimeoutZero,
6475                |timeout| AplicacaoError::PolicyTimeoutNotCanonical { timeout },
6476                |timeout| AplicacaoError::PolicyTimeoutExceedsCap { timeout },
6477            )?;
6478        }
6479        if let Some(r) = p.retries() {
6480            // Zero-floor + upper-cap bracket on the typed `:retries`
6481            // axis. See [`crate::render::require_positive_bounded_u32`]
6482            // for the ordering discipline (zero-floor arm strictly
6483            // precedes cap arm so `Some(0)` surfaces the self-locating
6484            // `PolicyRetriesZero` diagnostic with its omit-axis
6485            // remediation directly named, not the misleading
6486            // `0 > POLICY_RETRIES_MAX == false` cap-arm miss). Until
6487            // this bracket landed the top edge ran all the way to
6488            // `u32::MAX` and a struct-literal `MeshPolicy { retries:
6489            // Some(100_000), .. }` (or the equivalent author-surface
6490            // `(:retries 100000)` / `(:retries 4294967295)` typo
6491            // landing in the slot) silently passed validate. The
6492            // runtime substrate consuming the value (Envoy's
6493            // `retry_policy.num_retries`, the future
6494            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
6495            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
6496            // policy into a thundering-herd amplification vector —
6497            // the caller's one request fans out to `retries`
6498            // server-side calls per edge per traversal, multiplying
6499            // load by `(retries+1)^depth` across the
6500            // synchronous-`:contratos` subgraph at the precise moment
6501            // the substrate is already failing (transient failure is
6502            // the trigger), exactly the failure mode AWS App Mesh's
6503            // explicit `maxRetries ≤ 10` schema cap exists to prevent.
6504            // The bracket set is `1..=POLICY_RETRIES_MAX`. Peer with
6505            // the sibling capped-`u32` `:politicas` axes
6506            // (`max_failures`, `rate_limit.rate`) and the peer capped-
6507            // `u32` axes in `:supervisor :max-restarts` +
6508            // `:limits :cpu`; all five now route through the same
6509            // canonical bracket helper.
6510            crate::render::require_positive_bounded_u32(
6511                r,
6512                POLICY_RETRIES_MAX,
6513                || AplicacaoError::PolicyRetriesZero,
6514                |retries| AplicacaoError::PolicyRetriesExceedsCap { retries },
6515            )?;
6516        }
6517        if let Some(cb) = p.circuit_breaker() {
6518            // Zero-floor + upper-cap bracket on the typed
6519            // `:max-failures` axis. See
6520            // [`crate::render::require_positive_bounded_u32`] for the
6521            // ordering discipline (zero-floor arm strictly precedes
6522            // cap arm so `max_failures == 0` surfaces the
6523            // self-locating `PolicyBreakerZeroFailures` diagnostic
6524            // with its omit-axis remediation directly named, not the
6525            // misleading `0 > POLICY_BREAKER_MAX_FAILURES_MAX ==
6526            // false` cap-arm miss). Until this bracket landed the top
6527            // edge ran all the way to `u32::MAX` and a struct-literal
6528            // `CircuitBreaker { max_failures: 100_000, .. }` (or the
6529            // equivalent author-surface `(:max-failures 100000)` /
6530            // `(:max-failures 4294967295)` typo landing in the slot)
6531            // silently passed validate. The runtime substrate
6532            // consuming the value (Envoy's
6533            // `outlier_detection.consecutive_5xx`, the future
6534            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
6535            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
6536            // breaker policy into a no-op — the trip threshold is
6537            // structurally so high that no realistic
6538            // failures-per-`:window` traffic shape can reach it, the
6539            // breaker never trips, and every typed-slot consumer
6540            // emits an Envoy / Cilium L7 overlay carrying a
6541            // protection that is structurally never enforced. The
6542            // bracket set is `1..=POLICY_BREAKER_MAX_FAILURES_MAX`;
6543            // peer with `retries` and `rate_limit.rate` on the same
6544            // helper.
6545            crate::render::require_positive_bounded_u32(
6546                cb.max_failures(),
6547                POLICY_BREAKER_MAX_FAILURES_MAX,
6548                || AplicacaoError::PolicyBreakerZeroFailures,
6549                |max_failures| AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
6550            )?;
6551            // Zero-floor + integer-millisecond canonical-form +
6552            // upper-cap bracket on the typed `:window` axis. See
6553            // [`crate::render::require_positive_canonical_bounded_duration`]
6554            // for the full three-arm ordering discipline (peer to the
6555            // `:timeout` site immediately above); every validated
6556            // value lies in `1ms..=POLICY_BREAKER_WINDOW_MAX`
6557            // (1ms..=1h), integer-millisecond granularity — the same
6558            // top-and-bottom-edge discipline
6559            // [`POLICY_TIMEOUT_MAX`] applies on the sibling
6560            // duration-typed `:politicas :timeout` axis.
6561            crate::render::require_positive_canonical_bounded_duration(
6562                cb.window(),
6563                POLICY_BREAKER_WINDOW_MAX,
6564                || AplicacaoError::PolicyBreakerZeroWindow,
6565                |window| AplicacaoError::PolicyBreakerWindowNotCanonical { window },
6566                |window| AplicacaoError::PolicyBreakerWindowExceedsCap { window },
6567            )?;
6568        }
6569        if let Some(rl) = p.rate_limit() {
6570            // Zero-floor + upper-cap bracket on the typed
6571            // `:rate-limit` rate axis. See
6572            // [`crate::render::require_positive_bounded_u32`] for the
6573            // ordering discipline (zero-floor arm strictly precedes
6574            // cap arm so `rl.rate == 0` surfaces the self-locating
6575            // `PolicyRateLimitZero` diagnostic with its omit-axis
6576            // remediation directly named, not the misleading
6577            // `0 > POLICY_RATE_LIMIT_MAX == false` cap-arm miss).
6578            // Until this bracket landed the top edge ran all the way
6579            // to `u32::MAX` and a struct-literal
6580            // `RateLimit { rate: u32::MAX, .. }` (or the equivalent
6581            // author-surface `(:rate-limit "4294967295/s")` /
6582            // `(:rate-limit "100000000/m")` typo landing in the slot)
6583            // silently passed validate. The runtime substrate
6584            // consuming the value (Envoy's
6585            // `local_rate_limit.token_bucket.max_tokens`, the future
6586            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
6587            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
6588            // rate-limit policy into a no-op limiter: the bucket
6589            // capacity is structurally so high that no realistic
6590            // per-edge traffic shape can drain it, the limiter never
6591            // trips, and every typed-slot consumer emits a "rate
6592            // declared" L7 overlay carrying enforcement that is
6593            // structurally never reached — the canonical
6594            // declared-but-inert footgun the sibling
6595            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap arm closes on
6596            // the peer no-op-breaker shape. The bracket set is
6597            // `1..=POLICY_RATE_LIMIT_MAX`; peer with `retries` and
6598            // `max_failures` on the same helper. The rate bracket
6599            // strictly precedes the window-canonical gate so a
6600            // structurally absurd rate magnitude surfaces the more
6601            // fundamental amplification-shape diagnostic before the
6602            // narrower codec-round-trip-shape diagnostic on `:window`.
6603            crate::render::require_positive_bounded_u32(
6604                rl.rate(),
6605                POLICY_RATE_LIMIT_MAX,
6606                || AplicacaoError::PolicyRateLimitZero,
6607                |rate| AplicacaoError::PolicyRateLimitExceedsCap { rate },
6608            )?;
6609            // The `:rate-limit` author surface is the canonical
6610            // `"<n>/<s|m|h>"` form, and the [`rate_limit_codec`] parser
6611            // accepts exactly the three-unit set (1s/60s/3600s) the
6612            // [`rate_limit_codec::render`] formatter emits the canonical
6613            // unit suffix for. A `RateLimit` whose `:window` is anything
6614            // else (zero, 30s, 45s, 120s, 86400s, …) is constructible
6615            // programmatically (struct literals in Rust + the typed
6616            // `Duration` field) but renders to a `<n>/<k>s` fragment
6617            // (the codec's fall-through) the parser then rejects on
6618            // round-trip — silently breaking the THEORY.md §V.2.7
6619            // render-determinism contract for any consumer that
6620            // serializes-then-deserializes the typed slot. Lifting the
6621            // canonical-window invariant to a build-time gate at
6622            // `validate_politicas` makes the codec's round-trip property
6623            // a structural property of the validated typed value:
6624            // every `RateLimit` past `AplicacaoSpec::validate` has a
6625            // window the codec round-trips losslessly, so the next
6626            // typed-slot wiring (the future `CiliumClusterwideEnvoyConfig`
6627            // emitter for `:politicas :rate-limit`, MESH-COMPOSITION
6628            // §III.2 #3) reaches for `rate_limit.window` knowing the
6629            // value is in the codec's accepted set without re-validating
6630            // at the renderer layer. Same trajectory as c4213a4 (typed
6631            // WitContract endpoint/subject/slot value-shape gates) and
6632            // the b0c8389 :behavior + :upgrade-from script-path lifts:
6633            // the typed slot's valid set matches its codec's accepted
6634            // set, structurally.
6635            if !is_canonical_rate_limit_window(rl.window()) {
6636                return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical {
6637                    window: rl.window(),
6638                });
6639            }
6640        }
6641        Ok(())
6642    }
6643
6644    /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
6645    /// A synchronous edge is any contract whose typed [`WitTarget`] is
6646    /// `Http`, `Store`, or `Capability` — the caller blocks on the
6647    /// callee, so a cycle would deadlock at runtime. Pub-sub edges
6648    /// (`WitTarget::PubSub`) are skipped: an event publisher does not
6649    /// block on its subscribers, so they can never close a sync loop.
6650    ///
6651    /// Iterative DFS with three-coloring; the reported cycle is the
6652    /// path of caixa names traversed from the back-edge target around
6653    /// to itself, in declaration order. Adjacency lists and DFS roots
6654    /// are visited in `BTreeMap` key order so the diagnostic is
6655    /// deterministic across runs.
6656    fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
6657        use std::collections::{BTreeMap, BTreeSet};
6658
6659        #[derive(Clone, Copy, PartialEq, Eq)]
6660        enum Mark {
6661            White,
6662            Gray,
6663            Black,
6664        }
6665
6666        let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
6667        for m in self.membros() {
6668            adj.entry(m.nome()).or_default();
6669        }
6670        for c in self.contratos() {
6671            // target() was already called by validate(); re-running here
6672            // keeps detect_sync_cycles self-contained for callers that
6673            // reuse it (M4 per-edge policy resolver) without revalidating.
6674            //
6675            // The pub-sub-arm check routes through the lifted
6676            // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
6677            // arm-discriminator predicate rather than a raw `matches!(…,
6678            // WitTarget::PubSub { .. })` on the variant so a future
6679            // rebrand on the axis (an M4 per-edge WIT registry split of
6680            // [`WitTarget::PubSub`] into shape-specific peers, a
6681            // per-consumer rename that the accept-set already carries)
6682            // reaches this call site through the derive rather than a
6683            // scattered per-arm `matches!` rewrite — same
6684            // `IsVariant`-derived-arm-discriminator discipline the
6685            // peer closed-set typed enums ([`crate::CaixaKind`] via
6686            // f5bba80, [`PlacementStrategy`] via 766ec63,
6687            // [`crate::supervisor::RestartStrategy`] +
6688            // [`crate::supervisor::RestartPolicy`],
6689            // [`crate::upgrade::UpgradeInstruction`] via 915a934)
6690            // already route through on the substrate's other typed-enum
6691            // arm-discriminator axes.
6692            if c.target()?.is_pubsub() {
6693                continue;
6694            }
6695            adj.entry(c.source()).or_default().insert(c.destination());
6696        }
6697
6698        let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
6699        let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
6700
6701        // Stable DFS root order — BTreeMap iteration is sorted by key.
6702        let roots: Vec<&str> = adj.keys().copied().collect();
6703
6704        // Frame: (node, sorted-neighbours snapshot, next-edge index).
6705        for root in roots {
6706            if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
6707                continue;
6708            }
6709            let root_neighbors: Vec<&str> = adj
6710                .get(root)
6711                .map(|s| s.iter().copied().collect())
6712                .unwrap_or_default();
6713            let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
6714            color.insert(root, Mark::Gray);
6715
6716            loop {
6717                // Read+advance the top frame in one borrow scope so we
6718                // can later mutate the stack (push/pop) without holding
6719                // a borrow across.
6720                let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
6721                    let node = top.0;
6722                    if top.2 >= top.1.len() {
6723                        (node, None)
6724                    } else {
6725                        let nxt = top.1[top.2];
6726                        top.2 += 1;
6727                        (node, Some(nxt))
6728                    }
6729                });
6730                let Some((node, nxt_opt)) = step else { break };
6731                let Some(nxt) = nxt_opt else {
6732                    color.insert(node, Mark::Black);
6733                    stack.pop();
6734                    continue;
6735                };
6736                let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
6737                match nxt_color {
6738                    Mark::Gray => {
6739                        // Reconstruct the cycle from `node` back through
6740                        // the parent chain to `nxt`, then close.
6741                        let mut cycle = Vec::new();
6742                        let mut cur = node;
6743                        cycle.push(cur.to_string());
6744                        while cur != nxt {
6745                            match parent.get(cur).copied() {
6746                                Some(p) => {
6747                                    cur = p;
6748                                    cycle.push(cur.to_string());
6749                                }
6750                                None => break,
6751                            }
6752                        }
6753                        cycle.reverse();
6754                        cycle.push(nxt.to_string());
6755                        return Err(AplicacaoError::ContratoCycle { cycle });
6756                    }
6757                    Mark::White => {
6758                        parent.insert(nxt, node);
6759                        color.insert(nxt, Mark::Gray);
6760                        let nxt_neighbors: Vec<&str> = adj
6761                            .get(nxt)
6762                            .map(|s| s.iter().copied().collect())
6763                            .unwrap_or_default();
6764                        stack.push((nxt, nxt_neighbors, 0));
6765                    }
6766                    Mark::Black => {}
6767                }
6768            }
6769        }
6770        Ok(())
6771    }
6772
6773    /// Substrate-canonical destination-facing TCP port every emitted
6774    /// per-Aplicacao artifact must key `destination`-shaped port axes
6775    /// off. Returns the typed `:entrada :port` scalar when this
6776    /// Aplicacao's `:entrada` block names `destination` under its
6777    /// `:para` axis (the destination Servico *is* the ingress apex, so
6778    /// the substrate honors the author-declared listener port
6779    /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
6780    /// fallback otherwise (every non-apex destination — the internal
6781    /// mesh Servicos `:contratos` reach across, the future per-edge
6782    /// policy resolver's per-destination probe targets, the
6783    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
6784    /// L4 port resolver — reads the same substrate-canonical port floor
6785    /// by construction).
6786    ///
6787    /// Prior to this lift the "if :entrada matches this destination use
6788    /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
6789    /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
6790    /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
6791    /// prior to this lift), with no typed method on the substrate primitive
6792    /// that named the rule. A future per-destination port axis addition
6793    /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
6794    /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
6795    /// per-Servico listener ports land, a per-cluster override the operator
6796    /// pins through a future `:placement :default-port` slot — would have
6797    /// to be threaded through every renderer's inline cascade in lockstep
6798    /// or one consumer would silently disagree on which port a given
6799    /// destination Servico's ingress lands at. Lifting the rule to a
6800    /// typed method on the substrate primitive means the M4 CR
6801    /// materializer, the future per-edge policy resolver, and every
6802    /// downstream test-fixture navigator reach for exactly one typed
6803    /// dispatch — the resolver's accept-set moves as a unit on any
6804    /// future axis addition.
6805    ///
6806    /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
6807    /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
6808    /// the typed primitive, thin projections at each consumer"
6809    /// discipline lifts on the sibling `:contratos` payload / `:politicas
6810    /// :rate-limit` unit-suffix axes; extends the discipline onto the
6811    /// destination-facing port-resolution axis every per-Aplicacao
6812    /// L4-fallback renderer consumes.
6813    #[must_use]
6814    pub fn port_for_destination(&self, destination: &str) -> u16 {
6815        // Route the per-`:entrada` composite-reference read through
6816        // the lifted [`AplicacaoSpec::entrada`] accessor rather than
6817        // the raw `self.entrada.as_ref()` field access — the
6818        // per-destination L4-port fallback resolver's composite-
6819        // projection seed is now the canonical read-side surface
6820        // every per-Aplicacao entrada consumer routes through, peer
6821        // of the sibling `validate` per-`:entrada` shape-and-
6822        // membership gate migration on the same outer-composite
6823        // axis.
6824        // Route the per-`:entrada` apex-destination membership probe
6825        // through the lifted [`Entrada::destination`] accessor rather
6826        // than the raw `e.para == destination` field access — the last
6827        // un-lifted `.para` production-code read site on the per-
6828        // `:entrada` `:para` axis, sibling to the four caixa-core
6829        // consumer sites the peer 15ddd8c converge already routed
6830        // through the accessor (the three
6831        // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
6832        // membership gate sites: the `validate_entrada_para` DNS-1123
6833        // shape gate, the per-`:membros` membership lookup, and the
6834        // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
6835        // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
6836        // `entrada.para`-projection converge at
6837        // caixa-core/src/render.rs (the `gateway_api_http_route_name`
6838        // route-name projection site). Prior to this converge the
6839        // `port_for_destination` resolver was the solitary consumer
6840        // bypassing the typed dispatch on the `.para` axis — the two
6841        // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
6842        // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
6843        // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
6844        // reach through the same accessor family compose with this
6845        // resolver at the emit boundary via the apex-identity
6846        // invariant `spec.port_for_destination(entrada.destination())
6847        // == entrada.port` the sibling
6848        // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
6849        // pin pins across four permutations. A future extension of the
6850        // `:entrada :para` axis to a richer author surface (a per-
6851        // cluster alias overlay the operator pins through a future
6852        // `:placement`-scoped slot, a namespace-qualified rewrite the
6853        // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
6854        // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
6855        // §III.2 acknowledges) that lands on the accessor would silently
6856        // disagree between this resolver and the two `caixa-mesh` emit
6857        // sites — an author-declared `:para "cart"` value the accessor
6858        // rewrote to `"cart-v2"` under a future canary arm would leave
6859        // the resolver's membership arm falling through to
6860        // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
6861        // `.para`) while the peer emit-site consumers landed on the
6862        // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
6863        // silently disagreed on which destination port a given typed
6864        // `:entrada` resolves to at cluster-apply time. Pinned by the
6865        // drift-detection test
6866        // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
6867        // below.
6868        self.entrada()
6869            .filter(|e| e.destination() == destination)
6870            .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
6871    }
6872}
6873
6874/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
6875/// entry may name the Aplicacao's own `:nome`.
6876///
6877/// An Aplicacao that lists itself as a member is a degenerate self-edge in
6878/// the typed graph — the application graph is a DAG rooted at the Aplicacao
6879/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
6880/// Servicos that compose the app; an Aplicacao is never its own constituent),
6881/// and the lacre pipeline's closure-resolution would otherwise be handed a
6882/// node that is its own parent: a one-node cycle it either rejects far from
6883/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
6884/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
6885/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
6886/// label + lacre closure root), a member whose `:caixa` equals the
6887/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
6888/// peer.
6889///
6890/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
6891/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
6892/// gate `validate_upgrade_from_against_versao` and the supervision-tree
6893/// self-parent gate `crate::supervisor::validate_no_self_supervision`
6894/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
6895/// not a tree/mesh edge" discipline, here on the second typed-graph axis
6896/// (the Aplicacao :membros set; the supervision-tree :children list was the
6897/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
6898/// every validated Supervisor's children are distinct from its `:nome`,
6899/// every validated Aplicacao's membros are distinct from its `:nome`. The
6900/// transitive consequence is that `:entrada :para` and `:contratos`
6901/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
6902/// name the Aplicacao itself, without re-deriving the partition.
6903pub fn validate_no_self_membership(
6904    membros: &[Membro],
6905    parent_nome: &str,
6906) -> Result<(), AplicacaoError> {
6907    for m in membros {
6908        if m.nome() == parent_nome {
6909            return Err(AplicacaoError::MembroIsSelfAplicacao {
6910                caixa: parent_nome.to_string(),
6911            });
6912        }
6913    }
6914    Ok(())
6915}
6916
6917#[derive(Debug, Error, PartialEq, Eq)]
6918pub enum AplicacaoError {
6919    #[error("Aplicacao must declare at least one :membros entry")]
6920    NoMembros,
6921    #[error(
6922        ":membros entry has empty :caixa (every member must name a Servico; \
6923         omit the entry instead of carrying an empty name)"
6924    )]
6925    MembroCaixaEmpty,
6926    #[error(
6927        ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
6928         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
6929         name / label value the member name lands in; use a lowercase \
6930         alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
6931    )]
6932    MembroCaixaInvalid { caixa: String, reason: String },
6933    #[error(
6934        ":membros entry {caixa:?} has empty :versao (every member must pin a \
6935         semver constraint that resolves through the lacre pipeline)"
6936    )]
6937    MembroVersaoEmpty { caixa: String },
6938    #[error(
6939        ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
6940         requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
6941         `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
6942         carries; the lacre pipeline resolves both through the same parser)"
6943    )]
6944    MembroVersaoInvalid {
6945        caixa: String,
6946        versao: String,
6947        reason: String,
6948    },
6949    #[error(
6950        ":membros entry {caixa:?} appears more than once (the graph node set \
6951         is a set, not a multiset; duplicate members produce duplicate \
6952         programs.yaml entries and ambiguous :contratos membership lookups)"
6953    )]
6954    MembroDuplicate { caixa: String },
6955    #[error(
6956        "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
6957         never its own constituent Servico (the application graph is a DAG rooted \
6958         at the Aplicacao; :membros names the *other* caixas that compose the \
6959         app, not the app itself). Since every :nome is a globally-unique \
6960         substrate identity, a member naming the Aplicacao's own :nome is a \
6961         one-node lacre-closure recursion, not a coincidentally-named peer; \
6962         drop the self-referential :membros entry or rename it to the actual \
6963         constituent caixa."
6964    )]
6965    MembroIsSelfAplicacao { caixa: String },
6966    #[error(
6967        "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
6968         caixa declared in :membros; omit the contract or fill the {slot} field with a \
6969         member name)"
6970    )]
6971    ContratoCaixaEmpty { slot: &'static str },
6972    #[error(
6973        "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
6974         :contratos {slot} value names a member of :membros, which is itself a \
6975         DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
6976         object the member name lands in — Service, Pod, identity-based Cilium \
6977         selector; use a lowercase alphanumeric + hyphen identifier like \
6978         `\"checkout\"` or `\"cart-v2\"`)"
6979    )]
6980    ContratoCaixaInvalid {
6981        slot: &'static str,
6982        caixa: String,
6983        reason: String,
6984    },
6985    #[error("contrato references caixa {caixa:?} not declared in :membros")]
6986    ContratoMemberMissing { caixa: String },
6987    #[error(
6988        "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
6989         entry is an inter-Servico contract whose :de and :para must name distinct \
6990         :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
6991         the contract, or point :para at the member it actually calls)"
6992    )]
6993    ContratoSelfLoop { caixa: String, wit: String },
6994    #[error("contrato {de:?} → {para:?} has empty :wit")]
6995    EmptyWit { de: String, para: String },
6996    #[error(
6997        "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
6998         {reason} (the substrate dispatches `:wit` values on the canonical \
6999         lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
7000         `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
7001         demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
7002         kebab-case identifier per segment)"
7003    )]
7004    ContratoWitInvalid {
7005        de: String,
7006        para: String,
7007        wit: String,
7008        reason: String,
7009    },
7010    #[error(
7011        ":entrada :para is empty (every :entrada must route to a caixa declared in \
7012         :membros; fill the :para field with a member name)"
7013    )]
7014    EntradaParaEmpty,
7015    #[error(
7016        ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
7017         :entrada :para value names a member of :membros, which is itself a DNS-1123 \
7018         label per the K8s apiserver's `metadata.name` rule on every object the \
7019         member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
7020         Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
7021         `\"checkout\"` or `\"cart-v2\"`)"
7022    )]
7023    EntradaParaInvalid { para: String, reason: String },
7024    #[error(":entrada routes to caixa {para:?} not declared in :membros")]
7025    EntradaMemberMissing { para: String },
7026    #[error(":entrada must declare a non-empty :host")]
7027    EmptyEntradaHost,
7028    #[error(
7029        ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
7030         (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
7031         `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
7032         like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
7033    )]
7034    EntradaHostInvalid { host: String, reason: String },
7035    #[error(":entrada :port must be in 1..=65535, got 0")]
7036    EntradaPortZero,
7037    #[error(":entrada :paths entry is empty (use the empty list to match all)")]
7038    EntradaPathEmpty,
7039    #[error(
7040        ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
7041    )]
7042    EntradaPathNotAbsolute { path: String },
7043    #[error(
7044        ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
7045         value: {reason} (the K8s apiserver enforces the same shape on \
7046         `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
7047         single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
7048         requires percent-encoding `%XX` for non-ASCII and whitespace)"
7049    )]
7050    EntradaPathInvalid { path: String, reason: String },
7051    #[error(":entrada :paths entry {path:?} appears more than once")]
7052    EntradaPathDuplicate { path: String },
7053    #[error(
7054        ":placement {estrategia} requires at least one :clusters entry \
7055         (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
7056    )]
7057    PlacementWithoutClusters { estrategia: PlacementStrategy },
7058    #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
7059    PlacementClusterEmpty,
7060    #[error(
7061        ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
7062         (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
7063         in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
7064         future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
7065         — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
7066         identifier like `\"rio\"` or `\"mar-east\"`)"
7067    )]
7068    PlacementClusterInvalid { cluster: String, reason: String },
7069    #[error(":placement :clusters entry {cluster:?} appears more than once")]
7070    PlacementClusterDuplicate { cluster: String },
7071    #[error(
7072        ":placement :affinity must be non-empty when set (omit :affinity to express \
7073         `no placement hint`)"
7074    )]
7075    PlacementAffinityEmpty,
7076    #[error(
7077        ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
7078         (placement hints land verbatim in the M3 Adaptive compression overlay's \
7079         `placement.affinity` field and in every future M4 placement-engine routing \
7080         axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
7081         selector — both enforce the DNS-1123 label rule on admission; use a \
7082         lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
7083         `\"low-latency\"`, or `\"anti-affinity\"`)"
7084    )]
7085    PlacementAffinityInvalid { affinity: String, reason: String },
7086    #[error(":placement Sharded requires :shard-key")]
7087    ShardedWithoutKey,
7088    #[error(
7089        ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
7090         hashes every entity onto the same shard, defeating sharding entirely)"
7091    )]
7092    ShardedKeyEmpty,
7093    #[error(
7094        ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
7095         entity-id extractor expression: {reason} (the future M4 Akka-style \
7096         cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
7097         as a single-token property reference and hashes the extracted entity ID \
7098         to compute shard placement; use a printable-ASCII extractor expression \
7099         like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
7100         `\"${{tenant}}\"`)"
7101    )]
7102    ShardKeyInvalid { shard_key: String, reason: String },
7103    #[error(
7104        ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
7105         Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
7106         convention); :estrategia Replicated runs every cluster active-active and \
7107         :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
7108         distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
7109         to :estrategia Sharded if hash-keyed routing is the intent"
7110    )]
7111    ShardKeyOnNonSharded {
7112        estrategia: PlacementStrategy,
7113        shard_key: String,
7114    },
7115    #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
7116    ContratoMissingTarget {
7117        de: String,
7118        para: String,
7119        wit: String,
7120        expected: &'static str,
7121    },
7122    #[error(
7123        "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
7124         expected `:{expected}` only"
7125    )]
7126    ContratoWrongTarget {
7127        de: String,
7128        para: String,
7129        wit: String,
7130        expected: &'static str,
7131    },
7132    #[error(
7133        "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
7134         like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
7135         that matches no traffic and silently drops every request)"
7136    )]
7137    ContratoEndpointEmpty { de: String, para: String },
7138    #[error(
7139        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
7140         (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
7141         :entrada :paths)"
7142    )]
7143    ContratoEndpointNotAbsolute {
7144        de: String,
7145        para: String,
7146        endpoint: String,
7147    },
7148    #[error(
7149        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
7150         Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
7151         emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
7152         caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
7153         shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
7154         like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
7155         and whitespace)"
7156    )]
7157    ContratoEndpointInvalid {
7158        de: String,
7159        para: String,
7160        endpoint: String,
7161        reason: String,
7162    },
7163    #[error(
7164        "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
7165         subject is a no-op subscribe; omit :subject only if the WIT world is not \
7166         pub-sub-shaped)"
7167    )]
7168    ContratoSubjectEmpty { de: String, para: String },
7169    #[error(
7170        "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
7171         NATS subject: {reason} (the NATS server's subject parser enforces the \
7172         same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
7173         single-token and `>` multi-token wildcards — at publish/subscribe time; \
7174         use a token-by-token form like `\"checkout.events.charge.failed\"` or \
7175         `\"orders.*.completed\"` — a malformed subject silently drops every \
7176         message at runtime far from the source caixa.lisp)"
7177    )]
7178    ContratoSubjectInvalid {
7179        de: String,
7180        para: String,
7181        subject: String,
7182        reason: String,
7183    },
7184    #[error(
7185        "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
7186         addresses the bucket root, defeating the per-key isolation the slot exists \
7187         for; omit :slot only if the WIT world is not store-shaped)"
7188    )]
7189    ContratoSlotEmpty { de: String, para: String },
7190    #[error(
7191        "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
7192         WASI keyvalue store slot template: {reason} (the substrate enforces \
7193         the printable-ASCII intersection-floor every kv backend admits — \
7194         use a single-token path / template expression like `\"checkout/$orderId\"`, \
7195         `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
7196         percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
7197         slot either gets rejected on write by strict backends or silently \
7198         corrupts the next read on permissive ones, far from the source caixa.lisp)"
7199    )]
7200    ContratoSlotInvalid {
7201        de: String,
7202        para: String,
7203        slot: String,
7204        reason: String,
7205    },
7206    #[error(
7207        "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
7208         or an event-sourced indirection (MESH-COMPOSITION §III.3)",
7209        cycle.join(" → ")
7210    )]
7211    ContratoCycle { cycle: Vec<String> },
7212    #[error(
7213        ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
7214         than once (the typed graph edges are a set, not a multiset; duplicate \
7215         contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
7216         values that K8s admission rejects far from the source caixa.lisp)"
7217    )]
7218    ContratoDuplicate {
7219        de: String,
7220        para: String,
7221        wit: String,
7222        target: String,
7223    },
7224    #[error(
7225        ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
7226         contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
7227         express `no per-call deadline on this axis`"
7228    )]
7229    PolicyTimeoutZero,
7230    #[error(
7231        ":politicas :retries must be > 0 when set; omit :retries to express \
7232         `no retries on transient failure`"
7233    )]
7234    PolicyRetriesZero,
7235    #[error(
7236        ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
7237         (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
7238         retry policy into a thundering-herd amplification vector on transient \
7239         failure (one caller request fans out to `(retries+1)^depth` server-side \
7240         calls across the synchronous-:contratos subgraph), exactly the failure \
7241         mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
7242         Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
7243         or omit :retries to disable retries entirely"
7244    )]
7245    PolicyRetriesExceedsCap { retries: u32 },
7246    #[error(
7247        ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
7248         breaker trips on the first call); omit :circuit-breaker to disable it"
7249    )]
7250    PolicyBreakerZeroFailures,
7251    #[error(
7252        ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
7253         mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
7254         above this cap turns the typed breaker policy into a no-op: the trip \
7255         threshold is structurally so high that no realistic failures-per-:window \
7256         traffic shape can reach it, so the breaker never trips and every typed-slot \
7257         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
7258         Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
7259         structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
7260         Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
7261         omit :circuit-breaker to disable the breaker entirely"
7262    )]
7263    PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
7264    #[error(
7265        ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
7266         tracks no failures); omit :circuit-breaker to disable it"
7267    )]
7268    PolicyBreakerZeroWindow,
7269    #[error(
7270        ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
7271         request); omit :rate-limit to disable rate limiting"
7272    )]
7273    PolicyRateLimitZero,
7274    #[error(
7275        ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
7276         (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
7277         rate-limit policy into a no-op limiter: the token-bucket capacity is \
7278         structurally so high that no realistic per-edge traffic shape can drain it, \
7279         so the limiter never trips and every typed-slot consumer (the future \
7280         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
7281         local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
7282         that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
7283         Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
7284         Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
7285         Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
7286         to disable rate limiting entirely"
7287    )]
7288    PolicyRateLimitExceedsCap { rate: u32 },
7289    #[error(
7290        ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
7291         the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
7292         rate-limit codec round-trips losslessly; got {window:?} which renders to a \
7293         non-round-trippable form (omit :rate-limit to disable, or pick one of the \
7294         three canonical windows)"
7295    )]
7296    PolicyRateLimitWindowNotCanonical { window: Duration },
7297    #[error(
7298        ":politicas :timeout must be an integer number of milliseconds — the canonical \
7299         authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
7300         duration codec round-trips losslessly; got {timeout:?} which carries a \
7301         sub-millisecond residue that either truncates to a different `Duration` on \
7302         re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
7303         to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
7304         zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
7305         (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
7306    )]
7307    PolicyTimeoutNotCanonical { timeout: Duration },
7308    #[error(
7309        ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
7310         (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
7311         per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
7312         overlays carry a deadline so long no realistic synchronous-:contratos \
7313         traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
7314         CSE invariant degenerates to enforcement only at the per-Servico \
7315         `:limits :wall-clock` layer — far above the per-edge granularity the typed \
7316         `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
7317         (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
7318         ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
7319         maxes out at the same `3600s` ceiling) or omit :timeout to express \
7320         `no per-call deadline on this axis` (the synchronous-call deadline then \
7321         relies entirely on the per-Servico `:limits :wall-clock` axis)"
7322    )]
7323    PolicyTimeoutExceedsCap { timeout: Duration },
7324    #[error(
7325        ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
7326         the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
7327         the shared duration codec round-trips losslessly; got {window:?} which carries a \
7328         sub-millisecond residue that either truncates to a different `Duration` on \
7329         re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
7330         Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
7331    )]
7332    PolicyBreakerWindowNotCanonical { window: Duration },
7333    #[error(
7334        ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
7335         (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
7336         rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
7337         is structurally so long that transient failures are never forgotten, the breaker \
7338         trips once and stays tripped for the lifetime of the component, and every typed-slot \
7339         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
7340         outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
7341         Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
7342         default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
7343         the breaker entirely"
7344    )]
7345    PolicyBreakerWindowExceedsCap { window: Duration },
7346}
7347
7348#[cfg(test)]
7349mod tests {
7350    use super::*;
7351
7352    fn membro(name: &str, ver: &str) -> Membro {
7353        Membro {
7354            caixa: name.into(),
7355            versao: ver.into(),
7356        }
7357    }
7358
7359    fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
7360        WitContract {
7361            de: de.into(),
7362            para: para.into(),
7363            wit: "wasi:http/proxy".into(),
7364            endpoint: Some(ep.into()),
7365            subject: None,
7366            slot: None,
7367        }
7368    }
7369
7370    fn three_member_spec() -> AplicacaoSpec {
7371        AplicacaoSpec {
7372            membros: vec![
7373                membro("catalog", "^0.1"),
7374                membro("cart", "^0.1"),
7375                membro("payment", "^0.2"),
7376            ],
7377            contratos: vec![
7378                contract_http("cart", "catalog", "/products/:id"),
7379                contract_http("cart", "payment", "/charge"),
7380            ],
7381            politicas: MeshPolicy {
7382                timeout: Some(Duration::from_secs(30)),
7383                retries: Some(3),
7384                mtls_required: Some(true),
7385                ..Default::default()
7386            },
7387            placement: Placement {
7388                estrategia: PlacementStrategy::Replicated,
7389                clusters: vec!["rio".into(), "mar".into()],
7390                affinity: Some("data-locality".into()),
7391                shard_key: None,
7392            },
7393            entrada: Some(Entrada {
7394                host: "checkout.quero.cloud".into(),
7395                para: "cart".into(),
7396                paths: vec!["/api/cart".into(), "/api/products".into()],
7397                port: 8080,
7398            }),
7399        }
7400    }
7401
7402    #[test]
7403    fn happy_path_validates() {
7404        three_member_spec().validate().unwrap();
7405    }
7406
7407    #[test]
7408    fn rejects_empty_membros() {
7409        let mut s = three_member_spec();
7410        s.membros = vec![];
7411        assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
7412    }
7413
7414    #[test]
7415    fn rejects_empty_membro_caixa() {
7416        // A `:caixa ""` entry has no name to render into programs.yaml
7417        // and no caixa.lisp to resolve at lacre time.
7418        let mut s = three_member_spec();
7419        s.membros[1].caixa = String::new();
7420        assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
7421    }
7422
7423    #[test]
7424    fn rejects_empty_membro_versao() {
7425        // A `:versao ""` entry can't pin a semver constraint, so the
7426        // lacre pipeline fails far from the source.
7427        let mut s = three_member_spec();
7428        s.membros[2].versao = String::new();
7429        let err = s.validate().unwrap_err();
7430        assert!(
7431            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
7432            "got {err:?}"
7433        );
7434    }
7435
7436    #[test]
7437    fn rejects_duplicate_membro_caixa() {
7438        // Two `:membros` entries with the same `:caixa` collapse to one
7439        // node in the membership HashSet, which masks `:contratos`
7440        // membership errors and produces duplicate programs.yaml entries.
7441        let mut s = three_member_spec();
7442        s.membros.push(membro("cart", "^0.2"));
7443        let err = s.validate().unwrap_err();
7444        assert!(
7445            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
7446            "got {err:?}"
7447        );
7448    }
7449
7450    #[test]
7451    fn rejects_invalid_membro_versao_requirement() {
7452        // The fail-before-pass-after pin: a non-empty but malformed
7453        // semver requirement (`"^bad-version"`) silently passed
7454        // `validate()` on every pre-gate codebase because the prior
7455        // shape only refused the empty string. The parse failure
7456        // surfaced far downstream at lacre-resolve time with a
7457        // `semver::Error` that didn't name which `:membros` entry
7458        // carried the typo. The new gate moves the check to caixa-build
7459        // time at the source caixa.lisp.
7460        let mut s = three_member_spec();
7461        s.membros[2].versao = "^bad-version".into();
7462        let err = s.validate().unwrap_err();
7463        assert!(
7464            matches!(
7465                err,
7466                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
7467                    if caixa == "payment" && versao == "^bad-version"
7468            ),
7469            "got {err:?}"
7470        );
7471    }
7472
7473    #[test]
7474    fn rejects_membro_versao_with_double_caret_typo() {
7475        // `"^^0.1"` is the canonical doubled-caret typo — looks like a
7476        // Cargo-shaped requirement on first glance but fails the parser
7477        // because semver doesn't accept stacked operators. Pin this
7478        // adjacent-shape footgun explicitly so a future relaxation that
7479        // accepts "looks-canonical-but-isn't" forms surfaces here.
7480        let mut s = three_member_spec();
7481        s.membros[0].versao = "^^0.1".into();
7482        let err = s.validate().unwrap_err();
7483        assert!(
7484            matches!(
7485                err,
7486                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
7487                    if caixa == "catalog" && versao == "^^0.1"
7488            ),
7489            "got {err:?}"
7490        );
7491    }
7492
7493    #[test]
7494    fn rejects_membro_versao_with_v_prefixed_tag() {
7495        // `"v0.1"` is the canonical "git-tag-shape leaking into the
7496        // semver requirement slot" typo — an author copies the
7497        // publish-side git-tag string verbatim into `:versao`, but
7498        // Cargo's semver parser rejects the leading `v` (only digits +
7499        // canonical operators are valid in the major-version
7500        // position). The gate's diagnostic names which member entry
7501        // carried the v-prefix so the fix is one edit, not a grep
7502        // through every member's `:versao`. (Note: bare `x`-glob
7503        // shorthands like `^0.1.x` are *accepted* by the semver crate
7504        // as an `*` wildcard on the patch axis — they're a Cargo-side
7505        // valid shape, not a typo, so the gate intentionally lets them
7506        // through.)
7507        let mut s = three_member_spec();
7508        s.membros[1].versao = "v0.1".into();
7509        let err = s.validate().unwrap_err();
7510        assert!(
7511            matches!(
7512                err,
7513                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
7514                    if caixa == "cart" && versao == "v0.1"
7515            ),
7516            "got {err:?}"
7517        );
7518    }
7519
7520    #[test]
7521    fn accepts_canonical_membro_versao_forms() {
7522        // The four Cargo-shaped requirement forms `:deps :versao`
7523        // already accepts via `crate::parse_requirement` must pass the
7524        // membros gate without re-validating at the resolver layer.
7525        // Pin every leg so a future tightening of the canonical set
7526        // surfaces here as a test failure.
7527        for form in [
7528            "^0.1",      // caret — minor-range pin (the most common shape)
7529            "~0.1.2",    // tilde — patch-range pin
7530            "0.1.0",     // exact — single-version pin
7531            "*",         // wildcard — explicitly any-version (semver::VersionReq::STAR)
7532            ">=0.1, <2", // multi-range — comma-separated comparators
7533        ] {
7534            let mut s = three_member_spec();
7535            for m in &mut s.membros {
7536                m.versao = form.into();
7537            }
7538            s.validate()
7539                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
7540        }
7541    }
7542
7543    #[test]
7544    fn membro_versao_empty_takes_precedence_over_invalid() {
7545        // Order pin: the existing `MembroVersaoEmpty` diagnostic
7546        // (which doesn't try to parse) fires before the new
7547        // `MembroVersaoInvalid` parse-side diagnostic, so an empty
7548        // `:versao` keeps its narrower error message — `parse_requirement`
7549        // would also reject `""`, but the empty-string arm is the more
7550        // self-locating diagnostic for the author.
7551        let mut s = three_member_spec();
7552        s.membros[1].versao = String::new();
7553        let err = s.validate().unwrap_err();
7554        assert!(
7555            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
7556            "got {err:?}"
7557        );
7558    }
7559
7560    #[test]
7561    fn membro_versao_invalid_fires_before_duplicate_check() {
7562        // Order pin: a malformed requirement on a non-duplicate entry
7563        // surfaces *its own* diagnostic (which names the offending
7564        // `:versao` string), even when a later entry would otherwise
7565        // collapse onto an earlier name. The per-entry shape gate runs
7566        // inline before the duplicate-key insert, parallel to
7567        // `membros_validation_runs_before_contratos_membership_check`
7568        // and `duplicate_contrato_gate_runs_after_target_shape_check`.
7569        let mut s = three_member_spec();
7570        s.membros[0].versao = "^bad".into();
7571        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
7572        let err = s.validate().unwrap_err();
7573        assert!(
7574            matches!(
7575                err,
7576                AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
7577            ),
7578            "got {err:?}"
7579        );
7580    }
7581
7582    #[test]
7583    fn membro_versao_invalid_diagnostic_carries_offending_versao() {
7584        // The diagnostic-shape pin: the error names the offending
7585        // `:versao` value verbatim so the author can grep their
7586        // caixa.lisp without re-running the build, and carries a
7587        // non-empty `reason` from `semver::VersionReq::parse` so the
7588        // parser's own wording flows through to the diagnostic.
7589        let mut s = three_member_spec();
7590        s.membros[2].versao = "not-a-req".into();
7591        let err = s.validate().unwrap_err();
7592        let AplicacaoError::MembroVersaoInvalid {
7593            caixa,
7594            versao,
7595            reason,
7596        } = err
7597        else {
7598            panic!("expected MembroVersaoInvalid, got other variant");
7599        };
7600        assert_eq!(caixa, "payment");
7601        assert_eq!(versao, "not-a-req");
7602        assert!(
7603            !reason.is_empty(),
7604            "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
7605        );
7606    }
7607
7608    #[test]
7609    fn membro_versao_invalid_runs_before_contratos_check() {
7610        // A malformed `:versao` on any member must surface its own
7611        // diagnostic (which names *which* member to fix) before any
7612        // `:contratos` membership lookup raises `ContratoMemberMissing`.
7613        // The `:contratos` gate runs after `validate_membros`, so this
7614        // is structurally guaranteed — pin it explicitly so a future
7615        // refactor that reorders the gates surfaces here.
7616        let mut s = three_member_spec();
7617        s.membros[1].versao = "^^0.1".into();
7618        // Add a contrato whose `:para` doesn't exist — would normally
7619        // raise ContratoMemberMissing at the membership lookup, but
7620        // the membros gate must fire first.
7621        s.contratos
7622            .push(contract_http("cart", "phantom", "/never-reached"));
7623        let err = s.validate().unwrap_err();
7624        assert!(
7625            matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
7626            "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
7627        );
7628    }
7629
7630    #[test]
7631    fn membros_validation_runs_before_contratos_membership_check() {
7632        // If `:membros` carries a duplicate, the membership-collapse
7633        // would silently accept a `:contratos :para "phantom"` so long
7634        // as some entry hashes to "phantom". Pinning order: the
7635        // duplicate-membros error fires first, regardless of whether
7636        // contratos reference real members.
7637        let mut s = three_member_spec();
7638        s.membros = vec![
7639            membro("cart", "^0.1"),
7640            membro("cart", "^0.2"),
7641            membro("catalog", "^0.1"),
7642            membro("payment", "^0.1"),
7643        ];
7644        let err = s.validate().unwrap_err();
7645        assert!(
7646            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
7647            "got {err:?}"
7648        );
7649    }
7650
7651    #[test]
7652    fn distinct_membros_validate() {
7653        // Pin the happy-path: every `:membros` entry has a non-empty
7654        // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
7655        // The fixture already satisfies this; this test makes the
7656        // invariant explicit so a future refactor of the fixture can't
7657        // silently break the guarantee.
7658        three_member_spec().validate().unwrap();
7659    }
7660
7661    // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
7662
7663    #[test]
7664    fn rejects_membro_caixa_with_uppercase() {
7665        // The canonical "I copied the Servico's display name verbatim"
7666        // typo — caixa names are lowercase per K8s DNS-1123 label rule,
7667        // but author tools often round-trip a TitleCase or CamelCase
7668        // identifier from an ADR or a sketch. Pin the diagnostic names
7669        // the offending name and suggests the lower-cased fix in one
7670        // edit, mirroring the `rejects_entrada_host_with_uppercase`
7671        // gate's shape (c7d05ec).
7672        let mut s = three_member_spec();
7673        s.membros[1].caixa = "Cart".into();
7674        let err = s.validate().unwrap_err();
7675        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
7676            panic!("expected MembroCaixaInvalid, got other variant");
7677        };
7678        assert_eq!(caixa, "Cart");
7679        assert!(
7680            reason.contains("uppercase"),
7681            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
7682        );
7683        assert!(
7684            reason.contains("\"cart\""),
7685            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
7686        );
7687    }
7688
7689    #[test]
7690    fn rejects_membro_caixa_with_underscore() {
7691        // The canonical "I'm thinking of a Python module / Postgres
7692        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
7693        // label schema. K8s rejects `metadata.name: my_cart` at admission
7694        // time with an opaque `field is invalid` (no source-citing
7695        // diagnostic). The gate moves it to caixa-build time.
7696        let mut s = three_member_spec();
7697        s.membros[0].caixa = "my_cart".into();
7698        let err = s.validate().unwrap_err();
7699        assert!(
7700            matches!(
7701                err,
7702                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
7703                    if caixa == "my_cart" && reason.contains('_')
7704            ),
7705            "got {err:?}"
7706        );
7707    }
7708
7709    #[test]
7710    fn rejects_membro_caixa_with_dot() {
7711        // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
7712        // subdomain — even though K8s `metadata.name` itself accepts
7713        // dots (DNS-1123 subdomain rule), this string also lands as a
7714        // K8s Service name (DNS-1035 label — no dots) and as a label
7715        // value on identity-based Cilium selectors. The strictest floor
7716        // among the use sites wins. The "I want to namespace my member
7717        // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
7718        let mut s = three_member_spec();
7719        s.membros[2].caixa = "team.cart".into();
7720        let err = s.validate().unwrap_err();
7721        assert!(
7722            matches!(
7723                err,
7724                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
7725                    if caixa == "team.cart" && reason.contains('.')
7726            ),
7727            "got {err:?}"
7728        );
7729    }
7730
7731    #[test]
7732    fn rejects_membro_caixa_with_leading_hyphen() {
7733        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
7734        // with an alphanumeric. The K8s apiserver rejects `-cart`
7735        // outright; the renderer would emit a `metadata.name: "-cart"`
7736        // that fails admission far from the source caixa.lisp.
7737        let mut s = three_member_spec();
7738        s.membros[0].caixa = "-cart".into();
7739        let err = s.validate().unwrap_err();
7740        assert!(
7741            matches!(
7742                err,
7743                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
7744                    if caixa == "-cart" && reason.contains("start and end")
7745            ),
7746            "got {err:?}"
7747        );
7748    }
7749
7750    #[test]
7751    fn rejects_membro_caixa_with_trailing_hyphen() {
7752        // The symmetric arm of the boundary rule. Pin separately so
7753        // both ends of the label are covered against a future relaxation
7754        // that only checks one boundary.
7755        let mut s = three_member_spec();
7756        s.membros[1].caixa = "cart-".into();
7757        let err = s.validate().unwrap_err();
7758        assert!(
7759            matches!(
7760                err,
7761                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
7762                    if caixa == "cart-"
7763            ),
7764            "got {err:?}"
7765        );
7766    }
7767
7768    #[test]
7769    fn rejects_membro_caixa_with_unicode() {
7770        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
7771        // (`xn--…`) by the author before it reaches K8s. The byte-by-
7772        // byte ASCII validity check rejects multi-byte UTF-8 sequences
7773        // by the first byte that fails the `[a-z0-9-]` predicate.
7774        let mut s = three_member_spec();
7775        s.membros[2].caixa = "café".into();
7776        let err = s.validate().unwrap_err();
7777        assert!(
7778            matches!(
7779                err,
7780                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
7781                    if caixa == "café"
7782            ),
7783            "got {err:?}"
7784        );
7785    }
7786
7787    #[test]
7788    fn rejects_membro_caixa_with_whitespace() {
7789        // Whitespace is the canonical "I pasted from a sketch / doc"
7790        // footgun. The apiserver rejects every `metadata.name` value
7791        // carrying whitespace; pin the gate fires at the right boundary.
7792        let mut s = three_member_spec();
7793        s.membros[0].caixa = "my cart".into();
7794        let err = s.validate().unwrap_err();
7795        assert!(
7796            matches!(
7797                err,
7798                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
7799                    if caixa == "my cart"
7800            ),
7801            "got {err:?}"
7802        );
7803    }
7804
7805    #[test]
7806    fn rejects_membro_caixa_too_long() {
7807        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
7808        // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
7809        // exactly. The gate's reason names both the cap and the actual
7810        // length so the author can shorten in one edit.
7811        let mut s = three_member_spec();
7812        let too_long = "a".repeat(64);
7813        s.membros[1].caixa = too_long.clone();
7814        let err = s.validate().unwrap_err();
7815        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
7816            panic!("expected MembroCaixaInvalid");
7817        };
7818        assert_eq!(caixa, too_long);
7819        assert!(
7820            reason.contains("63") && reason.contains("64"),
7821            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
7822        );
7823    }
7824
7825    #[test]
7826    fn membro_caixa_max_length_validates() {
7827        // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
7828        // so a future tightening (e.g. dropping to 62) surfaces here as
7829        // a regression, mirroring `entrada_host_max_length_validates`
7830        // (c7d05ec).
7831        let mut s = three_member_spec();
7832        s.membros[2].caixa = "a".repeat(63);
7833        s.entrada.as_mut().unwrap().para = "a".repeat(63);
7834        // remove contratos referencing the renamed member; they'd
7835        // raise ContratoMemberMissing otherwise
7836        s.contratos
7837            .retain(|c| c.de != "payment" && c.para != "payment");
7838        s.validate().unwrap();
7839    }
7840
7841    #[test]
7842    fn accepts_canonical_membro_caixa_forms() {
7843        // The DNS-1123 label shapes a caixa author is realistically
7844        // going to write: single-word lowercase, hyphen-joined, ending
7845        // in a digit-suffixed version (`cart-v2`), starting with a
7846        // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
7847        // DNS-1035 which requires a letter at position 0), single-
7848        // character (`a` — boundary). Pin every leg so a future
7849        // tightening that bans (e.g.) digit-start identifiers surfaces
7850        // here.
7851        for form in [
7852            "checkout",
7853            "cart",
7854            "cart-v2",
7855            "a",
7856            "c0",
7857            "3rd-party-shim",
7858            "x-1-2-3-4",
7859        ] {
7860            let mut s = three_member_spec();
7861            // Renaming a member also requires updating downstream refs;
7862            // drop everything else and rebuild a minimal spec around
7863            // just the one renamed member.
7864            s.membros = vec![membro(form, "^0.1")];
7865            s.contratos = vec![];
7866            s.entrada = None;
7867            s.validate()
7868                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
7869        }
7870    }
7871
7872    #[test]
7873    fn membro_caixa_empty_takes_precedence_over_invalid() {
7874        // Order pin: the existing `MembroCaixaEmpty` diagnostic
7875        // (which doesn't try to parse) fires before the new
7876        // `MembroCaixaInvalid` parse-side diagnostic, so an empty
7877        // `:caixa` keeps its narrower error message — the new gate
7878        // would also reject `""`, but the empty-string arm is the more
7879        // self-locating diagnostic for the author. Mirrors the
7880        // `entrada_host_empty_takes_precedence_over_invalid` pin
7881        // (c7d05ec).
7882        let mut s = three_member_spec();
7883        s.membros[1].caixa = String::new();
7884        let err = s.validate().unwrap_err();
7885        assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
7886    }
7887
7888    #[test]
7889    fn membro_caixa_invalid_fires_before_versao_check() {
7890        // Order pin: an invalid-shape `:caixa` surfaces *its own*
7891        // diagnostic (which names the offending caixa name), even when
7892        // the same entry's `:versao` is also empty/invalid. The shape
7893        // gate runs first because the diagnostic is more self-locating —
7894        // an empty/invalid `:versao` on an invalid-shape caixa name is
7895        // a downstream-fix-after-the-caixa-rename concern.
7896        let mut s = three_member_spec();
7897        s.membros[1].caixa = "Cart".into();
7898        s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
7899        let err = s.validate().unwrap_err();
7900        assert!(
7901            matches!(
7902                err,
7903                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
7904            ),
7905            "got {err:?}"
7906        );
7907    }
7908
7909    #[test]
7910    fn membro_caixa_invalid_fires_before_duplicate_check() {
7911        // Order pin: a malformed-shape `:caixa` on an earlier entry
7912        // surfaces *its own* diagnostic, even when a later entry would
7913        // otherwise collapse onto a duplicate name. The per-entry shape
7914        // gate runs inline before the duplicate-key insert, parallel
7915        // to `membro_versao_invalid_fires_before_duplicate_check`.
7916        let mut s = three_member_spec();
7917        s.membros[0].caixa = "Catalog".into();
7918        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
7919        let err = s.validate().unwrap_err();
7920        assert!(
7921            matches!(
7922                err,
7923                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
7924            ),
7925            "got {err:?}"
7926        );
7927    }
7928
7929    #[test]
7930    fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
7931        // The diagnostic-shape pin: the error names the offending
7932        // `:caixa` value verbatim so the author can grep their
7933        // caixa.lisp without re-running the build, and carries a
7934        // non-empty `reason` naming the specific violation. Same
7935        // shape every typed-shape gate enshrines (c7d05ec's
7936        // `entrada_host_diagnostic_carries_offending_host`,
7937        // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
7938        let mut s = three_member_spec();
7939        s.membros[2].caixa = "BAD_NAME".into();
7940        let err = s.validate().unwrap_err();
7941        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
7942            panic!("expected MembroCaixaInvalid");
7943        };
7944        assert_eq!(caixa, "BAD_NAME");
7945        assert!(
7946            !reason.is_empty(),
7947            "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
7948        );
7949    }
7950
7951    #[test]
7952    fn rejects_contrato_with_unknown_de() {
7953        let mut s = three_member_spec();
7954        s.contratos.push(contract_http("phantom", "catalog", "/x"));
7955        let err = s.validate().unwrap_err();
7956        assert!(
7957            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
7958        );
7959    }
7960
7961    #[test]
7962    fn rejects_contrato_with_unknown_para() {
7963        let mut s = three_member_spec();
7964        s.contratos.push(contract_http("cart", "phantom", "/x"));
7965        let err = s.validate().unwrap_err();
7966        assert!(
7967            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
7968        );
7969    }
7970
7971    #[test]
7972    fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
7973        // The read-path pin: the phantom-`:de` refusal arm's
7974        // `ContratoMemberMissing.caixa` carrier must be observed through
7975        // the lifted [`WitContract::source`] accessor, not the raw
7976        // `.de.clone()` field-access `String`-carry. Peer of the sibling
7977        // per-`:contratos` self-loop arm's `.source().to_string()` /
7978        // `.world_ref().to_string()` `String`-carry sites the earlier
7979        // convergence lifted onto the same accessor pair. A future
7980        // silent detour that reintroduced the raw `.de.clone()` at the
7981        // wrap envelope while the shape-gate and membership lookup
7982        // routed through the accessor would surface here as a byte-equal
7983        // miss between the fired diagnostic's `caixa:` field and the
7984        // offending edge's `.source()` — pinning the accessor as the
7985        // sole read path across the phantom-name refusal arm's arg +
7986        // wrap-envelope emit surface.
7987        let mut s = three_member_spec();
7988        let phantom = contract_http("phantom", "catalog", "/x");
7989        s.contratos.push(phantom.clone());
7990        let err = s.validate().unwrap_err();
7991        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
7992            panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
7993        };
7994        assert_eq!(
7995            caixa,
7996            phantom.source(),
7997            "ContratoMemberMissing.caixa on the phantom-:de arm must \
7998             byte-equal WitContract::source — the wrap envelope must \
7999             route through the lifted accessor rather than the raw \
8000             .de.clone() field-access String-carry"
8001        );
8002    }
8003
8004    #[test]
8005    fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
8006        // The symmetric read-path pin on the `:para` phantom-name
8007        // refusal arm — same shape as the sibling `:de` pin above but
8008        // on the callee-Servico axis. Pins the wrap envelope's
8009        // `caixa:` field is observed through the lifted
8010        // [`WitContract::destination`] accessor, not the raw
8011        // `.para.clone()` field-access `String`-carry.
8012        let mut s = three_member_spec();
8013        let phantom = contract_http("cart", "phantom", "/x");
8014        s.contratos.push(phantom.clone());
8015        let err = s.validate().unwrap_err();
8016        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
8017            panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
8018        };
8019        assert_eq!(
8020            caixa,
8021            phantom.destination(),
8022            "ContratoMemberMissing.caixa on the phantom-:para arm must \
8023             byte-equal WitContract::destination — the wrap envelope \
8024             must route through the lifted accessor rather than the raw \
8025             .para.clone() field-access String-carry"
8026        );
8027    }
8028
8029    #[test]
8030    fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
8031        // The read-path pin on the `:de` DNS-1123-malformed shape-gate
8032        // refusal arm — the `validate_contrato_caixa` arg must be
8033        // observed through the lifted [`WitContract::source`] accessor,
8034        // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
8035        // value routes through the shared
8036        // [`crate::render::require_valid_dns_1123_label`] floor with the
8037        // accessor-projected value; the fired
8038        // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
8039        // the offending edge's `.source()`, pinning that the arg + the
8040        // downstream `caixa: caixa.to_string()` wrap route through the
8041        // same accessor's read path.
8042        let mut s = three_member_spec();
8043        let malformed = contract_http("BAD_NAME", "catalog", "/x");
8044        s.contratos.push(malformed.clone());
8045        let err = s.validate().unwrap_err();
8046        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
8047            panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
8048        };
8049        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
8050        assert_eq!(
8051            caixa,
8052            malformed.source(),
8053            "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
8054             byte-equal WitContract::source — the shape-gate arg + wrap \
8055             envelope must route through the lifted accessor rather \
8056             than the raw &c.de &String-borrow"
8057        );
8058    }
8059
8060    #[test]
8061    fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
8062        // Symmetric arm to the sibling `:de` malformed-shape pin above,
8063        // on the `:para` axis. Pins the shape-gate arg + wrap envelope
8064        // route through the lifted [`WitContract::destination`]
8065        // accessor. `:para` runs after the `:de` shape gate in the
8066        // canonical edge-direction order, so the `:de` value must be
8067        // well-shaped for the `:para` gate to fire — the `cart` :de is
8068        // canonical.
8069        let mut s = three_member_spec();
8070        let malformed = contract_http("cart", "BAD_NAME", "/x");
8071        s.contratos.push(malformed.clone());
8072        let err = s.validate().unwrap_err();
8073        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
8074            panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
8075        };
8076        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
8077        assert_eq!(
8078            caixa,
8079            malformed.destination(),
8080            "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
8081             byte-equal WitContract::destination — the shape-gate arg + \
8082             wrap envelope must route through the lifted accessor \
8083             rather than the raw &c.para &String-borrow"
8084        );
8085    }
8086
8087    // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
8088
8089    #[test]
8090    fn rejects_contrato_de_empty() {
8091        // `:de ""` previously fell through to `ContratoMemberMissing`
8092        // (with `caixa: ""`) because the validated `:membros :caixa`
8093        // set never contains the empty string. The narrower
8094        // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
8095        // the offending slot.
8096        let mut s = three_member_spec();
8097        s.contratos.push(contract_http("", "catalog", "/x"));
8098        let err = s.validate().unwrap_err();
8099        assert_eq!(
8100            err,
8101            AplicacaoError::ContratoCaixaEmpty {
8102                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
8103            },
8104            "got {err:?}"
8105        );
8106    }
8107
8108    #[test]
8109    fn rejects_contrato_para_empty() {
8110        // Symmetric arm to `:de ""` — `:para ""` previously fell
8111        // through to `ContratoMemberMissing { caixa: "" }`.
8112        let mut s = three_member_spec();
8113        s.contratos.push(contract_http("cart", "", "/x"));
8114        let err = s.validate().unwrap_err();
8115        assert_eq!(
8116            err,
8117            AplicacaoError::ContratoCaixaEmpty {
8118                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
8119            },
8120            "got {err:?}"
8121        );
8122    }
8123
8124    #[test]
8125    fn rejects_contrato_de_with_uppercase() {
8126        // The canonical "I copied the Servico's TitleCase display
8127        // name from an ADR" typo. Until this gate landed `:de "Cart"`
8128        // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
8129        // as "this caixa isn't in `:membros`" when the root cause is
8130        // "this `:de` value's shape can never legitimately match a
8131        // validated member (DNS-1123 labels are lowercase)". The
8132        // narrower diagnostic names the offending slot, the value
8133        // verbatim, and the parser-shaped reason.
8134        let mut s = three_member_spec();
8135        s.contratos.push(contract_http("Cart", "catalog", "/x"));
8136        let err = s.validate().unwrap_err();
8137        let AplicacaoError::ContratoCaixaInvalid {
8138            slot,
8139            caixa,
8140            reason,
8141        } = err
8142        else {
8143            panic!("expected ContratoCaixaInvalid, got other variant");
8144        };
8145        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
8146        assert_eq!(caixa, "Cart");
8147        assert!(
8148            reason.contains("uppercase"),
8149            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
8150        );
8151    }
8152
8153    #[test]
8154    fn rejects_contrato_para_with_underscore() {
8155        // The canonical "I'm thinking of a Python module" leak —
8156        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
8157        // Pin the `:para` axis surfaces the same diagnostic shape as
8158        // the `:de` axis on the underscore violation.
8159        let mut s = three_member_spec();
8160        s.contratos.push(contract_http("cart", "my_catalog", "/x"));
8161        let err = s.validate().unwrap_err();
8162        assert!(
8163            matches!(
8164                err,
8165                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
8166                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
8167            ),
8168            "got {err:?}"
8169        );
8170    }
8171
8172    #[test]
8173    fn rejects_contrato_de_with_dot() {
8174        // A `:contratos :de` value is a single DNS-1123 *label*, not
8175        // a subdomain — mirroring the `:membros :caixa` floor. The
8176        // strictest floor among the use sites wins.
8177        let mut s = three_member_spec();
8178        s.contratos
8179            .push(contract_http("team.cart", "catalog", "/x"));
8180        let err = s.validate().unwrap_err();
8181        assert!(
8182            matches!(
8183                err,
8184                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
8185                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
8186            ),
8187            "got {err:?}"
8188        );
8189    }
8190
8191    #[test]
8192    fn rejects_contrato_para_with_unicode() {
8193        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
8194        // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
8195        // validity check rejects multi-byte UTF-8 by the first
8196        // non-`[a-z0-9-]` byte.
8197        let mut s = three_member_spec();
8198        s.contratos.push(contract_http("cart", "café", "/x"));
8199        let err = s.validate().unwrap_err();
8200        assert!(
8201            matches!(
8202                err,
8203                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
8204                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
8205            ),
8206            "got {err:?}"
8207        );
8208    }
8209
8210    #[test]
8211    fn rejects_contrato_de_with_leading_hyphen() {
8212        // DNS-1123 boundary rule: labels must start and end with an
8213        // alphanumeric. K8s rejects `-cart` outright; the narrower
8214        // shape diagnostic now names the violation at caixa-build
8215        // time rather than the misframed membership-lookup arm.
8216        let mut s = three_member_spec();
8217        s.contratos.push(contract_http("-cart", "catalog", "/x"));
8218        let err = s.validate().unwrap_err();
8219        assert!(
8220            matches!(
8221                err,
8222                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
8223                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
8224            ),
8225            "got {err:?}"
8226        );
8227    }
8228
8229    #[test]
8230    fn contrato_de_empty_takes_precedence_over_invalid() {
8231        // Order pin: the `ContratoCaixaEmpty` arm fires before the
8232        // `ContratoCaixaInvalid` parse-side arm — same empty-first
8233        // cascade `validate_membro_caixa` / `validate_placement_cluster`
8234        // / `validate_entrada_host` already establish on their peer
8235        // name axes. The empty string is a structurally distinct
8236        // authoring footgun (the author left the field blank, vs.
8237        // typed a malformed value), so it gets its own diagnostic.
8238        let mut s = three_member_spec();
8239        s.contratos.push(contract_http("", "catalog", "/x"));
8240        let err = s.validate().unwrap_err();
8241        assert_eq!(
8242            err,
8243            AplicacaoError::ContratoCaixaEmpty {
8244                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
8245            }
8246        );
8247    }
8248
8249    #[test]
8250    fn contrato_de_shape_fires_before_para_shape() {
8251        // Per-axis order pin: within one `:contratos` entry, the `:de`
8252        // shape gate fires before the `:para` shape gate — same
8253        // edge-direction order the existing `ContratoMemberMissing` /
8254        // `ContratoSelfLoop` / target-dispatch checks use, so the
8255        // diagnostic for a contract with both `:de` and `:para`
8256        // malformed is stable. Authors fixing the surfaced `:de`
8257        // first will see `:para`'s diagnostic on re-run.
8258        let mut s = three_member_spec();
8259        s.contratos.push(contract_http("Cart", "Catalog", "/x"));
8260        let err = s.validate().unwrap_err();
8261        assert!(
8262            matches!(
8263                err,
8264                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
8265                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
8266            ),
8267            "got {err:?}"
8268        );
8269    }
8270
8271    #[test]
8272    fn contrato_shape_fires_before_membership_lookup() {
8273        // The load-bearing pin: an invalid-shape `:de` surfaces its
8274        // *own* diagnostic, not the misframed `ContratoMemberMissing`.
8275        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
8276        // an invalid-shape `:de` could never legitimately match any
8277        // member — the prior `ContratoMemberMissing` diagnostic was
8278        // a structural impossibility framed as a graph-membership
8279        // failure. The shape gate now routes every such input through
8280        // the narrower self-locating diagnostic.
8281        let mut s = three_member_spec();
8282        s.contratos.push(contract_http("Cart", "catalog", "/x"));
8283        let err = s.validate().unwrap_err();
8284        assert!(
8285            matches!(
8286                err,
8287                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
8288            ),
8289            "got {err:?}"
8290        );
8291        // And the symmetric case: an invalid-shape `:para` surfaces
8292        // its own diagnostic too, even when `:de` is well-shaped.
8293        let mut s = three_member_spec();
8294        s.contratos.push(contract_http("cart", "Catalog", "/x"));
8295        let err = s.validate().unwrap_err();
8296        assert!(
8297            matches!(
8298                err,
8299                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
8300            ),
8301            "got {err:?}"
8302        );
8303    }
8304
8305    #[test]
8306    fn contrato_shape_fires_before_self_edge_check() {
8307        // A `:de "Cart" :para "Cart"` entry is two distinct authoring
8308        // bugs: the shape violation (uppercase) and the self-edge
8309        // violation. The narrower per-axis shape diagnostic surfaces
8310        // first because fixing the shape may reveal that the author
8311        // also meant to point `:para` at a different member — the
8312        // self-edge framing is only useful once both endpoints have
8313        // valid shape.
8314        let mut s = three_member_spec();
8315        s.contratos.push(contract_http("Cart", "Cart", "/x"));
8316        let err = s.validate().unwrap_err();
8317        assert!(
8318            matches!(
8319                err,
8320                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
8321                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
8322            ),
8323            "got {err:?}"
8324        );
8325    }
8326
8327    #[test]
8328    fn contrato_well_shaped_phantom_still_raises_member_missing() {
8329        // Strict-improvement pin: a well-shaped `:de` that simply
8330        // isn't in `:membros` (a phantom reference — author meant
8331        // to add the member but didn't, or renamed and missed an
8332        // update) still surfaces `ContratoMemberMissing`, unchanged.
8333        // The shape gate only intercepts inputs that could never
8334        // legitimately match a validated member; legitimately-shaped
8335        // phantom references remain on the graph-membership axis.
8336        let mut s = three_member_spec();
8337        s.contratos
8338            .push(contract_http("phantom-shim", "catalog", "/x"));
8339        let err = s.validate().unwrap_err();
8340        assert!(
8341            matches!(
8342                err,
8343                AplicacaoError::ContratoMemberMissing { ref caixa }
8344                    if caixa == "phantom-shim"
8345            ),
8346            "got {err:?}"
8347        );
8348    }
8349
8350    #[test]
8351    fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
8352        // The diagnostic-shape pin: the error names the offending
8353        // slot (`:de` or `:para`) verbatim and the offending value
8354        // verbatim plus a non-empty parser-shaped reason, so the
8355        // author can grep their caixa.lisp for `:de "<name>"` /
8356        // `:para "<name>"` and fix it in one edit. Same diagnostic
8357        // shape as `MembroCaixaInvalid` (3f9d7a0) and
8358        // `PlacementClusterInvalid` (6c8c00b).
8359        let mut s = three_member_spec();
8360        s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
8361        let err = s.validate().unwrap_err();
8362        let AplicacaoError::ContratoCaixaInvalid {
8363            slot,
8364            caixa,
8365            reason,
8366        } = err
8367        else {
8368            panic!("expected ContratoCaixaInvalid, got {err:?}");
8369        };
8370        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
8371        assert_eq!(caixa, "BAD_NAME");
8372        assert!(
8373            !reason.is_empty(),
8374            "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
8375        );
8376    }
8377
8378    #[test]
8379    fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
8380        // Scalar-value pin: the two author-facing kebab-case labels the
8381        // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
8382        // admits on the `:contratos` per-entry endpoint-shape axis,
8383        // one arm per typed sub-slot. Mirrors the peer scalar-value
8384        // pin the sibling top-level M2 / M3 / Supervisor
8385        // author-facing-label consts carry
8386        // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
8387        // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
8388        // slot itself), so every altitude of the typed-slot algebra
8389        // shares the same "one canonical byte-string per arm"
8390        // discipline. A future rebrand (`:de` → `:from` matching the
8391        // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
8392        // sibling, `:para` → `:to` matching the same, or
8393        // `:de`/`:para` → `:source`/`:target` matching the WIT
8394        // world's `import`/`export` half-vocabulary) lands as an
8395        // edit to exactly one const, and every consumer that reaches
8396        // for the label picks it up at build time rather than at
8397        // runtime as a downstream `ContratoCaixaEmpty` /
8398        // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
8399        // diagnostic mismatch far from the rename's commit.
8400        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
8401        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
8402    }
8403
8404    #[test]
8405    fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
8406        // Production-through-const pin: the two per-axis labels the
8407        // per-`:contratos` entry endpoint-shape gate at
8408        // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
8409        // argument to [`validate_contrato_caixa`] route through the
8410        // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
8411        // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
8412        // future rebrand that reaches the const but not the gate (or
8413        // vice versa) surfaces here at build time rather than at
8414        // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
8415        // `slot: <stale-kebab-case>` diagnostic far from the rename's
8416        // commit. Mirror of the peer
8417        // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
8418        // pin (882f498) on the sibling M3 top-level slot axis.
8419        let mut s = three_member_spec();
8420        s.contratos.push(contract_http("", "catalog", "/x"));
8421        assert_eq!(
8422            s.validate().unwrap_err(),
8423            AplicacaoError::ContratoCaixaEmpty {
8424                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
8425            }
8426        );
8427        let mut s = three_member_spec();
8428        s.contratos.push(contract_http("cart", "", "/x"));
8429        assert_eq!(
8430            s.validate().unwrap_err(),
8431            AplicacaoError::ContratoCaixaEmpty {
8432                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
8433            }
8434        );
8435    }
8436
8437    #[test]
8438    fn accepts_canonical_contrato_caixa_forms() {
8439        // The DNS-1123 label shapes a caixa author is realistically
8440        // going to write on a `:contratos :de` / `:para`. Pin every
8441        // leg so a future tightening that bans (e.g.) digit-start
8442        // identifiers surfaces here, mirroring
8443        // `accepts_canonical_membro_caixa_forms` on the peer name
8444        // axis.
8445        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
8446            let mut s = three_member_spec();
8447            s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
8448            s.contratos = vec![contract_http("checkout", form, "/x")];
8449            s.entrada = None;
8450            s.validate().unwrap_or_else(|e| {
8451                panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
8452            });
8453
8454            let mut s = three_member_spec();
8455            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
8456            s.contratos = vec![contract_http(form, "catalog", "/x")];
8457            s.entrada = None;
8458            s.validate().unwrap_or_else(|e| {
8459                panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
8460            });
8461        }
8462    }
8463
8464    #[test]
8465    fn rejects_empty_wit() {
8466        let mut s = three_member_spec();
8467        s.contratos.push(WitContract {
8468            de: "cart".into(),
8469            para: "catalog".into(),
8470            wit: "".into(),
8471            endpoint: None,
8472            subject: None,
8473            slot: None,
8474        });
8475        let err = s.validate().unwrap_err();
8476        assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
8477    }
8478
8479    #[test]
8480    fn rejects_entrada_to_unknown_member() {
8481        let mut s = three_member_spec();
8482        s.entrada.as_mut().unwrap().para = "phantom".into();
8483        assert!(matches!(
8484            s.validate().unwrap_err(),
8485            AplicacaoError::EntradaMemberMissing { .. }
8486        ));
8487    }
8488
8489    // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
8490
8491    #[test]
8492    fn rejects_entrada_para_empty() {
8493        // `:para ""` previously fell through to
8494        // `EntradaMemberMissing { para: "" }` because the validated
8495        // `:membros :caixa` set never contains the empty string. The
8496        // narrower `EntradaParaEmpty` diagnostic now names the
8497        // offending slot directly — same empty-first cascade
8498        // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
8499        // `ContratoCaixaEmpty` establish on the peer name axes.
8500        let mut s = three_member_spec();
8501        s.entrada.as_mut().unwrap().para = String::new();
8502        let err = s.validate().unwrap_err();
8503        assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
8504    }
8505
8506    #[test]
8507    fn rejects_entrada_para_with_uppercase() {
8508        // The canonical "I copied the Servico's TitleCase display
8509        // name from an ADR" typo. Until this gate landed `:para "Cart"`
8510        // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
8511        // as "this caixa isn't in `:membros`" when the root cause is
8512        // "this `:para` value's shape can never legitimately match a
8513        // validated member (DNS-1123 labels are lowercase)". The
8514        // narrower diagnostic names the value verbatim plus the
8515        // parser-shaped reason.
8516        let mut s = three_member_spec();
8517        s.entrada.as_mut().unwrap().para = "Cart".into();
8518        let err = s.validate().unwrap_err();
8519        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
8520            panic!("expected EntradaParaInvalid, got other variant");
8521        };
8522        assert_eq!(para, "Cart");
8523        assert!(
8524            reason.contains("uppercase"),
8525            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
8526        );
8527    }
8528
8529    #[test]
8530    fn rejects_entrada_para_with_underscore() {
8531        // The canonical "I'm thinking of a Python module" leak —
8532        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
8533        let mut s = three_member_spec();
8534        s.entrada.as_mut().unwrap().para = "my_cart".into();
8535        let err = s.validate().unwrap_err();
8536        assert!(
8537            matches!(
8538                err,
8539                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8540                    if para == "my_cart" && reason.contains('_')
8541            ),
8542            "got {err:?}"
8543        );
8544    }
8545
8546    #[test]
8547    fn rejects_entrada_para_with_dot() {
8548        // An `:entrada :para` value is a single DNS-1123 *label*, not
8549        // a subdomain — mirroring the `:membros :caixa` floor. The
8550        // strictest floor among the use sites wins.
8551        let mut s = three_member_spec();
8552        s.entrada.as_mut().unwrap().para = "team.cart".into();
8553        let err = s.validate().unwrap_err();
8554        assert!(
8555            matches!(
8556                err,
8557                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8558                    if para == "team.cart" && reason.contains('.')
8559            ),
8560            "got {err:?}"
8561        );
8562    }
8563
8564    #[test]
8565    fn rejects_entrada_para_with_unicode() {
8566        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
8567        // (`xn--…`) before it reaches K8s.
8568        let mut s = three_member_spec();
8569        s.entrada.as_mut().unwrap().para = "café".into();
8570        let err = s.validate().unwrap_err();
8571        assert!(
8572            matches!(
8573                err,
8574                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
8575            ),
8576            "got {err:?}"
8577        );
8578    }
8579
8580    #[test]
8581    fn rejects_entrada_para_with_leading_hyphen() {
8582        // DNS-1123 boundary rule: labels must start and end with an
8583        // alphanumeric. K8s rejects `-cart` outright.
8584        let mut s = three_member_spec();
8585        s.entrada.as_mut().unwrap().para = "-cart".into();
8586        let err = s.validate().unwrap_err();
8587        assert!(
8588            matches!(
8589                err,
8590                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8591                    if para == "-cart" && reason.contains("start and end")
8592            ),
8593            "got {err:?}"
8594        );
8595    }
8596
8597    #[test]
8598    fn rejects_entrada_para_with_trailing_hyphen() {
8599        // Symmetric boundary arm.
8600        let mut s = three_member_spec();
8601        s.entrada.as_mut().unwrap().para = "cart-".into();
8602        let err = s.validate().unwrap_err();
8603        assert!(
8604            matches!(
8605                err,
8606                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8607                    if para == "cart-" && reason.contains("start and end")
8608            ),
8609            "got {err:?}"
8610        );
8611    }
8612
8613    #[test]
8614    fn rejects_entrada_para_too_long() {
8615        // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
8616        // bytes per label. K8s rejects longer names at admission on
8617        // every `metadata.name` axis.
8618        let mut s = three_member_spec();
8619        s.entrada.as_mut().unwrap().para = "a".repeat(64);
8620        let err = s.validate().unwrap_err();
8621        assert!(
8622            matches!(
8623                err,
8624                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8625                    if para.len() == 64 && reason.contains("max length")
8626            ),
8627            "got {err:?}"
8628        );
8629    }
8630
8631    #[test]
8632    fn entrada_para_empty_takes_precedence_over_invalid() {
8633        // Order pin: the `EntradaParaEmpty` arm fires before the
8634        // `EntradaParaInvalid` parse-side arm — same empty-first
8635        // cascade `validate_membro_caixa` / `validate_placement_cluster`
8636        // / `validate_contrato_caixa` already establish.
8637        let mut s = three_member_spec();
8638        s.entrada.as_mut().unwrap().para = String::new();
8639        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
8640    }
8641
8642    #[test]
8643    fn entrada_para_shape_fires_before_membership_lookup() {
8644        // The load-bearing pin: an invalid-shape `:para` surfaces its
8645        // *own* diagnostic, not the misframed `EntradaMemberMissing`.
8646        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
8647        // an invalid-shape `:para` could never legitimately match any
8648        // member — the prior `EntradaMemberMissing` diagnostic framed
8649        // a structural impossibility as a graph-membership failure.
8650        let mut s = three_member_spec();
8651        s.entrada.as_mut().unwrap().para = "Cart".into();
8652        let err = s.validate().unwrap_err();
8653        assert!(
8654            matches!(
8655                err,
8656                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
8657            ),
8658            "got {err:?}"
8659        );
8660    }
8661
8662    #[test]
8663    fn entrada_para_shape_fires_before_host_gate() {
8664        // Per-`:entrada` order pin: the `:para` shape gate fires
8665        // before the `:host` gate, mirroring the existing
8666        // `entrada_host_member_missing_takes_precedence_over_host_invalid`
8667        // ordering where the member-lookup arm preceded the host gate.
8668        // The shape gate slots ahead of that, so a malformed `:para`
8669        // surfaces its own diagnostic even when `:host` is also wrong.
8670        let mut s = three_member_spec();
8671        let e = s.entrada.as_mut().unwrap();
8672        e.para = "Cart".into();
8673        e.host = "BAD HOST".into();
8674        let err = s.validate().unwrap_err();
8675        assert!(
8676            matches!(
8677                err,
8678                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
8679            ),
8680            "got {err:?}"
8681        );
8682    }
8683
8684    #[test]
8685    fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
8686        // Strict-improvement pin: a well-shaped `:para` that simply
8687        // isn't in `:membros` (a phantom reference — author meant to
8688        // add the member but didn't, or renamed and missed an
8689        // update) still surfaces `EntradaMemberMissing`, unchanged.
8690        // The shape gate only intercepts inputs that could never
8691        // legitimately match a validated member.
8692        let mut s = three_member_spec();
8693        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
8694        let err = s.validate().unwrap_err();
8695        assert!(
8696            matches!(
8697                err,
8698                AplicacaoError::EntradaMemberMissing { ref para }
8699                    if para == "phantom-shim"
8700            ),
8701            "got {err:?}"
8702        );
8703    }
8704
8705    #[test]
8706    fn entrada_para_invalid_diagnostic_carries_offending_para() {
8707        // The diagnostic-shape pin: the error names the offending
8708        // `:para` value verbatim plus a non-empty parser-shaped
8709        // reason, so the author can grep their caixa.lisp for
8710        // `:para "<name>"` and fix it in one edit. Same diagnostic
8711        // shape as `MembroCaixaInvalid` (3f9d7a0),
8712        // `PlacementClusterInvalid` (6c8c00b), and
8713        // `ContratoCaixaInvalid` (8d5af6b).
8714        let mut s = three_member_spec();
8715        s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
8716        let err = s.validate().unwrap_err();
8717        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
8718            panic!("expected EntradaParaInvalid, got {err:?}");
8719        };
8720        assert_eq!(para, "BAD_NAME");
8721        assert!(
8722            !reason.is_empty(),
8723            "EntradaParaInvalid `reason` must carry a parser-shaped wording"
8724        );
8725    }
8726
8727    #[test]
8728    fn accepts_canonical_entrada_para_forms() {
8729        // Positive-control sweep covering the DNS-1123 label shapes a
8730        // caixa author is realistically going to write on `:entrada
8731        // :para`. Pin every leg so a future tightening that bans
8732        // (e.g.) digit-start identifiers surfaces here, mirroring
8733        // `accepts_canonical_membro_caixa_forms` and
8734        // `accepts_canonical_contrato_caixa_forms` on the peer name
8735        // axes.
8736        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
8737            let mut s = three_member_spec();
8738            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
8739            s.contratos = vec![contract_http(form, "catalog", "/x")];
8740            s.entrada = Some(Entrada {
8741                host: "checkout.quero.cloud".into(),
8742                para: form.into(),
8743                paths: vec!["/api".into()],
8744                port: 8080,
8745            });
8746            s.validate().unwrap_or_else(|e| {
8747                panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
8748            });
8749        }
8750    }
8751
8752    #[test]
8753    fn rejects_replicated_without_clusters() {
8754        let mut s = three_member_spec();
8755        s.placement.clusters = vec![];
8756        assert!(matches!(
8757            s.validate().unwrap_err(),
8758            AplicacaoError::PlacementWithoutClusters { .. }
8759        ));
8760    }
8761
8762    #[test]
8763    fn rejects_sharded_without_key() {
8764        let mut s = three_member_spec();
8765        s.placement.estrategia = PlacementStrategy::Sharded;
8766        s.placement.shard_key = None;
8767        s.placement.clusters = vec!["rio".into()];
8768        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
8769    }
8770
8771    #[test]
8772    fn sharded_with_key_validates() {
8773        let mut s = three_member_spec();
8774        s.placement.estrategia = PlacementStrategy::Sharded;
8775        s.placement.shard_key = Some("$tenantId".into());
8776        s.validate().unwrap();
8777    }
8778
8779    #[test]
8780    fn round_trip_via_json_preserves_shape() {
8781        let s = three_member_spec();
8782        let json = serde_json::to_string(&s.membros).unwrap();
8783        let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
8784        assert_eq!(back, s.membros);
8785
8786        let json = serde_json::to_string(&s.contratos).unwrap();
8787        let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
8788        assert_eq!(back, s.contratos);
8789
8790        let json = serde_json::to_string(&s.placement).unwrap();
8791        let back: Placement = serde_json::from_str(&json).unwrap();
8792        assert_eq!(back, s.placement);
8793
8794        let json = serde_json::to_string(&s.entrada).unwrap();
8795        let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
8796        assert_eq!(back, s.entrada);
8797    }
8798
8799    #[test]
8800    fn rate_limit_round_trip_seconds() {
8801        let policy = MeshPolicy {
8802            rate_limit: Some(RateLimit {
8803                rate: 100,
8804                window: Duration::from_secs(1),
8805            }),
8806            ..Default::default()
8807        };
8808        let json = serde_json::to_string(&policy).unwrap();
8809        assert!(json.contains("\"100/s\""));
8810        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
8811        assert_eq!(back.rate_limit.unwrap().rate, 100);
8812        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
8813    }
8814
8815    #[test]
8816    fn rate_limit_round_trip_minutes() {
8817        let policy = MeshPolicy {
8818            rate_limit: Some(RateLimit {
8819                rate: 5000,
8820                window: Duration::from_secs(60),
8821            }),
8822            ..Default::default()
8823        };
8824        let json = serde_json::to_string(&policy).unwrap();
8825        assert!(json.contains("\"5000/m\""));
8826    }
8827
8828    #[test]
8829    fn circuit_breaker_round_trip() {
8830        let policy = MeshPolicy {
8831            circuit_breaker: Some(CircuitBreaker {
8832                max_failures: 5,
8833                window: Duration::from_secs(60),
8834            }),
8835            ..Default::default()
8836        };
8837        let json = serde_json::to_string(&policy).unwrap();
8838        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
8839        assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
8840        assert_eq!(
8841            back.circuit_breaker.unwrap().window,
8842            Duration::from_secs(60)
8843        );
8844    }
8845
8846    #[test]
8847    fn rejects_http_contrato_without_endpoint() {
8848        let mut s = three_member_spec();
8849        s.contratos.push(WitContract {
8850            de: "cart".into(),
8851            para: "catalog".into(),
8852            wit: "wasi:http/proxy".into(),
8853            endpoint: None,
8854            subject: None,
8855            slot: None,
8856        });
8857        let err = s.validate().unwrap_err();
8858        assert!(matches!(
8859            err,
8860            AplicacaoError::ContratoMissingTarget {
8861                expected: WitTarget::HTTP_FIELD_NAME,
8862                ..
8863            }
8864        ));
8865    }
8866
8867    #[test]
8868    fn rejects_http_contrato_with_subject() {
8869        let mut s = three_member_spec();
8870        s.contratos.push(WitContract {
8871            de: "cart".into(),
8872            para: "catalog".into(),
8873            wit: "wasi:http/proxy".into(),
8874            endpoint: Some("/x".into()),
8875            subject: Some("not.allowed.here".into()),
8876            slot: None,
8877        });
8878        let err = s.validate().unwrap_err();
8879        assert!(matches!(
8880            err,
8881            AplicacaoError::ContratoWrongTarget {
8882                expected: WitTarget::HTTP_FIELD_NAME,
8883                ..
8884            }
8885        ));
8886    }
8887
8888    #[test]
8889    fn rejects_pubsub_contrato_without_subject() {
8890        let mut s = three_member_spec();
8891        s.contratos.push(WitContract {
8892            de: "cart".into(),
8893            para: "catalog".into(),
8894            wit: "nats:pub-sub".into(),
8895            endpoint: None,
8896            subject: None,
8897            slot: None,
8898        });
8899        let err = s.validate().unwrap_err();
8900        assert!(matches!(
8901            err,
8902            AplicacaoError::ContratoMissingTarget {
8903                expected: WitTarget::PUBSUB_FIELD_NAME,
8904                ..
8905            }
8906        ));
8907    }
8908
8909    #[test]
8910    fn rejects_pubsub_contrato_with_endpoint() {
8911        let mut s = three_member_spec();
8912        s.contratos.push(WitContract {
8913            de: "cart".into(),
8914            para: "catalog".into(),
8915            wit: "kafka:topic".into(),
8916            endpoint: Some("/wrong".into()),
8917            subject: Some("topic.x".into()),
8918            slot: None,
8919        });
8920        let err = s.validate().unwrap_err();
8921        assert!(matches!(
8922            err,
8923            AplicacaoError::ContratoWrongTarget {
8924                expected: WitTarget::PUBSUB_FIELD_NAME,
8925                ..
8926            }
8927        ));
8928    }
8929
8930    #[test]
8931    fn rejects_store_contrato_without_slot() {
8932        let mut s = three_member_spec();
8933        s.contratos.push(WitContract {
8934            de: "cart".into(),
8935            para: "catalog".into(),
8936            wit: "wasi:keyvalue/store".into(),
8937            endpoint: None,
8938            subject: None,
8939            slot: None,
8940        });
8941        let err = s.validate().unwrap_err();
8942        assert!(matches!(
8943            err,
8944            AplicacaoError::ContratoMissingTarget {
8945                expected: WitTarget::STORE_FIELD_NAME,
8946                ..
8947            }
8948        ));
8949    }
8950
8951    // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
8952
8953    #[test]
8954    fn rejects_http_contrato_with_empty_endpoint() {
8955        // `Some("")` for an HTTP endpoint passes the presence check
8956        // (target() previously returned WitTarget::Http { endpoint: "" })
8957        // but renders as a `path: ""` Cilium L7 rule that matches no
8958        // traffic. Same value-shape footgun closed for :entrada :paths
8959        // entries (eb3456d).
8960        let mut s = three_member_spec();
8961        s.contratos.push(WitContract {
8962            de: "cart".into(),
8963            para: "catalog".into(),
8964            wit: "wasi:http/proxy".into(),
8965            endpoint: Some(String::new()),
8966            subject: None,
8967            slot: None,
8968        });
8969        let err = s.validate().unwrap_err();
8970        assert!(
8971            matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
8972                if de == "cart" && para == "catalog"),
8973            "got {err:?}"
8974        );
8975    }
8976
8977    #[test]
8978    fn rejects_http_contrato_with_relative_endpoint() {
8979        // Cilium L7 :path + Gateway API PathPrefix both require a
8980        // leading `/`. Same shape required of :entrada :paths
8981        // (eb3456d). Lifted into target() so every consumer of the
8982        // typed WitTarget view inherits the guarantee.
8983        let mut s = three_member_spec();
8984        s.contratos.push(WitContract {
8985            de: "cart".into(),
8986            para: "catalog".into(),
8987            wit: "wasi:http/proxy".into(),
8988            endpoint: Some("products/:id".into()),
8989            subject: None,
8990            slot: None,
8991        });
8992        let err = s.validate().unwrap_err();
8993        assert!(
8994            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
8995                if endpoint == "products/:id"),
8996            "got {err:?}"
8997        );
8998    }
8999
9000    #[test]
9001    fn rejects_pubsub_contrato_with_empty_subject() {
9002        // NATS / Kafka publish without a subject is a no-op subscribe;
9003        // never the author's intent. Same empty-string rejection as
9004        // :membros :caixa, :placement :clusters entries, :entrada
9005        // :paths entries — every value carried by every typed slot is
9006        // value-shape-checked at validate().
9007        let mut s = three_member_spec();
9008        s.contratos.push(WitContract {
9009            de: "cart".into(),
9010            para: "catalog".into(),
9011            wit: "nats:pub-sub".into(),
9012            endpoint: None,
9013            subject: Some(String::new()),
9014            slot: None,
9015        });
9016        let err = s.validate().unwrap_err();
9017        assert!(
9018            matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
9019                if de == "cart" && para == "catalog"),
9020            "got {err:?}"
9021        );
9022    }
9023
9024    #[test]
9025    fn rejects_store_contrato_with_empty_slot() {
9026        // An empty slot template addresses the bucket root, defeating
9027        // the per-key isolation the slot exists for — a footgun on
9028        // `wasi:keyvalue/store` whose closest analog is the empty
9029        // shard-key rejected on :placement Sharded (c7c7799).
9030        let mut s = three_member_spec();
9031        s.contratos.push(WitContract {
9032            de: "cart".into(),
9033            para: "catalog".into(),
9034            wit: "wasi:keyvalue/store".into(),
9035            endpoint: None,
9036            subject: None,
9037            slot: Some(String::new()),
9038        });
9039        let err = s.validate().unwrap_err();
9040        assert!(
9041            matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
9042                if de == "cart" && para == "catalog"),
9043            "got {err:?}"
9044        );
9045    }
9046
9047    #[test]
9048    fn http_contrato_root_endpoint_validates() {
9049        // Pin the boundary case: a single-`/` endpoint is the catch-all
9050        // form the Gateway HTTPRoute renderer falls back to when
9051        // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
9052        // must remain a valid contrato endpoint too.
9053        let mut s = three_member_spec();
9054        s.contratos.push(contract_http("cart", "catalog", "/"));
9055        s.validate().unwrap();
9056    }
9057
9058    // ── :contratos :endpoint value-shape gate ────────────────────────────
9059    //
9060    // Mirrors the `:entrada :paths` value-shape suite on the peer
9061    // HTTP-path axis. Until this gate landed `WitContract::target()`
9062    // only refused the empty string + the missing-leading-`/` form
9063    // (c4213a4); a structurally invalid endpoint passed validate and
9064    // landed verbatim as a Cilium L7 `path:` rule
9065    // (caixa-mesh/src/lib.rs:311) that either silently dropped all
9066    // traffic or was rejected at apply time by Cilium policy admission.
9067    // Every authoring footgun the K8s Gateway API webhook / Cilium
9068    // policy validator would catch on admission now becomes a caixa-
9069    // build-time `ContratoEndpointInvalid` with the offending
9070    // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
9071    // shape as `EntradaPathInvalid` on the sibling axis; same shared
9072    // predicate (`crate::render::is_gateway_api_http_path`) ensures
9073    // drift between the two axes' rule enforcement is a build error
9074    // at the predicate.
9075
9076    fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
9077        // Fresh spec per call so the would-be-duplicate edge
9078        // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
9079        // `three_member_spec`'s pre-existing
9080        // `(cart, catalog, …, /products/:id)` entry — only the
9081        // endpoint payload differs.
9082        let mut s = three_member_spec();
9083        s.contratos.push(contract_http("cart", "catalog", ep));
9084        s.validate().unwrap_err()
9085    }
9086
9087    #[test]
9088    fn rejects_http_contrato_endpoint_with_query() {
9089        // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
9090        // silently rendered as a Cilium L7 `path: "/charge?token=X"`
9091        // rule the L7 matcher would never satisfy.
9092        let err = contrato_endpoint_err("/charge?token=X");
9093        assert!(
9094            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9095                if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
9096            "got {err:?}"
9097        );
9098    }
9099
9100    #[test]
9101    fn rejects_http_contrato_endpoint_with_fragment() {
9102        let err = contrato_endpoint_err("/charge#frag");
9103        assert!(
9104            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9105                if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
9106            "got {err:?}"
9107        );
9108    }
9109
9110    #[test]
9111    fn rejects_http_contrato_endpoint_with_whitespace() {
9112        let err = contrato_endpoint_err("/foo bar");
9113        assert!(
9114            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9115                if endpoint == "/foo bar" && reason.contains("whitespace")),
9116            "got {err:?}"
9117        );
9118    }
9119
9120    #[test]
9121    fn rejects_http_contrato_endpoint_with_control_char() {
9122        let err = contrato_endpoint_err("/api/\x01bar");
9123        assert!(
9124            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9125                if endpoint == "/api/\x01bar" && reason.contains("control character")),
9126            "got {err:?}"
9127        );
9128    }
9129
9130    #[test]
9131    fn rejects_http_contrato_endpoint_with_non_ascii() {
9132        let err = contrato_endpoint_err("/api/café");
9133        assert!(
9134            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9135                if endpoint == "/api/café" && reason.contains("non-ASCII")),
9136            "got {err:?}"
9137        );
9138    }
9139
9140    #[test]
9141    fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
9142        let err = contrato_endpoint_err("/api//cart");
9143        assert!(
9144            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9145                if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
9146            "got {err:?}"
9147        );
9148    }
9149
9150    #[test]
9151    fn rejects_http_contrato_endpoint_with_dot_segment() {
9152        let err = contrato_endpoint_err("/api/./cart");
9153        assert!(
9154            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9155                if endpoint == "/api/./cart" && reason.contains("`.` segment")),
9156            "got {err:?}"
9157        );
9158    }
9159
9160    #[test]
9161    fn rejects_http_contrato_endpoint_with_parent_segment() {
9162        // Path-traversal in a contrato endpoint is the canonical
9163        // "L7 rule that the workload's HTTP server's path-resolution
9164        // logic interprets differently than the policy enforcer"
9165        // footgun. Rejected outright at validate time.
9166        let err = contrato_endpoint_err("/api/../etc");
9167        assert!(
9168            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9169                if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
9170            "got {err:?}"
9171        );
9172    }
9173
9174    #[test]
9175    fn rejects_http_contrato_endpoint_too_long() {
9176        // 1025-byte endpoint — one over the Gateway API
9177        // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
9178        // path matcher has no inherent length limit but the policy
9179        // CR itself rides through the K8s apiserver, which enforces
9180        // ConfigMap-shaped limits; sharing the Gateway API cap is the
9181        // conservative floor.
9182        let big = format!("/api/{}", "a".repeat(1020));
9183        assert_eq!(big.len(), 1025);
9184        let err = contrato_endpoint_err(&big);
9185        assert!(
9186            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9187                if endpoint == &big && reason.contains("max length of 1024")),
9188            "got {err:?}"
9189        );
9190    }
9191
9192    #[test]
9193    fn http_contrato_endpoint_max_length_validates() {
9194        // 1024-byte endpoint — exactly the cap. Boundary pin: drift
9195        // in the cap surfaces here and at
9196        // `rejects_http_contrato_endpoint_too_long` simultaneously,
9197        // mirroring `entrada_path_max_length_validates` on the peer
9198        // axis.
9199        let big = format!("/api/{}", "a".repeat(1019));
9200        assert_eq!(big.len(), 1024);
9201        let mut s = three_member_spec();
9202        s.contratos.push(contract_http("cart", "catalog", &big));
9203        s.validate().unwrap();
9204    }
9205
9206    #[test]
9207    fn http_contrato_endpoint_accepts_canonical_forms() {
9208        // Positive-set sweep: every canonical HTTP-path shape the
9209        // sibling `:entrada :paths` axis accepts (the bare-root `/`,
9210        // plain paths, hidden-file-style `.config` segments distinct
9211        // from the `.` segment, digit-bearing segments, the canonical
9212        // route-template `:param` form, trailing-slash form,
9213        // percent-encoded segments, the `/foo..bar` interior-`..`-
9214        // substring forms that are NOT `..` segments) must remain a
9215        // valid contrato endpoint too. Drift between this list and
9216        // the entrada path positive sweep surfaces at the shared
9217        // `is_gateway_api_http_path` substrate-side suite — one
9218        // source of truth. Uses a fresh `(payment, catalog)` edge so
9219        // none of the swept endpoints collide with the pre-existing
9220        // `(cart, catalog, /products/:id)` / `(cart, payment,
9221        // /charge)` entries in `three_member_spec`.
9222        for ep in [
9223            "/",
9224            "/charge",
9225            "/v1/charge",
9226            "/api/.config",
9227            "/products/:id",
9228            "/api/cart/",
9229            "/api/caf%C3%A9",
9230            "/foo..bar",
9231            "/...",
9232        ] {
9233            let mut s = three_member_spec();
9234            s.contratos.push(contract_http("payment", "catalog", ep));
9235            s.validate()
9236                .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
9237        }
9238    }
9239
9240    #[test]
9241    fn contrato_endpoint_empty_takes_precedence_over_invalid() {
9242        // Ordering pin: `ContratoEndpointEmpty` is the more self-
9243        // locating diagnostic on `""` and must lead — the value-
9244        // shape gate is only reached after the empty-check fires.
9245        // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
9246        // on the peer axis.
9247        let mut s = three_member_spec();
9248        s.contratos.push(WitContract {
9249            de: "cart".into(),
9250            para: "catalog".into(),
9251            wit: "wasi:http/proxy".into(),
9252            endpoint: Some(String::new()),
9253            subject: None,
9254            slot: None,
9255        });
9256        let err = s.validate().unwrap_err();
9257        assert!(
9258            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
9259            "got {err:?}"
9260        );
9261    }
9262
9263    #[test]
9264    fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
9265        // Ordering pin: an endpoint without a leading `/` surfaces the
9266        // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
9267        // value-shape gate is only consulted on endpoints that already
9268        // satisfy the absolute-prefix invariant. Mirrors
9269        // `entrada_path_not_absolute_takes_precedence_over_invalid`.
9270        let err = contrato_endpoint_err("bad path");
9271        assert!(
9272            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
9273                if endpoint == "bad path"),
9274            "got {err:?}"
9275        );
9276    }
9277
9278    #[test]
9279    fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
9280        // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
9281        // `:para` + a non-empty reason flow through verbatim so the
9282        // author can grep their caixa.lisp for the offending contrato
9283        // block and fix it in one edit. Same shape as
9284        // `entrada_path_diagnostic_carries_offending_path`.
9285        let err = contrato_endpoint_err("/api?q=1");
9286        match err {
9287            AplicacaoError::ContratoEndpointInvalid {
9288                de,
9289                para,
9290                endpoint,
9291                reason,
9292            } => {
9293                assert_eq!(de, "cart");
9294                assert_eq!(para, "catalog");
9295                assert_eq!(endpoint, "/api?q=1");
9296                assert!(!reason.is_empty(), "reason field must be non-empty");
9297            }
9298            other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
9299        }
9300    }
9301
9302    #[test]
9303    fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
9304        // The compounding theorem: every &str inside a WitTarget
9305        // returned by target() is non-empty (and absolute, for Http).
9306        // Renderers downstream of typed_view() can rely on this
9307        // without re-checking — the type system carries the proof.
9308        let http = contract_http("cart", "catalog", "/x");
9309        match http.target().unwrap() {
9310            WitTarget::Http { endpoint } => {
9311                assert!(!endpoint.is_empty());
9312                assert!(endpoint.starts_with('/'));
9313            }
9314            other => panic!("expected Http, got {other:?}"),
9315        }
9316        let nats = WitContract {
9317            de: "a".into(),
9318            para: "b".into(),
9319            wit: "nats:pub-sub".into(),
9320            endpoint: None,
9321            subject: Some("topic.x".into()),
9322            slot: None,
9323        };
9324        match nats.target().unwrap() {
9325            WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
9326            other => panic!("expected PubSub, got {other:?}"),
9327        }
9328        let kv = WitContract {
9329            de: "a".into(),
9330            para: "b".into(),
9331            wit: "wasi:keyvalue/store".into(),
9332            endpoint: None,
9333            subject: None,
9334            slot: Some("checkout/$orderId".into()),
9335        };
9336        match kv.target().unwrap() {
9337            WitTarget::Store { slot } => assert!(!slot.is_empty()),
9338            other => panic!("expected Store, got {other:?}"),
9339        }
9340    }
9341
9342    #[test]
9343    fn target_diagnostic_names_offending_endpoint_value() {
9344        // When the malformed endpoint string is non-trivial, the
9345        // diagnostic carries the actual value back to the author —
9346        // not a generic "endpoint malformed" error.
9347        let bad = WitContract {
9348            de: "src".into(),
9349            para: "dst".into(),
9350            wit: "wasi:http/proxy".into(),
9351            endpoint: Some("api/v1/charge".into()),
9352            subject: None,
9353            slot: None,
9354        };
9355        match bad.target().unwrap_err() {
9356            AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
9357                assert_eq!(de, "src");
9358                assert_eq!(para, "dst");
9359                assert_eq!(endpoint, "api/v1/charge");
9360            }
9361            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
9362        }
9363    }
9364
9365    #[test]
9366    fn rejects_unknown_wit_with_target_set() {
9367        let mut s = three_member_spec();
9368        s.contratos.push(WitContract {
9369            de: "cart".into(),
9370            para: "catalog".into(),
9371            wit: "custom:exchange".into(),
9372            endpoint: Some("/leaked".into()),
9373            subject: None,
9374            slot: None,
9375        });
9376        let err = s.validate().unwrap_err();
9377        assert!(matches!(
9378            err,
9379            AplicacaoError::ContratoWrongTarget {
9380                expected: WitTarget::CAPABILITY_EXPECTED,
9381                ..
9382            }
9383        ));
9384    }
9385
9386    #[test]
9387    fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
9388        // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
9389        // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
9390        // fourth arm of the same "which payload field name goes in the
9391        // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
9392        // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
9393        // consts cover on the peer HTTP / PubSub / Store arms
9394        // (`wit_target_field_name_pins_per_variant`). Until this lift
9395        // landed the byte-string sat twice — once inline in the
9396        // [`WitContract::target`] Capability-arm rejection at the
9397        // production dispatch, once in `rejects_unknown_wit_with_target_set`
9398        // pinning against the same literal — with no compile-time link
9399        // between them. Same "one canonical declaration, next to the
9400        // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
9401        // lift established for the payload-less arm's human-readable
9402        // label axis; this test is the shape peer of
9403        // `wit_target_label_pins_per_variant`'s Capability-arm assertion
9404        // pair (routes-through-const + scalar-value pin) on the
9405        // wrong-target diagnostic-scalar axis.
9406        //
9407        // Fail-before-pass-after was verified locally by mutating the
9408        // const declaration to `"capability"` — the scalar-value pin
9409        // below fires (`"capability" != "none"`) and the routes-through
9410        // assertion below still holds (production and const walk in
9411        // lockstep), which is the correct behavior: a rename on the
9412        // const drifts here first, not at a downstream consumer.
9413        assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
9414
9415        let mut s = three_member_spec();
9416        s.contratos.push(WitContract {
9417            de: "cart".into(),
9418            para: "catalog".into(),
9419            wit: "custom:exchange".into(),
9420            endpoint: Some("/leaked".into()),
9421            subject: None,
9422            slot: None,
9423        });
9424        match s.validate().unwrap_err() {
9425            AplicacaoError::ContratoWrongTarget { expected, .. } => {
9426                assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
9427            }
9428            other => panic!("expected ContratoWrongTarget, got {other:?}"),
9429        }
9430    }
9431
9432    #[test]
9433    fn unknown_wit_capability_only_validates() {
9434        let mut s = three_member_spec();
9435        s.contratos.push(WitContract {
9436            de: "cart".into(),
9437            para: "catalog".into(),
9438            // A WIT world we haven't yet shaped — accept it as a typed
9439            // capability edge so authors aren't blocked while the WIT
9440            // registry catches up. No payload field may be carried.
9441            wit: "custom:exchange".into(),
9442            endpoint: None,
9443            subject: None,
9444            slot: None,
9445        });
9446        s.validate().unwrap();
9447        let added = s.contratos.last().unwrap();
9448        assert_eq!(added.target().unwrap(), WitTarget::Capability);
9449    }
9450
9451    #[test]
9452    fn target_typed_view_round_trips_each_shape() {
9453        let http = contract_http("cart", "catalog", "/products/:id");
9454        assert_eq!(
9455            http.target().unwrap(),
9456            WitTarget::Http {
9457                endpoint: "/products/:id"
9458            }
9459        );
9460        let nats = WitContract {
9461            de: "a".into(),
9462            para: "b".into(),
9463            wit: "nats:pub-sub".into(),
9464            endpoint: None,
9465            subject: Some("topic.x".into()),
9466            slot: None,
9467        };
9468        assert_eq!(
9469            nats.target().unwrap(),
9470            WitTarget::PubSub { subject: "topic.x" }
9471        );
9472        let kv = WitContract {
9473            de: "a".into(),
9474            para: "b".into(),
9475            wit: "wasi:keyvalue/store".into(),
9476            endpoint: None,
9477            subject: None,
9478            slot: Some("checkout/$orderId".into()),
9479        };
9480        assert_eq!(
9481            kv.target().unwrap(),
9482            WitTarget::Store {
9483                slot: "checkout/$orderId"
9484            }
9485        );
9486    }
9487
9488    #[test]
9489    fn wit_contract_kind_predicates() {
9490        let http = contract_http("a", "b", "/x");
9491        assert!(http.is_http());
9492        assert!(!http.is_pubsub());
9493        assert!(!http.is_store());
9494
9495        let nats = WitContract {
9496            de: "a".into(),
9497            para: "b".into(),
9498            wit: "nats:pub-sub".into(),
9499            endpoint: None,
9500            subject: Some("topic.x".into()),
9501            slot: None,
9502        };
9503        assert!(nats.is_pubsub());
9504        assert!(!nats.is_http());
9505
9506        let kv = WitContract {
9507            de: "a".into(),
9508            para: "b".into(),
9509            wit: "wasi:keyvalue/store".into(),
9510            endpoint: None,
9511            subject: None,
9512            slot: Some("checkout/$orderId".into()),
9513        };
9514        assert!(kv.is_store());
9515        assert!(!kv.is_http());
9516    }
9517
9518    // ── :contratos :wit value-shape gate ─────────────────────────────────
9519    //
9520    // Mirrors the `:contratos :endpoint` value-shape suite on the peer
9521    // dispatch-discriminator axis. Until this gate landed
9522    // `WitContract::target()` accepted any non-empty string and
9523    // silently demoted unrecognized shapes to a capability-only L4
9524    // edge — the canonical "I thought I had L7 HTTP routing, got
9525    // L4-only" footgun. Every authoring footgun the WIT registry's
9526    // own grammar rejects (uppercase, hyphen-for-colon typo,
9527    // whitespace, empty package, doubled `@`, …) now becomes a
9528    // caixa-build-time `ContratoWitInvalid` with the offending
9529    // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
9530    // as `ContratoEndpointInvalid` on the sibling axis; same shared
9531    // predicate (`crate::render::is_wit_world_ref`) ensures drift
9532    // between any two axes' rule enforcement is a build error at the
9533    // predicate, not piecemeal across renderers.
9534
9535    fn contrato_wit_err(wit: &str) -> AplicacaoError {
9536        // Fresh spec per call so the new contract doesn't collide on
9537        // identity with `three_member_spec`'s pre-existing entries.
9538        // The new edge uses `(payment, catalog)` — a pair the fixture
9539        // doesn't already declare — with no payload field set, so the
9540        // wit-shape gate fires before any payload-shape arm.
9541        let mut s = three_member_spec();
9542        s.contratos.push(WitContract {
9543            de: "payment".into(),
9544            para: "catalog".into(),
9545            wit: wit.into(),
9546            endpoint: None,
9547            subject: None,
9548            slot: None,
9549        });
9550        s.validate().unwrap_err()
9551    }
9552
9553    #[test]
9554    fn rejects_wit_with_uppercase_namespace() {
9555        // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
9556        // didn't match the lowercase `wasi:http/` prefix is_http() keys
9557        // off, so the dispatch fell through to the capability arm and
9558        // the contract silently rendered as an L4-only Cilium edge.
9559        // The new gate surfaces the uppercase typo at validate time
9560        // with the offending `:wit` named.
9561        let err = contrato_wit_err("WASI:http/proxy");
9562        assert!(
9563            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9564                if wit == "WASI:http/proxy" && reason.contains("lowercase")),
9565            "got {err:?}"
9566        );
9567    }
9568
9569    #[test]
9570    fn rejects_wit_with_hyphen_for_colon_typo() {
9571        // The canonical "I forgot the `:` separator" typo — pre-gate
9572        // this passed as Capability silently, so the renderer emitted
9573        // an L4-only policy where the author expected L7 HTTP rules.
9574        let err = contrato_wit_err("wasi-http/proxy");
9575        assert!(
9576            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9577                if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
9578            "got {err:?}"
9579        );
9580    }
9581
9582    #[test]
9583    fn rejects_wit_with_multiple_colons() {
9584        // Doubled `:` — the namespace/package split has nowhere to
9585        // anchor, so the dispatch silently demotes to Capability.
9586        let err = contrato_wit_err("wasi:http:proxy");
9587        assert!(
9588            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9589                if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
9590            "got {err:?}"
9591        );
9592    }
9593
9594    #[test]
9595    fn rejects_wit_with_empty_package() {
9596        // `wasi:` — namespace alone with no package. Pre-gate this
9597        // failed neither the is_http nor is_pubsub nor is_store
9598        // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
9599        // a bare `wasi:`), so it silently demoted to Capability.
9600        let err = contrato_wit_err("wasi:");
9601        assert!(
9602            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9603                if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
9604            "got {err:?}"
9605        );
9606    }
9607
9608    #[test]
9609    fn rejects_wit_with_underscore() {
9610        // Underscore — WIT identifiers are kebab-case, same rule
9611        // DNS-1123 enforces on its peer axes. The diagnostic carries
9612        // the explicit "use `-` instead" remediation.
9613        let err = contrato_wit_err("wasi:http_proxy");
9614        assert!(
9615            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9616                if wit == "wasi:http_proxy" && reason.contains('_')),
9617            "got {err:?}"
9618        );
9619    }
9620
9621    #[test]
9622    fn rejects_wit_with_whitespace() {
9623        // Whitespace mid-token — the prefix check matches but the
9624        // package-and-onward parse silently demoted to Capability.
9625        let err = contrato_wit_err("wasi:http proxy");
9626        assert!(
9627            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9628                if wit == "wasi:http proxy" && reason.contains("whitespace")),
9629            "got {err:?}"
9630        );
9631    }
9632
9633    #[test]
9634    fn rejects_wit_with_non_ascii() {
9635        // Un-percent-encoded non-ASCII byte — the canonical "I copied
9636        // the package name from a doc with smart quotes / accented
9637        // characters" footgun.
9638        let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
9639        assert!(
9640            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9641                if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
9642            "got {err:?}"
9643        );
9644    }
9645
9646    #[test]
9647    fn rejects_wit_with_consecutive_hyphens() {
9648        // `pub--sub` — WIT identifiers join words with single hyphens.
9649        let err = contrato_wit_err("nats:pub--sub");
9650        assert!(
9651            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9652                if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
9653            "got {err:?}"
9654        );
9655    }
9656
9657    #[test]
9658    fn rejects_wit_with_trailing_at_no_version() {
9659        // `wasi:http/proxy@` — the version-suffix author started to
9660        // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
9661        // parser would reject this; surface it at validate time.
9662        let err = contrato_wit_err("wasi:http/proxy@");
9663        assert!(
9664            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9665                if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
9666            "got {err:?}"
9667        );
9668    }
9669
9670    #[test]
9671    fn rejects_wit_too_long() {
9672        // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
9673        // The legitimate-shape arms all pass (lowercase, single `:`,
9674        // kebab-case identifiers); only the cap arm fires. Surfaces
9675        // the paste-from-binary / accidental-multi-line-blob landing
9676        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
9677        // on the peer axis.
9678        let big = format!("wasi:{}", "a".repeat(124));
9679        assert_eq!(big.len(), 129);
9680        let err = contrato_wit_err(&big);
9681        assert!(
9682            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9683                if wit == &big && reason.contains("max length of 128")),
9684            "got {err:?}"
9685        );
9686    }
9687
9688    #[test]
9689    fn wit_max_length_validates() {
9690        // 128-byte WIT reference — exactly the cap. Boundary pin:
9691        // drift in the cap surfaces here and at `rejects_wit_too_long`
9692        // simultaneously, mirroring
9693        // `http_contrato_endpoint_max_length_validates` on the peer
9694        // axis.
9695        let big = format!("wasi:{}", "a".repeat(123));
9696        assert_eq!(big.len(), 128);
9697        let mut s = three_member_spec();
9698        s.contratos.push(WitContract {
9699            de: "payment".into(),
9700            para: "catalog".into(),
9701            wit: big,
9702            endpoint: None,
9703            subject: None,
9704            slot: None,
9705        });
9706        s.validate().unwrap();
9707    }
9708
9709    #[test]
9710    fn wit_accepts_canonical_forms_at_aplicacao_layer() {
9711        // Positive-set sweep through the AplicacaoSpec::validate
9712        // surface (rather than the substrate-side predicate directly)
9713        // — pins every shape the existing test fixtures + the
9714        // checkout-aplicacao example carry, so the gate's accept-set
9715        // matches the substrate's emit-set. Drift between this list
9716        // and `render::tests::wit_world_ref_accepts_canonical_forms`
9717        // surfaces at the substrate layer's positive sweep — one
9718        // source of truth for the rule.
9719        for wit in [
9720            "wasi:http/proxy",
9721            "wasi:keyvalue/store",
9722            "nats:pub-sub",
9723            "kafka:topic",
9724            "custom:exchange",
9725            "pleme:cap/audit",
9726            "wasi:http/proxy@0.2.0",
9727        ] {
9728            // Payload field paired to the dispatched WIT shape so the
9729            // shape-↔-target arm doesn't fire instead of the wit-shape
9730            // arm we're exercising. Routes off the same
9731            // `wit_shape_is_http` / `wit_shape_is_pubsub` /
9732            // `wit_shape_is_store` free functions the production
9733            // `WitContract::is_http` / `is_pubsub` / `is_store`
9734            // methods delegate to (both consult the lifted
9735            // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
9736            // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
9737            // future prefix addition to the routing accept-set
9738            // reaches this test's payload-dispatch arm by
9739            // construction — no per-test-site drift can hide a
9740            // shape-→-target-slot mismatch that would silently
9741            // demote a canonical `:wit` value to the
9742            // `(None, None, None)` capability-only arm and let the
9743            // `AplicacaoSpec::validate` positive sweep pass on a
9744            // shape it should exercise as HTTP / pub-sub / store.
9745            let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
9746                (Some("/x".into()), None, None)
9747            } else if wit_shape_is_pubsub(wit) {
9748                (None, Some("topic.x".into()), None)
9749            } else if wit_shape_is_store(wit) {
9750                (None, None, Some("bucket/$key".into()))
9751            } else {
9752                (None, None, None)
9753            };
9754            let mut s = three_member_spec();
9755            s.contratos.push(WitContract {
9756                de: "payment".into(),
9757                para: "catalog".into(),
9758                wit: wit.into(),
9759                endpoint,
9760                subject,
9761                slot,
9762            });
9763            s.validate()
9764                .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
9765        }
9766    }
9767
9768    #[test]
9769    fn wit_shape_predicates_accept_canonical_prefix_set() {
9770        // Positive-set sweep pinning every prefix in
9771        // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
9772        // WIT_STORE_SHAPE_PREFIXES against the three free-function
9773        // dispatch predicates. The six prefixes are the load-bearing
9774        // routing keys the substrate's WIT-shape dispatch consults
9775        // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
9776        // key/value-store-slot admission); any drift between the
9777        // free-function accept-set and this list surfaces here
9778        // rather than at apply time as a silent
9779        // shape-→-capability-only demotion.
9780        assert!(wit_shape_is_http("wasi:http/proxy"));
9781        assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
9782        assert!(wit_shape_is_http("http:incoming"));
9783
9784        assert!(wit_shape_is_pubsub("nats:pub-sub"));
9785        assert!(wit_shape_is_pubsub("kafka:topic"));
9786
9787        assert!(wit_shape_is_store("wasi:keyvalue/store"));
9788        assert!(wit_shape_is_store("kv:cache/session"));
9789    }
9790
9791    #[test]
9792    fn wit_shape_predicates_reject_uncanonical_forms() {
9793        // Negative-set pin: the six canonical prefixes are
9794        // lowercase-only (mirrors the `is_wit_world_ref` substrate
9795        // predicate's lowercase invariant — see its docstring on the
9796        // "I thought I had L7 HTTP routing, got L4-only" footgun).
9797        // The empty string, an uppercase-prefixed form, a hyphen-
9798        // instead-of-colon typo, and a bare kebab identifier all miss
9799        // every shape arm — reachable-by-construction only via the
9800        // `is_wit_world_ref` gate that admission-checks the `:wit`
9801        // value first, but pinned here so any future
9802        // free-function change (e.g. a case-insensitive
9803        // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
9804        // this unit level.
9805        for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
9806            assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
9807            assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
9808            assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
9809        }
9810    }
9811
9812    #[test]
9813    fn wit_shape_predicates_partition_canonical_set() {
9814        // Every canonical prefix routes to exactly one shape arm —
9815        // the three prefix sets are pairwise disjoint. Pins the
9816        // routing property [`WitContract::target`] relies on: an
9817        // `is_http()` return of `true` guarantees `is_pubsub()` and
9818        // `is_store()` return `false`, so the shape-→-target-slot
9819        // dispatch (endpoint vs subject vs slot) is unambiguous.
9820        // Drift (e.g. a future `"kv:"` moved into the HTTP set
9821        // without removal from the store set) would silently route
9822        // one prefix to two arms and the first-matching-arm order
9823        // becomes load-bearing — this pin surfaces it as a build
9824        // error instead.
9825        for prefix in WIT_HTTP_SHAPE_PREFIXES {
9826            let sample = format!("{prefix}x");
9827            assert!(wit_shape_is_http(&sample));
9828            assert!(!wit_shape_is_pubsub(&sample));
9829            assert!(!wit_shape_is_store(&sample));
9830        }
9831        for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
9832            let sample = format!("{prefix}x");
9833            assert!(!wit_shape_is_http(&sample));
9834            assert!(wit_shape_is_pubsub(&sample));
9835            assert!(!wit_shape_is_store(&sample));
9836        }
9837        for prefix in WIT_STORE_SHAPE_PREFIXES {
9838            let sample = format!("{prefix}x");
9839            assert!(!wit_shape_is_http(&sample));
9840            assert!(!wit_shape_is_pubsub(&sample));
9841            assert!(wit_shape_is_store(&sample));
9842        }
9843    }
9844
9845    #[test]
9846    fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
9847        // Positive pin: [`wit_shape_matches`] is exactly the
9848        // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
9849        // parameterized on the accept-set. Two-prefix accept-set,
9850        // one-prefix accept-set, and empty accept-set (which must
9851        // reject everything, including the empty string — an empty
9852        // `any()` fold returns `false`) all pinned so a future
9853        // reimplementation that swaps `starts_with` for `contains`,
9854        // `==`, or a case-folded comparator surfaces at unit-test
9855        // time.
9856        let two = &["wasi:http/", "http:"];
9857        assert!(wit_shape_matches("wasi:http/proxy", two));
9858        assert!(wit_shape_matches("http:incoming", two));
9859        assert!(!wit_shape_matches("wasi:keyvalue/store", two));
9860
9861        let one = &["nats:"];
9862        assert!(wit_shape_matches("nats:pub-sub", one));
9863        assert!(!wit_shape_matches("kafka:topic", one));
9864
9865        // Empty accept-set matches nothing — the identity element
9866        // for the disjunctive `any()` fold across the prefix set.
9867        // Reachable via a future `wit_shape_is_<name>` const paired
9868        // to a still-empty prefix table on a nascent shape-arm draft.
9869        let empty: &[&str] = &[];
9870        assert!(!wit_shape_matches("wasi:http/proxy", empty));
9871        assert!(!wit_shape_matches("", empty));
9872
9873        // starts_with, not contains: a prefix embedded mid-string
9874        // never matches. Pins the routing invariant [`WitContract::target`]
9875        // relies on (an authored `:wit "custom:wasi:http/"` string
9876        // does not silently route through the HTTP arm just because
9877        // it happens to contain the canonical HTTP prefix).
9878        assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
9879    }
9880
9881    #[test]
9882    fn wit_shape_predicates_delegate_to_wit_shape_matches() {
9883        // Equivalence pin: each per-shape predicate is exactly
9884        // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
9885        // every canonical prefix + the empty string + one negative
9886        // sample against every peer so a future predicate that grew
9887        // its own inline `iter().any(starts_with)` (rather than
9888        // delegating through the lifted combinator) drifts loudly here
9889        // — the peer-const table's contents must agree with the
9890        // predicate's accept-set by construction.
9891        let samples = [
9892            String::new(),
9893            "wasi:http/proxy".to_string(),
9894            "http:incoming".to_string(),
9895            "nats:pub-sub".to_string(),
9896            "kafka:topic".to_string(),
9897            "wasi:keyvalue/store".to_string(),
9898            "kv:cache/session".to_string(),
9899            "custom-shape".to_string(),
9900            "WASI:HTTP/proxy".to_string(),
9901        ];
9902        for wit in &samples {
9903            assert_eq!(
9904                wit_shape_is_http(wit),
9905                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
9906                "wit_shape_is_http drifted from combinator on {wit:?}",
9907            );
9908            assert_eq!(
9909                wit_shape_is_pubsub(wit),
9910                wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
9911                "wit_shape_is_pubsub drifted from combinator on {wit:?}",
9912            );
9913            assert_eq!(
9914                wit_shape_is_store(wit),
9915                wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
9916                "wit_shape_is_store drifted from combinator on {wit:?}",
9917            );
9918        }
9919    }
9920
9921    #[test]
9922    fn wit_contract_shape_methods_delegate_to_free_functions() {
9923        // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
9924        // `is_store` are `&self` conveniences on top of the free
9925        // functions — for every canonical prefix the method's return
9926        // matches its free-function peer. Sweeps the union of the
9927        // three prefix sets so a future method that grew its own
9928        // inline prefix logic (rather than delegating) drifts loudly
9929        // here on the first prefix the free function accepts and the
9930        // method doesn't.
9931        for shape_set in [
9932            WIT_HTTP_SHAPE_PREFIXES,
9933            WIT_PUBSUB_SHAPE_PREFIXES,
9934            WIT_STORE_SHAPE_PREFIXES,
9935        ] {
9936            for prefix in shape_set {
9937                let c = WitContract {
9938                    de: "cart".into(),
9939                    para: "catalog".into(),
9940                    wit: format!("{prefix}x"),
9941                    endpoint: None,
9942                    subject: None,
9943                    slot: None,
9944                };
9945                assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
9946                assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
9947                assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
9948            }
9949        }
9950    }
9951
9952    #[test]
9953    fn empty_wit_takes_precedence_over_invalid() {
9954        // Ordering pin: `EmptyWit` is the more self-locating
9955        // diagnostic on `""` and must lead — the value-shape gate is
9956        // only reached after the empty-check fires. Mirrors
9957        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
9958        // the peer payload axis.
9959        let mut s = three_member_spec();
9960        s.contratos.push(WitContract {
9961            de: "payment".into(),
9962            para: "catalog".into(),
9963            wit: String::new(),
9964            endpoint: None,
9965            subject: None,
9966            slot: None,
9967        });
9968        let err = s.validate().unwrap_err();
9969        assert!(
9970            matches!(err, AplicacaoError::EmptyWit { .. }),
9971            "got {err:?}"
9972        );
9973    }
9974
9975    #[test]
9976    fn wit_invalid_fires_before_payload_shape_arm() {
9977        // Ordering pin: a malformed `:wit` surfaces *its own*
9978        // diagnostic (which names the offending wit verbatim) before
9979        // any payload-field check — a contrato whose wit is
9980        // structurally invalid AND carries a wrong target field
9981        // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
9982        // because the dispatch on the wit is what decides which
9983        // payload field is "right" in the first place. Without this
9984        // ordering, the author would see "wrong target field" for a
9985        // wit that hasn't even been parsed, which doesn't name the
9986        // root cause.
9987        let mut s = three_member_spec();
9988        s.contratos.push(WitContract {
9989            de: "payment".into(),
9990            para: "catalog".into(),
9991            // Hyphen-for-colon typo + endpoint set: pre-gate this
9992            // raised `ContratoWrongTarget { expected: "none" }` (the
9993            // Capability arm rejecting the endpoint), masking the
9994            // real authoring mistake (the wit isn't `wasi:http/proxy`).
9995            wit: "wasi-http/proxy".into(),
9996            endpoint: Some("/x".into()),
9997            subject: None,
9998            slot: None,
9999        });
10000        let err = s.validate().unwrap_err();
10001        assert!(
10002            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
10003                if wit == "wasi-http/proxy"),
10004            "got {err:?}"
10005        );
10006    }
10007
10008    #[test]
10009    fn wit_invalid_diagnostic_carries_offending_wit() {
10010        // Diagnostic-shape pin — the offending `:wit` + `:de` +
10011        // `:para` + a non-empty reason flow through verbatim so the
10012        // author can grep their caixa.lisp for the offending contrato
10013        // block and fix it in one edit. Same shape as
10014        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
10015        let err = contrato_wit_err("WASI:HTTP/proxy");
10016        match err {
10017            AplicacaoError::ContratoWitInvalid {
10018                de,
10019                para,
10020                wit,
10021                reason,
10022            } => {
10023                assert_eq!(de, "payment");
10024                assert_eq!(para, "catalog");
10025                assert_eq!(wit, "WASI:HTTP/proxy");
10026                assert!(!reason.is_empty(), "reason field must be non-empty");
10027            }
10028            other => panic!("expected ContratoWitInvalid, got {other:?}"),
10029        }
10030    }
10031
10032    // ── :contratos :subject value-shape gate ─────────────────────────────
10033    //
10034    // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
10035    // suites on the peer payload axes. Until this gate landed
10036    // `WitContract::target()` only refused the empty string; a
10037    // structurally invalid subject silently passed validate and the
10038    // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
10039    // Subject'` on publish / subscribe, or as a silent message drop,
10040    // far from the source caixa.lisp. Every authoring footgun the
10041    // NATS server's subject parser would catch on admission now
10042    // becomes a caixa-build-time `ContratoSubjectInvalid` with the
10043    // offending `:subject` + `:de` + `:para` named verbatim. Same
10044    // diagnostic shape as `ContratoEndpointInvalid` /
10045    // `ContratoWitInvalid` on the peer payload axes; same shared
10046    // predicate (`crate::render::is_nats_subject`) ensures drift
10047    // between any two axes' rule enforcement is a build error at the
10048    // predicate, not piecemeal across renderers.
10049
10050    fn contrato_subject_err(subject: &str) -> AplicacaoError {
10051        // Fresh spec per call so the new contract doesn't collide on
10052        // identity with `three_member_spec`'s pre-existing entries.
10053        // The new edge uses `(payment, catalog)` — a pair the fixture
10054        // doesn't already declare — with `:wit "nats:pub-sub"` and the
10055        // varying `:subject`, so the subject-shape gate fires cleanly
10056        // after the wit-shape gate (which `"nats:pub-sub"` passes).
10057        let mut s = three_member_spec();
10058        s.contratos.push(WitContract {
10059            de: "payment".into(),
10060            para: "catalog".into(),
10061            wit: "nats:pub-sub".into(),
10062            endpoint: None,
10063            subject: Some(subject.into()),
10064            slot: None,
10065        });
10066        s.validate().unwrap_err()
10067    }
10068
10069    #[test]
10070    fn rejects_pubsub_contrato_subject_with_whitespace() {
10071        // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
10072        // landed at the NATS server as a malformed subject the parser
10073        // rejects with `-ERR 'Invalid Subject'`. Now caught at the
10074        // source caixa.lisp.
10075        let err = contrato_subject_err("foo bar");
10076        assert!(
10077            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10078                if subject == "foo bar" && reason.contains("whitespace")),
10079            "got {err:?}"
10080        );
10081    }
10082
10083    #[test]
10084    fn rejects_pubsub_contrato_subject_with_control_char() {
10085        let err = contrato_subject_err("foo\x01bar");
10086        assert!(
10087            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10088                if subject == "foo\x01bar" && reason.contains("control character")),
10089            "got {err:?}"
10090        );
10091    }
10092
10093    #[test]
10094    fn rejects_pubsub_contrato_subject_with_non_ascii() {
10095        // Un-percent-encoded non-ASCII byte — the canonical "I copied
10096        // the subject from a doc with smart quotes / accented
10097        // characters" footgun.
10098        let err = contrato_subject_err("foo.caf\u{e9}");
10099        assert!(
10100            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10101                if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
10102            "got {err:?}"
10103        );
10104    }
10105
10106    #[test]
10107    fn rejects_pubsub_contrato_subject_with_leading_dot() {
10108        // Empty leading token — NATS rejects.
10109        let err = contrato_subject_err(".foo");
10110        assert!(
10111            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10112                if subject == ".foo" && reason.contains("must not start with `.`")),
10113            "got {err:?}"
10114        );
10115    }
10116
10117    #[test]
10118    fn rejects_pubsub_contrato_subject_with_trailing_dot() {
10119        // Empty trailing token — NATS rejects. The remediation
10120        // (use `>` instead) is in the reason string.
10121        let err = contrato_subject_err("foo.");
10122        assert!(
10123            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10124                if subject == "foo." && reason.contains("must not end with `.`")),
10125            "got {err:?}"
10126        );
10127    }
10128
10129    #[test]
10130    fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
10131        // The canonical "I forgot to fill in the middle segment"
10132        // typo — `"foo..bar"`. NATS rejects empty tokens.
10133        let err = contrato_subject_err("foo..bar");
10134        assert!(
10135            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10136                if subject == "foo..bar" && reason.contains("consecutive `.`")),
10137            "got {err:?}"
10138        );
10139    }
10140
10141    #[test]
10142    fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
10143        // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
10144        // as the final segment. Pre-gate this passed as a typed edge
10145        // and surfaced at runtime as a NATS subscribe rejection.
10146        let err = contrato_subject_err("foo.>.bar");
10147        assert!(
10148            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10149                if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
10150            "got {err:?}"
10151        );
10152    }
10153
10154    #[test]
10155    fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
10156        // `foo*.bar` — NATS wildcards are standalone tokens. The
10157        // remediation is in the reason string.
10158        let err = contrato_subject_err("foo*.bar");
10159        assert!(
10160            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10161                if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
10162            "got {err:?}"
10163        );
10164    }
10165
10166    #[test]
10167    fn rejects_pubsub_contrato_subject_with_invalid_char() {
10168        // `foo,bar` — comma is not a valid NATS subject character.
10169        // Pinned separately from the wildcard arms so the invalid-
10170        // character diagnostic is in force.
10171        let err = contrato_subject_err("foo,bar");
10172        assert!(
10173            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10174                if subject == "foo,bar" && reason.contains("invalid character")),
10175            "got {err:?}"
10176        );
10177    }
10178
10179    #[test]
10180    fn rejects_pubsub_contrato_subject_too_long() {
10181        // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
10182        // The legitimate-shape arms all pass (one all-`a` token, no
10183        // `.`, no wildcards); only the cap arm fires. Surfaces the
10184        // paste-from-binary / accidental-multi-line-blob landing
10185        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
10186        // on the peer axis.
10187        let big = "a".repeat(257);
10188        assert_eq!(big.len(), 257);
10189        let err = contrato_subject_err(&big);
10190        assert!(
10191            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10192                if subject == &big && reason.contains("max length of 256")),
10193            "got {err:?}"
10194        );
10195    }
10196
10197    #[test]
10198    fn pubsub_contrato_subject_max_length_validates() {
10199        // 256-byte subject — exactly the cap. Boundary pin: drift in
10200        // the cap surfaces here and at
10201        // `rejects_pubsub_contrato_subject_too_long` simultaneously,
10202        // mirroring `http_contrato_endpoint_max_length_validates` and
10203        // `wit_max_length_validates` on the peer axes.
10204        let big = "a".repeat(256);
10205        assert_eq!(big.len(), 256);
10206        let mut s = three_member_spec();
10207        s.contratos.push(WitContract {
10208            de: "payment".into(),
10209            para: "catalog".into(),
10210            wit: "nats:pub-sub".into(),
10211            endpoint: None,
10212            subject: Some(big),
10213            slot: None,
10214        });
10215        s.validate().unwrap();
10216    }
10217
10218    #[test]
10219    fn pubsub_contrato_subject_accepts_canonical_forms() {
10220        // Positive-set sweep: every canonical NATS subject shape the
10221        // substrate-side `is_nats_subject` predicate accepts (the
10222        // multi-dot `events.order.charged`, the snake_case / kebab-
10223        // case / mixed-case tokens, the digit-bearing tokens, the
10224        // single-token wildcard `*` at every segment position, and
10225        // the trailing `>` multi-token wildcard) must remain a valid
10226        // contrato subject too. Drift between this list and the
10227        // substrate-side `nats_subject_accepts_canonical_forms` sweep
10228        // surfaces at the shared predicate — one source of truth.
10229        // Uses a fresh `(payment, catalog)` edge so none of the swept
10230        // subjects collide with the pre-existing entries in
10231        // `three_member_spec`.
10232        for subject in [
10233            "checkout.events.charge.failed",
10234            "rio.events.order.charged",
10235            "orders",
10236            "orders.123",
10237            "snake_case.token",
10238            "kebab-case.token",
10239            "MixedCase.Token",
10240            "orders.*.charged",
10241            "*.events.*",
10242            "orders.>",
10243        ] {
10244            let mut s = three_member_spec();
10245            s.contratos.push(WitContract {
10246                de: "payment".into(),
10247                para: "catalog".into(),
10248                wit: "nats:pub-sub".into(),
10249                endpoint: None,
10250                subject: Some(subject.into()),
10251                slot: None,
10252            });
10253            s.validate()
10254                .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
10255        }
10256    }
10257
10258    #[test]
10259    fn contrato_subject_empty_takes_precedence_over_invalid() {
10260        // Ordering pin: `ContratoSubjectEmpty` is the more self-
10261        // locating diagnostic on `""` and must lead — the value-shape
10262        // gate is only reached after the empty-check fires. Mirrors
10263        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
10264        // the peer payload axis.
10265        let mut s = three_member_spec();
10266        s.contratos.push(WitContract {
10267            de: "payment".into(),
10268            para: "catalog".into(),
10269            wit: "nats:pub-sub".into(),
10270            endpoint: None,
10271            subject: Some(String::new()),
10272            slot: None,
10273        });
10274        let err = s.validate().unwrap_err();
10275        assert!(
10276            matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
10277            "got {err:?}"
10278        );
10279    }
10280
10281    #[test]
10282    fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
10283        // Diagnostic-shape pin — the offending `:subject` + `:de` +
10284        // `:para` + a non-empty reason flow through verbatim so the
10285        // author can grep their caixa.lisp for the offending contrato
10286        // block and fix it in one edit. Same shape as
10287        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
10288        // and `wit_invalid_diagnostic_carries_offending_wit`.
10289        let err = contrato_subject_err("foo..bar");
10290        match err {
10291            AplicacaoError::ContratoSubjectInvalid {
10292                de,
10293                para,
10294                subject,
10295                reason,
10296            } => {
10297                assert_eq!(de, "payment");
10298                assert_eq!(para, "catalog");
10299                assert_eq!(subject, "foo..bar");
10300                assert!(!reason.is_empty(), "reason field must be non-empty");
10301            }
10302            other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
10303        }
10304    }
10305
10306    #[test]
10307    fn target_view_pubsub_subject_passes_through_to_typed_view() {
10308        // The compounding theorem on the pub-sub axis: every
10309        // `WitTarget::PubSub { subject }` returned by `target()` carries
10310        // a NATS-server-accepted subject. Renderers downstream of
10311        // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
10312        // NATS Stream/Consumer CR emitter, the future `feira app graph`
10313        // view's subject labeller) can rely on this without re-checking
10314        // — the type system carries the proof. Mirrors
10315        // `target_view_payload_is_guaranteed_nonempty_after_target_call`
10316        // on the peer axes.
10317        let nats = WitContract {
10318            de: "a".into(),
10319            para: "b".into(),
10320            wit: "nats:pub-sub".into(),
10321            endpoint: None,
10322            subject: Some("orders.events.*.charged".into()),
10323            slot: None,
10324        };
10325        match nats.target().unwrap() {
10326            WitTarget::PubSub { subject } => {
10327                assert_eq!(subject, "orders.events.*.charged");
10328            }
10329            other => panic!("expected PubSub, got {other:?}"),
10330        }
10331    }
10332
10333    // ── :contratos :slot value-shape gate ────────────────────────────────
10334    //
10335    // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
10336    // (63e18a0) value-shape suites on the peer payload axes. Until this
10337    // gate landed `WitContract::target()` only refused the empty string
10338    // for the Store arm; a structurally invalid slot (raw whitespace,
10339    // control character, non-ASCII byte, paste-from-binary multi-line
10340    // blob) silently passed validate and surfaced at runtime as a
10341    // per-backend kv write rejection or a silent next-read corruption,
10342    // far from the source caixa.lisp with no field naming which
10343    // `:contratos` edge carried the typo. Every authoring footgun the
10344    // kv backend intersection-floor would catch on write now becomes a
10345    // caixa-build-time `ContratoSlotInvalid` with the offending
10346    // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
10347    // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
10348    // peer payload axes; same shared predicate
10349    // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
10350    // any two axes' rule enforcement is a build error at the
10351    // predicate, not piecemeal across renderers. Closes the typed
10352    // payload-axis value-shape trajectory across all three legs of the
10353    // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
10354
10355    fn contrato_slot_err(slot: &str) -> AplicacaoError {
10356        // Fresh spec per call so the new contract doesn't collide on
10357        // identity with `three_member_spec`'s pre-existing entries
10358        // and doesn't close a synchronous cycle the cycle detector
10359        // would reject before the slot-shape gate fires. The new edge
10360        // uses `(payment, catalog)` — a pair the fixture doesn't
10361        // already declare in either direction (the fixture carries
10362        // `cart -> catalog` and `cart -> payment`, so `payment ->
10363        // catalog` doesn't form a cycle on the sync subgraph) — with
10364        // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
10365        // slot-shape gate fires cleanly after the wit-shape gate
10366        // (which `"wasi:keyvalue/store"` passes). Same edge pair the
10367        // peer `contrato_subject_err` helper uses (63e18a0).
10368        let mut s = three_member_spec();
10369        s.contratos.push(WitContract {
10370            de: "payment".into(),
10371            para: "catalog".into(),
10372            wit: "wasi:keyvalue/store".into(),
10373            endpoint: None,
10374            subject: None,
10375            slot: Some(slot.into()),
10376        });
10377        s.validate().unwrap_err()
10378    }
10379
10380    #[test]
10381    fn rejects_store_contrato_slot_with_whitespace() {
10382        // Fail-before-pass-after pin — pre-gate `"check out/$order"`
10383        // silently landed at the kv backend with whitespace whose
10384        // runtime behavior varies unpredictably across backends (etcd
10385        // accepts, Redis accepts then breaks on next CLI op, DynamoDB
10386        // rejects on write). Now caught at the source caixa.lisp.
10387        let err = contrato_slot_err("check out/$order");
10388        assert!(
10389            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10390                if slot == "check out/$order" && reason.contains("whitespace")),
10391            "got {err:?}"
10392        );
10393    }
10394
10395    #[test]
10396    fn rejects_store_contrato_slot_with_tab() {
10397        // Tab byte arm-pinned separately from the space arm so a
10398        // future relaxation that admits one but not the other surfaces
10399        // here.
10400        let err = contrato_slot_err("check\tout");
10401        assert!(
10402            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10403                if slot == "check\tout" && reason.contains("whitespace")),
10404            "got {err:?}"
10405        );
10406    }
10407
10408    #[test]
10409    fn rejects_store_contrato_slot_with_control_char() {
10410        // SOH (0x01) — distinct from the whitespace arm. Redis admits
10411        // and corrupts on RESP protocol framing; DynamoDB rejects on
10412        // write.
10413        let err = contrato_slot_err("checkout/\x01order");
10414        assert!(
10415            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10416                if slot == "checkout/\x01order" && reason.contains("control character")),
10417            "got {err:?}"
10418        );
10419    }
10420
10421    #[test]
10422    fn rejects_store_contrato_slot_with_newline() {
10423        // Embedded newline — the canonical "the paste-from-binary slug
10424        // spans multiple lines" footgun. Distinct from the whitespace
10425        // arm because `\n` is a control character (0x0A).
10426        let err = contrato_slot_err("checkout\norder");
10427        assert!(
10428            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10429                if slot == "checkout\norder" && reason.contains("control character")),
10430            "got {err:?}"
10431        );
10432    }
10433
10434    #[test]
10435    fn rejects_store_contrato_slot_with_non_ascii() {
10436        // Un-percent-encoded non-ASCII byte — the canonical "I copied
10437        // the slot from a doc with accented characters" footgun. Each
10438        // kv backend re-encodes non-ASCII differently (etcd preserves
10439        // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
10440        // rejects), so the typed slot's value set is the intersection-
10441        // floor every backend admits identically (printable ASCII).
10442        let err = contrato_slot_err("ch\u{e9}ckout/$order");
10443        assert!(
10444            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10445                if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
10446            "got {err:?}"
10447        );
10448    }
10449
10450    #[test]
10451    fn rejects_store_contrato_slot_too_long() {
10452        // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
10453        // legitimate-shape arms all pass (a single all-`a` token, no
10454        // separators); only the cap arm fires. Surfaces the paste-
10455        // from-binary / accidental-multi-line-blob landing footgun.
10456        // Mirrors `rejects_pubsub_contrato_subject_too_long` and
10457        // `rejects_http_contrato_endpoint_too_long` on the peer
10458        // payload axes.
10459        let big = "a".repeat(513);
10460        assert_eq!(big.len(), 513);
10461        let err = contrato_slot_err(&big);
10462        assert!(
10463            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10464                if slot == &big && reason.contains("max length of 512")),
10465            "got {err:?}"
10466        );
10467    }
10468
10469    #[test]
10470    fn store_contrato_slot_max_length_validates() {
10471        // 512-byte slot — exactly the cap. Boundary pin: drift in the
10472        // cap surfaces here and at `rejects_store_contrato_slot_too_long`
10473        // simultaneously, mirroring
10474        // `pubsub_contrato_subject_max_length_validates` and
10475        // `http_contrato_endpoint_max_length_validates` on the peer
10476        // payload axes.
10477        let big = "a".repeat(512);
10478        assert_eq!(big.len(), 512);
10479        let mut s = three_member_spec();
10480        s.contratos.push(WitContract {
10481            de: "payment".into(),
10482            para: "catalog".into(),
10483            wit: "wasi:keyvalue/store".into(),
10484            endpoint: None,
10485            subject: None,
10486            slot: Some(big),
10487        });
10488        s.validate().unwrap();
10489    }
10490
10491    #[test]
10492    fn store_contrato_slot_accepts_canonical_forms() {
10493        // Positive-set sweep: every canonical kv slot template the
10494        // substrate-side `is_wasi_keyvalue_slot` predicate accepts
10495        // (single-token identifiers, path-namespaced `$`-templates,
10496        // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
10497        // snake_case / kebab-case / MixedCase tokens, digit-bearing
10498        // tokens, percent-encoded fragments) must remain valid
10499        // contrato slots too. Drift between this list and the
10500        // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
10501        // surfaces at the shared predicate — one source of truth.
10502        // Uses a fresh `(payment, catalog)` edge so none of the swept
10503        // slots collide with the pre-existing entries in
10504        // `three_member_spec`.
10505        for slot in [
10506            "checkout",
10507            "checkout/$orderId",
10508            "users:{tenant}/{id}",
10509            "session.<sid>",
10510            "session.tokens.<sid>",
10511            "snake_case_key",
10512            "kebab-case-key",
10513            "MixedCase",
10514            "shard0",
10515            "v2/key",
10516            "users/caf%C3%A9",
10517        ] {
10518            let mut s = three_member_spec();
10519            s.contratos.push(WitContract {
10520                de: "payment".into(),
10521                para: "catalog".into(),
10522                wit: "wasi:keyvalue/store".into(),
10523                endpoint: None,
10524                subject: None,
10525                slot: Some(slot.into()),
10526            });
10527            s.validate()
10528                .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
10529        }
10530    }
10531
10532    #[test]
10533    fn contrato_slot_empty_takes_precedence_over_invalid() {
10534        // Ordering pin: `ContratoSlotEmpty` is the more self-locating
10535        // diagnostic on `""` and must lead — the value-shape gate is
10536        // only reached after the empty-check fires. Mirrors
10537        // `contrato_subject_empty_takes_precedence_over_invalid` and
10538        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
10539        // the peer payload axes.
10540        let mut s = three_member_spec();
10541        s.contratos.push(WitContract {
10542            de: "payment".into(),
10543            para: "catalog".into(),
10544            wit: "wasi:keyvalue/store".into(),
10545            endpoint: None,
10546            subject: None,
10547            slot: Some(String::new()),
10548        });
10549        let err = s.validate().unwrap_err();
10550        assert!(
10551            matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
10552            "got {err:?}"
10553        );
10554    }
10555
10556    #[test]
10557    fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
10558        // Diagnostic-shape pin — the offending `:slot` + `:de` +
10559        // `:para` + a non-empty reason flow through verbatim so the
10560        // author can grep their caixa.lisp for the offending contrato
10561        // block and fix it in one edit. Same shape as
10562        // `contrato_subject_invalid_diagnostic_carries_offending_subject`
10563        // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
10564        // on the peer payload axes.
10565        let err = contrato_slot_err("check out/$order");
10566        match err {
10567            AplicacaoError::ContratoSlotInvalid {
10568                de,
10569                para,
10570                slot,
10571                reason,
10572            } => {
10573                assert_eq!(de, "payment");
10574                assert_eq!(para, "catalog");
10575                assert_eq!(slot, "check out/$order");
10576                assert!(!reason.is_empty(), "reason field must be non-empty");
10577            }
10578            other => panic!("expected ContratoSlotInvalid, got {other:?}"),
10579        }
10580    }
10581
10582    #[test]
10583    fn target_view_store_slot_passes_through_to_typed_view() {
10584        // The compounding theorem on the store axis: every
10585        // `WitTarget::Store { slot }` returned by `target()` carries a
10586        // kv-backend-accepted slot template. Renderers downstream of
10587        // `typed_view()` (the future per-Servico `:capabilities
10588        // wasi:keyvalue/store` axis emitter, the future `feira app
10589        // graph` view's slot labeller, the future kv-provider CR
10590        // materializer) can rely on this without re-checking — the
10591        // type system carries the proof. Mirrors
10592        // `target_view_pubsub_subject_passes_through_to_typed_view` on
10593        // the peer payload axis.
10594        let store = WitContract {
10595            de: "a".into(),
10596            para: "b".into(),
10597            wit: "wasi:keyvalue/store".into(),
10598            endpoint: None,
10599            subject: None,
10600            slot: Some("checkout/$orderId".into()),
10601        };
10602        match store.target().unwrap() {
10603            WitTarget::Store { slot } => {
10604                assert_eq!(slot, "checkout/$orderId");
10605            }
10606            other => panic!("expected Store, got {other:?}"),
10607        }
10608    }
10609
10610    #[test]
10611    fn rejects_self_loop_in_synchronous_contratos() {
10612        // A synchronous self-edge (`cart → cart` over HTTP) is now
10613        // rejected by the dedicated `ContratoSelfLoop` gate — a precise
10614        // "this edge is degenerate" diagnostic — rather than incidentally
10615        // by the cycle detector framing it as a `["cart", "cart"]`
10616        // multi-node deadlock.
10617        let mut s = three_member_spec();
10618        s.contratos.push(contract_http("cart", "cart", "/loop"));
10619        let err = s.validate().unwrap_err();
10620        match err {
10621            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
10622                assert_eq!(caixa, "cart");
10623                assert_eq!(wit, "wasi:http/proxy");
10624            }
10625            other => panic!("expected ContratoSelfLoop, got {other:?}"),
10626        }
10627    }
10628
10629    #[test]
10630    fn rejects_self_loop_in_pubsub_contratos() {
10631        // The cycle detector excludes pub-sub edges (acyclic by
10632        // construction), so before the explicit gate a `nats:pub-sub`
10633        // self-edge silently validated and rendered a self-allow CNP.
10634        // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
10635        let mut s = three_member_spec();
10636        s.contratos.push(WitContract {
10637            de: "payment".into(),
10638            para: "payment".into(),
10639            wit: "nats:pub-sub".into(),
10640            endpoint: None,
10641            subject: Some("rio.events.payment".into()),
10642            slot: None,
10643        });
10644        let err = s.validate().unwrap_err();
10645        match err {
10646            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
10647                assert_eq!(caixa, "payment");
10648                assert_eq!(wit, "nats:pub-sub");
10649            }
10650            other => panic!("expected ContratoSelfLoop, got {other:?}"),
10651        }
10652    }
10653
10654    #[test]
10655    fn self_loop_fires_before_payload_shape_check() {
10656        // The structural "this edge can't exist" error precedes the
10657        // narrower payload-shape diagnostics: a self-edge carrying an
10658        // otherwise-malformed endpoint still reports ContratoSelfLoop,
10659        // not ContratoEndpointInvalid.
10660        let mut s = three_member_spec();
10661        s.contratos.push(WitContract {
10662            de: "cart".into(),
10663            para: "cart".into(),
10664            wit: "wasi:http/proxy".into(),
10665            endpoint: Some("not-absolute".into()),
10666            subject: None,
10667            slot: None,
10668        });
10669        match s.validate().unwrap_err() {
10670            AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
10671            other => panic!("expected ContratoSelfLoop, got {other:?}"),
10672        }
10673    }
10674
10675    #[test]
10676    fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
10677        // A self-edge naming a non-member reports the more fundamental
10678        // ContratoMemberMissing first (the member doesn't exist), so the
10679        // self-loop gate is reached only once both endpoints resolve.
10680        let mut s = three_member_spec();
10681        s.contratos.push(contract_http("ghost", "ghost", "/loop"));
10682        match s.validate().unwrap_err() {
10683            AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
10684            other => panic!("expected ContratoMemberMissing, got {other:?}"),
10685        }
10686    }
10687
10688    #[test]
10689    fn rejects_two_node_synchronous_cycle() {
10690        let mut s = three_member_spec();
10691        // existing edges: cart → catalog, cart → payment
10692        // adding catalog → cart closes a 2-cycle on the HTTP subgraph
10693        s.contratos
10694            .push(contract_http("catalog", "cart", "/refresh"));
10695        let err = s.validate().unwrap_err();
10696        match err {
10697            AplicacaoError::ContratoCycle { cycle } => {
10698                // Cycle traversal should mention both endpoints, with
10699                // the back-edge target appearing as both first and last
10700                // element to close the loop.
10701                assert!(cycle.len() >= 3);
10702                assert_eq!(cycle.first(), cycle.last());
10703                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
10704                assert!(body.contains("cart"));
10705                assert!(body.contains("catalog"));
10706            }
10707            other => panic!("expected ContratoCycle, got {other:?}"),
10708        }
10709    }
10710
10711    #[test]
10712    fn rejects_three_node_synchronous_cycle() {
10713        let mut s = three_member_spec();
10714        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
10715        s.contratos = vec![
10716            contract_http("catalog", "cart", "/x"),
10717            contract_http("cart", "payment", "/y"),
10718            contract_http("payment", "catalog", "/z"),
10719        ];
10720        let err = s.validate().unwrap_err();
10721        match err {
10722            AplicacaoError::ContratoCycle { cycle } => {
10723                assert_eq!(cycle.first(), cycle.last());
10724                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
10725                assert_eq!(body.len(), 3);
10726                assert!(body.contains("cart"));
10727                assert!(body.contains("catalog"));
10728                assert!(body.contains("payment"));
10729            }
10730            other => panic!("expected ContratoCycle, got {other:?}"),
10731        }
10732    }
10733
10734    #[test]
10735    fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
10736        // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
10737        // "acyclic by construction" — so a cycle whose closing edge
10738        // is pub-sub should NOT raise ContratoCycle.
10739        let mut s = three_member_spec();
10740        s.contratos = vec![
10741            contract_http("catalog", "cart", "/x"),
10742            contract_http("cart", "payment", "/y"),
10743            // Closing edge is pub-sub — async; not a sync deadlock.
10744            WitContract {
10745                de: "payment".into(),
10746                para: "catalog".into(),
10747                wit: "nats:pub-sub".into(),
10748                endpoint: None,
10749                subject: Some("checkout.events.charge.completed".into()),
10750                slot: None,
10751            },
10752        ];
10753        s.validate().expect("pub-sub edge breaks the sync cycle");
10754    }
10755
10756    #[test]
10757    fn store_edge_counts_as_synchronous_for_cycle_detection() {
10758        // wasi:keyvalue/store is request/response; a cycle through one
10759        // *is* a sync deadlock, just like HTTP.
10760        let mut s = three_member_spec();
10761        s.contratos = vec![
10762            contract_http("catalog", "cart", "/x"),
10763            WitContract {
10764                de: "cart".into(),
10765                para: "catalog".into(),
10766                wit: "wasi:keyvalue/store".into(),
10767                endpoint: None,
10768                subject: None,
10769                slot: Some("session/$id".into()),
10770            },
10771        ];
10772        let err = s.validate().unwrap_err();
10773        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
10774    }
10775
10776    #[test]
10777    fn capability_edge_counts_as_synchronous_for_cycle_detection() {
10778        // Capability-only edges (unknown WIT shape, no payload) default
10779        // to synchronous — safer; authors with truly async capability
10780        // semantics can model them as pub-sub explicitly.
10781        let mut s = three_member_spec();
10782        s.contratos = vec![
10783            contract_http("catalog", "cart", "/x"),
10784            WitContract {
10785                de: "cart".into(),
10786                para: "catalog".into(),
10787                wit: "custom:exchange".into(),
10788                endpoint: None,
10789                subject: None,
10790                slot: None,
10791            },
10792        ];
10793        let err = s.validate().unwrap_err();
10794        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
10795    }
10796
10797    #[test]
10798    fn long_acyclic_chain_validates() {
10799        // A long sync chain (no back-edges) must validate even when
10800        // every node is reachable from the first.
10801        let mut s = three_member_spec();
10802        s.membros = vec![
10803            membro("a", "^0.1"),
10804            membro("b", "^0.1"),
10805            membro("c", "^0.1"),
10806            membro("d", "^0.1"),
10807            membro("e", "^0.1"),
10808        ];
10809        s.contratos = vec![
10810            contract_http("a", "b", "/1"),
10811            contract_http("b", "c", "/2"),
10812            contract_http("c", "d", "/3"),
10813            contract_http("d", "e", "/4"),
10814        ];
10815        s.entrada.as_mut().unwrap().para = "a".into();
10816        s.validate().unwrap();
10817    }
10818
10819    #[test]
10820    fn diamond_acyclic_validates() {
10821        // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
10822        let mut s = three_member_spec();
10823        s.membros = vec![
10824            membro("a", "^0.1"),
10825            membro("b", "^0.1"),
10826            membro("c", "^0.1"),
10827            membro("d", "^0.1"),
10828        ];
10829        s.contratos = vec![
10830            contract_http("a", "b", "/1"),
10831            contract_http("a", "c", "/2"),
10832            contract_http("b", "d", "/3"),
10833            contract_http("c", "d", "/4"),
10834        ];
10835        s.entrada.as_mut().unwrap().para = "a".into();
10836        s.validate().unwrap();
10837    }
10838
10839    // ── duplicate-`:contratos` build-error gate ──────────────────────────
10840
10841    #[test]
10842    fn rejects_duplicate_http_contrato() {
10843        // Fail-before-pass-after pin: the fixture's `cart → catalog`
10844        // HTTP edge appears once. Push an identical entry — same
10845        // (de, para, wit, endpoint) — and validate() must reject it.
10846        // Until this gate landed the typed surface accepted the
10847        // duplicate silently and caixa-mesh's `cilium_network_policies`
10848        // emitted two ``CiliumNetworkPolicy`` objects with identical
10849        // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
10850        // admission rejects on `kubectl apply` far from the source.
10851        let mut s = three_member_spec();
10852        s.contratos
10853            .push(contract_http("cart", "catalog", "/products/:id"));
10854        let err = s.validate().unwrap_err();
10855        assert!(
10856            matches!(
10857                err,
10858                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
10859                    if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
10860            ),
10861            "got {err:?}"
10862        );
10863    }
10864
10865    #[test]
10866    fn rejects_duplicate_pubsub_contrato() {
10867        // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
10868        // edges with identical (de, para, subject) are degenerate;
10869        // pin that the typed surface refuses both at validate time.
10870        let mut s = three_member_spec();
10871        let pubsub = WitContract {
10872            de: "payment".into(),
10873            para: "cart".into(),
10874            wit: "nats:pub-sub".into(),
10875            endpoint: None,
10876            subject: Some("checkout.events.charge.failed".into()),
10877            slot: None,
10878        };
10879        s.contratos.push(pubsub.clone());
10880        s.contratos.push(pubsub);
10881        let err = s.validate().unwrap_err();
10882        assert!(
10883            matches!(
10884                err,
10885                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
10886                    if de == "payment" && para == "cart" && wit == "nats:pub-sub"
10887            ),
10888            "got {err:?}"
10889        );
10890    }
10891
10892    #[test]
10893    fn rejects_duplicate_store_contrato() {
10894        // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
10895        // edges with identical (de, para, slot) collapse to one mesh-
10896        // policy edge; pin the build error.
10897        let mut s = three_member_spec();
10898        let store = WitContract {
10899            de: "cart".into(),
10900            para: "payment".into(),
10901            wit: "wasi:keyvalue/store".into(),
10902            endpoint: None,
10903            subject: None,
10904            slot: Some("checkout/$orderId".into()),
10905        };
10906        // Drop the conflicting HTTP `cart → payment` edge from the
10907        // fixture so the duplicate-store pair is the only one
10908        // distinguishable on this pair.
10909        s.contratos
10910            .retain(|c| !(c.de == "cart" && c.para == "payment"));
10911        s.contratos.push(store.clone());
10912        s.contratos.push(store);
10913        let err = s.validate().unwrap_err();
10914        assert!(
10915            matches!(
10916                err,
10917                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
10918                    if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
10919            ),
10920            "got {err:?}"
10921        );
10922    }
10923
10924    #[test]
10925    fn rejects_duplicate_capability_contrato() {
10926        // Same gate on the pure-capability axis (no payload selector).
10927        // Two contracts with identical (de, para, wit) and no
10928        // endpoint/subject/slot are duplicate edges; pin so a future
10929        // `target_label` change can't accidentally collapse the
10930        // capability arm into a None-shaped key that compares equal
10931        // to a populated one.
10932        let mut s = three_member_spec();
10933        let capability = WitContract {
10934            de: "cart".into(),
10935            para: "catalog".into(),
10936            wit: "pleme:cap/audit".into(),
10937            endpoint: None,
10938            subject: None,
10939            slot: None,
10940        };
10941        s.contratos.push(capability.clone());
10942        s.contratos.push(capability);
10943        let err = s.validate().unwrap_err();
10944        match err {
10945            AplicacaoError::ContratoDuplicate {
10946                de,
10947                para,
10948                wit,
10949                target,
10950            } => {
10951                assert_eq!(de, "cart");
10952                assert_eq!(para, "catalog");
10953                assert_eq!(wit, "pleme:cap/audit");
10954                assert!(
10955                    target.contains("capability"),
10956                    "capability-edge duplicate diagnostic must surface the \
10957                     no-payload shape (got target = {target:?})"
10958                );
10959            }
10960            other => panic!("expected ContratoDuplicate, got {other:?}"),
10961        }
10962    }
10963
10964    #[test]
10965    fn accepts_distinct_http_paths_between_same_pair() {
10966        // Negative pin: two HTTP contracts cart → catalog at distinct
10967        // endpoints (`/products/:id` and `/search`) are *not*
10968        // duplicates — they're distinct typed edges differing on the
10969        // payload axis. The duplicate-gate must not over-match here,
10970        // since the cart-calls-catalog-on-multiple-paths shape is the
10971        // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
10972        // example: cart calls catalog at /products/:id, payment at
10973        // /charge — same shape extends to two paths on one para).
10974        let mut s = three_member_spec();
10975        s.contratos
10976            .push(contract_http("cart", "catalog", "/search"));
10977        s.validate()
10978            .expect("distinct endpoints between same (de, para) must validate");
10979    }
10980
10981    #[test]
10982    fn accepts_same_endpoint_on_different_pairs() {
10983        // Negative pin: the same `/charge` endpoint reused on two
10984        // different (de, para) pairs is two distinct edges, not a
10985        // duplicate. Pinning this shape so the gate's identity key
10986        // includes both `de` and `para` (not just `(wit, endpoint)`).
10987        let mut s = three_member_spec();
10988        s.contratos
10989            .push(contract_http("payment", "catalog", "/charge"));
10990        s.validate()
10991            .expect("same endpoint reused on distinct (de, para) must validate");
10992    }
10993
10994    #[test]
10995    fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
10996        // Pin the diagnostic shape: the duplicate-edge error names
10997        // *which* target field carried the conflict, so the author
10998        // doesn't have to re-grep the source caixa.lisp to find it.
10999        // Same self-locating diagnostic discipline as
11000        // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
11001        let mut s = three_member_spec();
11002        s.contratos
11003            .push(contract_http("cart", "catalog", "/products/:id"));
11004        let err = s.validate().unwrap_err();
11005        let msg = format!("{err}");
11006        assert!(
11007            msg.contains("\"/products/:id\""),
11008            "duplicate-contrato diagnostic must name the offending \
11009             :endpoint payload (got: {msg:?})"
11010        );
11011        assert!(
11012            msg.contains("cart") && msg.contains("catalog"),
11013            "diagnostic must name both endpoints of the duplicate edge \
11014             (got: {msg:?})"
11015        );
11016    }
11017
11018    #[test]
11019    fn duplicate_contrato_gate_runs_after_membership_check() {
11020        // Order pin: a duplicate contract whose `:de` is *also* not in
11021        // `:membros` surfaces the membership error first — the
11022        // missing-member diagnostic is more locating than the
11023        // duplicate-edge one (the author has to fix the membership
11024        // before the duplicate is meaningful). Same ordering
11025        // discipline as `membros_validation_runs_before_contratos_membership_check`.
11026        let mut s = three_member_spec();
11027        s.contratos.push(contract_http("phantom", "catalog", "/x"));
11028        s.contratos.push(contract_http("phantom", "catalog", "/x"));
11029        let err = s.validate().unwrap_err();
11030        assert!(
11031            matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
11032            "membership-missing must fire before duplicate-edge (got {err:?})"
11033        );
11034    }
11035
11036    #[test]
11037    fn duplicate_contrato_gate_runs_after_target_shape_check() {
11038        // Order pin: a contract with a malformed target (e.g. an HTTP
11039        // wit world with an empty :endpoint) surfaces the target-shape
11040        // error first, not the duplicate one. Even when two such
11041        // malformed entries are identical, the per-contract `target()`
11042        // check fires inside the loop *before* the duplicate-key
11043        // insert, so the diagnostic remains the most-locating one.
11044        let mut s = three_member_spec();
11045        let malformed = WitContract {
11046            de: "cart".into(),
11047            para: "catalog".into(),
11048            wit: "wasi:http/proxy".into(),
11049            endpoint: Some(String::new()),
11050            subject: None,
11051            slot: None,
11052        };
11053        s.contratos.push(malformed.clone());
11054        s.contratos.push(malformed);
11055        let err = s.validate().unwrap_err();
11056        assert!(
11057            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
11058            "endpoint-empty must fire before duplicate-edge (got {err:?})"
11059        );
11060    }
11061
11062    #[test]
11063    fn wit_target_label_pins_per_variant_format() {
11064        // Label format is the single source of truth every duplicate-
11065        // `:contratos` diagnostic + every future `feira app graph`
11066        // consumer routes through. Pin the shape per variant so a
11067        // future edit to `WitTarget::label` (e.g. a JSON emitter that
11068        // strips the leading `:`, or a rename from `endpoint` →
11069        // `path`) surfaces as a red-red test rather than as a silent
11070        // downstream diagnostic drift. Together with the exhaustive
11071        // `match` on `WitTarget` inside `label()`, adding a future
11072        // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
11073        // peer, per-edge WIT registry variants) is a compile error at
11074        // the label site — not a fall-through into the `Capability`
11075        // "no payload" default the prior raw-field-probe helper
11076        // silently landed on.
11077        assert_eq!(
11078            WitTarget::Http {
11079                endpoint: "/charge",
11080            }
11081            .label(),
11082            "\
11083:endpoint \"/charge\""
11084        );
11085        assert_eq!(
11086            WitTarget::PubSub {
11087                subject: "events.checkout.paid",
11088            }
11089            .label(),
11090            "\
11091:subject \"events.checkout.paid\""
11092        );
11093        assert_eq!(
11094            WitTarget::Store {
11095                slot: "checkout/$order",
11096            }
11097            .label(),
11098            "\
11099:slot \"checkout/$order\""
11100        );
11101        assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
11102        // Capability-arm label routes through the lifted
11103        // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
11104        // declaration per arm, next to the variant" discipline the
11105        // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
11106        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
11107        // consts already carry extends to the payload-less arm; the
11108        // byte-string equality pin below plus this label-routes-
11109        // through-the-const pin make a future rebrand on either the
11110        // const declaration or the `label()` template a build error
11111        // here rather than a downstream consumer surprise.
11112        assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
11113        assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
11114    }
11115
11116    #[test]
11117    fn wit_target_display_routes_through_label_helper() {
11118        // Fail-before-pass-after pin on the fourth (and only remaining)
11119        // typed-shape-discriminator axis to converge onto the
11120        // three-path-convergence discipline the sibling M3
11121        // [`PlacementStrategy`] (0a2f653) and M2
11122        // [`crate::supervisor::RestartStrategy`] /
11123        // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
11124        // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
11125        // through [`WitTarget::label`], so every consumer reaching for
11126        // `format!("{v}")` on a typed payload target lands on the same
11127        // stable author-facing byte-string [`WitTarget::label`] returns
11128        // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
11129        // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
11130        // `:contratos` gate seeds via [`WitTarget::label`] at
11131        // aplicacao.rs:5491 already threads through.
11132        //
11133        // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
11134        // through to the `Debug` derive's structural output
11135        // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
11136        // rather than the [`WitTarget::label`] helper's stable byte-
11137        // string (`:endpoint "/charge"` — the author-facing `:contratos`
11138        // keyword form). Every future consumer that reaches for
11139        // `format!("{target}")` — the canonical shape every user-facing
11140        // pretty-print site on the sibling typed-enum axes
11141        // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
11142        // [`crate::supervisor::RestartPolicy`]) already uses — would
11143        // silently land under a different byte-string than the
11144        // [`WitTarget::label`] callers that the duplicate-`:contratos`
11145        // diagnostic already threads through, with the mismatch
11146        // surfacing as a downstream diagnostic / graph / audit line
11147        // reading one spelling while the substrate's own gate emitted
11148        // another.
11149        //
11150        // Pin the routing here so a future
11151        // `impl std::fmt::Display for WitTarget<'_>` reimplementation
11152        // that hand-rolls the per-arm formatting instead of delegating
11153        // to [`WitTarget::label`] fails at caixa-core build time.
11154        for variant in [
11155            WitTarget::Http {
11156                endpoint: "/charge",
11157            },
11158            WitTarget::PubSub {
11159                subject: "events.checkout.paid",
11160            },
11161            WitTarget::Store {
11162                slot: "checkout/$order",
11163            },
11164            WitTarget::Capability,
11165        ] {
11166            assert_eq!(
11167                variant.to_string(),
11168                variant.label(),
11169                "WitTarget::{variant:?} Display must route through \
11170                 WitTarget::label (single source of truth: the lifted \
11171                 payload_pair 4-arm dispatch the label helper already \
11172                 threads through)"
11173            );
11174        }
11175    }
11176
11177    #[test]
11178    fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
11179        // Consumer-side pin on the three-path convergence:
11180        // [`std::fmt::Display`] agrees byte-for-byte with the
11181        // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
11182        // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
11183        // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
11184        // Pre-lift the two paths were structurally independent — the
11185        // substrate-side gate reached for `target_view.label()` while a
11186        // future downstream diagnostic / graph / audit line reaching
11187        // for `format!("{target}")` would silently land on the `Debug`
11188        // derive's structural output. Pin the two paths byte-for-byte
11189        // here so any future variant addition (M4 `Rest`/`Grpc` split
11190        // of [`WitTarget::Http`], `Queue`-shaped peer of
11191        // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
11192        // match error at [`WitTarget::payload_pair`] rather than a
11193        // silent per-consumer dispatch miss.
11194        for variant in [
11195            WitTarget::Http {
11196                endpoint: "/charge",
11197            },
11198            WitTarget::PubSub {
11199                subject: "events.checkout.paid",
11200            },
11201            WitTarget::Store {
11202                slot: "checkout/$order",
11203            },
11204            WitTarget::Capability,
11205        ] {
11206            assert_eq!(
11207                format!("{variant}"),
11208                variant.label(),
11209                "WitTarget::{variant:?} Display byte-string must match \
11210                 the AplicacaoError::ContratoDuplicate `target:` carrier \
11211                 the AplicacaoSpec::validate duplicate-`:contratos` gate \
11212                 seeds via WitTarget::label — three-path convergence: \
11213                 Display + label + payload_pair all resolve to the same \
11214                 per-arm byte-string"
11215            );
11216        }
11217    }
11218
11219    #[test]
11220    fn wit_target_payload_pair_pins_per_variant() {
11221        // Pin the per-arm `(field-name, payload)` pair single-sourced
11222        // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
11223        // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
11224        // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
11225        // and [`WitTarget::field_name`] (returns the first component)
11226        // route through. Until this lift landed [`WitTarget::label`]
11227        // dispatched on the same three arms with a per-arm
11228        // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
11229        // paired [`WitTarget::HTTP_FIELD_NAME`] /
11230        // [`WitTarget::PUBSUB_FIELD_NAME`] /
11231        // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
11232        // canonical "same shape, written N times" duplication
11233        // THEORY.md §I.3.5 promotes to a build-time concern. A future
11234        // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
11235        // [`WitTarget::Http`], `Queue`-shaped peer of
11236        // [`WitTarget::Store`]) is one match-arm edit at
11237        // [`WitTarget::payload_pair`], visible here as a compile-time
11238        // exhaustiveness error on both this pin and the label-format
11239        // pin above.
11240        assert_eq!(
11241            WitTarget::Http {
11242                endpoint: "/charge"
11243            }
11244            .payload_pair(),
11245            Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
11246        );
11247        assert_eq!(
11248            WitTarget::PubSub {
11249                subject: "events.x",
11250            }
11251            .payload_pair(),
11252            Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
11253        );
11254        assert_eq!(
11255            WitTarget::Store {
11256                slot: "checkout/$order",
11257            }
11258            .payload_pair(),
11259            Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
11260        );
11261        assert_eq!(WitTarget::Capability.payload_pair(), None);
11262    }
11263
11264    #[test]
11265    fn wit_target_field_name_pins_per_variant() {
11266        // Pin the per-arm author-facing `:contratos` payload field
11267        // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
11268        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
11269        // + returned by [`WitTarget::field_name`]. Every downstream
11270        // consumer (the [`WitContract::target`] gate's `expected:`
11271        // scalar, the [`WitTarget::label`] template's keyword prefix,
11272        // the `feira app graph` verb's `endpoint=…` prefix) routes
11273        // through the same three peer consts, so a rename on the
11274        // author-surface `(defcaixa … :contratos ((:de … :para …
11275        // :wit … :endpoint …)))` field lands in exactly one place.
11276        assert_eq!(
11277            WitTarget::Http {
11278                endpoint: "/charge"
11279            }
11280            .field_name(),
11281            Some(WitTarget::HTTP_FIELD_NAME),
11282        );
11283        assert_eq!(
11284            WitTarget::PubSub {
11285                subject: "events.x",
11286            }
11287            .field_name(),
11288            Some(WitTarget::PUBSUB_FIELD_NAME),
11289        );
11290        assert_eq!(
11291            WitTarget::Store {
11292                slot: "checkout/$order",
11293            }
11294            .field_name(),
11295            Some(WitTarget::STORE_FIELD_NAME),
11296        );
11297        // Capability arm carries no payload field — the diagnostic
11298        // never reports `expected: "capability"` because the gate's
11299        // Capability arm accepts no payload at all (it fires the
11300        // "expected: none" WrongTarget error instead), so the field-
11301        // name method returns None here rather than a placeholder.
11302        assert_eq!(WitTarget::Capability.field_name(), None);
11303
11304        // Peer const scalar values pinned so a rename on either side
11305        // (author-surface field name in the `(defcaixa …)` DSL, or
11306        // the diagnostic's `expected:` scalar) can't drift without
11307        // failing here first.
11308        assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
11309        assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
11310        assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
11311    }
11312
11313    #[test]
11314    fn wit_target_field_names_are_pairwise_distinct() {
11315        // Distinctness pin: if any two of the three payload-field-name
11316        // scalars ever collapse (e.g. an accidental `endpoint` copy-
11317        // paste over the `subject` const), the [`WitContract::target`]
11318        // gate's diagnostic would point authors at the wrong field —
11319        // an "expected `:endpoint`" error on a pub-sub edge would
11320        // silently misroute the fix. Same cross-axis-distinctness
11321        // discipline as the peer M3 `:placement :estrategia` variant-
11322        // discriminator scalar-value pins (cc8f749) applied to the
11323        // payload-field-name axis.
11324        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
11325        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
11326        assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
11327    }
11328
11329    #[test]
11330    fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
11331        // 4-way distinctness pin extending the sibling
11332        // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
11333        // (which covers only the HTTP / PubSub / Store payload arms)
11334        // onto the fourth scalar the shared
11335        // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
11336        // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
11337        // (`"none"`), the payload-less Capability-arm rejection scalar.
11338        //
11339        // All four [`WitTarget::HTTP_FIELD_NAME`] /
11340        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
11341        // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
11342        // dispatch surface [`WitContract::target`] writes onto the
11343        // `ContratoWrongTarget::expected` field — the same `&'static
11344        // str` axis authors read as "this WIT world's shape admits
11345        // (only|not) `:<field>`". Pairwise-distinctness is the invariant
11346        // downstream consumers rely on: an `expected: "endpoint"`
11347        // diagnostic on a Capability-shaped edge tells the author to
11348        // add a `:endpoint "…"` slot to a WIT world that admits none,
11349        // silently misrouting the fix. Until this pin landed the three
11350        // payload-arm consts were distinctness-guarded by the sibling
11351        // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
11352        // scalar (d4f54f2) sat unguarded — a rebrand collision (the
11353        // author-facing vocabulary shift from `"none"` to `"endpoint"`
11354        // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
11355        // into per-shape peers) would have silently landed one
11356        // Capability-arm rejection on a payload-arm's `expected:` byte-
11357        // string and desynchronized the diagnostic from the author's
11358        // typed shape.
11359        //
11360        // Same 4-way pairwise-distinctness pin discipline as the peer
11361        // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
11362        // (cc8f749) applies on the sibling M3 closed-set typed-enum
11363        // scalar-value dispatch axis; extends the pin trajectory the
11364        // sibling `wit_target_field_names_are_pairwise_distinct`
11365        // 3-way pin opened to cover the last unguarded corner on the
11366        // `ContratoWrongTarget::expected` scalar-value axis.
11367        //
11368        // Fail-before-pass-after locally verified by mutating
11369        // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
11370        // — this pin fires as expected; restoring passes.
11371        let all = [
11372            WitTarget::HTTP_FIELD_NAME,
11373            WitTarget::PUBSUB_FIELD_NAME,
11374            WitTarget::STORE_FIELD_NAME,
11375            WitTarget::CAPABILITY_EXPECTED,
11376        ];
11377        for (i, a) in all.iter().enumerate() {
11378            for (j, b) in all.iter().enumerate() {
11379                if i != j {
11380                    assert_ne!(
11381                        a, b,
11382                        "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
11383                         STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
11384                         pairwise distinct — got duplicate {a:?} at indices \
11385                         {i} and {j}; all four scalars thread through the \
11386                         shared `AplicacaoError::ContratoWrongTarget::expected` \
11387                         &'static str axis, so a collapse silently misdirects \
11388                         the diagnostic on which typed shape the WIT world admits",
11389                    );
11390                }
11391            }
11392        }
11393    }
11394
11395    #[test]
11396    fn wit_target_is_variant_predicates_partition_the_arm_set() {
11397        // Fail-before-pass-after pin on the
11398        // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
11399        // each of the four variants exactly one of the generated
11400        // `is_http` / `is_pubsub` / `is_store` / `is_capability`
11401        // predicates returns `true` and the other three return
11402        // `false`. Prior to this derive the only production
11403        // arm-discriminator on [`WitTarget`] — the sync-cycle
11404        // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
11405        // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
11406        // the variant that expressed no compile-time link back to
11407        // the closed-set typed dispatch a future fifth
11408        // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
11409        // split of [`WitTarget::PubSub`] into shape-specific peers,
11410        // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
11411        // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
11412        // to thread through in lockstep or the DFS exclusion would
11413        // silently disagree with the peer diagnostic templates on
11414        // which arms carry sync-versus-async semantics. Peer of the
11415        // sibling [`crate::CaixaKind`] (f5bba80),
11416        // [`PlacementStrategy`] (766ec63),
11417        // [`crate::supervisor::RestartStrategy`],
11418        // [`crate::supervisor::RestartPolicy`], and
11419        // [`crate::upgrade::UpgradeInstruction`] (915a934)
11420        // `IsVariant` derives on the sibling closed-set typed-enum
11421        // discriminator axes — extends the same one-typed-dispatch-
11422        // per-variant discipline onto the last unlifted closed-set
11423        // typed-enum discriminator on the caixa surface (the M3
11424        // mesh-slot per-`:contratos` target-arm axis), closing the
11425        // arm-discriminator convergence trajectory across every
11426        // closed-set typed enum in caixa-core.
11427        let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
11428            (
11429                WitTarget::Http { endpoint: "/x" },
11430                [true, false, false, false],
11431            ),
11432            (
11433                WitTarget::PubSub {
11434                    subject: "events.x",
11435                },
11436                [false, true, false, false],
11437            ),
11438            (
11439                WitTarget::Store { slot: "kv/x" },
11440                [false, false, true, false],
11441            ),
11442            (WitTarget::Capability, [false, false, false, true]),
11443        ];
11444        for (variant, expected) in rows {
11445            let observed = [
11446                variant.is_http(),
11447                variant.is_pubsub(),
11448                variant.is_store(),
11449                variant.is_capability(),
11450            ];
11451            assert_eq!(
11452                observed, expected,
11453                "WitTarget::{variant:?} is_* predicates must partition \
11454                 the arm set (http, pubsub, store, capability); got {observed:?}"
11455            );
11456        }
11457    }
11458
11459    #[test]
11460    fn wit_target_is_variant_predicates_are_const_fn() {
11461        // The [`gen_platform::IsVariant`] derive emits `const fn`
11462        // predicates on the peer [`crate::CaixaKind`] +
11463        // [`crate::upgrade::UpgradeInstruction`] +
11464        // [`crate::supervisor::RestartStrategy`] +
11465        // [`crate::supervisor::RestartPolicy`] +
11466        // [`PlacementStrategy`] closed-set typed enums — pin the
11467        // same posture on [`WitTarget`] so a future accidental
11468        // downgrade to non-`const` (an added runtime helper reachable
11469        // only from a non-`const` context, a manual hand-rolled
11470        // `impl` that shadows the derive-generated method) trips at
11471        // caixa-core build time rather than surfacing as a downstream
11472        // `const`-context regression far from the derive declaration.
11473        //
11474        // Unlike the peer unit-variant enums (`CaixaKind` /
11475        // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
11476        // whose `const` constructors need no arguments, the three
11477        // payload-carrying [`WitTarget`] arms are const-constructed
11478        // through `&'static str` payloads — the same `'static`
11479        // lifetime the closed-set typed enum's four-arm partition
11480        // pin above already threads through.
11481        const HTTP: WitTarget<'static> = WitTarget::Http { endpoint: "/x" };
11482        const PUBSUB: WitTarget<'static> = WitTarget::PubSub { subject: "e" };
11483        const STORE: WitTarget<'static> = WitTarget::Store { slot: "kv/x" };
11484        const CAPABILITY: WitTarget<'static> = WitTarget::Capability;
11485        const IS_HTTP: bool = HTTP.is_http();
11486        const IS_PUBSUB: bool = PUBSUB.is_pubsub();
11487        const IS_STORE: bool = STORE.is_store();
11488        const IS_CAPABILITY: bool = CAPABILITY.is_capability();
11489        assert!(IS_HTTP);
11490        assert!(IS_PUBSUB);
11491        assert!(IS_STORE);
11492        assert!(IS_CAPABILITY);
11493    }
11494
11495    #[test]
11496    fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
11497        // Consumer-side pin on the sole production converge site:
11498        // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
11499        // edges from the synchronous-subgraph DFS via the lifted
11500        // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
11501        // predicate (rebound from the prior raw
11502        // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
11503        // variant). Byte-equivalent today (`is_pubsub` is the
11504        // derive-generated `matches!(self, Self::PubSub { .. })` by
11505        // construction, the `#[is_variant(name = "pubsub")]` override
11506        // aliasing the auto-derived `is_pub_sub` back to the sibling
11507        // [`WitContract::is_pubsub`] name); pin the behavior so a
11508        // future accidental drift (a rebind onto a peer arm
11509        // predicate, a manual hand-rolled `impl` that shadows the
11510        // derive-generated method with different semantics, a peer
11511        // arm rename that shifts which variant carries sync-versus-
11512        // async semantics) trips at caixa-core test time rather than
11513        // at some downstream operator's runtime dispatch far from the
11514        // rebind commit.
11515        //
11516        // The fixture constructs a two-Servico Aplicacao with one
11517        // pub-sub edge that would close a sync-cycle if the DFS did
11518        // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
11519        // pub-sub exclusion means the DFS sees only the `b → a` HTTP
11520        // edge, which is not a cycle. A regression in the converge
11521        // (a rebind that reads the pub-sub arm as sync) would report
11522        // `AplicacaoError::ContratoCycle`.
11523        let s = AplicacaoSpec {
11524            membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
11525            contratos: vec![
11526                // Pub-sub edge: DFS must skip via is_pubsub().
11527                WitContract {
11528                    de: "a".into(),
11529                    para: "b".into(),
11530                    wit: "nats:pub-sub".into(),
11531                    endpoint: None,
11532                    subject: Some("events.x".into()),
11533                    slot: None,
11534                },
11535                // HTTP edge: DFS must include.
11536                WitContract {
11537                    de: "b".into(),
11538                    para: "a".into(),
11539                    wit: "wasi:http/proxy".into(),
11540                    endpoint: Some("/x".into()),
11541                    subject: None,
11542                    slot: None,
11543                },
11544            ],
11545            politicas: MeshPolicy::default(),
11546            placement: Placement {
11547                estrategia: PlacementStrategy::Replicated,
11548                clusters: vec!["rio".into()],
11549                affinity: None,
11550                shard_key: None,
11551            },
11552            entrada: None,
11553        };
11554        s.validate()
11555            .expect("pub-sub edge must be excluded from sync-cycle DFS");
11556    }
11557
11558    #[test]
11559    fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
11560        // Consumer-side pin: the same three peer consts thread through
11561        // both the [`WitTarget::label`] template (leading-`:` keyword
11562        // prefix in the duplicate-`:contratos` diagnostic) and the
11563        // [`WitContract::target`] gate's [`AplicacaoError::
11564        // ContratoMissingTarget`] `expected:` scalar (the field the
11565        // author needs to add). Pin both routes at once so a future
11566        // refactor can't accidentally split them onto separate string
11567        // literals — the "one place, everywhere reaches for it"
11568        // invariant the peer const set carries.
11569        let http_label = WitTarget::Http { endpoint: "/x" }.label();
11570        assert!(
11571            http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
11572            "label must lead with :{} keyword (got {http_label:?})",
11573            WitTarget::HTTP_FIELD_NAME,
11574        );
11575
11576        let mut s = three_member_spec();
11577        s.contratos.push(WitContract {
11578            de: "cart".into(),
11579            para: "catalog".into(),
11580            wit: "kafka:topic".into(),
11581            endpoint: None,
11582            subject: None,
11583            slot: None,
11584        });
11585        match s.validate().unwrap_err() {
11586            AplicacaoError::ContratoMissingTarget { expected, .. } => {
11587                assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
11588            }
11589            other => panic!("expected ContratoMissingTarget, got {other:?}"),
11590        }
11591    }
11592
11593    #[test]
11594    fn duplicate_pubsub_diagnostic_names_offending_subject() {
11595        // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
11596        // on the pub-sub target axis: the duplicate-edge diagnostic
11597        // must name the `:subject` payload verbatim (not just the
11598        // `(de, para, wit)` triple). Prior to lifting the label onto
11599        // [`WitTarget::label`] the diagnostic derived the label from
11600        // raw [`WitContract`] `Option<String>` probes — a future
11601        // `WitTarget` variant addition (M4 per-edge WIT registry)
11602        // would silently fall through to the `Capability` "no
11603        // payload" default without a compiler warning. Pinning the
11604        // pub-sub arm's format closes the second of three
11605        // payload-carrying `WitTarget` arms this diagnostic threads
11606        // through.
11607        let mut s = three_member_spec();
11608        let pubsub = WitContract {
11609            de: "payment".into(),
11610            para: "cart".into(),
11611            wit: "nats:pub-sub".into(),
11612            endpoint: None,
11613            subject: Some("events.checkout.paid".into()),
11614            slot: None,
11615        };
11616        s.contratos.push(pubsub.clone());
11617        s.contratos.push(pubsub);
11618        let err = s.validate().unwrap_err();
11619        let msg = format!("{err}");
11620        assert!(
11621            msg.contains(":subject \"events.checkout.paid\""),
11622            "duplicate-pubsub diagnostic must name the offending \
11623             :subject payload (got: {msg:?})"
11624        );
11625    }
11626
11627    #[test]
11628    fn duplicate_store_diagnostic_names_offending_slot() {
11629        // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
11630        // key-value target axis: the diagnostic must name the `:slot`
11631        // payload verbatim. Third of three payload-carrying
11632        // `WitTarget` arms this diagnostic threads through, closing
11633        // the per-arm label pin trilogy (`Http` — 6841,
11634        // `PubSub` + `Store` — this test + peer above).
11635        let mut s = three_member_spec();
11636        let store = WitContract {
11637            de: "cart".into(),
11638            para: "payment".into(),
11639            wit: "wasi:keyvalue/store".into(),
11640            endpoint: None,
11641            subject: None,
11642            slot: Some("checkout/$orderId".into()),
11643        };
11644        s.contratos
11645            .retain(|c| !(c.de == "cart" && c.para == "payment"));
11646        s.contratos.push(store.clone());
11647        s.contratos.push(store);
11648        let err = s.validate().unwrap_err();
11649        let msg = format!("{err}");
11650        assert!(
11651            msg.contains(":slot \"checkout/$orderId\""),
11652            "duplicate-store diagnostic must name the offending :slot \
11653             payload (got: {msg:?})"
11654        );
11655    }
11656
11657    #[test]
11658    fn rejects_entrada_path_without_leading_slash() {
11659        let mut s = three_member_spec();
11660        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
11661        let err = s.validate().unwrap_err();
11662        assert!(
11663            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
11664            "got {err:?}"
11665        );
11666    }
11667
11668    #[test]
11669    fn rejects_empty_entrada_path() {
11670        let mut s = three_member_spec();
11671        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "".into()];
11672        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
11673    }
11674
11675    #[test]
11676    fn rejects_duplicate_entrada_paths() {
11677        let mut s = three_member_spec();
11678        s.entrada.as_mut().unwrap().paths = vec![
11679            "/api/cart".into(),
11680            "/api/products".into(),
11681            "/api/cart".into(),
11682        ];
11683        let err = s.validate().unwrap_err();
11684        assert!(
11685            matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
11686            "got {err:?}"
11687        );
11688    }
11689
11690    #[test]
11691    fn rejects_zero_entrada_port() {
11692        let mut s = three_member_spec();
11693        s.entrada.as_mut().unwrap().port = 0;
11694        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
11695    }
11696
11697    // ── :entrada :paths value-shape gate ─────────────────────────────
11698    //
11699    // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
11700    // sibling `:paths` axis. Every authoring footgun the K8s Gateway
11701    // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
11702    // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
11703    // time now becomes a caixa-build-time `EntradaPathInvalid` with
11704    // the offending `:paths` entry named verbatim.
11705
11706    #[test]
11707    fn rejects_entrada_path_with_query() {
11708        // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
11709        // silently passed validate and the Gateway API webhook
11710        // rejected it at apply time with no source citation.
11711        let mut s = three_member_spec();
11712        s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
11713        let err = s.validate().unwrap_err();
11714        assert!(
11715            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11716                if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
11717            "got {err:?}"
11718        );
11719    }
11720
11721    #[test]
11722    fn rejects_entrada_path_with_fragment() {
11723        let mut s = three_member_spec();
11724        s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
11725        let err = s.validate().unwrap_err();
11726        assert!(
11727            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11728                if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
11729            "got {err:?}"
11730        );
11731    }
11732
11733    #[test]
11734    fn rejects_entrada_path_with_space() {
11735        let mut s = three_member_spec();
11736        s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
11737        let err = s.validate().unwrap_err();
11738        assert!(
11739            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11740                if path == "/api/my cart" && reason.contains("whitespace")),
11741            "got {err:?}"
11742        );
11743    }
11744
11745    #[test]
11746    fn rejects_entrada_path_with_tab() {
11747        let mut s = three_member_spec();
11748        s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
11749        let err = s.validate().unwrap_err();
11750        assert!(
11751            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11752                if path == "/api/\tcart" && reason.contains("whitespace")),
11753            "got {err:?}"
11754        );
11755    }
11756
11757    #[test]
11758    fn rejects_entrada_path_with_control_char() {
11759        // 0x01 (SOH) — a non-whitespace control char surfaces the
11760        // distinct "control character" reason arm, separate from
11761        // the whitespace arm. Pinned so a future refactor that
11762        // collapses the two arms can't accidentally drop the more
11763        // self-locating diagnostic.
11764        let mut s = three_member_spec();
11765        s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
11766        let err = s.validate().unwrap_err();
11767        assert!(
11768            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11769                if path == "/api/\x01cart" && reason.contains("control character")),
11770            "got {err:?}"
11771        );
11772    }
11773
11774    #[test]
11775    fn rejects_entrada_path_with_non_ascii() {
11776        // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
11777        // unreserved-set rule rejects. The Gateway API webhook
11778        // rejects literal non-ASCII bytes; percent-encoding is the
11779        // only way to author non-ASCII in a path.
11780        let mut s = three_member_spec();
11781        s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
11782        let err = s.validate().unwrap_err();
11783        assert!(
11784            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11785                if path == "/api/café" && reason.contains("non-ASCII")),
11786            "got {err:?}"
11787        );
11788    }
11789
11790    #[test]
11791    fn rejects_entrada_path_with_consecutive_slashes() {
11792        let mut s = three_member_spec();
11793        s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
11794        let err = s.validate().unwrap_err();
11795        assert!(
11796            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11797                if path == "/api//cart" && reason.contains("consecutive `/`")),
11798            "got {err:?}"
11799        );
11800    }
11801
11802    #[test]
11803    fn rejects_entrada_path_with_dot_segment() {
11804        let mut s = three_member_spec();
11805        s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
11806        let err = s.validate().unwrap_err();
11807        assert!(
11808            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11809                if path == "/api/./cart" && reason.contains("`.` segment")),
11810            "got {err:?}"
11811        );
11812    }
11813
11814    #[test]
11815    fn rejects_entrada_path_with_trailing_dot_segment() {
11816        // The bare `/.` and the trailing `/foo/.` are both rejected
11817        // by the Gateway API webhook; pinned separately so a future
11818        // narrowing that catches only the inner form surfaces here.
11819        let mut s = three_member_spec();
11820        s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
11821        let err = s.validate().unwrap_err();
11822        assert!(
11823            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11824                if path == "/api/." && reason.contains("`.` segment")),
11825            "got {err:?}"
11826        );
11827    }
11828
11829    #[test]
11830    fn rejects_entrada_path_with_parent_segment() {
11831        let mut s = three_member_spec();
11832        s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
11833        let err = s.validate().unwrap_err();
11834        assert!(
11835            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11836                if path == "/api/../etc" && reason.contains("`..` parent-segment")),
11837            "got {err:?}"
11838        );
11839    }
11840
11841    #[test]
11842    fn rejects_entrada_path_with_trailing_parent_segment() {
11843        // Trailing `/..` — symmetric arm of the parent-segment rule,
11844        // pinned separately so a future relaxation that only checks
11845        // the inner form (`/../`) surfaces here.
11846        let mut s = three_member_spec();
11847        s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
11848        let err = s.validate().unwrap_err();
11849        assert!(
11850            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11851                if path == "/api/.." && reason.contains("`..` parent-segment")),
11852            "got {err:?}"
11853        );
11854    }
11855
11856    #[test]
11857    fn rejects_entrada_path_too_long() {
11858        // 1025-byte path — one over the Gateway API HTTPPathMatch.value
11859        // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
11860        // ASCII-alphanumeric body so only the length rule fires.
11861        let mut s = three_member_spec();
11862        let big = format!("/api/{}", "a".repeat(1020));
11863        assert_eq!(big.len(), 1025);
11864        s.entrada.as_mut().unwrap().paths = vec![big.clone()];
11865        let err = s.validate().unwrap_err();
11866        assert!(
11867            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11868                if path == &big && reason.contains("max length of 1024")),
11869            "got {err:?}"
11870        );
11871    }
11872
11873    #[test]
11874    fn entrada_path_max_length_validates() {
11875        // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
11876        // maxLength cap. Boundary pin: drift in the cap surfaces here
11877        // and at `rejects_entrada_path_too_long` simultaneously.
11878        let mut s = three_member_spec();
11879        let big = format!("/api/{}", "a".repeat(1019));
11880        assert_eq!(big.len(), 1024);
11881        s.entrada.as_mut().unwrap().paths = vec![big];
11882        s.validate().unwrap();
11883    }
11884
11885    #[test]
11886    fn entrada_accepts_canonical_paths() {
11887        // Positive-control sweep — every form the Gateway API
11888        // apiserver accepts must round-trip through validate. Covers
11889        // the root catch-all, plain paths, dot-prefixed segments
11890        // (hidden-file-style, distinct from `.` and `..` segments
11891        // which are rejected), digit-bearing segments, the canonical
11892        // route-template `:param` form (`:` is RFC 3986 reserved-set
11893        // valid in paths), trailing-slash form, percent-encoded
11894        // segments, and an interior `..` *substring* (`/foo..bar` is
11895        // not the `..` segment and is allowed).
11896        for path in [
11897            "/",
11898            "/api/cart",
11899            "/healthz",
11900            "/api/.config",
11901            "/v1/products",
11902            "/products/:id",
11903            "/api/cart/",
11904            "/api/caf%C3%A9",
11905            "/foo..bar",
11906            "/...",
11907        ] {
11908            let mut s = three_member_spec();
11909            s.entrada.as_mut().unwrap().paths = vec![path.into()];
11910            s.validate()
11911                .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
11912        }
11913    }
11914
11915    #[test]
11916    fn entrada_path_empty_takes_precedence_over_invalid() {
11917        // Ordering pin: `EntradaPathEmpty` is the more self-locating
11918        // diagnostic on `""` and must lead — `validate_entrada_path`
11919        // is only reached after the empty-check fires at the call
11920        // site. (The predicate itself defends against direct
11921        // invocation by returning the same error on `""`.)
11922        let mut s = three_member_spec();
11923        s.entrada.as_mut().unwrap().paths = vec!["".into()];
11924        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
11925    }
11926
11927    #[test]
11928    fn entrada_path_not_absolute_takes_precedence_over_invalid() {
11929        // Ordering pin: a path without a leading `/` surfaces the
11930        // narrower `EntradaPathNotAbsolute` diagnostic first; the
11931        // value-shape gate is only consulted on paths that already
11932        // satisfy the absolute-prefix invariant.
11933        let mut s = three_member_spec();
11934        // `bad path` would fire the whitespace rule under the
11935        // value-shape gate, but missing-leading-`/` is the more
11936        // self-locating diagnostic.
11937        s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
11938        let err = s.validate().unwrap_err();
11939        assert!(
11940            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
11941            "got {err:?}"
11942        );
11943    }
11944
11945    #[test]
11946    fn entrada_path_invalid_fires_before_duplicate_check() {
11947        // Ordering pin: a malformed path on the *first* entry of a
11948        // would-be duplicate pair fires the value-shape gate before
11949        // the duplicate gate, mirroring the
11950        // `placement_cluster_invalid_fires_before_duplicate_check`
11951        // (6cbb900) pattern on the peer axis.
11952        let mut s = three_member_spec();
11953        s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
11954        let err = s.validate().unwrap_err();
11955        assert!(
11956            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
11957            "got {err:?}"
11958        );
11959    }
11960
11961    #[test]
11962    fn entrada_path_diagnostic_carries_offending_path() {
11963        // Diagnostic-shape pin — the offending path + a non-empty
11964        // reason flow through verbatim so the author can grep their
11965        // caixa.lisp for `:paths` and fix it in one edit. Same shape
11966        // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
11967        let mut s = three_member_spec();
11968        s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
11969        let err = s.validate().unwrap_err();
11970        match err {
11971            AplicacaoError::EntradaPathInvalid { path, reason } => {
11972                assert_eq!(path, "/api?q=1");
11973                assert!(!reason.is_empty(), "reason field must be non-empty");
11974            }
11975            other => panic!("expected EntradaPathInvalid, got {other:?}"),
11976        }
11977    }
11978
11979    #[test]
11980    fn rejects_entrada_path_with_curly_brace_template_form() {
11981        // Per-axis pin on the shared `is_gateway_api_http_path`
11982        // reserved-byte arm: the canonical "I wrote an OpenAPI
11983        // path-template `{id}` instead of the Gateway API `:id` form"
11984        // footgun the K8s apiserver would otherwise catch at admission
11985        // time on every `HTTPRoute.spec.rules[].matches[].path.value`
11986        // landing site, far from the caixa.lisp. Surfaces as
11987        // `EntradaPathInvalid` carrying the offending path verbatim
11988        // plus the canonical `%7B`/`%7D` percent-encoding remediation
11989        // — the substrate-side `gateway_api_http_path_rejects_every_
11990        // reserved_printable_ascii_byte` predicate-level sweep pins the
11991        // full eleven-byte set; this per-axis pin confirms the
11992        // diagnostic flows through to the `EntradaPathInvalid` variant.
11993        let mut s = three_member_spec();
11994        s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
11995        let err = s.validate().unwrap_err();
11996        assert!(
11997            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11998                if path == "/api/cart/{id}"
11999                    && reason.contains("reserved character")
12000                    && reason.contains("'{'")
12001                    && reason.contains("%7B")),
12002            "got {err:?}"
12003        );
12004    }
12005
12006    #[test]
12007    fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
12008        // Per-axis peer of `rejects_entrada_path_with_curly_brace_
12009        // template_form` on the sibling `:contratos :endpoint` axis.
12010        // Same shared `is_gateway_api_http_path` reserved-byte arm
12011        // fires through `ContratoEndpointInvalid`, with the offending
12012        // endpoint + `:de` + `:para` + reason flowing through verbatim.
12013        // Pins that the lifted predicate's tightening lands on both
12014        // caller axes simultaneously — one source of truth for the
12015        // Gateway API HTTPPathMatch.value accepted set.
12016        let err = contrato_endpoint_err("/api/cart/{id}");
12017        assert!(
12018            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12019                if endpoint == "/api/cart/{id}"
12020                    && reason.contains("reserved character")
12021                    && reason.contains("'{'")
12022                    && reason.contains("%7B")),
12023            "got {err:?}"
12024        );
12025    }
12026
12027    // ── :entrada :host value-shape gate ──────────────────────────────
12028    //
12029    // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
12030    // the sibling `:host` axis. Every authoring footgun the K8s
12031    // Gateway API v1 apiserver would catch at admission time becomes
12032    // a caixa-build-time `EntradaHostInvalid` with the offending
12033    // `:host` named verbatim. Same diagnostic shape as
12034    // `MembroVersaoInvalid` (9888b13).
12035
12036    #[test]
12037    fn rejects_entrada_host_with_scheme() {
12038        // Fail-before-pass-after pin — pre-gate codebases silently
12039        // accepted `https://…` and the apiserver rejected it at apply
12040        // time with no source citation.
12041        let mut s = three_member_spec();
12042        s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
12043        let err = s.validate().unwrap_err();
12044        assert!(
12045            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
12046                if host == "https://checkout.quero.cloud"),
12047            "got {err:?}"
12048        );
12049    }
12050
12051    #[test]
12052    fn rejects_entrada_host_with_port() {
12053        // The `:8080` port suffix is the canonical "I forgot the port
12054        // belongs in `:entrada :port`" footgun. The top-level `:` arm
12055        // (introduced after the per-label loop-only impl silently
12056        // surfaced a deep "label \"cloud:8080\" contains invalid
12057        // character ':'" leak) names the canonical fix verbatim — the
12058        // `:entrada :port` slot.
12059        let mut s = three_member_spec();
12060        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
12061        let err = s.validate().unwrap_err();
12062        assert!(
12063            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
12064                if host == "checkout.quero.cloud:8080"
12065                && reason.contains(":entrada :port")),
12066            "got {err:?}"
12067        );
12068    }
12069
12070    #[test]
12071    fn rejects_entrada_host_with_trailing_colon() {
12072        // Trailing `:` (e.g. an in-progress `:host "example.com:"`
12073        // edit) — the per-label loop would land it as a deep
12074        // "label \"com:\" must start and end with an alphanumeric"
12075        // / "contains invalid character ':'" leak. The top-level
12076        // `:` arm pre-empts with the canonical `:port` slot
12077        // diagnostic.
12078        let mut s = three_member_spec();
12079        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
12080        let err = s.validate().unwrap_err();
12081        assert!(
12082            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
12083                if host == "checkout.quero.cloud:"
12084                && reason.contains(":entrada :port")),
12085            "got {err:?}"
12086        );
12087    }
12088
12089    #[test]
12090    fn rejects_entrada_host_unbracketed_ipv6_literal() {
12091        // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
12092        // literals across the board (peer with `rejects_entrada_host_
12093        // ipv4_literal` above for the four-label-all-digit IPv4 arm).
12094        // Before this top-level `:` arm landed the per-label loop
12095        // surfaced a single-label byte-class diagnostic that named the
12096        // `:` byte but not the IP-literal prohibition. The top-level
12097        // `:` arm names both the `:port` slot and the IP-literal
12098        // prohibition verbatim, so an author whose `:host "2001:..."`
12099        // value lands here gets a self-locating fix either way.
12100        let mut s = three_member_spec();
12101        s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
12102        let err = s.validate().unwrap_err();
12103        assert!(
12104            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
12105                if host == "2001:db8::1"
12106                && reason.contains("IPv6")),
12107            "got {err:?}"
12108        );
12109    }
12110
12111    #[test]
12112    fn rejects_entrada_host_wildcard_with_port() {
12113        // Wildcard host with port suffix — the `*.` strip and the
12114        // per-label loop on `["foo", "quero", "cloud:8080"]` would
12115        // surface the deep byte-class leak. The top-level `:` arm sits
12116        // upstream of the `*.` strip, so it names the canonical `:port`
12117        // fix verbatim regardless of whether the host is wildcard-led.
12118        let mut s = three_member_spec();
12119        s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
12120        let err = s.validate().unwrap_err();
12121        assert!(
12122            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
12123                if host == "*.quero.cloud:8080"
12124                && reason.contains(":entrada :port")),
12125            "got {err:?}"
12126        );
12127    }
12128
12129    #[test]
12130    fn rejects_entrada_host_with_path() {
12131        let mut s = three_member_spec();
12132        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
12133        let err = s.validate().unwrap_err();
12134        assert!(
12135            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
12136                if host == "checkout.quero.cloud/api"),
12137            "got {err:?}"
12138        );
12139    }
12140
12141    #[test]
12142    fn rejects_entrada_host_with_uppercase() {
12143        // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
12144        // rejected, not silently lower-cased.
12145        let mut s = three_member_spec();
12146        s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
12147        let err = s.validate().unwrap_err();
12148        assert!(
12149            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12150                if reason.contains("uppercase")),
12151            "got {err:?}"
12152        );
12153    }
12154
12155    #[test]
12156    fn rejects_entrada_host_with_underscore() {
12157        // RFC 1123 allows `[a-z0-9-]` only; underscore is the
12158        // canonical "I'm thinking of HTTP cookies / SRV records" leak.
12159        let mut s = three_member_spec();
12160        s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
12161        let err = s.validate().unwrap_err();
12162        assert!(
12163            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12164                if reason.contains('_')),
12165            "got {err:?}"
12166        );
12167    }
12168
12169    #[test]
12170    fn rejects_entrada_host_ipv4_literal() {
12171        // Gateway API v1 explicitly forbids IP literals as Hostnames.
12172        let mut s = three_member_spec();
12173        s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
12174        let err = s.validate().unwrap_err();
12175        assert!(
12176            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12177                if reason.contains("IPv4")),
12178            "got {err:?}"
12179        );
12180    }
12181
12182    #[test]
12183    fn rejects_entrada_host_with_trailing_dot() {
12184        // The Gateway API regex anchors at end-of-string with no
12185        // trailing `.` allowance — the FQDN root-dot form is rejected.
12186        let mut s = three_member_spec();
12187        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
12188        let err = s.validate().unwrap_err();
12189        assert!(
12190            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
12191                if host == "checkout.quero.cloud."),
12192            "got {err:?}"
12193        );
12194    }
12195
12196    #[test]
12197    fn rejects_entrada_host_with_leading_dot() {
12198        let mut s = three_member_spec();
12199        s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
12200        let err = s.validate().unwrap_err();
12201        assert!(
12202            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12203                if reason.contains("empty label")),
12204            "got {err:?}"
12205        );
12206    }
12207
12208    #[test]
12209    fn rejects_entrada_host_with_consecutive_dots() {
12210        let mut s = three_member_spec();
12211        s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
12212        let err = s.validate().unwrap_err();
12213        assert!(
12214            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12215                if reason.contains("empty label")),
12216            "got {err:?}"
12217        );
12218    }
12219
12220    #[test]
12221    fn rejects_entrada_host_with_leading_hyphen_label() {
12222        let mut s = three_member_spec();
12223        s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
12224        let err = s.validate().unwrap_err();
12225        assert!(
12226            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12227                if reason.contains("alphanumeric")),
12228            "got {err:?}"
12229        );
12230    }
12231
12232    #[test]
12233    fn rejects_entrada_host_with_trailing_hyphen_label() {
12234        let mut s = three_member_spec();
12235        s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
12236        let err = s.validate().unwrap_err();
12237        assert!(
12238            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12239                if reason.contains("alphanumeric")),
12240            "got {err:?}"
12241        );
12242    }
12243
12244    #[test]
12245    fn rejects_entrada_host_with_inner_wildcard() {
12246        // Gateway API allows `*` only as the first label (`*.foo`);
12247        // any inner or trailing `*` is rejected.
12248        let mut s = three_member_spec();
12249        s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
12250        let err = s.validate().unwrap_err();
12251        assert!(
12252            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12253                if reason.contains("wildcard")),
12254            "got {err:?}"
12255        );
12256    }
12257
12258    #[test]
12259    fn rejects_entrada_host_bare_wildcard() {
12260        // `*.` with no domain is meaningless; Gateway API rejects it.
12261        let mut s = three_member_spec();
12262        s.entrada.as_mut().unwrap().host = "*.".into();
12263        let err = s.validate().unwrap_err();
12264        assert!(
12265            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12266                if reason.contains("wildcard")),
12267            "got {err:?}"
12268        );
12269    }
12270
12271    #[test]
12272    fn rejects_entrada_host_with_whitespace() {
12273        let mut s = three_member_spec();
12274        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
12275        let err = s.validate().unwrap_err();
12276        assert!(
12277            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12278                if reason.contains("whitespace")),
12279            "got {err:?}"
12280        );
12281    }
12282
12283    #[test]
12284    fn rejects_entrada_host_space_names_offending_byte() {
12285        // Embedded space in the `:entrada :host` axis surfaces the
12286        // byte-naming diagnostic through the lifted
12287        // `find_ascii_whitespace_byte` predicate. Peer with the
12288        // sibling `parse_rejects_leading_whitespace` pins on
12289        // `supervisor::duration_codec` (a7ae622) — same "the
12290        // diagnostic carries the offending byte's `0x{b:02x}` shape"
12291        // discipline extended from the shared duration codec to the
12292        // Gateway API v1 Hostname axis.
12293        let mut s = three_member_spec();
12294        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
12295        let err = s.validate().unwrap_err();
12296        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12297            panic!("expected EntradaHostInvalid, got {err:?}");
12298        };
12299        assert!(
12300            reason.contains("ASCII whitespace byte"),
12301            "expected byte-naming diagnostic, got {reason:?}"
12302        );
12303        assert!(
12304            reason.contains("0x20"),
12305            "expected offending space byte 0x20, got {reason:?}"
12306        );
12307    }
12308
12309    #[test]
12310    fn rejects_entrada_host_tab_names_offending_byte() {
12311        // Embedded tab byte in the `:entrada :host` axis — the
12312        // canonical paste-from-YAML-block-scalar / paste-from-
12313        // indented-doc footgun. Pins that the lifted predicate covers
12314        // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
12315        // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
12316        // not just the leading-space case the pre-lift `.bytes().any`
12317        // arm's opaque "must not contain whitespace" reason already
12318        // covered. Peer with `parse_rejects_tab_byte` on
12319        // `supervisor::duration_codec` (a7ae622).
12320        let mut s = three_member_spec();
12321        s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
12322        let err = s.validate().unwrap_err();
12323        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12324            panic!("expected EntradaHostInvalid, got {err:?}");
12325        };
12326        assert!(
12327            reason.contains("ASCII whitespace byte"),
12328            "expected byte-naming diagnostic, got {reason:?}"
12329        );
12330        assert!(
12331            reason.contains("0x09"),
12332            "expected offending tab byte 0x09, got {reason:?}"
12333        );
12334    }
12335
12336    #[test]
12337    fn rejects_entrada_host_lf_names_offending_byte() {
12338        // Embedded LF byte in the `:entrada :host` axis — the
12339        // canonical paste-from-shell-heredoc / paste-from-multiline-
12340        // doc footgun the caixa-mesh YAML emitter would silently
12341        // reinterpret at the Gateway API v1 HTTPRoute admission
12342        // layer (an embedded LF byte in a YAML plain scalar either
12343        // truncates the value at the emitter or crashes the parser
12344        // on the k8s-apiserver side). Pins the third representative
12345        // of the full ASCII-whitespace set through the shared
12346        // predicate.
12347        let mut s = three_member_spec();
12348        s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
12349        let err = s.validate().unwrap_err();
12350        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12351            panic!("expected EntradaHostInvalid, got {err:?}");
12352        };
12353        assert!(
12354            reason.contains("ASCII whitespace byte"),
12355            "expected byte-naming diagnostic, got {reason:?}"
12356        );
12357        assert!(
12358            reason.contains("0x0a"),
12359            "expected offending LF byte 0x0a, got {reason:?}"
12360        );
12361    }
12362
12363    #[test]
12364    fn rejects_entrada_host_nbsp_names_offending_codepoint() {
12365        // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
12366        // axis — the canonical paste-from-typography /
12367        // paste-from-word-processor footgun. Before the non-ASCII
12368        // Unicode `White_Space` scan lifted through the shared
12369        // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
12370        // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
12371        // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
12372        // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
12373        // with the far-from-source `label "…" must start and end
12374        // with an alphanumeric` diagnostic — burying the
12375        // paste-from-typography origin under a label-shape leak.
12376        // Peer with the sibling non-ASCII-whitespace pins at
12377        // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
12378        // — 1b75b38), `limits::parse_duration`,
12379        // `limits::parse_millicores`, and the shared duration codec
12380        // — same "the diagnostic carries the offending Unicode
12381        // codepoint's `U+XXXX` shape" discipline extended from every
12382        // typed-magnitude codec to the Gateway API v1 Hostname axis.
12383        let mut s = three_member_spec();
12384        s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
12385        let err = s.validate().unwrap_err();
12386        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12387            panic!("expected EntradaHostInvalid, got {err:?}");
12388        };
12389        assert!(
12390            reason.contains("non-ASCII Unicode whitespace character"),
12391            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
12392        );
12393        assert!(
12394            reason.contains("U+00A0"),
12395            "expected offending NBSP codepoint U+00A0, got {reason:?}"
12396        );
12397    }
12398
12399    #[test]
12400    fn rejects_entrada_host_line_separator_names_offending_codepoint() {
12401        // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
12402        // `:entrada :host` axis — the canonical paste-from-web-doc /
12403        // paste-from-published-HTML footgun. `char::is_whitespace`
12404        // returns true for `U+2028` per the Unicode `White_Space`
12405        // property, so `str::trim` at any downstream site would
12406        // silently strip it — same drift class as NBSP but on a
12407        // different codepoint region. Pins the second representative
12408        // (non-Latin-1 `char::is_whitespace` member) through the
12409        // shared predicate. Peer with
12410        // `parse_byte_size_rejects_internal_line_separator` on
12411        // `limits::parse_byte_size` (1b75b38).
12412        let mut s = three_member_spec();
12413        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
12414        let err = s.validate().unwrap_err();
12415        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12416            panic!("expected EntradaHostInvalid, got {err:?}");
12417        };
12418        assert!(
12419            reason.contains("non-ASCII Unicode whitespace character"),
12420            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
12421        );
12422        assert!(
12423            reason.contains("U+2028"),
12424            "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
12425        );
12426    }
12427
12428    #[test]
12429    fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
12430        // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
12431        // labels in the `:entrada :host` axis — the canonical
12432        // paste-from-CJK-typography footgun (CJK IMEs default to
12433        // full-width whitespace when the space bar is pressed in
12434        // Japanese / Chinese input modes). Pins the third
12435        // representative of the non-ASCII Unicode `White_Space` set
12436        // through the shared predicate: the CJK block, distinct from
12437        // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
12438        // SEPARATOR `U+2028` — covering the same axis breadth the
12439        // sibling `parse_byte_size_rejects_trailing_ideographic_space`
12440        // (1b75b38) pins on `limits::parse_byte_size`.
12441        let mut s = three_member_spec();
12442        s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
12443        let err = s.validate().unwrap_err();
12444        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12445            panic!("expected EntradaHostInvalid, got {err:?}");
12446        };
12447        assert!(
12448            reason.contains("non-ASCII Unicode whitespace character"),
12449            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
12450        );
12451        assert!(
12452            reason.contains("U+3000"),
12453            "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
12454        );
12455    }
12456
12457    #[test]
12458    fn rejects_entrada_host_too_long() {
12459        // Total length cap = 253; build a 254-byte host out of two
12460        // 63-byte labels + one 62-byte label + dots.
12461        let mut s = three_member_spec();
12462        let big = format!(
12463            "{}.{}.{}.{}",
12464            "a".repeat(63),
12465            "b".repeat(63),
12466            "c".repeat(63),
12467            "d".repeat(254 - 63 * 3 - 3)
12468        );
12469        assert_eq!(big.len(), 254);
12470        s.entrada.as_mut().unwrap().host = big;
12471        let err = s.validate().unwrap_err();
12472        assert!(
12473            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12474                if reason.contains("max length of 253")),
12475            "got {err:?}"
12476        );
12477    }
12478
12479    #[test]
12480    fn rejects_entrada_host_label_too_long() {
12481        let mut s = three_member_spec();
12482        // 64-byte label — one over the per-label cap.
12483        s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
12484        let err = s.validate().unwrap_err();
12485        assert!(
12486            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12487                if reason.contains("label max length of 63")),
12488            "got {err:?}"
12489        );
12490    }
12491
12492    #[test]
12493    fn entrada_host_diagnostic_carries_offending_host() {
12494        // Diagnostic-shape pin — the offending host + a non-empty
12495        // reason flow through verbatim so the author can grep their
12496        // caixa.lisp for `:host "<host>"` and fix it in one edit.
12497        let mut s = three_member_spec();
12498        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
12499        let err = s.validate().unwrap_err();
12500        match err {
12501            AplicacaoError::EntradaHostInvalid { host, reason } => {
12502                assert_eq!(host, "checkout.quero.cloud:8080");
12503                assert!(!reason.is_empty(), "reason field must be non-empty");
12504            }
12505            other => panic!("expected EntradaHostInvalid, got {other:?}"),
12506        }
12507    }
12508
12509    #[test]
12510    fn entrada_host_empty_takes_precedence_over_invalid() {
12511        // Ordering pin: `EmptyEntradaHost` is the more self-locating
12512        // diagnostic on `""` and must lead — `validate_entrada_host`
12513        // is only reached after the empty-check fires at the call
12514        // site. (The predicate itself defends against direct
12515        // invocation by returning the same error on `""`.)
12516        let mut s = three_member_spec();
12517        s.entrada.as_mut().unwrap().host = String::new();
12518        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
12519    }
12520
12521    #[test]
12522    fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
12523        // Ordering pin: a missing :para member is the more
12524        // self-locating diagnostic and fires before the host gate.
12525        let mut s = three_member_spec();
12526        let e = s.entrada.as_mut().unwrap();
12527        e.para = "ghost".into();
12528        e.host = "BAD HOST".into();
12529        let err = s.validate().unwrap_err();
12530        assert!(
12531            matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
12532            "got {err:?}"
12533        );
12534    }
12535
12536    #[test]
12537    fn entrada_host_invalid_fires_before_port_zero() {
12538        // Ordering pin: the host gate fires before the port gate so
12539        // a malformed host is named even when the port is also wrong.
12540        let mut s = three_member_spec();
12541        let e = s.entrada.as_mut().unwrap();
12542        e.host = "Checkout.quero.cloud".into();
12543        e.port = 0;
12544        let err = s.validate().unwrap_err();
12545        assert!(
12546            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
12547                if host == "Checkout.quero.cloud"),
12548            "got {err:?}"
12549        );
12550    }
12551
12552    #[test]
12553    fn entrada_accepts_canonical_hosts() {
12554        // Positive-control sweep — every form the Gateway API
12555        // apiserver accepts must round-trip through validate. Covers
12556        // a plain DNS subdomain, a leading wildcard, a single-label
12557        // host (cluster-internal), a max-length-edge label, a
12558        // hyphen-bearing label, and a Punycode IDN label.
12559        for host in [
12560            "checkout.quero.cloud",
12561            "*.quero.cloud",
12562            "checkout",
12563            // 63-byte label — exactly the per-label cap.
12564            "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
12565            "foo-bar.quero.cloud",
12566            // Punycode IDN — valid because the author pre-encoded.
12567            "xn--bcher-kva.example.com",
12568        ] {
12569            let mut s = three_member_spec();
12570            s.entrada.as_mut().unwrap().host = host.into();
12571            s.validate()
12572                .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
12573        }
12574    }
12575
12576    #[test]
12577    fn entrada_host_max_length_validates() {
12578        // 253-byte host is the cap exactly — must validate. Build a
12579        // 253-byte host out of three 63-byte labels + one 61-byte
12580        // label + 3 dots = 252 bytes, then pad one byte to 253.
12581        let mut s = three_member_spec();
12582        let host = format!(
12583            "{}.{}.{}.{}",
12584            "a".repeat(63),
12585            "b".repeat(63),
12586            "c".repeat(63),
12587            "d".repeat(253 - 63 * 3 - 3)
12588        );
12589        assert_eq!(host.len(), 253);
12590        s.entrada.as_mut().unwrap().host = host;
12591        s.validate().unwrap();
12592    }
12593
12594    #[test]
12595    fn entrada_host_total_length_cap_threads_lifted_render_const() {
12596        // Cross-crate-side pin: the aplicacao-side `:entrada :host`
12597        // total-length gate now reads the K8s Gateway API v1 Hostname
12598        // `maxLength: 253` cap from the lifted
12599        // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
12600        // of truth — the same constant every future Gateway-API-Hostname
12601        // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
12602        // materializer's per-host validator, the future per-`Certificate`
12603        // SAN emitter for cert-manager, the multi-`:entrada`
12604        // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
12605        // from. Before the lift, the aplicacao-side reader consumed a
12606        // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
12607        // 253-byte value as the peer render-side canonical bounds
12608        // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
12609        // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
12610        // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
12611        // module boundary — a future 253-byte drift on either side would
12612        // silently split into two axes' worth of admission-schema mismatch
12613        // without a build-time signal. Pin the cap through a fresh 254-
12614        // byte host that hits the total-length arm, then read the reason
12615        // for the exact byte count the shared constant carries: any future
12616        // regression on the lift (a private alias reintroduced, a hard-
12617        // coded literal at the arm, a mismatch between the aplicacao-side
12618        // and render-side canonicals) surfaces as this pin's diagnostic
12619        // failing to match, not as a per-cluster admission rejection far
12620        // from the caixa.lisp source line.
12621        let mut s = three_member_spec();
12622        let over_cap = format!(
12623            "{}.{}.{}.{}",
12624            "a".repeat(63),
12625            "b".repeat(63),
12626            "c".repeat(63),
12627            "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
12628        );
12629        assert_eq!(
12630            over_cap.len(),
12631            crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
12632        );
12633        s.entrada.as_mut().unwrap().host = over_cap;
12634        let err = s.validate().unwrap_err();
12635        match err {
12636            AplicacaoError::EntradaHostInvalid { reason, .. } => {
12637                let needle = format!(
12638                    "max length of {} bytes",
12639                    crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
12640                );
12641                assert!(
12642                    reason.contains(&needle),
12643                    "diagnostic must name the lifted \
12644                     GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
12645                );
12646            }
12647            other => panic!("expected EntradaHostInvalid, got {other:?}"),
12648        }
12649    }
12650
12651    #[test]
12652    fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
12653        // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
12654        // on the per-label-cap axis. Before the lift, the aplicacao-side
12655        // per-label arm consumed a private const alias
12656        // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
12657        // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
12658        // split from it at the module boundary — every `.`-separated
12659        // label in a Gateway API v1 Hostname is a DNS-1123 label under
12660        // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
12661        // so the private alias's 63 and the canonical const's 63 were
12662        // pinning the same underlying rule twice. Pin the cap through a
12663        // 64-byte label that hits the per-label arm, then read the reason
12664        // for the exact byte count the shared constant carries: any
12665        // future drift on either side (a private alias reintroduced, a
12666        // hard-coded literal at the arm, a mismatch between the two
12667        // 63-byte pins) surfaces at this pin's diagnostic rather than at
12668        // a per-cluster admission rejection whose "field is invalid"
12669        // opacity misframes the root cause.
12670        let mut s = three_member_spec();
12671        let over_cap_label = format!(
12672            "{}.quero.cloud",
12673            "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
12674        );
12675        s.entrada.as_mut().unwrap().host = over_cap_label;
12676        let err = s.validate().unwrap_err();
12677        match err {
12678            AplicacaoError::EntradaHostInvalid { reason, .. } => {
12679                let needle = format!(
12680                    "label max length of {} bytes",
12681                    crate::render::DNS_1123_LABEL_MAX_LEN,
12682                );
12683                assert!(
12684                    reason.contains(&needle),
12685                    "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
12686                     cap verbatim on the per-label arm, got: {reason:?}",
12687                );
12688            }
12689            other => panic!("expected EntradaHostInvalid, got {other:?}"),
12690        }
12691    }
12692
12693    #[test]
12694    fn entrada_with_empty_paths_validates() {
12695        // Empty `:paths` is the documented "match every path" form;
12696        // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
12697        let mut s = three_member_spec();
12698        s.entrada.as_mut().unwrap().paths = vec![];
12699        s.validate().unwrap();
12700    }
12701
12702    #[test]
12703    fn entrada_root_path_validates() {
12704        // The author-supplied bare-root `:entrada :paths` entry is the
12705        // same byte-shape the peer emit-side catch-all constant
12706        // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
12707        // the author's `:paths` list is empty — sweeping the test-side
12708        // probe literal onto the lifted const closes the two-axis pin
12709        // (author-side admit + emit-side canonical fallback) around
12710        // one `&'static str`, so a future rebrand of the catch-all
12711        // reaches both consumers by construction. Peer to
12712        // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
12713        // on the canonical-literal pin surface.
12714        let mut s = three_member_spec();
12715        s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
12716        s.validate().unwrap();
12717    }
12718
12719    #[test]
12720    fn placement_strategy_variants_round_trip() {
12721        for s in [
12722            PlacementStrategy::SingleNode,
12723            PlacementStrategy::Replicated,
12724            PlacementStrategy::Sharded,
12725        ] {
12726            let p = Placement {
12727                estrategia: s,
12728                clusters: vec!["rio".into()],
12729                affinity: None,
12730                shard_key: if s.is_sharded() {
12731                    Some("$key".into())
12732                } else {
12733                    None
12734                },
12735            };
12736            let json = serde_json::to_string(&p).unwrap();
12737            let back: Placement = serde_json::from_str(&json).unwrap();
12738            assert_eq!(back, p);
12739        }
12740    }
12741
12742    #[test]
12743    fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
12744        // The fail-before-pass-after pin: pre-lift there was no
12745        // single-source binding between the [`PlacementStrategy`]
12746        // variant name the `Serialize` derive emits and the byte-
12747        // string every downstream cluster-side dispatcher (the
12748        // `lareira-fleet-programs` aggregator's per-entry strategy
12749        // branch, the future `app-operator` reconciler, the M3
12750        // Adaptive compression pass's per-strategy weighting) probes
12751        // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
12752        // future `#[serde(rename_all = "kebab-case")]` attribute on
12753        // the enum — or a variant rename in the source — would
12754        // silently rebrand the emitted scalar under one spelling
12755        // while every downstream dispatcher still probed the other,
12756        // with the failure surfacing at the aggregator's dispatch
12757        // step or the operator's reconcile posture (workloads coming
12758        // up under the `default()` `Replicated` arm rather than the
12759        // typed slot's declared strategy) far from the source
12760        // rebrand commit and with no field naming the drift. Pinning
12761        // the two paths (the `Serialize` derive's serialized string
12762        // AND the [`PlacementStrategy::as_str`] helper) to the same
12763        // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
12764        // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
12765        // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
12766        // makes any future drift on either endpoint fail here at
12767        // caixa-core build time.
12768        for (variant, expected) in [
12769            (
12770                PlacementStrategy::SingleNode,
12771                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
12772            ),
12773            (
12774                PlacementStrategy::Replicated,
12775                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
12776            ),
12777            (
12778                PlacementStrategy::Sharded,
12779                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
12780            ),
12781        ] {
12782            let json = serde_json::to_string(&variant).unwrap();
12783            assert_eq!(
12784                json,
12785                format!("\"{expected}\""),
12786                "PlacementStrategy::{variant:?} must serialize to {expected:?}"
12787            );
12788            assert_eq!(
12789                variant.as_str(),
12790                expected,
12791                "PlacementStrategy::{variant:?}.as_str() must return the lifted \
12792                 M3_PLACEMENT_ESTRATEGIA_* constant"
12793            );
12794        }
12795    }
12796
12797    #[test]
12798    fn m3_placement_estrategia_consts_are_pairwise_distinct() {
12799        // Cross-arm drift-detection pin on the M3
12800        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
12801        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
12802        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
12803        // scalar-value pentad: a future collapse of two canonical
12804        // variant byte-strings onto the same value (an accidental
12805        // copy-paste flip of
12806        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
12807        // read `"SingleNode"`, a per-arm rebrand that lands one const
12808        // without touching its paired peer) would silently reroute
12809        // every downstream operator's per-strategy dispatch onto the
12810        // sibling arm's reconcile branch and pass every
12811        // propagation-probe test that expected only the stale arm's
12812        // value — a `Replicated`-declared Aplicacao would come up
12813        // under the `SingleNode` primary-and-standby reconcile
12814        // posture, so every-cluster active-active workload would
12815        // silently collapse onto one-cluster-runs-at-a-time takeover
12816        // semantics against its declared strategy, with no field
12817        // naming the strategy-value drift root cause. Peer of the
12818        // sibling
12819        // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
12820        // (09ffb2d) /
12821        // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
12822        // (ccdf955) /
12823        // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
12824        // (d739850) distinctness pins on the sibling OTP-shape /
12825        // caixa-kind closed-set typed-enum discriminator axes — the
12826        // fourth (and structurally the M3 mesh-primitive-defining)
12827        // closed-set typed-enum axis to converge on the same
12828        // "pairwise-distinct-by-construction" discipline.
12829        //
12830        // Fail-before-pass-after locally verified by mutating
12831        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
12832        // also read `"SingleNode"` — this pin fires as expected;
12833        // restoring passes.
12834        let all = [
12835            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
12836            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
12837            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
12838        ];
12839        for (i, a) in all.iter().enumerate() {
12840            for (j, b) in all.iter().enumerate() {
12841                if i != j {
12842                    assert_ne!(
12843                        a, b,
12844                        "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
12845                         distinct — got duplicate {a:?} at indices {i} and {j}",
12846                    );
12847                }
12848            }
12849        }
12850    }
12851
12852    #[test]
12853    fn placement_strategy_display_routes_through_as_str_helper() {
12854        // The fail-before-pass-after pin: pre-lift the sibling
12855        // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
12856        // / [`crate::supervisor::RestartPolicy`] both carried a stable
12857        // [`std::fmt::Display`] surface via their
12858        // `#[discriminant(also_display)]` gen-platform derive, but
12859        // [`PlacementStrategy`] did not — every consumer reaching for
12860        // a strategy byte-string past the wire format had to pick
12861        // between three paths ([`PlacementStrategy::as_str`], the
12862        // `Serialize` derive's serialized string, or `format!("{v:?}")`
12863        // on the `Debug` derive), any two of which a future variant
12864        // rename or `#[serde(rename_all = "kebab-case")]` attribute
12865        // would silently desynchronize. Wiring [`std::fmt::Display`]
12866        // through [`PlacementStrategy::as_str`] closes the third path:
12867        // every `format!("{v}")` call reaches the same lifted
12868        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
12869        // and the [`PlacementStrategy::as_str`] helper already route
12870        // through, so a future variant rename lands at exactly one
12871        // place. Pin the routing here so a future
12872        // `impl std::fmt::Display for PlacementStrategy` reimplementation
12873        // that hand-rolls the arms instead of delegating to
12874        // [`PlacementStrategy::as_str`] fails at caixa-core build time.
12875        for variant in [
12876            PlacementStrategy::SingleNode,
12877            PlacementStrategy::Replicated,
12878            PlacementStrategy::Sharded,
12879        ] {
12880            assert_eq!(
12881                variant.to_string(),
12882                variant.as_str(),
12883                "PlacementStrategy::{variant:?} Display must route through \
12884                 PlacementStrategy::as_str (single source of truth: the lifted \
12885                 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
12886            );
12887        }
12888    }
12889
12890    #[test]
12891    fn placement_strategy_display_matches_serialized_wire_byte_string() {
12892        // The fail-before-pass-after pin on the second half of the
12893        // three-path convergence: `Display` (user-facing text) agrees
12894        // byte-for-byte with the `Serialize` derive's wire format
12895        // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
12896        // scalar) on every variant. Pre-lift the two paths were
12897        // structurally independent — a future
12898        // `#[serde(rename_all = "kebab-case")]` attribute on the enum
12899        // would silently rebrand the emitted wire scalar
12900        // (`single-node`, `replicated`, `sharded`) while every consumer
12901        // that pretty-prints the strategy (the M3 diagnostic templates,
12902        // the future `feira app graph` per-Aplicacao strategy line,
12903        // the future M4 CR materializer's admission-webhook rejection
12904        // body) would still emit the TitleCase form the `as_str` /
12905        // `Display` route returns, with the mismatch surfacing at
12906        // consumer parse time / operator dispatch time far from the
12907        // source rebrand commit. Pin the two paths byte-for-byte here
12908        // so any future serde-attribute or variant-rename drift is a
12909        // caixa-core-build-time test failure at this call, not a
12910        // silent per-consumer dispatch miss.
12911        for variant in [
12912            PlacementStrategy::SingleNode,
12913            PlacementStrategy::Replicated,
12914            PlacementStrategy::Sharded,
12915        ] {
12916            let wire = serde_json::to_string(&variant).unwrap();
12917            // Strip the outer `"…"` the JSON string form carries — the
12918            // wire scalar the K8s / YAML apiserver consumes is the
12919            // enclosed byte-string, not the quote wrapper.
12920            let unquoted = wire
12921                .strip_prefix('"')
12922                .and_then(|s| s.strip_suffix('"'))
12923                .expect("serialized PlacementStrategy is a JSON string");
12924            assert_eq!(
12925                variant.to_string(),
12926                unquoted,
12927                "PlacementStrategy::{variant:?} Display byte-string must match the \
12928                 Serialize derive's wire byte-string (three-path convergence: \
12929                 Display + as_str + Serialize all resolve to the same \
12930                 M3_PLACEMENT_ESTRATEGIA_* const)"
12931            );
12932        }
12933    }
12934
12935    #[test]
12936    fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
12937        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
12938        // derive on [`PlacementStrategy`]: for each of the three variants
12939        // exactly one of the generated `is_single_node` / `is_replicated`
12940        // / `is_sharded` predicates returns `true` and the other two
12941        // return `false`. Prior to this derive the three per-arm
12942        // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
12943        // (the `placement_strategy_variants_round_trip` fixture, the
12944        // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
12945        // fixture, and the
12946        // `validate_placement_reads_through_lifted_estrategia_accessor`
12947        // fixture) each open-coded a per-arm PartialEq compare against
12948        // the enum variant — three sites that expressed no compile-time
12949        // link back to the closed-set typed dispatch a future fourth
12950        // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
12951        // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
12952        // would have to thread through in lockstep or one fixture would
12953        // silently disagree with the others on which arms consume the
12954        // `:shard-key` axis. Peer of the sibling
12955        // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
12956        // / [`crate::supervisor::RestartPolicy`] /
12957        // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
12958        // the sibling closed-set typed-enum discriminator axes — extends
12959        // the same one-typed-dispatch-per-variant discipline onto the
12960        // fifth (and only remaining) closed-set typed-enum discriminator
12961        // on the caixa surface, closing the axis on the M3 mesh-slot
12962        // family.
12963        let rows: [(PlacementStrategy, [bool; 3]); 3] = [
12964            (PlacementStrategy::SingleNode, [true, false, false]),
12965            (PlacementStrategy::Replicated, [false, true, false]),
12966            (PlacementStrategy::Sharded, [false, false, true]),
12967        ];
12968        for (variant, expected) in rows {
12969            let observed = [
12970                variant.is_single_node(),
12971                variant.is_replicated(),
12972                variant.is_sharded(),
12973            ];
12974            assert_eq!(
12975                observed, expected,
12976                "PlacementStrategy::{variant:?} is_* predicates must partition \
12977                 the arm set (single_node, replicated, sharded); got {observed:?}"
12978            );
12979        }
12980    }
12981
12982    #[test]
12983    fn placement_strategy_is_variant_predicates_are_const_fn() {
12984        // The [`gen_platform::IsVariant`] derive emits `const fn`
12985        // predicates on the peer [`crate::CaixaKind`] +
12986        // [`crate::upgrade::UpgradeInstruction`] +
12987        // [`crate::supervisor::RestartStrategy`] +
12988        // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
12989        // pin the same posture on [`PlacementStrategy`] so a future
12990        // accidental downgrade to non-`const` (an added runtime helper
12991        // reachable only from a non-`const` context, a manual hand-rolled
12992        // `impl` that shadows the derive-generated method) trips at
12993        // caixa-core build time rather than surfacing as a downstream
12994        // `const`-context regression far from the derive declaration.
12995        const IS_SINGLE_NODE: bool = PlacementStrategy::SingleNode.is_single_node();
12996        const IS_REPLICATED: bool = PlacementStrategy::Replicated.is_replicated();
12997        const IS_SHARDED: bool = PlacementStrategy::Sharded.is_sharded();
12998        assert!(IS_SINGLE_NODE);
12999        assert!(IS_REPLICATED);
13000        assert!(IS_SHARDED);
13001    }
13002
13003    #[test]
13004    fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
13005        // Pin the M3 diagnostic template routes through the typed
13006        // [`PlacementStrategy`] Display byte-string (rebound from the
13007        // prior `{estrategia:?}` `Debug` route). Pre-lift the two
13008        // routes emitted identical bytes (the `Debug` derive on a
13009        // unit variant emits the variant name verbatim, exactly what
13010        // `as_str` returns), but the two paths were structurally
13011        // independent — a future `#[serde(rename_all = "…")]`
13012        // attribute or variant rename would coordinate the wire /
13013        // `Display` / `as_str` triple through the lifted const but
13014        // leave the `Debug` route on the compiler-derived variant name,
13015        // silently desynchronizing the diagnostic byte-string from the
13016        // wire byte-string. Rebinding the template onto `Display`
13017        // ties the diagnostic to the same lifted
13018        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
13019        // emits — drift becomes structurally impossible. Pin the
13020        // byte-string here so a future edit that reverts the template
13021        // to `{estrategia:?}` is caught at caixa-core test time, not
13022        // at consumer dispatch time.
13023        for (variant, expected_scalar) in [
13024            (
13025                PlacementStrategy::SingleNode,
13026                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
13027            ),
13028            (
13029                PlacementStrategy::Replicated,
13030                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
13031            ),
13032            (
13033                PlacementStrategy::Sharded,
13034                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
13035            ),
13036        ] {
13037            let err = AplicacaoError::PlacementWithoutClusters {
13038                estrategia: variant,
13039            };
13040            let msg = err.to_string();
13041            assert!(
13042                msg.starts_with(&format!(":placement {expected_scalar} requires")),
13043                "PlacementWithoutClusters diagnostic for {variant:?} must open \
13044                 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
13045            );
13046        }
13047    }
13048
13049    #[test]
13050    fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
13051        // Peer of
13052        // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
13053        // on the second M3 diagnostic that carries the typed
13054        // [`PlacementStrategy`] in its `#[error(…)]` template. Both
13055        // diagnostics now route the strategy scalar through the same
13056        // [`std::fmt::Display`] surface, tying the diagnostic
13057        // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
13058        // const set the wire format also emits. The two non-Sharded
13059        // arms are exercised here (the diagnostic exists to flag a
13060        // `:shard-key` slot the current strategy will never consume);
13061        // the peer `Sharded` arm never reaches this diagnostic (the
13062        // `Sharded` strategy consumes `:shard-key` — the
13063        // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
13064        // slot instead).
13065        for (variant, expected_scalar) in [
13066            (
13067                PlacementStrategy::SingleNode,
13068                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
13069            ),
13070            (
13071                PlacementStrategy::Replicated,
13072                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
13073            ),
13074        ] {
13075            let err = AplicacaoError::ShardKeyOnNonSharded {
13076                estrategia: variant,
13077                shard_key: "$tenantId".into(),
13078            };
13079            let msg = err.to_string();
13080            assert!(
13081                msg.starts_with(&format!(":placement {expected_scalar} carries")),
13082                "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
13083                 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
13084            );
13085        }
13086    }
13087
13088    #[test]
13089    fn rejects_zero_policy_timeout() {
13090        let mut s = three_member_spec();
13091        s.politicas.timeout = Some(Duration::ZERO);
13092        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
13093    }
13094
13095    #[test]
13096    fn rejects_zero_policy_retries() {
13097        let mut s = three_member_spec();
13098        s.politicas.retries = Some(0);
13099        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
13100    }
13101
13102    #[test]
13103    fn rejects_policy_retries_above_cap() {
13104        // The fail-before-pass-after pin: `Some(11)` is structurally
13105        // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
13106        // passed validate on every pre-gate codebase because the
13107        // typed slot's only check was the zero-floor arm. The
13108        // thundering-herd amplification vector only surfaced at the
13109        // runtime substrate (Envoy / Cilium L7 retry overlay)
13110        // far from the source caixa.lisp with no field naming the
13111        // offending policy.
13112        let mut s = three_member_spec();
13113        s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
13114        assert_eq!(
13115            s.validate().unwrap_err(),
13116            AplicacaoError::PolicyRetriesExceedsCap {
13117                retries: POLICY_RETRIES_MAX + 1
13118            }
13119        );
13120    }
13121
13122    #[test]
13123    fn rejects_policy_retries_far_above_cap() {
13124        // The `u32::MAX` worst case — the four-billion-retry policy
13125        // a typo (`(:retries 4294967295)`) or struct-literal
13126        // copy-paste lands in the slot. Pin the cap arm's coverage
13127        // explicitly across the full `u32` overflow so a future
13128        // relaxation that drops the upper bound surfaces here.
13129        let mut s = three_member_spec();
13130        s.politicas.retries = Some(u32::MAX);
13131        assert_eq!(
13132            s.validate().unwrap_err(),
13133            AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
13134        );
13135    }
13136
13137    #[test]
13138    fn accepts_policy_retries_at_cap() {
13139        // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
13140        // must validate. The cap is inclusive on the top edge,
13141        // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
13142        // discipline on the sibling [`crate::LimitsSpec::memory`]
13143        // axis. Pin the boundary explicitly so a future off-by-one
13144        // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
13145        // surfaces here as a test failure rather than a silent
13146        // contract narrowing.
13147        let mut s = three_member_spec();
13148        s.politicas.retries = Some(POLICY_RETRIES_MAX);
13149        s.validate()
13150            .expect("retries == POLICY_RETRIES_MAX must validate");
13151    }
13152
13153    #[test]
13154    fn accepts_policy_retries_typical_values() {
13155        // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
13156        // every value in the validated set must pass. The
13157        // Envoy / Istio production-playbook recommendation band
13158        // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
13159        // (`maxRetries ≤ 10`) both lie within this set.
13160        for r in 1..=POLICY_RETRIES_MAX {
13161            let mut s = three_member_spec();
13162            s.politicas.retries = Some(r);
13163            s.validate()
13164                .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
13165        }
13166    }
13167
13168    #[test]
13169    fn policy_retries_zero_takes_precedence_over_cap() {
13170        // The cross-arm ordering pin: `Some(0)` is structurally
13171        // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
13172        // (cap), but the zero-floor diagnostic is the more
13173        // self-locating one (it directly names the omit-axis
13174        // remediation), so the validate gate must fire on zero
13175        // first. Pin the order so a future refactor that reorders
13176        // the arms surfaces here as a test failure rather than a
13177        // silent diagnostic regression. Same shape every other
13178        // zero-then-shape ordering on this surface uses
13179        // ([`AplicacaoError::PolicyTimeoutZero`] then
13180        // [`AplicacaoError::PolicyTimeoutNotCanonical`];
13181        // [`AplicacaoError::PolicyBreakerZeroWindow`] then
13182        // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
13183        let mut s = three_member_spec();
13184        s.politicas.retries = Some(0);
13185        assert_eq!(
13186            s.validate().unwrap_err(),
13187            AplicacaoError::PolicyRetriesZero,
13188            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
13189        );
13190    }
13191
13192    #[test]
13193    fn policy_retries_cap_diagnostic_carries_offending_value() {
13194        // The diagnostic-shape pin: the offending `u32` is carried
13195        // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
13196        // variant so the surfaced error message names the value the
13197        // author wrote (`":politicas :retries (47) exceeds the
13198        // mesh-policy ceiling …"`), not just the cap. Same
13199        // self-locating diagnostic shape every other typed-cap arm
13200        // on this surface carries
13201        // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
13202        // offending byte count verbatim).
13203        let mut s = three_member_spec();
13204        s.politicas.retries = Some(47);
13205        let err = s.validate().unwrap_err();
13206        assert!(
13207            matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
13208            "got {err:?}"
13209        );
13210        let msg = err.to_string();
13211        assert!(
13212            msg.contains("47"),
13213            ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
13214        );
13215    }
13216
13217    #[test]
13218    fn policy_retries_cap_is_aws_app_mesh_aligned() {
13219        // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
13220        // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
13221        // schema cap — the only upstream mesh-policy schema that
13222        // documents an explicit hard cap. Pinning the literal value
13223        // here surfaces a future drift (a relaxation to 20, a
13224        // tightening to 5) as a deliberate test edit, not a silent
13225        // contract narrowing.
13226        assert_eq!(POLICY_RETRIES_MAX, 10);
13227    }
13228
13229    #[test]
13230    fn rejects_circuit_breaker_zero_max_failures() {
13231        let mut s = three_member_spec();
13232        s.politicas.circuit_breaker = Some(CircuitBreaker {
13233            max_failures: 0,
13234            window: Duration::from_secs(60),
13235        });
13236        assert_eq!(
13237            s.validate().unwrap_err(),
13238            AplicacaoError::PolicyBreakerZeroFailures
13239        );
13240    }
13241
13242    #[test]
13243    fn rejects_circuit_breaker_max_failures_above_cap() {
13244        // The fail-before-pass-after pin: `1001` is structurally one
13245        // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
13246        // silently passed validate on every pre-gate codebase
13247        // because the typed slot's only check was the zero-floor
13248        // arm. The breaker-no-op vector only surfaced at the runtime
13249        // substrate (Envoy / Cilium L7 outlier-detection overlay)
13250        // far from the source caixa.lisp with no field naming the
13251        // offending policy.
13252        let mut s = three_member_spec();
13253        s.politicas.circuit_breaker = Some(CircuitBreaker {
13254            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
13255            window: Duration::from_secs(60),
13256        });
13257        assert_eq!(
13258            s.validate().unwrap_err(),
13259            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
13260                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
13261            }
13262        );
13263    }
13264
13265    #[test]
13266    fn rejects_circuit_breaker_max_failures_far_above_cap() {
13267        // The `u32::MAX` worst case — the four-billion-failure
13268        // threshold a typo (`(:max-failures 4294967295)`) or a
13269        // struct-literal copy-paste lands in the slot. Pin the cap
13270        // arm's coverage explicitly across the full `u32` overflow
13271        // so a future relaxation that drops the upper bound surfaces
13272        // here.
13273        let mut s = three_member_spec();
13274        s.politicas.circuit_breaker = Some(CircuitBreaker {
13275            max_failures: u32::MAX,
13276            window: Duration::from_secs(60),
13277        });
13278        assert_eq!(
13279            s.validate().unwrap_err(),
13280            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
13281                max_failures: u32::MAX,
13282            }
13283        );
13284    }
13285
13286    #[test]
13287    fn accepts_circuit_breaker_max_failures_at_cap() {
13288        // The boundary value — exactly
13289        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
13290        // cap is inclusive on the top edge, matching the
13291        // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
13292        // discipline on the sibling capped axes. Pin the boundary
13293        // explicitly so a future off-by-one tightening
13294        // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
13295        // surfaces here as a test failure rather than a silent
13296        // contract narrowing.
13297        let mut s = three_member_spec();
13298        s.politicas.circuit_breaker = Some(CircuitBreaker {
13299            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
13300            window: Duration::from_secs(60),
13301        });
13302        s.validate()
13303            .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
13304    }
13305
13306    #[test]
13307    fn accepts_circuit_breaker_max_failures_typical_values() {
13308        // The documented production-playbook band positive-control
13309        // sweep — every value Hystrix / Istio / Envoy / Polly /
13310        // Resilience4j recommend (5..=50) must pass, plus a sweep
13311        // through the hyperscale band (100, 500, 1000) the cap
13312        // accepts. Pin the inclusive validated set explicitly so a
13313        // future tightening of the ceiling surfaces here.
13314        for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
13315            let mut s = three_member_spec();
13316            s.politicas.circuit_breaker = Some(CircuitBreaker {
13317                max_failures: n,
13318                window: Duration::from_secs(60),
13319            });
13320            s.validate()
13321                .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
13322        }
13323    }
13324
13325    #[test]
13326    fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
13327        // The cross-arm ordering pin: `0` is structurally outside
13328        // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
13329        // (cap), but the zero-floor diagnostic is the more
13330        // self-locating one (it directly names the omit-axis
13331        // remediation), so the validate gate must fire on zero
13332        // first. Same shape every other zero-then-shape ordering on
13333        // this surface uses
13334        // ([`AplicacaoError::PolicyRetriesZero`] then
13335        // [`AplicacaoError::PolicyRetriesExceedsCap`];
13336        // [`AplicacaoError::PolicyTimeoutZero`] then
13337        // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
13338        let mut s = three_member_spec();
13339        s.politicas.circuit_breaker = Some(CircuitBreaker {
13340            max_failures: 0,
13341            window: Duration::from_secs(60),
13342        });
13343        assert_eq!(
13344            s.validate().unwrap_err(),
13345            AplicacaoError::PolicyBreakerZeroFailures,
13346            "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
13347        );
13348    }
13349
13350    #[test]
13351    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
13352        // The cross-arm ordering pin between the cap and the
13353        // sibling `:window` gates (zero-window, canonical-window).
13354        // A breaker carrying both an over-cap `max_failures` AND a
13355        // structurally invalid window (zero, sub-ms) must surface
13356        // the cap diagnostic first — the cap arm is wired
13357        // immediately after the zero-failure arm and strictly
13358        // before the window arms, so the offending value the
13359        // diagnostic names matches the order the author would
13360        // discover the gates by reading top-to-bottom through
13361        // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
13362        // future refactor that reorders the arms surfaces here as a
13363        // test failure rather than a silent diagnostic regression.
13364        let mut s = three_member_spec();
13365        s.politicas.circuit_breaker = Some(CircuitBreaker {
13366            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
13367            window: Duration::ZERO,
13368        });
13369        assert_eq!(
13370            s.validate().unwrap_err(),
13371            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
13372                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
13373            },
13374            "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
13375        );
13376    }
13377
13378    #[test]
13379    fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
13380        // The diagnostic-shape pin: the offending `u32` is carried
13381        // verbatim into the
13382        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
13383        // variant so the surfaced error message names the value the
13384        // author wrote (`":politicas :circuit-breaker :max-failures
13385        // (50000) exceeds the mesh-policy ceiling …"`), not just
13386        // the cap. Same self-locating diagnostic shape every other
13387        // typed-cap arm on this surface carries
13388        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
13389        // offending retry count verbatim,
13390        // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
13391        // offending byte count verbatim).
13392        let mut s = three_member_spec();
13393        s.politicas.circuit_breaker = Some(CircuitBreaker {
13394            max_failures: 50_000,
13395            window: Duration::from_secs(60),
13396        });
13397        let err = s.validate().unwrap_err();
13398        assert!(
13399            matches!(
13400                err,
13401                AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
13402                    max_failures: 50_000
13403                }
13404            ),
13405            "got {err:?}"
13406        );
13407        let msg = err.to_string();
13408        assert!(
13409            msg.contains("50000"),
13410            ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
13411        );
13412    }
13413
13414    #[test]
13415    fn policy_breaker_max_failures_cap_pins_canonical_value() {
13416        // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
13417        // value at 1000 — an order of magnitude above every
13418        // documented production-playbook recommendation band
13419        // (Hystrix `requestVolumeThreshold` default 20, Istio
13420        // `outlierDetection.consecutive5xxErrors` default 5, Envoy
13421        // `outlier_detection.consecutive_5xx` default 5, Polly /
13422        // Resilience4j typical 5..=50) and below the
13423        // clearly-pathological "effectively no protection" floor
13424        // (10_000, 100_000, u32::MAX). Pinning the literal value
13425        // here surfaces a future drift (a relaxation to 10_000, a
13426        // tightening to 100) as a deliberate test edit, not a
13427        // silent contract narrowing.
13428        assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
13429    }
13430
13431    #[test]
13432    fn rejects_circuit_breaker_zero_window() {
13433        let mut s = three_member_spec();
13434        s.politicas.circuit_breaker = Some(CircuitBreaker {
13435            max_failures: 5,
13436            window: Duration::ZERO,
13437        });
13438        assert_eq!(
13439            s.validate().unwrap_err(),
13440            AplicacaoError::PolicyBreakerZeroWindow
13441        );
13442    }
13443
13444    #[test]
13445    fn rejects_zero_rate_limit() {
13446        let mut s = three_member_spec();
13447        s.politicas.rate_limit = Some(RateLimit {
13448            rate: 0,
13449            window: Duration::from_secs(1),
13450        });
13451        assert_eq!(
13452            s.validate().unwrap_err(),
13453            AplicacaoError::PolicyRateLimitZero
13454        );
13455    }
13456
13457    #[test]
13458    fn rejects_rate_limit_zero_window() {
13459        // `RateLimit { rate: 100, window: Duration::ZERO }` is
13460        // constructible programmatically (the typed `Duration` field
13461        // imposes no nonzero invariant) but renders through
13462        // `rate_limit_codec::render` as `"100/0s"` — a fragment the
13463        // codec's `parse` rejects as `unknown rate-limit window unit
13464        // "0s"`. Until this validate-time gate landed the typed slot
13465        // accepted the value silently and the round-trip break only
13466        // surfaced at deserialize time (potentially in a downstream
13467        // consumer that never re-validates). Pin the rejection at
13468        // `AplicacaoSpec::validate` so the typed slot's valid set
13469        // matches the codec's round-trippable set structurally.
13470        let mut s = three_member_spec();
13471        s.politicas.rate_limit = Some(RateLimit {
13472            rate: 100,
13473            window: Duration::ZERO,
13474        });
13475        assert_eq!(
13476            s.validate().unwrap_err(),
13477            AplicacaoError::PolicyRateLimitWindowNotCanonical {
13478                window: Duration::ZERO
13479            }
13480        );
13481    }
13482
13483    #[test]
13484    fn rejects_rate_limit_arbitrary_seconds_window() {
13485        // 45 seconds is a valid `Duration` but not one of the three
13486        // canonical rate-limit windows the codec round-trips
13487        // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
13488        // refuses on round-trip — same round-trip-break shape the
13489        // zero-window arm above pins, with a non-zero magnitude to
13490        // guard against a future "reject only zero" half-measure.
13491        let mut s = three_member_spec();
13492        let window = Duration::from_secs(45);
13493        s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
13494        assert_eq!(
13495            s.validate().unwrap_err(),
13496            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
13497        );
13498    }
13499
13500    #[test]
13501    fn rejects_rate_limit_two_minute_window() {
13502        // 120 seconds = 2 minutes is a "looks-canonical" but
13503        // not-canonical window: it's a clean integer multiple of the
13504        // minute unit, but the codec only round-trips the
13505        // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
13506        // A `Duration::from_secs(120)` window renders as `"100/120s"`
13507        // which the parser rejects. Pinning this case rules out a
13508        // future "accept any clean multiple of s/m/h" relaxation
13509        // that would silently break the codec contract.
13510        let mut s = three_member_spec();
13511        let window = Duration::from_secs(120);
13512        s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
13513        assert_eq!(
13514            s.validate().unwrap_err(),
13515            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
13516        );
13517    }
13518
13519    #[test]
13520    fn rejects_rate_limit_subsecond_window() {
13521        // A sub-second window (e.g. 500ms) is a valid `Duration` but
13522        // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
13523        // Pin the rejection so a future relaxation can't silently
13524        // admit fractional-second windows that the codec can't
13525        // round-trip.
13526        let mut s = three_member_spec();
13527        let window = Duration::from_millis(500);
13528        s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
13529        assert_eq!(
13530            s.validate().unwrap_err(),
13531            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
13532        );
13533    }
13534
13535    #[test]
13536    fn rejects_policy_rate_limit_above_cap() {
13537        // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
13538        // is structurally one past the cap and silently passed
13539        // validate on every pre-gate codebase because the typed slot's
13540        // only `rate` check was the zero-floor arm. The no-op-limiter
13541        // shape only surfaced at the runtime substrate (Envoy's
13542        // `local_rate_limit.token_bucket.max_tokens`, the future
13543        // Cilium L7 rate-limit overlay) far from the source caixa.lisp
13544        // with no field naming the offending policy.
13545        let mut s = three_member_spec();
13546        s.politicas.rate_limit = Some(RateLimit {
13547            rate: POLICY_RATE_LIMIT_MAX + 1,
13548            window: Duration::from_secs(1),
13549        });
13550        assert_eq!(
13551            s.validate().unwrap_err(),
13552            AplicacaoError::PolicyRateLimitExceedsCap {
13553                rate: POLICY_RATE_LIMIT_MAX + 1
13554            }
13555        );
13556    }
13557
13558    #[test]
13559    fn rejects_policy_rate_limit_far_above_cap() {
13560        // The `u32::MAX` worst case — the four-billion-token rate-limit
13561        // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
13562        // copy-paste lands in the slot. Pin the cap arm's coverage
13563        // explicitly across the full `u32` overflow so a future
13564        // relaxation that drops the upper bound surfaces here. Peer to
13565        // `rejects_policy_retries_far_above_cap` on the sibling
13566        // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
13567        // on the sibling `:max-failures` axis.
13568        let mut s = three_member_spec();
13569        s.politicas.rate_limit = Some(RateLimit {
13570            rate: u32::MAX,
13571            window: Duration::from_secs(1),
13572        });
13573        assert_eq!(
13574            s.validate().unwrap_err(),
13575            AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
13576        );
13577    }
13578
13579    #[test]
13580    fn accepts_policy_rate_limit_at_cap() {
13581        // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
13582        // must validate. The cap is inclusive on the top edge, matching
13583        // every other typed upper bound in this crate
13584        // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
13585        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
13586        // across all three canonical windows so a future off-by-one
13587        // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
13588        // window-conditional cap surfaces here as a test failure rather
13589        // than a silent contract narrowing.
13590        for secs in [1u64, 60, 3600] {
13591            let mut s = three_member_spec();
13592            s.politicas.rate_limit = Some(RateLimit {
13593                rate: POLICY_RATE_LIMIT_MAX,
13594                window: Duration::from_secs(secs),
13595            });
13596            s.validate().unwrap_or_else(|e| {
13597                panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
13598            });
13599        }
13600    }
13601
13602    #[test]
13603    fn accepts_policy_rate_limit_typical_values() {
13604        // The documented production-playbook recommendation band —
13605        // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
13606        // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
13607        // Enterprise ~1M per-hour. Every value in the validated set
13608        // must pass; pin the band explicitly so a future tightening
13609        // surfaces here.
13610        for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
13611            for secs in [1u64, 60, 3600] {
13612                let mut s = three_member_spec();
13613                s.politicas.rate_limit = Some(RateLimit {
13614                    rate,
13615                    window: Duration::from_secs(secs),
13616                });
13617                s.validate().unwrap_or_else(|e| {
13618                    panic!("rate={rate} window={secs}s must validate; got {e:?}")
13619                });
13620            }
13621        }
13622    }
13623
13624    #[test]
13625    fn policy_rate_limit_zero_takes_precedence_over_cap() {
13626        // The cross-arm ordering pin: `rate == 0` is structurally
13627        // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
13628        // (cap), but the zero-floor diagnostic is the more
13629        // self-locating one (it directly names the omit-axis
13630        // remediation). Pin the order so a future refactor that
13631        // reorders the arms surfaces here as a test failure rather
13632        // than a silent diagnostic regression. Same shape every other
13633        // zero-then-cap ordering on this surface uses
13634        // ([`AplicacaoError::PolicyRetriesZero`] then
13635        // [`AplicacaoError::PolicyRetriesExceedsCap`];
13636        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
13637        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
13638        let mut s = three_member_spec();
13639        s.politicas.rate_limit = Some(RateLimit {
13640            rate: 0,
13641            window: Duration::from_secs(1),
13642        });
13643        assert_eq!(
13644            s.validate().unwrap_err(),
13645            AplicacaoError::PolicyRateLimitZero,
13646            "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
13647        );
13648    }
13649
13650    #[test]
13651    fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
13652        // Two-axis-bad pin: rate above cap *and* window non-canonical.
13653        // The validate gate must fire on the rate cap first — the
13654        // amplification-shape (no-op limiter) diagnostic is the more
13655        // fundamental one; the window-canonical diagnostic is the
13656        // narrower codec-round-trip shape. Pin the ordering so a future
13657        // refactor that reorders the rate-then-window check arms
13658        // surfaces here as a test failure rather than a silent
13659        // diagnostic regression.
13660        let mut s = three_member_spec();
13661        s.politicas.rate_limit = Some(RateLimit {
13662            rate: POLICY_RATE_LIMIT_MAX + 1,
13663            window: Duration::from_secs(45),
13664        });
13665        assert_eq!(
13666            s.validate().unwrap_err(),
13667            AplicacaoError::PolicyRateLimitExceedsCap {
13668                rate: POLICY_RATE_LIMIT_MAX + 1
13669            },
13670            "above-cap rate must surface the cap diagnostic, not the window diagnostic"
13671        );
13672    }
13673
13674    #[test]
13675    fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
13676        // The diagnostic-shape pin: the offending `u32` is carried
13677        // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
13678        // variant so the surfaced error message names the value the
13679        // author wrote (`":politicas :rate-limit rate (5000000) exceeds
13680        // the mesh-policy ceiling …"`), not just the cap. Same
13681        // self-locating diagnostic shape every other typed-cap arm on
13682        // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
13683        // carries the offending retries count verbatim,
13684        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
13685        // the offending failure count verbatim).
13686        let mut s = three_member_spec();
13687        s.politicas.rate_limit = Some(RateLimit {
13688            rate: 5_000_000,
13689            window: Duration::from_secs(1),
13690        });
13691        let err = s.validate().unwrap_err();
13692        assert!(
13693            matches!(
13694                err,
13695                AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
13696            ),
13697            "got {err:?}"
13698        );
13699        let msg = err.to_string();
13700        assert!(
13701            msg.contains("5000000"),
13702            ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
13703        );
13704    }
13705
13706    #[test]
13707    fn policy_rate_limit_cap_pins_canonical_value() {
13708        // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
13709        // 1_000_000 — two-to-three orders of magnitude above every
13710        // documented production-playbook recommendation band (Envoy /
13711        // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
13712        // Gateway 10_000..=100_000 per-minute) and below the
13713        // clearly-pathological "paste-from-binary blob" floor
13714        // (100_000_000, u32::MAX). Pinning the literal value here
13715        // surfaces a future drift (a relaxation to 10_000_000, a
13716        // tightening to 100_000) as a deliberate test edit, not a
13717        // silent contract narrowing.
13718        assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
13719    }
13720
13721    #[test]
13722    fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
13723        // Both axes are invalid here: rate == 0 *and* window is
13724        // non-canonical. The validate gate must fire on rate first
13725        // (matching the existing `rejects_zero_rate_limit` ordering),
13726        // so the existing diagnostic continues to lead with the
13727        // simpler "zero rate" framing. Pinning the order of checks
13728        // so a future refactor that reorders the arms surfaces here
13729        // as a test failure rather than a silent diagnostic
13730        // regression.
13731        let mut s = three_member_spec();
13732        s.politicas.rate_limit = Some(RateLimit {
13733            rate: 0,
13734            window: Duration::from_secs(45),
13735        });
13736        assert_eq!(
13737            s.validate().unwrap_err(),
13738            AplicacaoError::PolicyRateLimitZero
13739        );
13740    }
13741
13742    #[test]
13743    fn rate_limit_canonical_windows_validate() {
13744        // The three canonical windows the codec round-trips
13745        // losslessly — 1s / 60s / 3600s — must all pass `validate()`
13746        // unchanged. Pin the full canonical set as a positive case
13747        // (the existing `rate_limit_round_trip_seconds` /
13748        // `rate_limit_round_trip_minutes` tests pin the
13749        // serialize-then-deserialize property at the codec layer; this
13750        // test pins the validate-side complement so a future tightening
13751        // of the canonical set — e.g. dropping `:hour` — surfaces here
13752        // as a test failure rather than a silent contract narrowing).
13753        for secs in [1u64, 60, 3600] {
13754            let mut s = three_member_spec();
13755            s.politicas.rate_limit = Some(RateLimit {
13756                rate: 100,
13757                window: Duration::from_secs(secs),
13758            });
13759            s.validate().expect("canonical window must validate");
13760        }
13761    }
13762
13763    #[test]
13764    fn rate_limit_validated_value_round_trips_through_codec() {
13765        // The structural property the validate gate enforces:
13766        // every `RateLimit` past `AplicacaoSpec::validate` round-trips
13767        // losslessly through the `rate_limit_codec` (serialize → string
13768        // → deserialize → equal value). Pin this end-to-end so a future
13769        // change to either side (the validate gate's accepted window
13770        // set, the codec's parse/render unit set) that breaks the
13771        // alignment surfaces here. The previous-state shape (typed
13772        // slot accepts arbitrary `Duration`, codec only round-trips
13773        // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
13774        // window — the validate gate now forecloses that.
13775        for secs in [1u64, 60, 3600] {
13776            let mut s = three_member_spec();
13777            s.politicas.rate_limit = Some(RateLimit {
13778                rate: 250,
13779                window: Duration::from_secs(secs),
13780            });
13781            s.validate().unwrap();
13782            let json = serde_json::to_string(&s.politicas).unwrap();
13783            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
13784            assert_eq!(
13785                back.rate_limit, s.politicas.rate_limit,
13786                "every validated :rate-limit must round-trip losslessly through the codec"
13787            );
13788        }
13789    }
13790
13791    #[test]
13792    fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
13793        // The hour-window canonical form (`"<n>/h"`) was missing from
13794        // the prior `rate_limit_round_trip_seconds` / `_minutes` test
13795        // pair. Now that the validate gate pins 3600s as part of the
13796        // canonical set, pin its serialize-side render shape too so
13797        // the third leg of the s/m/h tripod is explicitly tested.
13798        let policy = MeshPolicy {
13799            rate_limit: Some(RateLimit {
13800                rate: 10000,
13801                window: Duration::from_secs(3600),
13802            }),
13803            ..Default::default()
13804        };
13805        let json = serde_json::to_string(&policy).unwrap();
13806        assert!(
13807            json.contains("\"10000/h\""),
13808            "hour-window canonical form must render with `h` suffix (got: {json})"
13809        );
13810        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
13811        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
13812    }
13813
13814    #[test]
13815    fn is_canonical_rate_limit_window_predicate_tracks_codec() {
13816        // Pin the predicate's accepted set against the codec's
13817        // accepted set explicitly. A future addition to the codec
13818        // (e.g. accepting `:day`/`:week` as authoring units) must be
13819        // accompanied by a parallel addition here, and a regression
13820        // that drops one of the three canonical units from either
13821        // side surfaces as a test failure. The predicate is the
13822        // single source of truth for the canonical-window set; this
13823        // test enshrines that the codec's parse arms and the
13824        // predicate's accept arms agree exactly.
13825        assert!(super::is_canonical_rate_limit_window(Duration::from_secs(
13826            1
13827        )));
13828        assert!(super::is_canonical_rate_limit_window(Duration::from_secs(
13829            60
13830        )));
13831        assert!(super::is_canonical_rate_limit_window(Duration::from_secs(
13832            3600
13833        )));
13834        // Non-canonical windows the predicate rejects.
13835        assert!(!super::is_canonical_rate_limit_window(Duration::ZERO));
13836        assert!(!super::is_canonical_rate_limit_window(Duration::from_secs(
13837            2
13838        )));
13839        assert!(!super::is_canonical_rate_limit_window(Duration::from_secs(
13840            30
13841        )));
13842        assert!(!super::is_canonical_rate_limit_window(Duration::from_secs(
13843            120
13844        )));
13845        assert!(!super::is_canonical_rate_limit_window(Duration::from_secs(
13846            86400
13847        )));
13848        // Sub-second windows: even `Duration::from_millis(1000)` is
13849        // exactly 1s and accepted; `Duration::from_millis(500)` is
13850        // sub-second and rejected.
13851        assert!(super::is_canonical_rate_limit_window(
13852            Duration::from_millis(1000)
13853        ));
13854        assert!(!super::is_canonical_rate_limit_window(
13855            Duration::from_millis(500)
13856        ));
13857        assert!(!super::is_canonical_rate_limit_window(
13858            Duration::from_millis(1500)
13859        ));
13860    }
13861
13862    #[test]
13863    fn rate_limit_unit_table_projections_are_mutual_inverses() {
13864        // Bidirection pin against the lifted [`RATE_LIMIT_UNIT_TABLE`]
13865        // (the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}`
13866        // bijection every consumer of the rate-limit unit surface
13867        // reads from). Until this table landed the three (str,
13868        // Duration) pairs sat scattered across four peer sites —
13869        // `rate_limit_codec::parse`'s `match unit` arm, `render`'s
13870        // `if secs == 1 { "s" } else if …` cascade, and
13871        // `is_canonical_rate_limit_window`'s `secs == 1 || 60 ||
13872        // 3600` disjunction — each carrying its own hand-written copy
13873        // with no compile-time link between them. A future
13874        // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
13875        // sub-second window) would have to be threaded through all
13876        // three sites in lockstep or a drift would silently split
13877        // the accepted-window set. Lifting the pairs onto one const
13878        // + two projection helpers collapses the surface: this pin
13879        // enshrines that both projections agree on every table row
13880        // and neither leaks a spurious entry the other doesn't
13881        // recognize.
13882        for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
13883            let window = super::rate_limit_window_from_unit(unit)
13884                .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
13885            assert_eq!(
13886                window,
13887                Duration::from_secs(secs),
13888                "unit {unit:?} must resolve to {secs}s"
13889            );
13890            assert_eq!(
13891                super::rate_limit_window_unit(window),
13892                Some(unit),
13893                "Duration({secs}s) must render as {unit:?}"
13894            );
13895        }
13896        // Non-table units yield None on the `unit → Duration`
13897        // projection — a future `"d"` addition to the table would
13898        // flip this arm; today it pins the current three-row table's
13899        // rejection semantics.
13900        assert!(super::rate_limit_window_from_unit("d").is_none());
13901        assert!(super::rate_limit_window_from_unit("ms").is_none());
13902        assert!(super::rate_limit_window_from_unit("").is_none());
13903        // Non-table Durations yield None on the `Duration → unit`
13904        // projection — pins that the two projections agree on the
13905        // "not in the table" semantic too, so a drift where the
13906        // parse-side accepts a value the render-side can't emit is
13907        // a build error at the two-arm pair, not a silent codec
13908        // round-trip break.
13909        assert!(super::rate_limit_window_unit(Duration::from_secs(2)).is_none());
13910        assert!(super::rate_limit_window_unit(Duration::from_secs(86_400)).is_none());
13911        assert!(super::rate_limit_window_unit(Duration::from_millis(1500)).is_none());
13912    }
13913
13914    #[test]
13915    fn rate_limit_unit_all_enumerates_every_arm_once() {
13916        // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
13917        // enumerate every arm of the closed-set enum exactly once, in
13918        // the canonical shortest-to-longest window order (Second before
13919        // Minute before Hour) — the same order the sibling
13920        // [`crate::supervisor::RestartStrategy`] /
13921        // [`crate::supervisor::RestartPolicy`] /
13922        // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
13923        // typed enums carry (the arm declared first is the arm listed
13924        // first). A future variant addition that extends the enum
13925        // without appending to [`RateLimitUnit::ALL`] leaves the
13926        // exhaustive iteration surface silently short one arm — the
13927        // codec's parse arm would then reject the new suffix even
13928        // though the enum knows it. This pin closes the drift.
13929        assert_eq!(
13930            super::RateLimitUnit::ALL,
13931            &[
13932                super::RateLimitUnit::Second,
13933                super::RateLimitUnit::Minute,
13934                super::RateLimitUnit::Hour,
13935            ],
13936            "RateLimitUnit::ALL must enumerate every arm exactly once, \
13937             in canonical shortest-to-longest window order"
13938        );
13939    }
13940
13941    #[test]
13942    fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
13943        // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
13944        // every arm's [`RateLimitUnit::as_suffix`] output must parse
13945        // back through [`RateLimitUnit::from_suffix`] to the same
13946        // variant. A future arm addition that lands `as_suffix` but
13947        // forgets `from_suffix` (`from_suffix` iterates
13948        // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
13949        // is the load-bearing carrier of the round-trip; the sibling
13950        // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
13951        // the `ALL` half) trips here at caixa-core build time rather
13952        // than surfacing as a codec round-trip miss (a `render` emit
13953        // that lands a suffix the paired `parse` cannot decode).
13954        for unit in super::RateLimitUnit::ALL {
13955            let suffix = unit.as_suffix();
13956            let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
13957                panic!(
13958                    "RateLimitUnit::from_suffix({suffix:?}) must accept every \
13959                     RateLimitUnit::as_suffix output — got None for {unit:?}"
13960                )
13961            });
13962            assert_eq!(
13963                parsed, *unit,
13964                "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
13965                 must return RateLimitUnit::{unit:?}"
13966            );
13967        }
13968    }
13969
13970    #[test]
13971    fn rate_limit_unit_from_window_and_window_round_trip() {
13972        // Total round-trip pin on the `(from_window, window)` pair:
13973        // every arm's [`RateLimitUnit::window`] output must parse back
13974        // through [`RateLimitUnit::from_window`] to the same variant.
13975        // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
13976        // on the peer `Duration` axis — the two round-trip pins
13977        // together enshrine that both projections of the typed
13978        // canonical-unit bijection are total on the arm-set.
13979        for unit in super::RateLimitUnit::ALL {
13980            let window = unit.window();
13981            let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
13982                panic!(
13983                    "RateLimitUnit::from_window({window:?}) must accept every \
13984                     RateLimitUnit::window output — got None for {unit:?}"
13985                )
13986            });
13987            assert_eq!(
13988                parsed, *unit,
13989                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
13990                 must return RateLimitUnit::{unit:?}"
13991            );
13992        }
13993    }
13994
13995    #[test]
13996    fn rate_limit_unit_projections_are_pairwise_distinct() {
13997        // Distinctness pin: [`RateLimitUnit::as_suffix`] and
13998        // [`RateLimitUnit::window`] outputs must be pairwise distinct
13999        // across every arm — an accidental copy-paste flip that
14000        // reroutes one arm's suffix or window to also match another
14001        // silently collapses two arms onto one, so
14002        // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
14003        // (both using `find` on `Self::ALL`) would return whichever
14004        // arm the linear scan lands on first — a match-arm-ordering-
14005        // dependent outcome the closed-set typed-enum shape is meant
14006        // to rule out structurally. Peer of the sibling
14007        // `caixa_kind_wire_consts_are_pairwise_distinct` /
14008        // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
14009        // other closed-set typed-enum discriminator axes.
14010        let all = super::RateLimitUnit::ALL;
14011        for (i, a) in all.iter().enumerate() {
14012            for (j, b) in all.iter().enumerate() {
14013                if i != j {
14014                    assert_ne!(
14015                        a.as_suffix(),
14016                        b.as_suffix(),
14017                        "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
14018                         must be distinct — a collision silently collapses two \
14019                         arms onto one under from_suffix's linear scan"
14020                    );
14021                    assert_ne!(
14022                        a.window(),
14023                        b.window(),
14024                        "RateLimitUnit::{a:?}.window() and {b:?}.window() \
14025                         must be distinct — a collision silently collapses two \
14026                         arms onto one under from_window's linear scan"
14027                    );
14028                }
14029            }
14030        }
14031    }
14032
14033    #[test]
14034    fn rate_limit_unit_display_routes_through_as_suffix() {
14035        // Route pin: [`std::fmt::Display`] must byte-equal
14036        // [`RateLimitUnit::as_suffix`] on every arm — the single
14037        // source of truth for the canonical suffix. A future
14038        // reimplementation that hand-rolls the arms instead of
14039        // delegating to [`RateLimitUnit::as_suffix`] would silently
14040        // desynchronize `format!("{u}")` from the codec's parse arm
14041        // (which uses `as_suffix` to compare suffixes). Peer of the
14042        // sibling `caixa_kind_display_routes_through_as_str_helper` /
14043        // `placement_strategy_display_routes_through_as_str_helper`
14044        // pins on the peer closed-set typed-enum Display axes.
14045        for unit in super::RateLimitUnit::ALL {
14046            assert_eq!(
14047                unit.to_string(),
14048                unit.as_suffix(),
14049                "RateLimitUnit::{unit:?} Display must route through \
14050                 as_suffix (single source of truth: the canonical suffix \
14051                 the codec parses and renders)"
14052            );
14053        }
14054    }
14055
14056    #[test]
14057    fn rate_limit_unit_from_window_rejects_non_canonical() {
14058        // Rejection pin on the parser's accept-set: any Duration
14059        // outside the three-arm [`RateLimitUnit::window`] output set
14060        // (sub-second residue, or a second-magnitude outside `{1, 60,
14061        // 3600}`) must return `None`. A future accidental widening of
14062        // the accept-set (rounding down sub-second residue to the
14063        // nearest arm, admitting `Duration::from_secs(30)` as a
14064        // half-minute unit) would silently drift the parser's accept-
14065        // set from the emitter's — a validated slot with a
14066        // non-canonical window would then round-trip through the
14067        // codec to a canonical form the author never wrote.
14068        assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
14069        assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
14070        assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
14071        assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
14072        assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
14073        assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
14074        assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
14075    }
14076
14077    #[test]
14078    fn rate_limit_unit_from_suffix_rejects_unknown() {
14079        // Rejection pin on the suffix parser's accept-set: any string
14080        // outside the three-arm [`RateLimitUnit::as_suffix`] output
14081        // set must return `None`. Peer of the sibling
14082        // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
14083        // the [`crate::CaixaKind`] `from_wire` accept-set.
14084        for bad in [
14085            "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
14086            " s",
14087        ] {
14088            assert!(
14089                super::RateLimitUnit::from_suffix(bad).is_none(),
14090                "RateLimitUnit::from_suffix({bad:?}) must return None — the \
14091                 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
14092                 outputs"
14093            );
14094        }
14095    }
14096
14097    #[test]
14098    fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
14099        // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
14100        // every canonical `:window` magnitude the validate gate
14101        // accepts must map to the paired [`RateLimitUnit`] arm through
14102        // this accessor. A future validate-gate rebrand that widened
14103        // the accepted-window set without extending [`RateLimitUnit`]
14104        // would silently split the accessor's `Some`-return set from
14105        // the validate gate's accept-set — a slot that satisfies
14106        // validate would land at the accessor with `None`, so a
14107        // consumer past validate that pattern-matches on the returned
14108        // `Some` would silently miss the newly-accepted magnitude.
14109        for (window_secs, expected) in [
14110            (1u64, super::RateLimitUnit::Second),
14111            (60, super::RateLimitUnit::Minute),
14112            (3600, super::RateLimitUnit::Hour),
14113        ] {
14114            let rl = RateLimit {
14115                rate: 100,
14116                window: Duration::from_secs(window_secs),
14117            };
14118            assert_eq!(
14119                rl.canonical_unit(),
14120                Some(expected),
14121                "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
14122                 must return Some({expected:?})"
14123            );
14124        }
14125        // Non-canonical windows the validate gate rejects also return
14126        // None here — the accessor is the typed-enum projection of
14127        // the sibling `is_canonical_rate_limit_window` predicate.
14128        let bad = RateLimit {
14129            rate: 100,
14130            window: Duration::from_secs(30),
14131        };
14132        assert!(
14133            bad.canonical_unit().is_none(),
14134            "RateLimit with a non-canonical window must return None from \
14135             canonical_unit — the validate gate rejects the same set"
14136        );
14137    }
14138
14139    #[test]
14140    fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
14141        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
14142        // derive: for each of the three variants, exactly one of the
14143        // generated `is_second` / `is_minute` / `is_hour` predicates
14144        // returns `true` and the other two return `false`. Peer of
14145        // the sibling
14146        // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
14147        // sibling `IsVariant`-derived closed-set typed-enum pins.
14148        let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
14149            (super::RateLimitUnit::Second, [true, false, false]),
14150            (super::RateLimitUnit::Minute, [false, true, false]),
14151            (super::RateLimitUnit::Hour, [false, false, true]),
14152        ];
14153        for (variant, expected) in rows {
14154            let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
14155            assert_eq!(
14156                observed, expected,
14157                "RateLimitUnit::{variant:?} is_* predicates must partition \
14158                 the arm set (second, minute, hour); got {observed:?}"
14159            );
14160        }
14161    }
14162
14163    #[test]
14164    fn rejects_policy_timeout_sub_millisecond() {
14165        // A purely sub-millisecond `Duration` (`from_micros(500)` =
14166        // 500_000 ns) is not the zero `Duration` — the `is_zero()`
14167        // arm passes — but `as_millis() == 0`, so the shared codec's
14168        // `render` arm returns the literal `"0s"`, which the
14169        // codec's `parse` arm then deserializes as `Duration::ZERO`
14170        // and the `PolicyTimeoutZero` zero-floor gate would reject
14171        // on re-validate. Pin the rejection at the typed slot's
14172        // canonical-floor gate so the round-trip break surfaces at
14173        // validate time, naming the offending `Duration`, rather
14174        // than at the next serialize → deserialize round-trip far
14175        // from the source `caixa.lisp`.
14176        let mut s = three_member_spec();
14177        let timeout = Duration::from_micros(500);
14178        s.politicas.timeout = Some(timeout);
14179        assert_eq!(
14180            s.validate().unwrap_err(),
14181            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
14182        );
14183    }
14184
14185    #[test]
14186    fn rejects_policy_timeout_non_integer_millisecond() {
14187        // A `Duration` with non-integer-millisecond residue
14188        // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
14189        // through the shared codec's `render` arm as `"1ms"` (the
14190        // `as_millis()` floor truncates), which the codec's `parse`
14191        // arm then deserializes as `Duration::from_millis(1)` =
14192        // 1_000_000 ns — silently *different* from the original.
14193        // Pin the rejection so this round-trip break surfaces at
14194        // validate time, where the offending `Duration` is named,
14195        // rather than as a silent value-laundered round-trip on the
14196        // next codec round-trip.
14197        let mut s = three_member_spec();
14198        let timeout = Duration::from_micros(1500);
14199        s.politicas.timeout = Some(timeout);
14200        assert_eq!(
14201            s.validate().unwrap_err(),
14202            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
14203        );
14204    }
14205
14206    #[test]
14207    fn accepts_policy_timeout_integer_millisecond_forms() {
14208        // The codec's accepted set — integer multiples of 1ms — is
14209        // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
14210        // `1h` all pass the canonical gate. Pin the canonical-forms
14211        // sweep so a future tightening of the codec's grammar (e.g.
14212        // dropping `:ms`) surfaces here as a test failure rather
14213        // than a silent contract narrowing on the typed slot.
14214        for timeout in [
14215            Duration::from_millis(1),
14216            Duration::from_millis(500),
14217            Duration::from_millis(1500),
14218            Duration::from_secs(30),
14219            Duration::from_secs(120),
14220            Duration::from_secs(3600),
14221        ] {
14222            let mut s = three_member_spec();
14223            s.politicas.timeout = Some(timeout);
14224            s.validate()
14225                .expect("integer-millisecond :timeout must validate");
14226        }
14227    }
14228
14229    #[test]
14230    fn policy_timeout_zero_takes_precedence_over_canonical() {
14231        // `Duration::ZERO` carries `subsec_nanos() == 0` and would
14232        // pass the canonical-millisecond gate; the more self-locating
14233        // `PolicyTimeoutZero` arm (which names the omit-axis
14234        // remediation directly) must fire first. Pin the ordering so
14235        // a future refactor that reorders the arms surfaces here as a
14236        // test failure rather than a silent diagnostic regression.
14237        let mut s = three_member_spec();
14238        s.politicas.timeout = Some(Duration::ZERO);
14239        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
14240    }
14241
14242    #[test]
14243    fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
14244        // The diagnostic envelope carries the offending `Duration`
14245        // verbatim so the author can grep their `caixa.lisp` for
14246        // `:timeout "<value>"` and fix it in one edit. Same
14247        // diagnostic shape every other typed-slot canonical-form
14248        // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
14249        // peer `:rate-limit :window` axis.
14250        let mut s = three_member_spec();
14251        let timeout = Duration::from_nanos(1_000_001);
14252        s.politicas.timeout = Some(timeout);
14253        match s.validate().unwrap_err() {
14254            AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
14255                assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
14256            }
14257            other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
14258        }
14259    }
14260
14261    #[test]
14262    fn rejects_policy_timeout_above_cap() {
14263        // The fail-before-pass-after pin: 3601s = 1h + 1s is
14264        // structurally one canonical-tick past the
14265        // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
14266        // integer-millisecond magnitude the canonical-form arm above
14267        // accepts cleanly, that the codec round-trips losslessly as
14268        // `"3601s"`, and that silently passed validate on every
14269        // pre-gate codebase because the typed slot's only checks were
14270        // the zero-floor and canonical-form arms. The mesh-level
14271        // deadline degenerates only at the runtime substrate (Envoy
14272        // / Cilium L7 timeout overlay) far from the source
14273        // `caixa.lisp` with no field naming the offending policy.
14274        let mut s = three_member_spec();
14275        let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
14276        s.politicas.timeout = Some(timeout);
14277        assert_eq!(
14278            s.validate().unwrap_err(),
14279            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
14280        );
14281    }
14282
14283    #[test]
14284    fn rejects_policy_timeout_one_millisecond_above_cap() {
14285        // Boundary case: exactly 1ms past the cap (the granularity
14286        // the canonical-form gate enforces). Catches a future
14287        // "strictly less than" half-measure and pins the diagnostic
14288        // to name the offending `Duration` verbatim. Peer of
14289        // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
14290        // boundary pin on the sibling `:limits :memory` top edge.
14291        let mut s = three_member_spec();
14292        let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
14293        s.politicas.timeout = Some(timeout);
14294        assert_eq!(
14295            s.validate().unwrap_err(),
14296            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
14297        );
14298    }
14299
14300    #[test]
14301    fn rejects_policy_timeout_far_above_cap() {
14302        // The "obvious authoring footgun" case: a `(:timeout "24h")`
14303        // or `(:timeout "86400s")` — values the canonical-form arm
14304        // accepts as integer-millisecond magnitudes, the codec
14305        // round-trips losslessly through serde, but the mesh-level
14306        // policy cannot honor (a 24-hour synchronous-`:contratos`
14307        // deadline is operationally indistinguishable from
14308        // omit-the-axis). Until this gate landed validate accepted
14309        // it. Pin both common above-cap values (24h, 7d) so a future
14310        // relaxation that drops the upper bound surfaces here.
14311        for timeout in [
14312            Duration::from_secs(86_400),    // 24h
14313            Duration::from_secs(604_800),   // 7d
14314            Duration::from_secs(1_000_000), // ~11.5 days
14315        ] {
14316            let mut s = three_member_spec();
14317            s.politicas.timeout = Some(timeout);
14318            assert_eq!(
14319                s.validate().unwrap_err(),
14320                AplicacaoError::PolicyTimeoutExceedsCap { timeout }
14321            );
14322        }
14323    }
14324
14325    #[test]
14326    fn accepts_policy_timeout_at_cap() {
14327        // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
14328        // must validate. The cap is inclusive on the top edge,
14329        // matching the [`POLICY_RETRIES_MAX`] /
14330        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
14331        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
14332        // sibling capped axes. Pin the boundary explicitly so a
14333        // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
14334        // instead of `>`) surfaces here as a test failure rather
14335        // than a silent contract narrowing.
14336        let mut s = three_member_spec();
14337        s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
14338        s.validate()
14339            .expect("timeout == POLICY_TIMEOUT_MAX must validate");
14340    }
14341
14342    #[test]
14343    fn accepts_policy_timeout_typical_values() {
14344        // The documented production-playbook band positive-control
14345        // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
14346        // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
14347        // plus a sweep through the long-running-workflow band
14348        // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
14349        // validated set explicitly so a future tightening of the
14350        // ceiling surfaces here as a deliberate test edit, not a
14351        // silent contract narrowing.
14352        for timeout in [
14353            Duration::from_millis(1),
14354            Duration::from_millis(500),
14355            Duration::from_secs(1),
14356            Duration::from_secs(10),
14357            Duration::from_secs(15), // Envoy default
14358            Duration::from_secs(30),
14359            Duration::from_secs(60), // AWS App Mesh typical
14360            Duration::from_secs(300),
14361            Duration::from_secs(900),
14362            Duration::from_secs(1800),
14363            Duration::from_secs(3600), // exactly 1h, the cap
14364        ] {
14365            let mut s = three_member_spec();
14366            s.politicas.timeout = Some(timeout);
14367            s.validate()
14368                .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
14369        }
14370    }
14371
14372    #[test]
14373    fn policy_timeout_zero_takes_precedence_over_cap() {
14374        // The cross-arm ordering pin: `Duration::ZERO` is
14375        // structurally outside both `>= 1ms` (zero-floor) and
14376        // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
14377        // diagnostic is the more self-locating one (it directly
14378        // names the omit-axis remediation), so the validate gate
14379        // must fire on zero first. Same shape every other
14380        // zero-then-shape ordering on this surface uses
14381        // ([`AplicacaoError::PolicyRetriesZero`] then
14382        // [`AplicacaoError::PolicyRetriesExceedsCap`];
14383        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
14384        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
14385        let mut s = three_member_spec();
14386        s.politicas.timeout = Some(Duration::ZERO);
14387        assert_eq!(
14388            s.validate().unwrap_err(),
14389            AplicacaoError::PolicyTimeoutZero,
14390            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
14391        );
14392    }
14393
14394    #[test]
14395    fn policy_timeout_canonical_takes_precedence_over_cap() {
14396        // The cross-arm ordering pin: a `Duration` that is *both*
14397        // sub-millisecond (non-canonical-form) and structurally
14398        // above the cap surfaces the canonical-form diagnostic
14399        // first, because the round-trip-shape break is the more
14400        // fundamental issue (the value can't even round-trip
14401        // through the codec, so the cap diagnostic naming
14402        // `1ms..=1h` would be misleading — there's no integer-ms
14403        // form of the offending value). Pin the order so a future
14404        // refactor that reorders the arms surfaces here as a test
14405        // failure rather than a silent diagnostic regression.
14406        let mut s = three_member_spec();
14407        // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
14408        // *and* total magnitude above the 1h cap.
14409        let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
14410        s.politicas.timeout = Some(timeout);
14411        assert_eq!(
14412            s.validate().unwrap_err(),
14413            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
14414            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
14415        );
14416    }
14417
14418    #[test]
14419    fn policy_timeout_cap_diagnostic_carries_offending_value() {
14420        // The diagnostic-shape pin: the offending `Duration` is
14421        // carried verbatim into the
14422        // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
14423        // surfaced error message names the value the author wrote
14424        // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
14425        // exceeds the mesh-policy ceiling …"`), not just the cap.
14426        // Same self-locating diagnostic shape every other typed-cap
14427        // arm on this surface carries
14428        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
14429        // offending retry count verbatim).
14430        let mut s = three_member_spec();
14431        let timeout = Duration::from_secs(7200); // 2h
14432        s.politicas.timeout = Some(timeout);
14433        let err = s.validate().unwrap_err();
14434        assert!(
14435            matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
14436            "got {err:?}"
14437        );
14438        let msg = err.to_string();
14439        assert!(
14440            msg.contains("7200"),
14441            ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
14442        );
14443    }
14444
14445    #[test]
14446    fn policy_timeout_cap_pins_canonical_value() {
14447        // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
14448        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
14449        // the shared duration codec emits as a clean canonical
14450        // string (`"<n>h"`). Pinning the literal value here surfaces
14451        // a future drift (a relaxation to 24h, a tightening to 5m)
14452        // as a deliberate test edit, not a silent contract
14453        // narrowing. Same shape every other typed-cap value pin on
14454        // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
14455        assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
14456        assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
14457    }
14458
14459    #[test]
14460    fn policy_timeout_cap_value_round_trips_through_codec() {
14461        // The codec round-trip property the cap arm preserves: the
14462        // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
14463        // the shared duration codec — every value at the cap renders
14464        // to a clean canonical string (`"1h"`) and parses back to
14465        // the same `Duration`. Pin this so a future drift between
14466        // the cap constant and the codec's largest emitted unit
14467        // surfaces here. Same shape every other typed boundary pin
14468        // on this surface uses
14469        // (`wasm32_memory_cap_matches_parsed_4_gib`).
14470        let policy = MeshPolicy {
14471            timeout: Some(POLICY_TIMEOUT_MAX),
14472            ..Default::default()
14473        };
14474        let json = serde_json::to_string(&policy).unwrap();
14475        // The codec emits `"1h"` for the canonical 1-hour magnitude.
14476        assert!(
14477            json.contains("\"1h\""),
14478            "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
14479        );
14480        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
14481        assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
14482    }
14483
14484    #[test]
14485    fn rejects_circuit_breaker_window_sub_millisecond() {
14486        // Peer of the `:timeout` sub-millisecond arm on the second
14487        // typed-`Duration` `:politicas` axis: a purely sub-ms
14488        // `Duration` (`from_micros(500)`) renders through the shared
14489        // codec as `"0s"`, which the codec parses back to
14490        // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
14491        // zero-floor gate then rejects on re-validate.
14492        let mut s = three_member_spec();
14493        let window = Duration::from_micros(500);
14494        s.politicas.circuit_breaker = Some(CircuitBreaker {
14495            max_failures: 5,
14496            window,
14497        });
14498        assert_eq!(
14499            s.validate().unwrap_err(),
14500            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
14501        );
14502    }
14503
14504    #[test]
14505    fn rejects_circuit_breaker_window_non_integer_millisecond() {
14506        // Peer of the `:timeout` non-integer-ms arm: a `Duration`
14507        // with non-integer-millisecond residue renders through the
14508        // shared codec as the truncated `"<n>ms"` form, parsing back
14509        // to a *different* `Duration` on the next round-trip.
14510        let mut s = three_member_spec();
14511        let window = Duration::from_micros(1500);
14512        s.politicas.circuit_breaker = Some(CircuitBreaker {
14513            max_failures: 5,
14514            window,
14515        });
14516        assert_eq!(
14517            s.validate().unwrap_err(),
14518            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
14519        );
14520    }
14521
14522    #[test]
14523    fn accepts_circuit_breaker_window_integer_millisecond_forms() {
14524        // The canonical-forms sweep on the breaker axis: every
14525        // integer-ms multiple the codec round-trips losslessly
14526        // passes the canonical gate.
14527        for window in [
14528            Duration::from_millis(1),
14529            Duration::from_millis(500),
14530            Duration::from_millis(1500),
14531            Duration::from_secs(30),
14532            Duration::from_secs(60),
14533            Duration::from_secs(3600),
14534        ] {
14535            let mut s = three_member_spec();
14536            s.politicas.circuit_breaker = Some(CircuitBreaker {
14537                max_failures: 5,
14538                window,
14539            });
14540            s.validate()
14541                .expect("integer-millisecond :circuit-breaker :window must validate");
14542        }
14543    }
14544
14545    #[test]
14546    fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
14547        // `Duration::ZERO` would pass the canonical-ms gate (the
14548        // sub-ns residue is zero) but must surface the narrower
14549        // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
14550        // remediation.
14551        let mut s = three_member_spec();
14552        s.politicas.circuit_breaker = Some(CircuitBreaker {
14553            max_failures: 5,
14554            window: Duration::ZERO,
14555        });
14556        assert_eq!(
14557            s.validate().unwrap_err(),
14558            AplicacaoError::PolicyBreakerZeroWindow
14559        );
14560    }
14561
14562    #[test]
14563    fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
14564        // Both axes invalid: max_failures == 0 *and* window is
14565        // sub-ms. The validate gate must fire on max_failures first
14566        // (matching the existing ordering pin
14567        // `rejects_circuit_breaker_zero_max_failures` enshrines), so
14568        // the existing diagnostic continues to lead with the simpler
14569        // "zero threshold" framing.
14570        let mut s = three_member_spec();
14571        s.politicas.circuit_breaker = Some(CircuitBreaker {
14572            max_failures: 0,
14573            window: Duration::from_micros(500),
14574        });
14575        assert_eq!(
14576            s.validate().unwrap_err(),
14577            AplicacaoError::PolicyBreakerZeroFailures
14578        );
14579    }
14580
14581    #[test]
14582    fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
14583        let mut s = three_member_spec();
14584        let window = Duration::from_nanos(60_000_000_001);
14585        s.politicas.circuit_breaker = Some(CircuitBreaker {
14586            max_failures: 5,
14587            window,
14588        });
14589        match s.validate().unwrap_err() {
14590            AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
14591                assert_eq!(w, window, "diagnostic must carry the offending Duration");
14592            }
14593            other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
14594        }
14595    }
14596
14597    #[test]
14598    fn rejects_circuit_breaker_window_above_cap() {
14599        // The fail-before-pass-after pin: 3601s = 1h + 1s is
14600        // structurally one canonical-tick past the
14601        // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
14602        // integer-millisecond magnitude the canonical-form arm above
14603        // accepts cleanly, that the codec round-trips losslessly as
14604        // `"3601s"`, and that silently passed validate on every
14605        // pre-gate codebase because the typed slot's only checks were
14606        // the zero-floor and canonical-form arms. The
14607        // rolling-window-to-lifetime-counter degeneration surfaces
14608        // only at the runtime substrate (Envoy's outlier_detection
14609        // interval, the future CiliumClusterwideEnvoyConfig overlay)
14610        // far from the source `caixa.lisp` with no field naming the
14611        // offending policy.
14612        let mut s = three_member_spec();
14613        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
14614        s.politicas.circuit_breaker = Some(CircuitBreaker {
14615            max_failures: 5,
14616            window,
14617        });
14618        assert_eq!(
14619            s.validate().unwrap_err(),
14620            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
14621        );
14622    }
14623
14624    #[test]
14625    fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
14626        // Boundary case: exactly 1ms past the cap (the granularity the
14627        // canonical-form gate enforces). Catches a future "strictly
14628        // less than" half-measure and pins the diagnostic to name the
14629        // offending `Duration` verbatim. Peer of
14630        // `rejects_policy_timeout_one_millisecond_above_cap` on the
14631        // sibling duration-typed `:politicas :timeout` top edge.
14632        let mut s = three_member_spec();
14633        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
14634        s.politicas.circuit_breaker = Some(CircuitBreaker {
14635            max_failures: 5,
14636            window,
14637        });
14638        assert_eq!(
14639            s.validate().unwrap_err(),
14640            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
14641        );
14642    }
14643
14644    #[test]
14645    fn rejects_circuit_breaker_window_far_above_cap() {
14646        // The "obvious authoring footgun" case: a `(:window "24h")` or
14647        // `(:window "86400s")` — values the canonical-form arm
14648        // accepts as integer-millisecond magnitudes, the codec
14649        // round-trips losslessly through serde, but the
14650        // rolling-window breaker contract cannot honor (a 24-hour
14651        // rolling failure window is operationally a lifetime counter).
14652        // Until this gate landed validate accepted it. Pin both common
14653        // above-cap values (24h, 7d) so a future relaxation that
14654        // drops the upper bound surfaces here.
14655        for window in [
14656            Duration::from_secs(86_400),    // 24h
14657            Duration::from_secs(604_800),   // 7d
14658            Duration::from_secs(1_000_000), // ~11.5 days
14659        ] {
14660            let mut s = three_member_spec();
14661            s.politicas.circuit_breaker = Some(CircuitBreaker {
14662                max_failures: 5,
14663                window,
14664            });
14665            assert_eq!(
14666                s.validate().unwrap_err(),
14667                AplicacaoError::PolicyBreakerWindowExceedsCap { window }
14668            );
14669        }
14670    }
14671
14672    #[test]
14673    fn accepts_circuit_breaker_window_at_cap() {
14674        // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
14675        // (1h) — must validate. The cap is inclusive on the top edge,
14676        // matching the [`POLICY_TIMEOUT_MAX`] /
14677        // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
14678        // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
14679        // sibling capped axes. Pin the boundary explicitly so a
14680        // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
14681        // instead of `>`) surfaces here as a test failure rather than
14682        // a silent contract narrowing.
14683        let mut s = three_member_spec();
14684        s.politicas.circuit_breaker = Some(CircuitBreaker {
14685            max_failures: 5,
14686            window: POLICY_BREAKER_WINDOW_MAX,
14687        });
14688        s.validate()
14689            .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
14690    }
14691
14692    #[test]
14693    fn accepts_circuit_breaker_window_typical_values() {
14694        // The documented production-playbook band positive-control
14695        // sweep — every value Hystrix / resilience4j / Istio / Envoy
14696        // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
14697        // through the long-tail failure-detection band (15m, 30m, 1h)
14698        // the cap accepts. Pin the inclusive validated set explicitly
14699        // so a future tightening of the ceiling surfaces here as a
14700        // deliberate test edit, not a silent contract narrowing.
14701        for window in [
14702            Duration::from_millis(1),
14703            Duration::from_millis(500),
14704            Duration::from_secs(1),
14705            Duration::from_secs(10), // Hystrix / Istio / Envoy default
14706            Duration::from_secs(30),
14707            Duration::from_secs(60),  // resilience4j typical
14708            Duration::from_secs(300), // AWS App Mesh typical
14709            Duration::from_secs(900),
14710            Duration::from_secs(1800),
14711            Duration::from_secs(3600), // exactly 1h, the cap
14712        ] {
14713            let mut s = three_member_spec();
14714            s.politicas.circuit_breaker = Some(CircuitBreaker {
14715                max_failures: 5,
14716                window,
14717            });
14718            s.validate()
14719                .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
14720        }
14721    }
14722
14723    #[test]
14724    fn circuit_breaker_zero_window_takes_precedence_over_cap() {
14725        // The cross-arm ordering pin: `Duration::ZERO` is structurally
14726        // outside both `>= 1ms` (zero-floor) and
14727        // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
14728        // diagnostic is the more self-locating one (it directly names
14729        // the omit-axis remediation), so the validate gate must fire
14730        // on zero first. Same shape every other zero-then-cap
14731        // ordering on this surface uses
14732        // ([`AplicacaoError::PolicyTimeoutZero`] then
14733        // [`AplicacaoError::PolicyTimeoutExceedsCap`];
14734        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
14735        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
14736        let mut s = three_member_spec();
14737        s.politicas.circuit_breaker = Some(CircuitBreaker {
14738            max_failures: 5,
14739            window: Duration::ZERO,
14740        });
14741        assert_eq!(
14742            s.validate().unwrap_err(),
14743            AplicacaoError::PolicyBreakerZeroWindow,
14744            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
14745        );
14746    }
14747
14748    #[test]
14749    fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
14750        // The cross-arm ordering pin: a `Duration` that is *both*
14751        // sub-millisecond (non-canonical-form) and structurally above
14752        // the cap surfaces the canonical-form diagnostic first,
14753        // because the round-trip-shape break is the more fundamental
14754        // issue (the value can't even round-trip through the codec, so
14755        // the cap diagnostic naming `1ms..=1h` would be misleading —
14756        // there's no integer-ms form of the offending value). Pin the
14757        // order so a future refactor that reorders the arms surfaces
14758        // here as a test failure rather than a silent diagnostic
14759        // regression. Peer of
14760        // `policy_timeout_canonical_takes_precedence_over_cap` on the
14761        // sibling duration-typed `:politicas :timeout` axis.
14762        let mut s = three_member_spec();
14763        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
14764        s.politicas.circuit_breaker = Some(CircuitBreaker {
14765            max_failures: 5,
14766            window,
14767        });
14768        assert_eq!(
14769            s.validate().unwrap_err(),
14770            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
14771            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
14772        );
14773    }
14774
14775    #[test]
14776    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
14777        // The cross-arm ordering pin between the two breaker axes: a
14778        // `CircuitBreaker` whose *both* `max_failures` is above its
14779        // cap *and* `window` is above its cap surfaces the
14780        // max-failures cap diagnostic first, because the validate
14781        // gate visits the failures arm before the window arm. Pin the
14782        // order so a future refactor that reorders the breaker arms
14783        // surfaces here.
14784        let mut s = three_member_spec();
14785        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
14786        s.politicas.circuit_breaker = Some(CircuitBreaker {
14787            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
14788            window,
14789        });
14790        assert_eq!(
14791            s.validate().unwrap_err(),
14792            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
14793                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
14794            },
14795            "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
14796        );
14797    }
14798
14799    #[test]
14800    fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
14801        // The diagnostic-shape pin: the offending `Duration` is
14802        // carried verbatim into the
14803        // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
14804        // the surfaced error message names the value the author wrote
14805        // (`":politicas :circuit-breaker :window (Duration { secs:
14806        // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
14807        // just the cap. Same self-locating diagnostic shape every
14808        // other typed-cap arm on this surface carries
14809        // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
14810        // offending `Duration` verbatim).
14811        let mut s = three_member_spec();
14812        let window = Duration::from_secs(7200); // 2h
14813        s.politicas.circuit_breaker = Some(CircuitBreaker {
14814            max_failures: 5,
14815            window,
14816        });
14817        let err = s.validate().unwrap_err();
14818        assert!(
14819            matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
14820            "got {err:?}"
14821        );
14822        let msg = err.to_string();
14823        assert!(
14824            msg.contains("7200"),
14825            ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
14826        );
14827    }
14828
14829    #[test]
14830    fn circuit_breaker_window_cap_pins_canonical_value() {
14831        // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
14832        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
14833        // shared duration codec emits as a clean canonical string
14834        // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
14835        // the sibling duration-typed `:politicas :timeout` axis (the
14836        // two duration-typed `:politicas` axes share a uniform top
14837        // edge). Pinning the literal value here surfaces a future
14838        // drift (a relaxation to 24h, a tightening to 5m) as a
14839        // deliberate test edit, not a silent contract narrowing. Same
14840        // shape every other typed-cap value pin on this surface uses
14841        // (`policy_timeout_cap_pins_canonical_value`).
14842        assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
14843        assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
14844        assert_eq!(
14845            POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
14846            "the two duration-typed `:politicas` caps share the same top edge"
14847        );
14848    }
14849
14850    #[test]
14851    fn circuit_breaker_window_cap_value_round_trips_through_codec() {
14852        // The codec round-trip property the cap arm preserves: the
14853        // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
14854        // through the shared duration codec — every value at the cap
14855        // renders to a clean canonical string (`"1h"`) and parses back
14856        // to the same `Duration`. Pin this so a future drift between
14857        // the cap constant and the codec's largest emitted unit
14858        // surfaces here. Same shape every other typed boundary pin on
14859        // this surface uses
14860        // (`policy_timeout_cap_value_round_trips_through_codec`).
14861        let policy = MeshPolicy {
14862            circuit_breaker: Some(CircuitBreaker {
14863                max_failures: 5,
14864                window: POLICY_BREAKER_WINDOW_MAX,
14865            }),
14866            ..Default::default()
14867        };
14868        let json = serde_json::to_string(&policy).unwrap();
14869        // The codec emits `"1h"` for the canonical 1-hour magnitude.
14870        assert!(
14871            json.contains("\"1h\""),
14872            "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
14873        );
14874        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
14875        assert_eq!(
14876            back.circuit_breaker.unwrap().window,
14877            POLICY_BREAKER_WINDOW_MAX
14878        );
14879    }
14880
14881    #[test]
14882    fn is_integer_millisecond_duration_predicate_tracks_codec() {
14883        // Pin the predicate's accepted set against the codec's
14884        // accepted set explicitly. The codec parses
14885        // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
14886        // accepted value is an integer-millisecond multiple — so the
14887        // predicate must accept exactly that set. Same shape every
14888        // other predicate-on-the-typed-slot helper carries
14889        // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
14890        // Read directly from the codec-owned predicate — the crate's
14891        // single source of truth every typed-`Duration` axis now routes
14892        // through via
14893        // [`crate::render::require_positive_canonical_bounded_duration`].
14894        use super::supervisor::duration_codec::is_integer_millisecond_duration;
14895        assert!(is_integer_millisecond_duration(Duration::ZERO));
14896        assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
14897        assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
14898        assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
14899        assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
14900        assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
14901        // Non-integer-millisecond residue: rejected.
14902        assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
14903        assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
14904        assert!(!is_integer_millisecond_duration(Duration::from_micros(
14905            1500
14906        )));
14907        assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
14908        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
14909            999_999
14910        )));
14911        // The 1-ns-past-1ms boundary: rejected (no longer a clean
14912        // integer-millisecond multiple).
14913        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
14914            1_000_001
14915        )));
14916    }
14917
14918    #[test]
14919    fn policy_timeout_validated_value_round_trips_through_codec() {
14920        // The structural property the canonical-ms gate enforces:
14921        // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
14922        // round-trips losslessly through the shared `duration_codec`
14923        // (serialize → string → deserialize → equal value). Pin this
14924        // end-to-end so a future change to either side (the validate
14925        // gate's accepted granularity, the codec's parse/render unit
14926        // set) that breaks the alignment surfaces here. The
14927        // previous-state shape (typed slot accepts arbitrary
14928        // `Duration`, codec only round-trips integer-ms) would fail
14929        // this test for any `Duration::from_micros(1500)` timeout —
14930        // the validate gate now forecloses that.
14931        for timeout in [
14932            Duration::from_millis(1),
14933            Duration::from_millis(1500),
14934            Duration::from_secs(30),
14935            Duration::from_secs(3600),
14936        ] {
14937            let mut s = three_member_spec();
14938            s.politicas.timeout = Some(timeout);
14939            s.validate().unwrap();
14940            let json = serde_json::to_string(&s.politicas).unwrap();
14941            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
14942            assert_eq!(
14943                back.timeout, s.politicas.timeout,
14944                "every validated :timeout must round-trip losslessly through the codec"
14945            );
14946        }
14947    }
14948
14949    #[test]
14950    fn circuit_breaker_window_validated_value_round_trips_through_codec() {
14951        // Peer of the `:timeout` round-trip property on the breaker
14952        // axis.
14953        for window in [
14954            Duration::from_millis(1),
14955            Duration::from_millis(1500),
14956            Duration::from_secs(30),
14957            Duration::from_secs(3600),
14958        ] {
14959            let mut s = three_member_spec();
14960            s.politicas.circuit_breaker = Some(CircuitBreaker {
14961                max_failures: 5,
14962                window,
14963            });
14964            s.validate().unwrap();
14965            let json = serde_json::to_string(&s.politicas).unwrap();
14966            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
14967            assert_eq!(
14968                back.circuit_breaker.unwrap().window,
14969                window,
14970                "every validated :circuit-breaker :window must round-trip losslessly"
14971            );
14972        }
14973    }
14974
14975    #[test]
14976    fn empty_politicas_validates() {
14977        // Omitting every policy axis is fine — defaults express "no
14978        // policy on this axis", not "policy = 0". The fixture's typical
14979        // values continue to validate; this test pins that
14980        // MeshPolicy::default() is a clean pass through validate().
14981        let mut s = three_member_spec();
14982        s.politicas = MeshPolicy::default();
14983        s.validate().unwrap();
14984    }
14985
14986    #[test]
14987    fn typical_politicas_validates_with_every_axis_set() {
14988        // The full §III.1 example block (timeout + retries + breaker +
14989        // mtls + rate-limit) — every axis nonzero — must remain a
14990        // clean pass.
14991        let mut s = three_member_spec();
14992        s.politicas = MeshPolicy {
14993            timeout: Some(Duration::from_secs(30)),
14994            retries: Some(3),
14995            circuit_breaker: Some(CircuitBreaker {
14996                max_failures: 5,
14997                window: Duration::from_secs(60),
14998            }),
14999            mtls_required: Some(true),
15000            rate_limit: Some(RateLimit {
15001                rate: 100,
15002                window: Duration::from_secs(1),
15003            }),
15004        };
15005        s.validate().unwrap();
15006    }
15007
15008    #[test]
15009    fn rejects_empty_cluster_name() {
15010        let mut s = three_member_spec();
15011        s.placement.clusters = vec!["rio".into(), "".into()];
15012        assert_eq!(
15013            s.validate().unwrap_err(),
15014            AplicacaoError::PlacementClusterEmpty
15015        );
15016    }
15017
15018    #[test]
15019    fn rejects_duplicate_cluster_names() {
15020        let mut s = three_member_spec();
15021        s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
15022        let err = s.validate().unwrap_err();
15023        assert!(
15024            matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
15025            "got {err:?}"
15026        );
15027    }
15028
15029    #[test]
15030    fn rejects_placement_cluster_with_uppercase() {
15031        // The canonical "I copied the cluster's display name verbatim"
15032        // typo — K8s context names are lowercase per DNS-1123 label
15033        // rule, but org docs often round-trip a TitleCase identifier
15034        // (`Rio`, `Mar-East`) from an ADR. Mirrors the
15035        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
15036        // on the peer name axis.
15037        let mut s = three_member_spec();
15038        s.placement.clusters = vec!["Rio".into(), "mar".into()];
15039        let err = s.validate().unwrap_err();
15040        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
15041            panic!("expected PlacementClusterInvalid, got other variant");
15042        };
15043        assert_eq!(cluster, "Rio");
15044        assert!(
15045            reason.contains("uppercase"),
15046            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
15047        );
15048        assert!(
15049            reason.contains("\"rio\""),
15050            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
15051        );
15052    }
15053
15054    #[test]
15055    fn rejects_placement_cluster_with_underscore() {
15056        // The canonical "I'm thinking of an env var / hostname slug"
15057        // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
15058        // schema. K8s context filtering on `my_cluster` silently misses
15059        // the cluster the author intended; the gate moves it to caixa-
15060        // build time. Same shape as `rejects_membro_caixa_with_underscore`
15061        // (3f9d7a0).
15062        let mut s = three_member_spec();
15063        s.placement.clusters = vec!["my_cluster".into()];
15064        let err = s.validate().unwrap_err();
15065        assert!(
15066            matches!(
15067                err,
15068                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
15069                    if cluster == "my_cluster" && reason.contains('_')
15070            ),
15071            "got {err:?}"
15072        );
15073    }
15074
15075    #[test]
15076    fn rejects_placement_cluster_with_dot() {
15077        // A `:placement :clusters` entry is a single DNS-1123 *label*,
15078        // not a subdomain — even though K8s context names sometimes
15079        // carry a dotted form via kubeconfig conventions, the strictest
15080        // floor among the use sites (DNS-1035 cluster.x-k8s.io
15081        // `metadata.name`, Cilium identity label values) wins. The "I
15082        // want to namespace my cluster names with `.`" intent is
15083        // expressed via `-` (`mar-east`).
15084        let mut s = three_member_spec();
15085        s.placement.clusters = vec!["team.rio".into()];
15086        let err = s.validate().unwrap_err();
15087        assert!(
15088            matches!(
15089                err,
15090                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
15091                    if cluster == "team.rio" && reason.contains('.')
15092            ),
15093            "got {err:?}"
15094        );
15095    }
15096
15097    #[test]
15098    fn rejects_placement_cluster_with_leading_hyphen() {
15099        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
15100        // with an alphanumeric. The K8s apiserver rejects `-rio`
15101        // outright; the rendered fan-out would emit a `metadata.name:
15102        // "-rio"` that fails admission far from the source caixa.lisp.
15103        let mut s = three_member_spec();
15104        s.placement.clusters = vec!["-rio".into()];
15105        let err = s.validate().unwrap_err();
15106        assert!(
15107            matches!(
15108                err,
15109                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
15110                    if cluster == "-rio" && reason.contains("start and end")
15111            ),
15112            "got {err:?}"
15113        );
15114    }
15115
15116    #[test]
15117    fn rejects_placement_cluster_with_trailing_hyphen() {
15118        // The symmetric arm of the boundary rule. Pin separately so
15119        // both ends are covered against a future relaxation that only
15120        // checks one boundary (parallel to
15121        // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
15122        let mut s = three_member_spec();
15123        s.placement.clusters = vec!["rio-".into()];
15124        let err = s.validate().unwrap_err();
15125        assert!(
15126            matches!(
15127                err,
15128                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
15129                    if cluster == "rio-"
15130            ),
15131            "got {err:?}"
15132        );
15133    }
15134
15135    #[test]
15136    fn rejects_placement_cluster_with_unicode() {
15137        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
15138        // before it reaches K8s. The byte-by-byte ASCII validity check
15139        // rejects multi-byte UTF-8 sequences by the first byte that
15140        // fails `[a-z0-9-]`.
15141        let mut s = three_member_spec();
15142        s.placement.clusters = vec!["rió".into()];
15143        let err = s.validate().unwrap_err();
15144        assert!(
15145            matches!(
15146                err,
15147                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
15148                    if cluster == "rió"
15149            ),
15150            "got {err:?}"
15151        );
15152    }
15153
15154    #[test]
15155    fn rejects_placement_cluster_with_whitespace() {
15156        // Whitespace is the canonical "I pasted from a sketch / doc"
15157        // footgun. The apiserver rejects every cluster `metadata.name`
15158        // value carrying whitespace.
15159        let mut s = three_member_spec();
15160        s.placement.clusters = vec!["rio cluster".into()];
15161        let err = s.validate().unwrap_err();
15162        assert!(
15163            matches!(
15164                err,
15165                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
15166                    if cluster == "rio cluster"
15167            ),
15168            "got {err:?}"
15169        );
15170    }
15171
15172    #[test]
15173    fn rejects_placement_cluster_too_long() {
15174        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
15175        // pin. The diagnostic names both the cap (63) and the actual
15176        // length so the author can shorten in one edit. Mirrors
15177        // `rejects_membro_caixa_too_long` (3f9d7a0).
15178        let mut s = three_member_spec();
15179        let too_long = "a".repeat(64);
15180        s.placement.clusters = vec![too_long.clone()];
15181        let err = s.validate().unwrap_err();
15182        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
15183            panic!("expected PlacementClusterInvalid");
15184        };
15185        assert_eq!(cluster, too_long);
15186        assert!(
15187            reason.contains("63") && reason.contains("64"),
15188            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
15189        );
15190    }
15191
15192    #[test]
15193    fn placement_cluster_max_length_validates() {
15194        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
15195        // future tightening (e.g. dropping to 62) surfaces here as a
15196        // regression, mirroring `membro_caixa_max_length_validates`
15197        // (3f9d7a0).
15198        let mut s = three_member_spec();
15199        s.placement.clusters = vec!["a".repeat(63)];
15200        s.validate().unwrap();
15201    }
15202
15203    #[test]
15204    fn accepts_canonical_placement_cluster_forms() {
15205        // The DNS-1123 label shapes a caixa author is realistically
15206        // going to write for cluster names: single-word lowercase
15207        // (`rio`), regional hyphen-joined (`mar-east`), single
15208        // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
15209        // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
15210        // Pin every leg so a future tightening that bans (e.g.) digit-
15211        // start identifiers surfaces here.
15212        for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
15213            let mut s = three_member_spec();
15214            s.placement.clusters = vec![form.into()];
15215            s.validate().unwrap_or_else(|e| {
15216                panic!("canonical cluster form {form:?} must validate, got {e:?}")
15217            });
15218        }
15219    }
15220
15221    #[test]
15222    fn placement_cluster_empty_takes_precedence_over_invalid() {
15223        // Order pin: the existing `PlacementClusterEmpty` diagnostic
15224        // (which doesn't try to parse) fires before the new
15225        // `PlacementClusterInvalid` parse-side diagnostic, so an empty
15226        // `:clusters` entry keeps its narrower error message — the new
15227        // gate would also reject `""`, but the empty-string arm is the
15228        // more self-locating diagnostic. Mirrors the
15229        // `membro_caixa_empty_takes_precedence_over_invalid` pin
15230        // (3f9d7a0).
15231        let mut s = three_member_spec();
15232        s.placement.clusters = vec!["rio".into(), "".into()];
15233        let err = s.validate().unwrap_err();
15234        assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
15235    }
15236
15237    #[test]
15238    fn placement_cluster_invalid_fires_before_duplicate_check() {
15239        // Order pin: a malformed-shape `:clusters` entry surfaces *its
15240        // own* diagnostic, even when a later entry would otherwise
15241        // collapse onto a duplicate name. The per-entry shape gate runs
15242        // inline before the duplicate-key insert, parallel to
15243        // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
15244        let mut s = three_member_spec();
15245        s.placement.clusters = vec!["Rio".into(), "rio".into()];
15246        let err = s.validate().unwrap_err();
15247        assert!(
15248            matches!(
15249                err,
15250                AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
15251            ),
15252            "got {err:?}"
15253        );
15254    }
15255
15256    #[test]
15257    fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
15258        // The diagnostic-shape pin: the error names the offending
15259        // `:clusters` value verbatim so the author can grep their
15260        // caixa.lisp without re-running the build, and carries a
15261        // non-empty `reason` naming the specific violation. Same shape
15262        // every typed-shape gate enshrines
15263        // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
15264        // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
15265        let mut s = three_member_spec();
15266        s.placement.clusters = vec!["BAD_CLUSTER".into()];
15267        let err = s.validate().unwrap_err();
15268        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
15269            panic!("expected PlacementClusterInvalid");
15270        };
15271        assert_eq!(cluster, "BAD_CLUSTER");
15272        assert!(
15273            !reason.is_empty(),
15274            "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
15275        );
15276    }
15277
15278    #[test]
15279    fn rejects_sharded_with_empty_clusters() {
15280        // §III.1: Sharded uses :clusters as the shard pool. An empty
15281        // pool means "shard across no clusters" — meaningless, same as
15282        // Replicated with no hosts.
15283        let mut s = three_member_spec();
15284        s.placement.estrategia = PlacementStrategy::Sharded;
15285        s.placement.shard_key = Some("$tenantId".into());
15286        s.placement.clusters = vec![];
15287        assert!(matches!(
15288            s.validate().unwrap_err(),
15289            AplicacaoError::PlacementWithoutClusters {
15290                estrategia: PlacementStrategy::Sharded
15291            }
15292        ));
15293    }
15294
15295    #[test]
15296    fn rejects_sharded_with_empty_shard_key() {
15297        let mut s = three_member_spec();
15298        s.placement.estrategia = PlacementStrategy::Sharded;
15299        s.placement.shard_key = Some("".into());
15300        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
15301    }
15302
15303    #[test]
15304    fn rejects_shard_key_under_replicated_strategy() {
15305        // The fail-before-pass-after pin: a `:placement (:estrategia
15306        // Replicated :shard-key "tenantId")` manifest carries the
15307        // hash-keyed-distribution slot on a strategy that never consumes
15308        // it. Before the gate the typed slot's value silently vanished
15309        // at the renderer layer (caixa-mesh emits `placement.shardKey`
15310        // verbatim regardless of strategy; the Akka-style cluster-
15311        // sharding reconciler keys off `estrategia == Sharded` and
15312        // ignores the slot otherwise), with no diagnostic. Lifting the
15313        // rejection to a build-time gate makes the
15314        // `shard_key.is_some() == matches!(estrategia, Sharded)`
15315        // partition a structural property of every validated
15316        // [`Placement`].
15317        let mut s = three_member_spec();
15318        // The fixture already uses Replicated; just add a shard-key.
15319        s.placement.shard_key = Some("$tenantId".into());
15320        let err = s.validate().unwrap_err();
15321        let AplicacaoError::ShardKeyOnNonSharded {
15322            estrategia,
15323            shard_key,
15324        } = err
15325        else {
15326            panic!("expected ShardKeyOnNonSharded, got {err:?}");
15327        };
15328        assert_eq!(estrategia, PlacementStrategy::Replicated);
15329        assert_eq!(shard_key, "$tenantId");
15330    }
15331
15332    #[test]
15333    fn rejects_shard_key_under_singlenode_strategy() {
15334        // Peer of the Replicated case above on the SingleNode arm: OTP
15335        // distributed-app takeover (one cluster runs at a time) has no
15336        // hash-keyed routing axis to consume `:shard-key` either, so
15337        // the rejection fires on both non-Sharded arms uniformly.
15338        let mut s = three_member_spec();
15339        s.placement.estrategia = PlacementStrategy::SingleNode;
15340        s.placement.shard_key = Some("$tenantId".into());
15341        let err = s.validate().unwrap_err();
15342        let AplicacaoError::ShardKeyOnNonSharded {
15343            estrategia,
15344            shard_key,
15345        } = err
15346        else {
15347            panic!("expected ShardKeyOnNonSharded, got {err:?}");
15348        };
15349        assert_eq!(estrategia, PlacementStrategy::SingleNode);
15350        assert_eq!(shard_key, "$tenantId");
15351    }
15352
15353    #[test]
15354    fn rejects_empty_shard_key_under_replicated_strategy() {
15355        // The `Some("")` case under non-Sharded is rejected by
15356        // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
15357        // fires before the empty-value gate), not
15358        // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
15359        // the `Sharded` arm). Pin the partition so a future reorder of
15360        // the validate_placement match arms doesn't silently swap which
15361        // diagnostic the author sees — both are author errors, but
15362        // ShardKeyOnNonSharded names which strategy is the actual fix
15363        // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
15364        // only says "pick a non-empty key".
15365        let mut s = three_member_spec();
15366        s.placement.shard_key = Some(String::new());
15367        let err = s.validate().unwrap_err();
15368        assert!(
15369            matches!(
15370                err,
15371                AplicacaoError::ShardKeyOnNonSharded {
15372                    estrategia: PlacementStrategy::Replicated,
15373                    ref shard_key,
15374                } if shard_key.is_empty()
15375            ),
15376            "got {err:?}"
15377        );
15378    }
15379
15380    #[test]
15381    fn replicated_without_shard_key_validates() {
15382        // The complement of the rejection: `:placement :estrategia
15383        // Replicated` with `:shard-key None` is the canonical happy
15384        // path on every existing fixture. Pin the no-shard-key case so
15385        // the new gate doesn't accidentally fire on `None`.
15386        let mut s = three_member_spec();
15387        assert!(matches!(
15388            s.placement.estrategia,
15389            PlacementStrategy::Replicated
15390        ));
15391        s.placement.shard_key = None;
15392        s.validate().unwrap();
15393    }
15394
15395    #[test]
15396    fn singlenode_without_shard_key_validates() {
15397        // Peer of the Replicated no-shard-key case on the SingleNode
15398        // arm — both non-Sharded strategies must validate cleanly when
15399        // the slot is omitted.
15400        let mut s = three_member_spec();
15401        s.placement.estrategia = PlacementStrategy::SingleNode;
15402        s.placement.shard_key = None;
15403        s.validate().unwrap();
15404    }
15405
15406    fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
15407        // Fixture builder for the `:placement :shard-key` shape gate
15408        // tests: a three-member Aplicacao on the `Sharded` strategy
15409        // with the supplied `:shard-key` slot. Co-locates the
15410        // arm-construction so every test below carries one line of
15411        // setup (the offending `:shard-key` value) and the assertion.
15412        let mut s = three_member_spec();
15413        s.placement.estrategia = PlacementStrategy::Sharded;
15414        s.placement.shard_key = Some(key.into());
15415        s
15416    }
15417
15418    #[test]
15419    fn rejects_shard_key_with_embedded_space() {
15420        // The canonical paste-from-aligned-doc footgun:
15421        // `:shard-key "$tenant Id"` — the Akka-style entity-id
15422        // extractor reads the slot as a single-token reference, and an
15423        // embedded space breaks the token boundary at the runtime
15424        // hash-extractor pass with no diagnostic naming the offending
15425        // entry.
15426        let s = sharded_spec_with_key("$tenant Id");
15427        let err = s.validate().unwrap_err();
15428        assert!(
15429            matches!(
15430                err,
15431                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
15432                    if shard_key == "$tenant Id" && reason.contains("space")
15433            ),
15434            "got {err:?}"
15435        );
15436    }
15437
15438    #[test]
15439    fn rejects_shard_key_with_leading_space() {
15440        // Leading-space arm of the embedded-whitespace footgun — the
15441        // paste-from-aligned-doc / paste-from-CSV-cell variant where
15442        // the leading column-padding leaked into the slot.
15443        let s = sharded_spec_with_key(" $tenantId");
15444        let err = s.validate().unwrap_err();
15445        assert!(
15446            matches!(
15447                err,
15448                AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
15449                    if shard_key == " $tenantId"
15450            ),
15451            "got {err:?}"
15452        );
15453    }
15454
15455    #[test]
15456    fn rejects_shard_key_with_trailing_newline() {
15457        // The canonical paste-from-shell-heredoc footgun — every
15458        // `<<EOF` heredoc terminator paste leaves a trailing newline
15459        // the YAML emitter then folds away inconsistently across
15460        // emitter implementations.
15461        let s = sharded_spec_with_key("$tenantId\n");
15462        let err = s.validate().unwrap_err();
15463        assert!(
15464            matches!(
15465                err,
15466                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
15467                    if shard_key == "$tenantId\n" && reason.contains("0x0a")
15468            ),
15469            "got {err:?}"
15470        );
15471    }
15472
15473    #[test]
15474    fn rejects_shard_key_with_embedded_tab() {
15475        // The paste-from-aligned-doc tab-stop variant — tabs land
15476        // alongside spaces in copy-paste from formatted columns.
15477        let s = sharded_spec_with_key("$tenant\tId");
15478        let err = s.validate().unwrap_err();
15479        assert!(
15480            matches!(
15481                err,
15482                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
15483                    if shard_key == "$tenant\tId" && reason.contains("tab")
15484            ),
15485            "got {err:?}"
15486        );
15487    }
15488
15489    #[test]
15490    fn rejects_shard_key_with_control_character() {
15491        // The paste-from-binary / paste-from-screen-cleared-terminal
15492        // footgun — an embedded `\x01` (SOH) byte that some YAML
15493        // emitters silently strip and others escape as ``,
15494        // breaking round-trip across emitter implementations.
15495        let s = sharded_spec_with_key("$tenant\u{0001}Id");
15496        let err = s.validate().unwrap_err();
15497        assert!(
15498            matches!(
15499                err,
15500                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
15501                    if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
15502            ),
15503            "got {err:?}"
15504        );
15505    }
15506
15507    #[test]
15508    fn rejects_shard_key_with_non_ascii() {
15509        // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
15510        // footgun — non-ASCII bytes normalize differently between the
15511        // caixa-mesh-side YAML emitter and the in-cluster reconciler's
15512        // YAML parser, the same entity ID can silently map to two
15513        // distinct shards on a re-render.
15514        let s = sharded_spec_with_key("$tenàntId");
15515        let err = s.validate().unwrap_err();
15516        assert!(
15517            matches!(
15518                err,
15519                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
15520                    if shard_key == "$tenàntId" && reason.contains("non-ASCII")
15521            ),
15522            "got {err:?}"
15523        );
15524    }
15525
15526    #[test]
15527    fn rejects_shard_key_too_long() {
15528        // Length cap pin: 64 bytes — one byte over the
15529        // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
15530        // here is a paste-from-doc multi-line blob landing in
15531        // `:shard-key` instead of a single-token extractor expression.
15532        let too_long = "a".repeat(64);
15533        let s = sharded_spec_with_key(&too_long);
15534        let err = s.validate().unwrap_err();
15535        let AplicacaoError::ShardKeyInvalid {
15536            ref shard_key,
15537            ref reason,
15538        } = err
15539        else {
15540            panic!("expected ShardKeyInvalid, got {err:?}");
15541        };
15542        assert_eq!(shard_key, &too_long);
15543        assert!(
15544            reason.contains("63") && reason.contains("64"),
15545            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
15546        );
15547    }
15548
15549    #[test]
15550    fn shard_key_max_length_validates() {
15551        // Boundary pin: 63 bytes exactly — the
15552        // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
15553        // dropping to 62) surfaces here as a regression, mirroring
15554        // `placement_cluster_max_length_validates` /
15555        // `placement_affinity_max_length_validates` on the peer
15556        // identifier-shaped slots.
15557        let s = sharded_spec_with_key(&"a".repeat(63));
15558        s.validate().unwrap();
15559    }
15560
15561    #[test]
15562    fn accepts_canonical_shard_key_forms() {
15563        // The Akka-style entity-id extractor shapes a caixa author is
15564        // realistically going to write — pin every leg so a future
15565        // tightening that bans (e.g.) the `${...}` interpolation
15566        // variant or the `metadata.<field>` JSONPath form surfaces
15567        // here as a regression. The canonical forms span:
15568        //
15569        //   - bare property name (`tenantId`, `customerId`)
15570        //   - Akka `ExtractEntityId` placeholder (`$tenantId`)
15571        //   - JSONPath-style nested reference (`metadata.tenantId`,
15572        //     `$.user.id`)
15573        //   - interpolation-style template (`${tenant}`)
15574        //   - snake_case property name (`customer_id`)
15575        //   - kebab-case property name (`customer-id` — accepted
15576        //     because the slot is a printable-ASCII single-token
15577        //     reference, not a DNS-1123 label like
15578        //     `:placement :affinity` / `:clusters`)
15579        //   - single character (`a`, `$` — boundary)
15580        for form in [
15581            "tenantId",
15582            "customerId",
15583            "$tenantId",
15584            "metadata.tenantId",
15585            "$.user.id",
15586            "${tenant}",
15587            "customer_id",
15588            "customer-id",
15589            "a",
15590            "$",
15591        ] {
15592            let s = sharded_spec_with_key(form);
15593            s.validate().unwrap_or_else(|e| {
15594                panic!("canonical shard-key form {form:?} must validate, got {e:?}")
15595            });
15596        }
15597    }
15598
15599    #[test]
15600    fn shard_key_empty_takes_precedence_over_invalid() {
15601        // Order pin: the existing `ShardedKeyEmpty` diagnostic
15602        // (reserved for the `Sharded` `Some("")` arm) fires before the
15603        // new `ShardKeyInvalid` parse-side diagnostic, so an empty
15604        // `:shard-key` keeps its narrower error message — the new gate
15605        // would also reject `""` defensively, but the empty-string arm
15606        // is the more self-locating diagnostic. Mirrors the
15607        // `placement_cluster_empty_takes_precedence_over_invalid` pin
15608        // on the peer identifier-shaped slot.
15609        let s = sharded_spec_with_key("");
15610        let err = s.validate().unwrap_err();
15611        assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
15612    }
15613
15614    #[test]
15615    fn shard_key_invalid_diagnostic_carries_offending_value() {
15616        // The diagnostic-shape pin: the error names the offending
15617        // `:shard-key` value verbatim so the author can grep their
15618        // caixa.lisp without re-running the build, and carries a
15619        // parser-shaped `reason:` naming the specific violation —
15620        // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
15621        // on the peer identifier-shaped slot.
15622        let s = sharded_spec_with_key("$tenant Id");
15623        let err = s.validate().unwrap_err();
15624        let AplicacaoError::ShardKeyInvalid {
15625            ref shard_key,
15626            ref reason,
15627        } = err
15628        else {
15629            panic!("expected ShardKeyInvalid, got {err:?}");
15630        };
15631        assert_eq!(shard_key, "$tenant Id");
15632        assert!(
15633            !reason.is_empty(),
15634            "reason must name the specific violation, got empty string"
15635        );
15636    }
15637
15638    #[test]
15639    fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
15640        // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
15641        // `:shard-key` carried on non-Sharded strategies) fires before
15642        // the shape gate, so a malformed `:shard-key` carried on (e.g.)
15643        // a `Replicated` strategy surfaces the more self-locating
15644        // strategy-mismatch diagnostic (naming the actual fix — drop
15645        // the slot, or switch to Sharded) rather than the shape
15646        // diagnostic. The strategy-mismatch arm is the more actionable
15647        // diagnostic: a malformed shard-key on Replicated is "you
15648        // shouldn't have a :shard-key here at all", not "your
15649        // :shard-key value is malformed".
15650        let mut s = three_member_spec();
15651        // Replicated is the default fixture strategy.
15652        s.placement.shard_key = Some("$tenant Id".into());
15653        let err = s.validate().unwrap_err();
15654        assert!(
15655            matches!(
15656                err,
15657                AplicacaoError::ShardKeyOnNonSharded {
15658                    estrategia: PlacementStrategy::Replicated,
15659                    ..
15660                }
15661            ),
15662            "got {err:?}"
15663        );
15664    }
15665
15666    #[test]
15667    fn rejects_empty_affinity_hint() {
15668        let mut s = three_member_spec();
15669        s.placement.affinity = Some("".into());
15670        assert_eq!(
15671            s.validate().unwrap_err(),
15672            AplicacaoError::PlacementAffinityEmpty
15673        );
15674    }
15675
15676    #[test]
15677    fn placement_without_affinity_validates() {
15678        // Omitting :affinity is fine — the placement engine falls back
15679        // to the default heuristic. Pin the no-hint case so the
15680        // affinity-empty rejection doesn't accidentally fire on `None`.
15681        let mut s = three_member_spec();
15682        s.placement.affinity = None;
15683        s.validate().unwrap();
15684    }
15685
15686    #[test]
15687    fn rejects_placement_affinity_with_uppercase() {
15688        // The canonical "I copied the ADR's display name verbatim" typo
15689        // — placement hints land verbatim in K8s label-selector
15690        // territory, where the apiserver enforces the DNS-1123 label
15691        // rule (lowercase-only) on every identity-keyed admission axis.
15692        // Mirrors `rejects_placement_cluster_with_uppercase` on the
15693        // sibling slot.
15694        let mut s = three_member_spec();
15695        s.placement.affinity = Some("DataLocality".into());
15696        let err = s.validate().unwrap_err();
15697        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
15698            panic!("expected PlacementAffinityInvalid, got other variant");
15699        };
15700        assert_eq!(affinity, "DataLocality");
15701        assert!(
15702            reason.contains("uppercase"),
15703            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
15704        );
15705        assert!(
15706            reason.contains("\"datalocality\""),
15707            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
15708        );
15709    }
15710
15711    #[test]
15712    fn rejects_placement_affinity_with_underscore() {
15713        // The canonical "I'm thinking of an env var / Python identifier"
15714        // leak — `_` is forbidden by every DNS-1123 label schema. Same
15715        // shape as `rejects_placement_cluster_with_underscore` on the
15716        // sibling slot.
15717        let mut s = three_member_spec();
15718        s.placement.affinity = Some("data_locality".into());
15719        let err = s.validate().unwrap_err();
15720        assert!(
15721            matches!(
15722                err,
15723                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
15724                    if affinity == "data_locality" && reason.contains('_')
15725            ),
15726            "got {err:?}"
15727        );
15728    }
15729
15730    #[test]
15731    fn rejects_placement_affinity_with_dot() {
15732        // A `:placement :affinity` value is a single DNS-1123 *label*
15733        // (it lands as a K8s label value selector key), not a subdomain.
15734        // The "I want to namespace my hint with `.`" intent is expressed
15735        // via `-` (`data-locality-east`).
15736        let mut s = three_member_spec();
15737        s.placement.affinity = Some("data.locality".into());
15738        let err = s.validate().unwrap_err();
15739        assert!(
15740            matches!(
15741                err,
15742                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
15743                    if affinity == "data.locality" && reason.contains('.')
15744            ),
15745            "got {err:?}"
15746        );
15747    }
15748
15749    #[test]
15750    fn rejects_placement_affinity_with_unicode() {
15751        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
15752        // before it reaches K8s. The byte-by-byte ASCII validity check
15753        // rejects multi-byte UTF-8 sequences by the first byte that
15754        // fails `[a-z0-9-]`.
15755        let mut s = three_member_spec();
15756        s.placement.affinity = Some("data-localité".into());
15757        let err = s.validate().unwrap_err();
15758        assert!(
15759            matches!(
15760                err,
15761                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
15762                    if affinity == "data-localité"
15763            ),
15764            "got {err:?}"
15765        );
15766    }
15767
15768    #[test]
15769    fn rejects_placement_affinity_with_leading_hyphen() {
15770        // DNS-1123 boundary rule: labels must start with an
15771        // alphanumeric. Pin separately from the trailing-hyphen arm so
15772        // a future relaxation that only checks one boundary surfaces
15773        // here as a regression (parallel to
15774        // `rejects_placement_cluster_with_leading_hyphen`).
15775        let mut s = three_member_spec();
15776        s.placement.affinity = Some("-data-locality".into());
15777        let err = s.validate().unwrap_err();
15778        assert!(
15779            matches!(
15780                err,
15781                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
15782                    if affinity == "-data-locality" && reason.contains("start and end")
15783            ),
15784            "got {err:?}"
15785        );
15786    }
15787
15788    #[test]
15789    fn rejects_placement_affinity_with_trailing_hyphen() {
15790        // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
15791        // ends are covered against a future relaxation.
15792        let mut s = three_member_spec();
15793        s.placement.affinity = Some("data-locality-".into());
15794        let err = s.validate().unwrap_err();
15795        assert!(
15796            matches!(
15797                err,
15798                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
15799                    if affinity == "data-locality-"
15800            ),
15801            "got {err:?}"
15802        );
15803    }
15804
15805    #[test]
15806    fn rejects_placement_affinity_with_whitespace() {
15807        // Whitespace is the canonical "I pasted from a sketch / doc"
15808        // footgun. The apiserver rejects every label-selector value
15809        // carrying whitespace.
15810        let mut s = three_member_spec();
15811        s.placement.affinity = Some("data locality".into());
15812        let err = s.validate().unwrap_err();
15813        assert!(
15814            matches!(
15815                err,
15816                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
15817                    if affinity == "data locality"
15818            ),
15819            "got {err:?}"
15820        );
15821    }
15822
15823    #[test]
15824    fn rejects_placement_affinity_too_long() {
15825        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
15826        // pin. The diagnostic names both the cap (63) and the actual
15827        // length so the author can shorten in one edit. Mirrors
15828        // `rejects_placement_cluster_too_long`.
15829        let mut s = three_member_spec();
15830        let too_long = "a".repeat(64);
15831        s.placement.affinity = Some(too_long.clone());
15832        let err = s.validate().unwrap_err();
15833        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
15834            panic!("expected PlacementAffinityInvalid");
15835        };
15836        assert_eq!(affinity, too_long);
15837        assert!(
15838            reason.contains("63") && reason.contains("64"),
15839            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
15840        );
15841    }
15842
15843    #[test]
15844    fn placement_affinity_max_length_validates() {
15845        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
15846        // future tightening (e.g. dropping to 62) surfaces here as a
15847        // regression, mirroring `placement_cluster_max_length_validates`.
15848        let mut s = three_member_spec();
15849        s.placement.affinity = Some("a".repeat(63));
15850        s.validate().unwrap();
15851    }
15852
15853    #[test]
15854    fn accepts_canonical_placement_affinity_forms() {
15855        // The DNS-1123 label shapes a caixa author is realistically
15856        // going to write for placement hints: the M3 canonical examples
15857        // (`data-locality`, `low-latency`, `anti-affinity`), the
15858        // single-token form (`affinity`), the single-character boundary
15859        // (`a`), the digit-start (DNS-1123 allows this, unlike
15860        // DNS-1035), and a regional-suffixed form. Pin every leg so a
15861        // future tightening that bans (e.g.) digit-start identifiers
15862        // surfaces here.
15863        for form in [
15864            "data-locality",
15865            "low-latency",
15866            "anti-affinity",
15867            "affinity",
15868            "a",
15869            "3-tier",
15870            "locality-east",
15871        ] {
15872            let mut s = three_member_spec();
15873            s.placement.affinity = Some(form.into());
15874            s.validate().unwrap_or_else(|e| {
15875                panic!("canonical affinity form {form:?} must validate, got {e:?}")
15876            });
15877        }
15878    }
15879
15880    #[test]
15881    fn placement_affinity_empty_takes_precedence_over_invalid() {
15882        // Order pin: the existing `PlacementAffinityEmpty` diagnostic
15883        // (which doesn't try to parse) fires before the new
15884        // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
15885        // `:affinity` keeps its narrower error message — the new gate
15886        // would also reject `""`, but the empty-string arm is the more
15887        // self-locating diagnostic. Mirrors the
15888        // `placement_cluster_empty_takes_precedence_over_invalid` pin.
15889        let mut s = three_member_spec();
15890        s.placement.affinity = Some(String::new());
15891        let err = s.validate().unwrap_err();
15892        assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
15893    }
15894
15895    #[test]
15896    fn placement_affinity_invalid_diagnostic_carries_offending_value() {
15897        // The diagnostic shape pin: every rejection carries the offending
15898        // `affinity:` verbatim plus a parser-shaped `reason:` so the
15899        // author can grep their caixa.lisp for `:affinity "<hint>"` and
15900        // fix it in one edit. Mirrors the
15901        // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
15902        // pin on the sibling slot.
15903        let mut s = three_member_spec();
15904        s.placement.affinity = Some("Data_Locality".into());
15905        let err = s.validate().unwrap_err();
15906        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
15907            panic!("expected PlacementAffinityInvalid");
15908        };
15909        assert_eq!(affinity, "Data_Locality");
15910        assert!(
15911            !reason.is_empty(),
15912            "diagnostic reason must not be empty (got: {reason:?})"
15913        );
15914    }
15915
15916    #[test]
15917    fn singlenode_with_takeover_candidates_validates() {
15918        // OTP distributed-application convention (MESH-COMPOSITION
15919        // §II.1): SingleNode runs on one cluster at a time but the
15920        // :clusters list enumerates the takeover candidates. Multiple
15921        // entries are not a contradiction — they are the failover pool.
15922        let mut s = three_member_spec();
15923        s.placement.estrategia = PlacementStrategy::SingleNode;
15924        s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
15925        s.validate().unwrap();
15926    }
15927
15928    // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
15929
15930    #[test]
15931    fn mesh_policy_default_is_empty() {
15932        // The Default impl carries None on every axis — the typed
15933        // analog of an unset `:politicas (())` slot. Renderers that
15934        // overlay the policy onto a cluster artifact key off this
15935        // predicate to skip the slot entirely; pinning so a future
15936        // axis added to MeshPolicy can't silently break the contract
15937        // (a new field whose Default is non-None would flip is_empty
15938        // to false on every existing caixa, surfacing here).
15939        assert!(MeshPolicy::default().is_empty());
15940    }
15941
15942    #[test]
15943    fn mesh_policy_with_only_timeout_is_not_empty() {
15944        let p = MeshPolicy {
15945            timeout: Some(Duration::from_secs(30)),
15946            ..Default::default()
15947        };
15948        assert!(!p.is_empty());
15949    }
15950
15951    #[test]
15952    fn mesh_policy_with_only_retries_is_not_empty() {
15953        let p = MeshPolicy {
15954            retries: Some(3),
15955            ..Default::default()
15956        };
15957        assert!(!p.is_empty());
15958    }
15959
15960    #[test]
15961    fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
15962        let p = MeshPolicy {
15963            circuit_breaker: Some(CircuitBreaker {
15964                max_failures: 5,
15965                window: Duration::from_secs(60),
15966            }),
15967            ..Default::default()
15968        };
15969        assert!(!p.is_empty());
15970    }
15971
15972    #[test]
15973    fn mesh_policy_with_only_mtls_required_is_not_empty() {
15974        // Even `mtls_required: Some(false)` (an explicit opt-out) is
15975        // not empty — the author *named* the axis, the renderer needs
15976        // to honor that vs. fall back to the cluster default.
15977        let p = MeshPolicy {
15978            mtls_required: Some(false),
15979            ..Default::default()
15980        };
15981        assert!(!p.is_empty());
15982    }
15983
15984    #[test]
15985    fn mesh_policy_with_only_rate_limit_is_not_empty() {
15986        let p = MeshPolicy {
15987            rate_limit: Some(RateLimit {
15988                rate: 100,
15989                window: Duration::from_secs(1),
15990            }),
15991            ..Default::default()
15992        };
15993        assert!(!p.is_empty());
15994    }
15995
15996    #[test]
15997    fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
15998        // The three-member happy-path fixture sets timeout + retries +
15999        // mtls_required — every populated axis must read non-empty.
16000        // Pin the round-trip so the M3.x per-:politicas emitter (the
16001        // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
16002        // on is_empty() to decide whether to emit at all without
16003        // re-deriving the contract from inline field probes.
16004        assert!(!three_member_spec().politicas.is_empty());
16005    }
16006
16007    // ── shared duration codec: cross-slot integer-magnitude gate ──
16008    //
16009    // The integer-magnitude discipline applied to
16010    // `supervisor::duration_codec::parse` lifts onto every typed slot
16011    // that routes through the shared codec — `MeshPolicy::timeout`
16012    // (`:politicas :timeout`) and `CircuitBreaker::window`
16013    // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
16014    // These cross-slot tests pin that the gate fires at the serde
16015    // layer for both typed slots, not just for the supervisor side.
16016
16017    #[test]
16018    fn policy_timeout_serde_rejects_fractional_seconds() {
16019        // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
16020        // so the shared codec's integer-magnitude gate applies on
16021        // deserialize. `"1.5s"` previously parsed to 1500ms and round-
16022        // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
16023        // deserialize with the canonical-form diagnostic naming the
16024        // offending `"1.5"` and the remediation `"1500ms"`.
16025        let payload = r#"{"timeout":"1.5s"}"#;
16026        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16027        let msg = err.to_string();
16028        assert!(
16029            msg.contains("not a non-negative integer"),
16030            "expected integer-magnitude diagnostic in {msg:?}"
16031        );
16032        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
16033        assert!(
16034            msg.contains("\"1500ms\""),
16035            "missing canonical-form remediation in {msg:?}"
16036        );
16037    }
16038
16039    #[test]
16040    fn policy_timeout_serde_rejects_leading_plus_sign() {
16041        // Pin the leading-`+` arm cross-slot — the prior f64 parser
16042        // accepted `"+30s"` silently and round-tripped to `"30s"`.
16043        let payload = r#"{"timeout":"+30s"}"#;
16044        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16045        let msg = err.to_string();
16046        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
16047    }
16048
16049    #[test]
16050    fn circuit_breaker_window_serde_rejects_fractional_minutes() {
16051        // `CircuitBreaker::window` uses `with =
16052        // "supervisor::duration_codec_required"` (the required-Duration
16053        // variant that delegates to the same shared parser). `"0.5m"`
16054        // parsed to 30s and round-tripped to `"30s"` on next emit —
16055        // DRIFT closed.
16056        let payload = format!(
16057            r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
16058            max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
16059            window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
16060        );
16061        let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
16062        let msg = err.to_string();
16063        assert!(
16064            msg.contains("not a non-negative integer"),
16065            "expected integer-magnitude diagnostic in {msg:?}"
16066        );
16067        assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
16068        assert!(
16069            msg.contains("\"30s\""),
16070            "missing canonical-form remediation in {msg:?}"
16071        );
16072    }
16073
16074    #[test]
16075    fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
16076        // Pin the happy-path on the cross-slot side: every canonical
16077        // author shape `render` ever emits parses cleanly through the
16078        // shared codec on the `CircuitBreaker` slot. The
16079        // codec's accepted set (post-gate) is exactly its emitted set
16080        // for the integer-magnitude class.
16081        for window_lit in ["30s", "500ms", "2m", "1h"] {
16082            let payload = format!(
16083                r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
16084                max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
16085                window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
16086            );
16087            let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
16088                panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
16089            });
16090            assert_eq!(cb.max_failures, 5);
16091        }
16092    }
16093
16094    // ── rate_limit_codec: integer-magnitude gate ──
16095    //
16096    // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
16097    // / 737a676 / d53c922 trajectory landed on every typed-duration /
16098    // typed-byte-size codec in caixa-core lifts onto the fifth typed
16099    // codec — `rate_limit_codec` — through the digit-only magnitude
16100    // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
16101    // These tests pin the gate at the serde layer for `:politicas
16102    // :rate-limit` (the only typed slot the codec backs), and at the
16103    // codec-internal `parse` layer for the canonical positive cases.
16104
16105    #[test]
16106    fn rate_limit_serde_rejects_fractional_rate() {
16107        // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
16108        // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
16109        // wording, which didn't name the canonical-form remediation or
16110        // the round-trip drift the next emit would produce. Now refused
16111        // at deserialize with the canonical-form diagnostic naming the
16112        // offending `"1.5"` magnitude and the round-trip drift wording.
16113        let payload = r#"{"rateLimit":"1.5/s"}"#;
16114        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16115        let msg = err.to_string();
16116        assert!(
16117            msg.contains("not a non-negative integer"),
16118            "expected integer-magnitude diagnostic in {msg:?}"
16119        );
16120        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
16121        assert!(
16122            msg.contains("THEORY.md"),
16123            "missing render-determinism contract citation in {msg:?}"
16124        );
16125    }
16126
16127    #[test]
16128    fn rate_limit_serde_rejects_leading_plus_sign() {
16129        // `u32::from_str("+100")` returns `Ok(100)` (Rust's
16130        // permissive-`+` parse), so `"+100/s"` silently parsed to
16131        // `RateLimit { 100, 1s }` and round-tripped through `render` to
16132        // `"100/s"` — a *different* canonical string on the next emit,
16133        // breaking the THEORY.md Part V render-determinism contract
16134        // exactly the way the peer duration codecs' `"+30s"` case did.
16135        // This is the load-bearing class the digit-only gate closes
16136        // beyond what `u32::from_str`'s strictness covers on its own.
16137        let payload = r#"{"rateLimit":"+100/s"}"#;
16138        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16139        let msg = err.to_string();
16140        assert!(
16141            msg.contains("not a non-negative integer"),
16142            "expected integer-magnitude diagnostic in {msg:?}"
16143        );
16144        assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
16145    }
16146
16147    #[test]
16148    fn rate_limit_serde_rejects_leading_minus_sign() {
16149        // The signed-negative arm: `"-1/s"` lands on the
16150        // non-canonical-but-numeric branch via the `i64` fallback (the
16151        // `f64` parse also succeeds), surfacing the canonical-form
16152        // diagnostic. Replaces the prior value-laundered "not a u32"
16153        // wording with the unified diagnostic across signs.
16154        let payload = r#"{"rateLimit":"-1/s"}"#;
16155        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16156        let msg = err.to_string();
16157        assert!(
16158            msg.contains("not a non-negative integer"),
16159            "expected integer-magnitude diagnostic in {msg:?}"
16160        );
16161        assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
16162    }
16163
16164    #[test]
16165    fn rate_limit_serde_rejects_decimal_shaped_integer() {
16166        // `"100.0/s"` is integer-valued numerically but not in the
16167        // codec's accepted set — `render` emits `"100/s"`, so the
16168        // round-trip would drift. Lifted to the canonical-form
16169        // diagnostic peer with the duration codec's `"1.0s"` case
16170        // (1c55a2a).
16171        let payload = r#"{"rateLimit":"100.0/s"}"#;
16172        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16173        let msg = err.to_string();
16174        assert!(
16175            msg.contains("not a non-negative integer"),
16176            "expected integer-magnitude diagnostic in {msg:?}"
16177        );
16178        assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
16179    }
16180
16181    #[test]
16182    fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
16183        // Non-numeric, non-digit-only input lands on the existing
16184        // narrower `"not a u32"` arm (preserved for diagnostic-shape
16185        // stability on the parser-shape footgun case). Pin this so a
16186        // future relaxation of the numeric-fallback predicate doesn't
16187        // silently collapse garbage onto the canonical-form arm — same
16188        // partition the peer duration codecs draw between
16189        // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
16190        let payload = r#"{"rateLimit":"abc/s"}"#;
16191        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16192        let msg = err.to_string();
16193        assert!(
16194            msg.contains("not a u32"),
16195            "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
16196        );
16197        assert!(
16198            !msg.contains("not a non-negative integer"),
16199            "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
16200        );
16201    }
16202
16203    #[test]
16204    fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
16205        // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
16206        // u32's range. The digit-only gate passes; `u32::from_str`
16207        // fails on overflow. Surface that with the overflow-shaped
16208        // diagnostic naming the offending magnitude verbatim, peer
16209        // with `supervisor::duration_codec`'s overflow arm. Pinning
16210        // the wording so a future refactor doesn't silently collapse
16211        // overflow onto the canonical-form arm.
16212        let payload = r#"{"rateLimit":"4294967296/s"}"#;
16213        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16214        let msg = err.to_string();
16215        assert!(
16216            msg.contains("overflows u32"),
16217            "expected overflow diagnostic in {msg:?}"
16218        );
16219        assert!(
16220            msg.contains("\"4294967296\""),
16221            "missing offending magnitude in {msg:?}"
16222        );
16223    }
16224
16225    #[test]
16226    fn rate_limit_serde_rejects_leading_zero_magnitude() {
16227        // `"0100/s"` is digit-only, so the existing
16228        // non-digit-only / sign / fractional arm doesn't catch it —
16229        // `u32::from_str("0100")` returns `Ok(100)`, so before this
16230        // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
16231        // round-tripped through `render` to `"100/s"` — a *different*
16232        // canonical string on the next emit, breaking the THEORY.md
16233        // Part V render-determinism contract exactly the way the
16234        // peer `"+100/s"` case did before the leading-`+` arm landed.
16235        // This is the load-bearing class the leading-zero gate closes
16236        // beyond what the existing digit-only / sign / fractional
16237        // gates cover, and the peer arm to the leading-`+` test
16238        // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
16239        // canonical-form-drift axis.
16240        let payload = r#"{"rateLimit":"0100/s"}"#;
16241        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16242        let msg = err.to_string();
16243        assert!(
16244            msg.contains("non-canonical leading zero"),
16245            "expected leading-zero diagnostic in {msg:?}"
16246        );
16247        assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
16248        assert!(
16249            msg.contains("THEORY.md"),
16250            "missing render-determinism contract citation in {msg:?}"
16251        );
16252    }
16253
16254    #[test]
16255    fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
16256        // `"00/s"` is the degenerate leading-zero case — every byte
16257        // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
16258        // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
16259        // a *different* canonical string, same render-determinism
16260        // violation. The single-byte `"0/s"` itself is in the
16261        // accepted set (round-trips losslessly through `render`,
16262        // refused downstream by `PolicyRateLimitZero`); the
16263        // multi-byte `"00/s"` is not. Pins the boundary between the
16264        // accepted single-`0` and the rejected leading-zero class.
16265        let payload = r#"{"rateLimit":"00/s"}"#;
16266        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16267        let msg = err.to_string();
16268        assert!(
16269            msg.contains("non-canonical leading zero"),
16270            "expected leading-zero diagnostic in {msg:?}"
16271        );
16272        assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
16273    }
16274
16275    #[test]
16276    fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
16277        // Cross-window pin — the gate is window-agnostic; the
16278        // leading-zero class is a property of the magnitude, not the
16279        // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
16280        // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
16281        // single-window coverage extended across the three canonical
16282        // windows the codec accepts.
16283        let payload = r#"{"rateLimit":"007/h"}"#;
16284        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16285        let msg = err.to_string();
16286        assert!(
16287            msg.contains("non-canonical leading zero"),
16288            "expected leading-zero diagnostic in {msg:?}"
16289        );
16290        assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
16291    }
16292
16293    #[test]
16294    fn rate_limit_serde_rejects_leading_whitespace() {
16295        // `" 100/s"` — the canonical paste-from-aligned-doc /
16296        // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
16297        // the top-level `s.trim()` silently ate the leading space and
16298        // parsed the value to `RateLimit { 100, 1s }`, which then
16299        // round-tripped through `render` to `"100/s"` (a *different*
16300        // canonical string on the next emit) — the exact
16301        // canonical-form-drift class the leading-`+` / leading-zero
16302        // arms already close, extended to the whitespace byte class.
16303        let payload = r#"{"rateLimit":" 100/s"}"#;
16304        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16305        let msg = err.to_string();
16306        assert!(
16307            msg.contains("contains whitespace byte"),
16308            "expected whitespace diagnostic in {msg:?}"
16309        );
16310        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
16311        assert!(
16312            msg.contains("THEORY.md"),
16313            "missing render-determinism contract citation in {msg:?}"
16314        );
16315    }
16316
16317    #[test]
16318    fn rate_limit_serde_rejects_trailing_whitespace() {
16319        // `"100/s "` — the canonical shell-history / trailing-space
16320        // paste footgun. Before this gate the top-level `s.trim()`
16321        // silently ate the trailing space and parsed to
16322        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
16323        // next emit — same canonical-form drift as the leading-space
16324        // sibling, closed on the same whitespace-byte arm.
16325        let payload = r#"{"rateLimit":"100/s "}"#;
16326        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16327        let msg = err.to_string();
16328        assert!(
16329            msg.contains("contains whitespace byte"),
16330            "expected whitespace diagnostic in {msg:?}"
16331        );
16332        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
16333    }
16334
16335    #[test]
16336    fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
16337        // `"100 / s"` — the canonical typographically-spaced author
16338        // shape (the same idiom every prose reference to a rate limit
16339        // renders as, mistakenly retained when the value is pasted
16340        // into a codec-shaped slot). Before this gate the per-part
16341        // `rate_str.trim()` / `unit.trim()` calls silently ate both
16342        // spaces on either side of `/` and parsed to
16343        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
16344        // codec's *internal* whitespace-tolerance vector, orthogonal
16345        // to the leading / trailing surface but the same canonical-
16346        // form-drift class. Pins the arm as strictly stronger than the
16347        // pre-existing top-level `s.trim()` behavior: it fires on
16348        // whitespace anywhere in the value, not just at the string
16349        // boundary.
16350        let payload = r#"{"rateLimit":"100 / s"}"#;
16351        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16352        let msg = err.to_string();
16353        assert!(
16354            msg.contains("contains whitespace byte"),
16355            "expected whitespace diagnostic in {msg:?}"
16356        );
16357        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
16358    }
16359
16360    #[test]
16361    fn rate_limit_serde_rejects_tab_byte() {
16362        // `"\t100/s"` — the canonical paste-from-indented-doc /
16363        // paste-from-YAML-block-scalar footgun where a tab byte leads
16364        // the magnitude. Pins that the gate covers tab (`0x09`) as
16365        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
16366        // members and both would be silently swallowed by `s.trim()`
16367        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
16368        // space alone to the full ASCII-whitespace set (space `0x20`,
16369        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
16370        // the tab arm as a representative of the non-space members.
16371        let payload = r#"{"rateLimit":"\t100/s"}"#;
16372        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16373        let msg = err.to_string();
16374        assert!(
16375            msg.contains("contains whitespace byte"),
16376            "expected whitespace diagnostic in {msg:?}"
16377        );
16378        assert!(
16379            msg.contains("0x09"),
16380            "missing offending tab byte in {msg:?}"
16381        );
16382    }
16383
16384    // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
16385    //
16386    // Successor to the ASCII-whitespace arm (1ad7755) on
16387    // `rate_limit_codec` — closes the strictly-complementary class the
16388    // byte-scan cannot see, through the lifted
16389    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
16390
16391    #[test]
16392    fn rate_limit_serde_rejects_leading_nbsp() {
16393        // NBSP prefix — paste-from-typography footgun. Byte-scan
16394        // misses, `str::trim` silently strips it, value drifts to
16395        // `"100/s"` on next serialize.
16396        let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
16397        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16398        let msg = err.to_string();
16399        assert!(
16400            msg.contains("non-ASCII Unicode whitespace character"),
16401            "expected non-ASCII whitespace diagnostic in {msg:?}"
16402        );
16403        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
16404    }
16405
16406    #[test]
16407    fn rate_limit_serde_rejects_internal_em_space() {
16408        // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
16409        // paste-from-typography footgun on the `<integer>/<unit>`
16410        // shape.
16411        let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
16412        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16413        let msg = err.to_string();
16414        assert!(
16415            msg.contains("non-ASCII Unicode whitespace character"),
16416            "expected non-ASCII whitespace diagnostic in {msg:?}"
16417        );
16418        assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
16419    }
16420
16421    #[test]
16422    fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
16423        // Positive-control pin: every ASCII-only canonical form the
16424        // renderer emits stays accepted through the new arm.
16425        for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
16426            let payload = format!(r#"{{"rateLimit":{lit}}}"#);
16427            let p: MeshPolicy = serde_json::from_str(&payload)
16428                .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
16429            assert!(p.rate_limit.is_some());
16430        }
16431    }
16432
16433    #[test]
16434    fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
16435        // The boundary case — `"0/s"` is the canonical form
16436        // `render(RateLimit { 0, 1s })` emits, so the codec accepts
16437        // it at the parse layer; the downstream
16438        // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
16439        // `rate == 0` at the typed-validate layer above. Pins the
16440        // partition: the leading-zero gate at the codec layer does
16441        // not poach the rate-zero semantic-validation arm at the
16442        // typed-validate layer above (a future stricter codec must
16443        // not reject `"0/s"` here, or it'd collapse the diagnostic
16444        // partitioning that lets `PolicyRateLimitZero` name the
16445        // offending typed slot).
16446        let payload = r#"{"rateLimit":"0/s"}"#;
16447        let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
16448            panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
16449        });
16450        let rl = policy.rate_limit.expect("rate_limit must be Some");
16451        assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
16452        assert_eq!(
16453            rl.window,
16454            Duration::from_secs(1),
16455            "single-`0` magnitude with `s` unit must parse to window=1s"
16456        );
16457    }
16458
16459    #[test]
16460    fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
16461        // The complementary boundary pin — every magnitude
16462        // `render` emits starts with `[1-9]` (or is the single byte
16463        // `"0"`), so the canonical-form predicate is `(len == 1) ||
16464        // (first byte != '0')`. Pinning the `len > 1 && first byte ==
16465        // '1'` case explicitly so a future tightening of the gate
16466        // (e.g. an over-eager "no leading digit < 5" rule, or a
16467        // mistakenly anchored start-of-magnitude byte check) lands
16468        // here before the canonical-forms-iterating test would catch
16469        // it.
16470        let payload = r#"{"rateLimit":"100/s"}"#;
16471        let policy: MeshPolicy = serde_json::from_str(payload)
16472            .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
16473        let rl = policy.rate_limit.expect("rate_limit must be Some");
16474        assert_eq!(
16475            rl.rate, 100,
16476            "canonical-100 magnitude must parse to rate=100"
16477        );
16478    }
16479
16480    #[test]
16481    fn rate_limit_serde_accepts_integer_canonical_forms() {
16482        // Pin the happy-path: every canonical author shape `render`
16483        // ever emits parses cleanly through the codec post-gate. The
16484        // codec's accepted set (post-gate) is exactly its emitted set
16485        // for the integer-magnitude class — same property
16486        // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
16487        // gates guarantee on the peer codecs. Iterating across rate
16488        // magnitudes (including `"0"`, which the codec accepts even
16489        // though `validate_politicas` rejects `rate == 0` at the typed
16490        // layer above) closes the codec contract at the parse layer
16491        // independently of the validate layer.
16492        for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
16493            for unit_lit in ["s", "m", "h"] {
16494                let lit = format!("{rate_lit}/{unit_lit}");
16495                let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
16496                let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
16497                    panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
16498                });
16499                let rl = policy.rate_limit.expect("rate_limit must be Some");
16500                assert_eq!(
16501                    rl.rate,
16502                    rate_lit.parse::<u32>().unwrap(),
16503                    "rate mismatch for {lit:?}"
16504                );
16505            }
16506        }
16507    }
16508
16509    #[test]
16510    fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
16511        // The structural property the gate enforces: serialize ∘
16512        // deserialize is the identity on every canonical author shape.
16513        // Peer of `parse_byte_size`'s and `parse_duration`'s
16514        // `_round_trips_through_render_for_every_canonical_form` tests
16515        // on the rate-limit axis. Before the gate, `"+100/s"` violated
16516        // this (`parse` → `RateLimit { 100, 1s }` → `render` →
16517        // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
16518        for rate in [1u32, 100, 5000, 1_000_000] {
16519            for (window, unit) in [
16520                (Duration::from_secs(1), "s"),
16521                (Duration::from_secs(60), "m"),
16522                (Duration::from_secs(3600), "h"),
16523            ] {
16524                let policy = MeshPolicy {
16525                    rate_limit: Some(RateLimit { rate, window }),
16526                    ..Default::default()
16527                };
16528                let json = serde_json::to_string(&policy).unwrap();
16529                let expected = format!("\"{rate}/{unit}\"");
16530                assert!(
16531                    json.contains(&expected),
16532                    "expected {expected:?} in {json:?}"
16533                );
16534                let back: MeshPolicy = serde_json::from_str(&json).unwrap();
16535                assert_eq!(
16536                    back.rate_limit, policy.rate_limit,
16537                    "round-trip for {json:?}"
16538                );
16539            }
16540        }
16541    }
16542
16543    // ── self-membership cross-slot gate ──────────────────────────────
16544
16545    #[test]
16546    fn validate_no_self_membership_rejects_self_named_membro() {
16547        // An Aplicacao whose `:membros` lists its own `:nome` is a
16548        // one-node lacre-closure recursion — rejected, naming the parent.
16549        let membros = vec![
16550            membro("catalog", "^0.1"),
16551            membro("checkout", "^0.1"),
16552            membro("cart", "^0.1"),
16553        ];
16554        let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
16555        assert!(
16556            matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
16557            "got {err:?}"
16558        );
16559    }
16560
16561    #[test]
16562    fn validate_no_self_membership_accepts_distinct_membros() {
16563        // Positive control: distinct member names (including a member
16564        // that is itself an Aplicacao — recursive composition is valid,
16565        // MESH-COMPOSITION §V) pass the gate.
16566        let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
16567        validate_no_self_membership(&membros, "checkout").unwrap();
16568    }
16569
16570    #[test]
16571    fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
16572        // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
16573        // `NoMembros` arm (the more-fundamental "graph must have nodes"
16574        // gate), not by this cross-slot self-edge gate. Keeping the
16575        // self-membership predicate vacuously-ok on the empty input
16576        // matches its supervisor-axis peer
16577        // (`validate_no_self_supervision_empty_children_is_ok`) and
16578        // makes the gate composable from any future call site (an M4
16579        // CR materializer's per-membros validator) without re-checking
16580        // emptiness.
16581        validate_no_self_membership(&[], "checkout").unwrap();
16582    }
16583
16584    #[test]
16585    fn validate_no_self_membership_diagnostic_names_offending_caixa() {
16586        // Pinning the Display: the self-membership diagnostic must name
16587        // the offending caixa verbatim + the "lists itself" framing the
16588        // author can grep for, so the cluster-far failure surfaces at
16589        // build time with one-line remediation. Same diagnostic shape
16590        // as the supervisor-axis `ChildSupervisesSelf` peer.
16591        let membros = vec![membro("orquestra", "^0.1")];
16592        let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
16593        let msg = err.to_string();
16594        assert!(
16595            msg.contains("orquestra"),
16596            "diagnostic must name the offending caixa nome (got: {msg:?})"
16597        );
16598        assert!(
16599            msg.contains("lists itself"),
16600            "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
16601        );
16602    }
16603
16604    #[test]
16605    fn default_servico_port_constant_pins_canonical_8080_literal() {
16606        // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
16607        // at the verbatim `8080` literal both consumers (the
16608        // `Entrada::port` serde default via [`default_port`] and the
16609        // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
16610        // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
16611        // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
16612        // discipline (a085b26) on the per-renderer canonical-K8s-axis
16613        // string-constant axis: a future refactor that drifts the
16614        // constant out from under either consumer surfaces here ahead
16615        // of every per-renderer's first emission. The literal value
16616        // matches the well-known HTTP-alt port the `pleme-computeunit`
16617        // library chart already emits as its `trigger.service.port`
16618        // default — by construction the same value the substrate
16619        // assumes about every Servico's in-cluster L4 listener.
16620        assert_eq!(
16621            DEFAULT_SERVICO_PORT, 8080,
16622            "canonical Servico port literal must remain `8080` verbatim — \
16623             this is the value both the `Entrada::port` serde default and the \
16624             caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
16625        );
16626    }
16627
16628    #[test]
16629    fn default_port_helper_returns_canonical_servico_port_constant() {
16630        // The bridge-arm — pins that the [`default_port`] helper
16631        // [`Entrada::port`]'s `#[serde(default = "default_port")]`
16632        // attribute hooks routes through the lifted
16633        // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
16634        // literal. A future refactor that re-introduces the `8080`
16635        // literal at the helper's return site (silently re-opening
16636        // the drift footgun this lift closed) surfaces here ahead of
16637        // every author-side `(:entrada (:host … :para …))` slot
16638        // without an explicit `:port`. Peer with the
16639        // `default_namespace_re_export_points_at_caixa_core_canonical`
16640        // pin on the caixa-mesh-side re-export axis.
16641        assert_eq!(
16642            default_port(),
16643            DEFAULT_SERVICO_PORT,
16644            "the serde-default helper must route through the lifted constant"
16645        );
16646    }
16647
16648    #[test]
16649    fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
16650        // The end-to-end pin — an author-surface `(:entrada (:host …
16651        // :para …))` without an explicit `:port` slot deserializes to
16652        // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
16653        // verbatim. Routes the canonical lifted constant through both
16654        // the serde-default machinery (the `#[serde(default =
16655        // "default_port")]` attribute) and the typed-value-shape
16656        // contract (the resulting [`Entrada::port`] value). A future
16657        // refactor that drifts either axis — replacing the serde
16658        // hook's helper, changing the typed slot's wire shape — would
16659        // surface here before any per-renderer's CNP / Gateway /
16660        // HTTPRoute emission consumed the drifted default.
16661        let entrada: Entrada =
16662            serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
16663        assert_eq!(
16664            entrada.port, DEFAULT_SERVICO_PORT,
16665            "the serde default must materialize as the lifted canonical Servico port"
16666        );
16667    }
16668
16669    #[test]
16670    fn servico_port_min_pins_canonical_accept_set_floor() {
16671        // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
16672        // verbatim `1` literal every typed `:entrada :port` acceptance
16673        // gate keys off. Peer with the
16674        // [`default_servico_port_constant_pins_canonical_8080_literal`]
16675        // discipline on the canonical-Servico-port-constant axis: a
16676        // future refactor that drifts the accept-set floor out from
16677        // under the sole consumer at [`AplicacaoSpec::validate`]'s
16678        // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
16679        // every per-`:entrada` `EntradaPortZero` diagnostic. The
16680        // literal value matches the IANA-registered TCP/UDP port
16681        // space floor (`1..=65535` — port `0` is the "any ephemeral"
16682        // sentinel, not a well-defined destination the substrate's
16683        // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
16684        // axis can honor).
16685        assert_eq!(
16686            SERVICO_PORT_MIN, 1,
16687            "canonical Servico port accept-set floor must remain `1` verbatim — \
16688             this is the value the `AplicacaoSpec::validate` gate at \
16689             `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
16690        );
16691    }
16692
16693    #[test]
16694    fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
16695        // The cross-const invariant pin — the substrate's canonical
16696        // default port must satisfy its own accept-set floor by
16697        // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
16698        // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
16699        // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
16700        // override the operator pins through a future
16701        // `:placement :default-port` slot that lands out-of-range, a
16702        // per-edition Servico-port migration that lifted the floor
16703        // above the previous default without coordinating the pair —
16704        // would silently invalidate the serde-default emission at
16705        // every author-side `(:entrada (:host … :para …))` slot
16706        // without an explicit `:port`: the default port would fall
16707        // below the accept-set floor, the `AplicacaoSpec::validate`
16708        // gate would reject every default-carrying Aplicacao as
16709        // `EntradaPortZero`, and the substrate's typed
16710        // `(defcaixa … :kind Aplicacao)` surface would fail validate
16711        // on every Aplicacao whose author omitted `:entrada :port`
16712        // for the substrate's chosen default — a class of authoring-
16713        // surface footguns the compile-time pin structurally closes.
16714        // Peer with the
16715        // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
16716        // (27f9b34) cross-const invariant pin discipline on the peer
16717        // canonical-Helm-per-values-block child-chart-enablement-toggle
16718        // axis pair.
16719        assert!(
16720            SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
16721            "the substrate's canonical default port ({DEFAULT_SERVICO_PORT}) must \
16722             satisfy its own accept-set floor (SERVICO_PORT_MIN = {SERVICO_PORT_MIN}) — \
16723             every default-carrying `(:entrada (:host … :para …))` slot without an \
16724             explicit `:port` inherits `DEFAULT_SERVICO_PORT` through the serde default \
16725             hook and must pass the `AplicacaoSpec::validate` floor gate by construction"
16726        );
16727    }
16728
16729    #[test]
16730    fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
16731        // The gate-site pin — asserts the `AplicacaoSpec::validate`
16732        // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
16733        // `EntradaPortZero` diagnostic on the below-floor input
16734        // `port: 0` (the only below-floor value the `u16` field can
16735        // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
16736        // is the singleton `{0}`). A future refactor that drifts the
16737        // gate off the lifted const (silently re-introducing an
16738        // inline `if e.port == 0` byte-check) surfaces here — the
16739        // pin cannot distinguish `< 1` from `== 0` on the current
16740        // floor, but it *does* pin that the diagnostic fires on `0`
16741        // through whichever gate is wired, so any future accept-set
16742        // floor migration (a hypothetical unprivileged-only
16743        // migration lifting `SERVICO_PORT_MIN` to `1024`) must
16744        // update this test alongside the const declaration —
16745        // structurally guaranteeing the gate + accept-set + pin
16746        // trio move together. Peer with the
16747        // [`rejects_zero_entrada_port`] behavioral pin on the same
16748        // per-`:entrada :port` axis — that pin asserts the pre-lift
16749        // behavioral contract (`port: 0` → `EntradaPortZero`); this
16750        // pin adds the structural link to the lifted floor const.
16751        assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
16752        let mut s = three_member_spec();
16753        s.entrada.as_mut().unwrap().port = 0;
16754        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
16755    }
16756
16757    // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
16758
16759    #[test]
16760    fn membro_serde_keys_match_lifted_membro_key_consts() {
16761        // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
16762        // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
16763        // name the exact camelCase JSON keys the
16764        // `#[serde(rename_all = "camelCase")]` attribute on
16765        // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
16766        // that each canonical byte-sequence appears verbatim in the
16767        // JSON — a future accidental `rename_all = "snake_case"` /
16768        // `"kebab-case"` / verbatim-field-name flip at the derive
16769        // attribute (any of which would silently break every downstream
16770        // JSON consumer that reaches for one of the two consts via
16771        // `Value::get(...)`) surfaces here as a build-time test failure
16772        // at `aplicacao.rs`, not as an apply-time
16773        // `.get(<stale-canonical-const>)` returning `None` far from the
16774        // derive-attr drift's commit. Peer with the sibling
16775        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
16776        // (40cc4e5) pin on the M2 supervision-tree top-level axis —
16777        // same discipline the SupervisorSpec top-level lift established,
16778        // extended here to the M3 [`Membro`] per-`:membros` axis.
16779        let m = Membro {
16780            caixa: "catalog".into(),
16781            versao: "^0.1".into(),
16782        };
16783        let json = serde_json::to_string(&m).unwrap();
16784        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
16785            let quoted = format!("\"{key}\"");
16786            assert!(
16787                json.contains(&quoted),
16788                "serialized Membro must carry the lifted MEMBRO_KEY_* \
16789                 byte-sequence {quoted} verbatim in the JSON emission \
16790                 (got: {json})",
16791            );
16792        }
16793    }
16794
16795    #[test]
16796    fn membro_key_consts_are_pairwise_distinct() {
16797        // Cross-axis drift-detection pin: a future collapse of the two
16798        // canonical [`Membro`] per-entry byte-strings onto the same
16799        // value (e.g. an accidental copy-paste flip of
16800        // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
16801        // silently reroute every downstream probe on one axis onto the
16802        // sibling axis's overlay entry and pass every propagation-probe
16803        // test that expected only the stale axis's value. Peer of the
16804        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
16805        // (40cc4e5).
16806        let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
16807        for (i, a) in all.iter().enumerate() {
16808            for b in all.iter().skip(i + 1) {
16809                assert_ne!(
16810                    a, b,
16811                    "MEMBRO_KEY_* consts must be pairwise-distinct \
16812                     canonical byte-sequences — got `{a}` == `{b}`",
16813                );
16814            }
16815        }
16816    }
16817
16818    // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
16819    //    URL-path fallback resolver every HTTPRoute-aware renderer
16820    //    reaching for a per-rule path-list resolution routes through.
16821    //    The four pin tests below fix the four-way accept-set the
16822    //    resolver must always honor: (:paths-non-empty-verbatim,
16823    //    :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
16824    //    :paths-preserves-order-across-multiple-entries) — drift on any
16825    //    arm surfaces at caixa-core build time rather than at cluster-
16826    //    apply time. Peer discipline with `MeshPolicy::is_empty` on the
16827    //    sibling `:politicas` typed-primitive dispatch axis.
16828
16829    fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
16830        Entrada {
16831            host: "example.com".into(),
16832            para: "cart".into(),
16833            paths: paths.into_iter().map(String::from).collect(),
16834            port: DEFAULT_SERVICO_PORT,
16835        }
16836    }
16837
16838    #[test]
16839    fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
16840        // The typed `:entrada :paths` slot carries an author-declared
16841        // list — the resolver returns each entry verbatim, no
16842        // catch-all substitution. The canonical "author declared
16843        // paths, honor them verbatim" arm of the path-list dispatch.
16844        let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
16845        assert_eq!(
16846            e.resolved_paths(),
16847            vec!["/api/cart", "/api/products"],
16848            "resolved_paths must return each `:entrada :paths` entry \
16849             verbatim when the typed slot is non-empty (got {:?})",
16850            e.resolved_paths(),
16851        );
16852    }
16853
16854    #[test]
16855    fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
16856        // Empty `:entrada :paths` slot — the resolver substitutes the
16857        // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
16858        // catch-all fallback verbatim. Pins the empty-arm of the
16859        // resolver's four-way accept-set against a future silent
16860        // detour that returned an empty Vec (which would emit an
16861        // HTTPRoute with zero rules — silently dropping every
16862        // external `:entrada` flow at admission time), routed to a
16863        // different fallback shape, or dropped the catch-all
16864        // altogether.
16865        let e = entrada_with_paths(vec![]);
16866        assert_eq!(
16867            e.resolved_paths(),
16868            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
16869            "resolved_paths on empty `:entrada :paths` must fall back \
16870             to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
16871             all — got {:?}",
16872            e.resolved_paths(),
16873        );
16874    }
16875
16876    #[test]
16877    fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
16878        // Single-entry `:entrada :paths` — the resolver returns the
16879        // single declared path verbatim, NOT the catch-all fallback
16880        // (author declared a path, honor it — the empty-arm and the
16881        // len-1 arm are semantically distinct axes of the resolver's
16882        // accept-set). Pins that the resolver treats "author declared
16883        // one path" as authored input, not as the empty case.
16884        let e = entrada_with_paths(vec!["/api/only"]);
16885        assert_eq!(
16886            e.resolved_paths(),
16887            vec!["/api/only"],
16888            "resolved_paths on single-entry `:entrada :paths` must \
16889             return the declared path verbatim, NOT the catch-all \
16890             fallback (got {:?})",
16891            e.resolved_paths(),
16892        );
16893    }
16894
16895    #[test]
16896    fn resolved_paths_preserves_author_declared_order() {
16897        // The `:entrada :paths` list is author-ordered — the resolver
16898        // preserves the author's declaration order verbatim, since
16899        // per-rule dispatch order at the K8s Gateway API HTTPRoute
16900        // consumer is significant (first-match-wins under the
16901        // path-prefix matcher). Pins against a future silent
16902        // re-sort / dedup / normalize detour that reordered author
16903        // input.
16904        let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
16905        assert_eq!(
16906            e.resolved_paths(),
16907            vec!["/z/last", "/a/first", "/m/mid"],
16908            "resolved_paths must preserve author-declared `:entrada \
16909             :paths` order verbatim — got {:?}",
16910            e.resolved_paths(),
16911        );
16912    }
16913
16914    // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
16915    //    slot `&[String]` slice accessor every per-`:entrada` consumer
16916    //    that must see the author's declaration verbatim (not the
16917    //    fallback-applied projection the sibling `resolved_paths`
16918    //    returns) routes through. The three pin tests below fix the
16919    //    accept-set the accessor must honor: (:non-empty-byte-equal,
16920    //    :empty-projects-empty-slice, :preserves-author-declared-order)
16921    //    — drift on any arm surfaces at caixa-core build time rather
16922    //    than at cluster-apply time. Peer discipline with the sibling
16923    //    [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
16924    //    peer M3 mesh-slot `Vec<String>`-carry axis.
16925
16926    #[test]
16927    fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
16928        // Byte-equal pin: [`Entrada::paths`] must project the raw
16929        // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
16930        // slice borrowed from the typed slot's own [`Vec<String>`]
16931        // storage — no re-ordering, no dedup, no per-entry normalization,
16932        // no fallback substitution (the fallback-applying projection is
16933        // the sibling [`Entrada::resolved_paths`] resolver). Pins against
16934        // a future silent detour that re-normalized the list, dropped
16935        // duplicates the [`AplicacaoSpec::validate`]
16936        // `EntradaPathDuplicate` refusal already rejects at build time,
16937        // or (most severe) accidentally routed through the fallback-
16938        // applying sibling and returned the substrate catch-all when
16939        // the author declared an empty list — collapsing the raw-slot
16940        // and fallback-applied axes into one and breaking the
16941        // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
16942        //
16943        // Peer of the sibling
16944        // [`Placement::clusters`]-shape byte-equal pin
16945        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
16946        // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
16947        let fixtures: Vec<Vec<String>> = vec![
16948            Vec::new(),
16949            vec!["/api/cart".into()],
16950            vec!["/api/cart".into(), "/api/products".into()],
16951            vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
16952        ];
16953        for paths in fixtures {
16954            let e = Entrada {
16955                host: "example.com".into(),
16956                para: "cart".into(),
16957                paths: paths.clone(),
16958                port: DEFAULT_SERVICO_PORT,
16959            };
16960            assert_eq!(
16961                e.paths(),
16962                paths.as_slice(),
16963                "Entrada::paths must return :entrada :paths verbatim \
16964                 (got {:?}, expected {:?})",
16965                e.paths(),
16966                paths.as_slice(),
16967            );
16968            assert_eq!(
16969                e.paths(),
16970                e.paths.as_slice(),
16971                "Entrada::paths accessor and .paths.as_slice() field \
16972                 access must byte-equal — the accessor is the substrate-\
16973                 primitive typed dispatch every downstream per-`:entrada` \
16974                 raw-slot path-list consumer must route through",
16975            );
16976            assert_eq!(
16977                e.paths().len(),
16978                e.paths.len(),
16979                "Entrada::paths().len() must byte-equal self.paths.len() \
16980                 — a length drift would silently split the paired \
16981                 pre-flight cascade-head `.is_empty()` probe input in \
16982                 the sibling [`Entrada::resolved_paths`] resolver from \
16983                 the per-entry validate loop's traversal input in \
16984                 [`AplicacaoSpec::validate`]",
16985            );
16986        }
16987    }
16988
16989    #[test]
16990    fn resolved_paths_reads_through_lifted_paths_accessor() {
16991        // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
16992        // pre-flight `.paths().is_empty()` cascade-head probe (which
16993        // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
16994        // catch-all fallback arm when the accessor projects the empty
16995        // slice) and the per-entry `.paths().iter().map(String::as_str)`
16996        // projection (which must reach every entry in the same order
16997        // the accessor projects, so the sibling
16998        // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
16999        // per-entry projection stay in lockstep by construction) must
17000        // both key off the lifted accessor. Pins the two-site coherence
17001        // by exercising each production consumer end-to-end: (1) the
17002        // catch-all-fallback arm under the empty slice, (2) the
17003        // author-declared-verbatim arm under a two-entry cohort whose
17004        // per-entry projection must byte-equal the input's per-entry
17005        // author-declared paths in the author's declared order.
17006        //
17007        // Peer of the sibling M3
17008        // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
17009        // `validate_placement_reads_through_lifted_clusters_accessor`
17010        // on the sibling `Placement::clusters` reader-site convergence.
17011        let empty = entrada_with_paths(vec![]);
17012        assert_eq!(
17013            empty.resolved_paths(),
17014            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
17015            "resolved_paths on empty :entrada :paths must trip the \
17016             lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
17017             catch-all fallback — routing through the lifted paths() \
17018             accessor must not silently drop the fallback arm",
17019        );
17020
17021        let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
17022        assert_eq!(
17023            declared.resolved_paths(),
17024            vec!["/api/cart", "/api/products"],
17025            "resolved_paths on non-empty :entrada :paths must return each \
17026             entry verbatim in the author's declared order — routing \
17027             through the lifted paths() accessor must not silently \
17028             reorder or drop entries",
17029        );
17030        // Byte-equal pin against the raw-slot accessor to keep the
17031        // fallback-applying resolver's per-entry projection input in
17032        // lockstep with the raw-slot accessor's projection.
17033        let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
17034        assert_eq!(
17035            declared.resolved_paths(),
17036            raw_projected,
17037            "resolved_paths non-empty projection must byte-equal the \
17038             lifted paths() accessor's per-entry String::as_str projection \
17039             — the two projections share the same input slice by \
17040             construction, so any drift here would surface a silent \
17041             re-ordering / dedup / normalization detour in the resolver",
17042        );
17043    }
17044
17045    #[test]
17046    fn validate_reads_through_lifted_entrada_paths_accessor() {
17047        // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
17048        // per-entry value-shape gate's `for p in e.paths()` traversal
17049        // (which must reach every entry in the same order the accessor
17050        // projects, so both the per-entry `EntradaPathEmpty` /
17051        // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
17052        // the duplicate-detection HashSet insert that trips
17053        // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
17054        // projection) must route through the lifted accessor. Pins the
17055        // coherence by exercising each production consumer end-to-end:
17056        // (1) the `EntradaPathEmpty` refusal fires on the second entry
17057        // of a two-entry cohort whose head is valid but tail is empty
17058        // (which requires the loop to reach the second entry through
17059        // the accessor), and (2) the `EntradaPathDuplicate` refusal
17060        // fires on the second entry of a two-entry cohort that shares
17061        // a path (which requires the loop to reach both entries — a
17062        // first-entry-only projection would silently pass since the
17063        // dedup HashSet has room for the first insert).
17064        //
17065        // Peer of the sibling
17066        // `validate_placement_reads_through_lifted_clusters_accessor`
17067        // on the sibling `Placement::clusters` reader-site convergence.
17068        let base = crate::AplicacaoSpec {
17069            membros: vec![crate::Membro {
17070                caixa: "cart".into(),
17071                versao: "^0.1".into(),
17072            }],
17073            contratos: Vec::new(),
17074            politicas: crate::MeshPolicy::default(),
17075            placement: crate::Placement {
17076                estrategia: crate::PlacementStrategy::SingleNode,
17077                clusters: vec!["rio".into()],
17078                shard_key: None,
17079                affinity: None,
17080            },
17081            entrada: Some(Entrada {
17082                host: "example.com".into(),
17083                para: "cart".into(),
17084                paths: vec!["/api/cart".into(), String::new()],
17085                port: DEFAULT_SERVICO_PORT,
17086            }),
17087        };
17088        assert_eq!(
17089            base.validate(),
17090            Err(crate::AplicacaoError::EntradaPathEmpty),
17091            "validate must trip EntradaPathEmpty on the second entry of \
17092             a two-entry cohort — routing through the lifted paths() \
17093             accessor must not silently short-circuit the loop at the \
17094             valid head entry",
17095        );
17096
17097        let mut dup = base;
17098        dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
17099        assert_eq!(
17100            dup.validate(),
17101            Err(crate::AplicacaoError::EntradaPathDuplicate {
17102                path: "/api/cart".into(),
17103            }),
17104            "validate must trip EntradaPathDuplicate on the second entry \
17105             of a two-entry cohort that shares a path — routing through \
17106             the lifted paths() accessor must not silently short-circuit \
17107             the dedup HashSet insert at the first entry",
17108        );
17109    }
17110
17111    // ── Entrada::hostname / Entrada::hostnames — the substrate-
17112    //    canonical per-`:entrada` DNS-hostname resolver pair every
17113    //    Gateway-API-aware renderer reaching for a per-listener
17114    //    singular `hostname:` filter (Gateway) or a per-route plural
17115    //    `spec.hostnames[]` filter list (HTTPRoute) routes through.
17116    //    The three pin tests below fix the two-way accept-set the pair
17117    //    must always honor: (:singular-byte-equal-to-host,
17118    //    :plural-is-singleton-of-singular, :plural-len-is-one) — drift
17119    //    on any arm surfaces at caixa-core build time rather than at
17120    //    cluster-apply time when the API server refuses the HTTPRoute
17121    //    for non-intersecting hostname filters. Peer discipline with
17122    //    the sibling `resolved_paths` accept-set pin block above on the
17123    //    per-`:entrada` path-list resolver axis.
17124
17125    fn entrada_with_host(host: &str) -> Entrada {
17126        Entrada {
17127            host: host.into(),
17128            para: "cart".into(),
17129            paths: Vec::new(),
17130            port: DEFAULT_SERVICO_PORT,
17131        }
17132    }
17133
17134    #[test]
17135    fn hostname_returns_entrada_host_byte_equal() {
17136        // The canonical singular-axis pin: [`Entrada::hostname`] must
17137        // return the `:entrada :host` field byte-for-byte, borrowed
17138        // from the typed slot's own [`String`] storage. Pins against a
17139        // future silent detour that re-normalized the host (an
17140        // accidental `.to_lowercase()` — validate_entrada_host already
17141        // enforces lowercase, so any re-normalization is redundant + a
17142        // drift surface between the validator and the accessor), a
17143        // trailing-`.` fully-qualified DNS shape substitution, or a
17144        // Punycode round-trip that lowered a Unicode host through IDNA.
17145        let e = entrada_with_host("checkout.quero.cloud");
17146        assert_eq!(
17147            e.hostname(),
17148            "checkout.quero.cloud",
17149            "Entrada::hostname must return :entrada :host verbatim \
17150             (got {:?})",
17151            e.hostname(),
17152        );
17153        assert_eq!(
17154            e.hostname(),
17155            e.host.as_str(),
17156            "Entrada::hostname must byte-equal the .host field access",
17157        );
17158    }
17159
17160    #[test]
17161    fn hostnames_returns_singleton_of_hostname_accessor() {
17162        // The pair-invariant pin: [`Entrada::hostnames`] must always
17163        // return exactly `vec![hostname()]` — the singleton list whose
17164        // sole entry is the substrate's canonical per-`:entrada`
17165        // singular hostname. Pins the two-consumer coherence axis: the
17166        // Gateway listener's singular `hostname:` filter and the
17167        // HTTPRoute's plural `spec.hostnames[]` filter list must
17168        // agree, else the Gateway API v1.x conformance layer rejects
17169        // the HTTPRoute at attach time with
17170        // `Accepted:False/NoMatchingParent` (the parent Gateway's
17171        // listener hostname doesn't intersect the route's hostname
17172        // filter list) — a divergence whose apply-time symptom is far
17173        // from any single-site commit and never surfaces in the
17174        // emitted YAML. Pinning the pair-invariant here makes any
17175        // future accidental split (an accidental `.to_string() + "."`
17176        // trailing-`.` on the plural side that didn't land on the
17177        // singular side, an accidental prefix stripping on one axis,
17178        // an accidental wildcard prepend the SNI fan-out overlay
17179        // authors on the plural side without a paired singular
17180        // migration) trip at caixa-core build time.
17181        let e = entrada_with_host("checkout.quero.cloud");
17182        assert_eq!(
17183            e.hostnames(),
17184            vec![e.hostname()],
17185            "Entrada::hostnames must return `vec![hostname()]` under \
17186             the pair-invariant — got {:?} vs. singleton {:?}",
17187            e.hostnames(),
17188            vec![e.hostname()],
17189        );
17190    }
17191
17192    #[test]
17193    fn hostnames_is_singleton_under_single_host_author_surface() {
17194        // The singleton-shape pin: under today's single-hostname-per-
17195        // `:entrada` author surface (the `:host` slot is a single
17196        // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
17197        // must always return a list of length exactly one. Pins
17198        // against a future silent detour that returned an empty list
17199        // (which would emit an HTTPRoute with `spec.hostnames: []` —
17200        // matching every incoming Host header regardless of the
17201        // Aplicacao's declared ingress apex, silently over-matching
17202        // every foreign VirtualHost the parent Gateway also fronts) or
17203        // a duplicated entry (which the Gateway API v1.x parser
17204        // accepts as a `[]-length-2 list of equal hostnames]` but
17205        // whose semantics differ from the intended singleton). The
17206        // author-surface extension point ("a future `:entrada
17207        // :alt-hosts` list overlay" the docstring names) is the sole
17208        // future axis that flips this pin — that migration will re-
17209        // author this test to pin the new plural cardinality.
17210        let e = entrada_with_host("checkout.quero.cloud");
17211        assert_eq!(
17212            e.hostnames().len(),
17213            1,
17214            "Entrada::hostnames must be a singleton under today's \
17215             single-hostname-per-`:entrada` author surface — got \
17216             length {}: {:?}",
17217            e.hostnames().len(),
17218            e.hostnames(),
17219        );
17220    }
17221
17222    // ── Entrada::destination — the substrate-canonical per-`:entrada`
17223    //    destination-Servico scalar accessor every Gateway-API
17224    //    HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
17225    //    discriminator arg (HTTPRoute name composer) or a per-rule
17226    //    `backendRefs[0].name` axis routes through. The two pin tests
17227    //    below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
17228    //    either arm surfaces at caixa-core build time rather than at
17229    //    cluster-apply time when an HTTPRoute's `metadata.name` and
17230    //    `backendRefs[]` silently disagree on which destination Servico
17231    //    the ingress fronts. Peer discipline with the sibling
17232    //    `resolved_paths` + `hostname` + `hostnames` accept-set pin
17233    //    blocks above on the per-`:entrada` path-list / DNS-hostname
17234    //    resolver axes.
17235
17236    #[test]
17237    fn destination_returns_entrada_para_byte_equal() {
17238        // The canonical destination-scalar pin: [`Entrada::destination`]
17239        // must return the `:entrada :para` field byte-for-byte, borrowed
17240        // from the typed slot's own [`String`] storage. Pins against a
17241        // future silent detour that re-normalized the destination (an
17242        // accidental `.to_lowercase()` — the destination Servico is
17243        // already validated as a DNS-1123 label upstream, so any
17244        // re-normalization is redundant + a drift surface between the
17245        // validator and the accessor), a namespace-prefix rewrite (an
17246        // accidental `format!("{namespace}/{para}")` per-CR fully-
17247        // qualified rewrite that didn't land on the peer axis), or a
17248        // per-cluster suffix stamp the operator authors on one
17249        // consumer without the other.
17250        for para in ["cart", "checkout", "catalog", "orders-v2"] {
17251            let e = Entrada {
17252                host: "checkout.quero.cloud".into(),
17253                para: para.into(),
17254                paths: Vec::new(),
17255                port: DEFAULT_SERVICO_PORT,
17256            };
17257            assert_eq!(
17258                e.destination(),
17259                para,
17260                "Entrada::destination must return :entrada :para verbatim \
17261                 (got {:?}, expected {para:?})",
17262                e.destination(),
17263            );
17264            assert_eq!(
17265                e.destination(),
17266                e.para.as_str(),
17267                "Entrada::destination must byte-equal the .para field access",
17268            );
17269        }
17270    }
17271
17272    #[test]
17273    fn destination_borrows_from_entrada_para_storage() {
17274        // The borrow-not-copy pin: [`Entrada::destination`] must
17275        // return a `&str` slice that borrows from the typed slot's
17276        // own [`String`] storage — same-address invariant with
17277        // `entrada.para.as_str()`. Pins against a future silent detour
17278        // that allocated a fresh `String` (`self.para.clone()` in the
17279        // body would type-check but silently drop the borrow, and
17280        // every downstream consumer that assumed the returned slice
17281        // outlives `&self` would break on a stale-reference use-after-
17282        // free). Peer with the sibling `hostname_returns_entrada_
17283        // host_byte_equal` on the singular-DNS-hostname axis.
17284        let e = entrada_with_host("checkout.quero.cloud");
17285        let dest = e.destination();
17286        let para_slice = e.para.as_str();
17287        assert_eq!(
17288            dest.as_ptr(),
17289            para_slice.as_ptr(),
17290            "Entrada::destination must borrow from the .para String's \
17291             backing storage — a fresh allocation here means the \
17292             accessor no longer names the substrate-primitive typed \
17293             dispatch and every downstream consumer would silently \
17294             carry a detached copy",
17295        );
17296        assert_eq!(
17297            dest.len(),
17298            para_slice.len(),
17299            "Entrada::destination and .para.as_str() must byte-equal in \
17300             length as well as in address",
17301        );
17302    }
17303
17304    #[test]
17305    fn port_returns_entrada_port_verbatim_across_permutations() {
17306        // The canonical L4-port-scalar pin: [`Entrada::port`] must
17307        // return the `:entrada :port` field verbatim as a `u16` across
17308        // every author-declared value in the validated accept-set
17309        // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
17310        // silent detour that clamped the port (an accidental
17311        // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
17312        // land on the peer [`AplicacaoSpec::port_for_destination`]
17313        // resolver), rewrote it through a per-cluster port-remap table
17314        // the operator authors on one consumer without the other, or
17315        // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
17316        // serde-default value (which would silently collapse the
17317        // distinction between "author explicitly declared `:port 8080`"
17318        // and "author omitted the slot and inherited the default" the
17319        // future per-cluster override slot depends on). Peer with the
17320        // sibling `destination_returns_entrada_para_byte_equal` +
17321        // `hostname_returns_entrada_host_byte_equal` pins on the
17322        // per-`:entrada` `&str` scalar axes.
17323        for port in [
17324            SERVICO_PORT_MIN,
17325            DEFAULT_SERVICO_PORT,
17326            8443u16,
17327            9090u16,
17328            u16::MAX,
17329        ] {
17330            let e = Entrada {
17331                host: "checkout.quero.cloud".into(),
17332                para: "cart".into(),
17333                paths: Vec::new(),
17334                port,
17335            };
17336            assert_eq!(
17337                e.port(),
17338                port,
17339                "Entrada::port must return :entrada :port verbatim \
17340                 (got {}, expected {port})",
17341                e.port(),
17342            );
17343            assert_eq!(
17344                e.port(),
17345                e.port,
17346                "Entrada::port accessor and .port field access must \
17347                 byte-equal — the accessor is the substrate-primitive \
17348                 typed dispatch every downstream L4-port consumer must \
17349                 route through",
17350            );
17351        }
17352    }
17353
17354    #[test]
17355    fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
17356        // Two-consumer coherence pin: the
17357        // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
17358        // (which reads through [`Entrada::port`] to compare against
17359        // [`SERVICO_PORT_MIN`]) and the
17360        // [`AplicacaoSpec::port_for_destination`] resolver (which reads
17361        // through [`Entrada::port`] to emit the per-destination
17362        // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
17363        // lifted accessor, so any future rebrand on the typed slot's
17364        // reader shape lands at exactly one place. Pins the two-site
17365        // coherence by exercising a below-floor port through validate
17366        // (which must reject) and a validated in-accept-set port through
17367        // port_for_destination (which must emit the same value the
17368        // accessor returns).
17369        let mut spec = three_member_spec();
17370        if let Some(e) = spec.entrada.as_mut() {
17371            e.port = 0;
17372        }
17373        assert_eq!(
17374            spec.validate().unwrap_err(),
17375            AplicacaoError::EntradaPortZero,
17376            "validate must reject `:entrada :port 0` through the lifted \
17377             Entrada::port accessor — port zero lies below \
17378             SERVICO_PORT_MIN and the validator routes through port() \
17379             to name the floor",
17380        );
17381
17382        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
17383            let mut spec = three_member_spec();
17384            if let Some(e) = spec.entrada.as_mut() {
17385                e.port = port;
17386            }
17387            spec.validate().expect(
17388                "entrada with in-accept-set :port must validate — the \
17389                 structural-floor gate reads through Entrada::port",
17390            );
17391            let entrada_ref = spec.entrada.as_ref().expect(":entrada present");
17392            assert_eq!(
17393                spec.port_for_destination(entrada_ref.destination()),
17394                entrada_ref.port(),
17395                "port_for_destination(entrada.destination()) must equal \
17396                 entrada.port() — the two consumers of the per-:entrada \
17397                 L4-port axis (validator, per-destination resolver) both \
17398                 route through Entrada::port",
17399            );
17400        }
17401    }
17402
17403    #[test]
17404    fn wit_contract_source_returns_de_byte_equal_across_permutations() {
17405        // The canonical caller-Servico-scalar pin: [`WitContract::source`]
17406        // must return the `:contratos :de` field byte-for-byte, borrowed
17407        // from the typed slot's own [`String`] storage. Peer of the
17408        // sibling `destination_returns_entrada_para_byte_equal` pin on
17409        // the per-`:entrada` axis — same "the substrate-primitive
17410        // accessor must byte-equal the raw field access verbatim across
17411        // every author-declared value" discipline extended to the
17412        // per-`:contratos` caller arm. Pins against a future silent
17413        // detour that re-normalized the caller (an accidental
17414        // `.to_lowercase()` — every `:contratos :de` is validated as a
17415        // DNS-1123 label upstream via `validate_contrato_caixa`, so any
17416        // re-normalization is redundant + a drift surface between the
17417        // validator and the accessor), a namespace-prefix rewrite (an
17418        // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
17419        // rewrite that didn't land on the peer axis), or a per-cluster
17420        // suffix stamp the operator authors on one consumer without the
17421        // other.
17422        for de in ["cart", "checkout", "catalog", "orders-v2"] {
17423            let c = WitContract {
17424                de: de.into(),
17425                para: "downstream".into(),
17426                wit: "wasi:http/proxy".into(),
17427                endpoint: Some("/lookup".into()),
17428                subject: None,
17429                slot: None,
17430            };
17431            assert_eq!(
17432                c.source(),
17433                de,
17434                "WitContract::source must return :contratos :de verbatim \
17435                 (got {:?}, expected {de:?})",
17436                c.source(),
17437            );
17438            assert_eq!(
17439                c.source(),
17440                c.de.as_str(),
17441                "WitContract::source must byte-equal the .de field access",
17442            );
17443        }
17444    }
17445
17446    #[test]
17447    fn wit_contract_source_borrows_from_de_storage() {
17448        // The borrow-not-copy pin: [`WitContract::source`] must return a
17449        // `&str` slice that borrows from the typed slot's own [`String`]
17450        // storage — same-address invariant with `c.de.as_str()`. Pins
17451        // against a future silent detour that allocated a fresh `String`
17452        // (`self.de.clone()` in the body would type-check but silently
17453        // drop the borrow, and every downstream consumer that assumed
17454        // the returned slice outlives `&self` would break on a stale-
17455        // reference use-after-free). Peer of the sibling
17456        // `destination_borrows_from_entrada_para_storage` on the
17457        // per-`:entrada` axis.
17458        let c = WitContract {
17459            de: "cart".into(),
17460            para: "catalog".into(),
17461            wit: "wasi:http/proxy".into(),
17462            endpoint: Some("/lookup".into()),
17463            subject: None,
17464            slot: None,
17465        };
17466        let src = c.source();
17467        let de_slice = c.de.as_str();
17468        assert_eq!(
17469            src.as_ptr(),
17470            de_slice.as_ptr(),
17471            "WitContract::source must borrow from the .de String's \
17472             backing storage — a fresh allocation here means the \
17473             accessor no longer names the substrate-primitive typed \
17474             dispatch and every downstream consumer would silently \
17475             carry a detached copy",
17476        );
17477        assert_eq!(
17478            src.len(),
17479            de_slice.len(),
17480            "WitContract::source and .de.as_str() must byte-equal in \
17481             length as well as in address",
17482        );
17483    }
17484
17485    #[test]
17486    fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
17487        // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
17488        // must return the `:contratos :para` field byte-for-byte,
17489        // borrowed from the typed slot's own [`String`] storage. Peer of
17490        // the sibling `destination_returns_entrada_para_byte_equal` on
17491        // the per-`:entrada` axis — both accessors name "the destination-
17492        // Servico byte-string" concept on their respective mesh-slot
17493        // atoms (per-ingress apex vs. per-typed-edge callee) and both
17494        // must project the underlying `.para` field verbatim so every
17495        // downstream renderer that composes them with peer accessors
17496        // (e.g. `spec.port_for_destination(c.destination())` at the CNP
17497        // per-edge L4 port emit site) reads the same byte-string the
17498        // author declared.
17499        for para in ["catalog", "payment", "orders", "inventory-v3"] {
17500            let c = WitContract {
17501                de: "cart".into(),
17502                para: para.into(),
17503                wit: "wasi:http/proxy".into(),
17504                endpoint: Some("/lookup".into()),
17505                subject: None,
17506                slot: None,
17507            };
17508            assert_eq!(
17509                c.destination(),
17510                para,
17511                "WitContract::destination must return :contratos :para \
17512                 verbatim (got {:?}, expected {para:?})",
17513                c.destination(),
17514            );
17515            assert_eq!(
17516                c.destination(),
17517                c.para.as_str(),
17518                "WitContract::destination must byte-equal the .para \
17519                 field access",
17520            );
17521        }
17522    }
17523
17524    #[test]
17525    fn wit_contract_destination_borrows_from_para_storage() {
17526        // The borrow-not-copy pin: [`WitContract::destination`] must
17527        // return a `&str` slice that borrows from the typed slot's own
17528        // [`String`] storage — same-address invariant with
17529        // `c.para.as_str()`. Peer of the sibling
17530        // `destination_borrows_from_entrada_para_storage` on the
17531        // per-`:entrada` axis.
17532        let c = WitContract {
17533            de: "cart".into(),
17534            para: "catalog".into(),
17535            wit: "wasi:http/proxy".into(),
17536            endpoint: Some("/lookup".into()),
17537            subject: None,
17538            slot: None,
17539        };
17540        let dest = c.destination();
17541        let para_slice = c.para.as_str();
17542        assert_eq!(
17543            dest.as_ptr(),
17544            para_slice.as_ptr(),
17545            "WitContract::destination must borrow from the .para \
17546             String's backing storage — a fresh allocation here means \
17547             the accessor no longer names the substrate-primitive typed \
17548             dispatch and every downstream consumer would silently \
17549             carry a detached copy",
17550        );
17551        assert_eq!(
17552            dest.len(),
17553            para_slice.len(),
17554            "WitContract::destination and .para.as_str() must byte-equal \
17555             in length as well as in address",
17556        );
17557    }
17558
17559    #[test]
17560    fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
17561        // The canonical per-`:contratos` WIT-world-reference scalar pin:
17562        // [`WitContract::world_ref`] must return the `:contratos :wit`
17563        // field byte-for-byte, borrowed from the typed slot's own
17564        // [`String`] storage. Sibling of the peer per-`:contratos`
17565        // [`WitContract::source`] / [`WitContract::destination`]
17566        // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
17567        // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
17568        // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
17569        // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
17570        // "the substrate-primitive accessor must byte-equal the raw
17571        // field access verbatim across every author-declared value"
17572        // discipline extended to the per-`:contratos` WIT-world arm.
17573        // Pins against a future silent detour that re-canonicalized the
17574        // WIT world reference (an accidental `.to_lowercase()` pass that
17575        // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
17576        // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
17577        // gate is already lowercase-prefixed so any re-normalization is
17578        // redundant + a drift surface between the validator and the
17579        // accessor), an M4-promotion-shape rewrite that formatted a
17580        // typed WIT-world enum through [`Display`] and silently drifted
17581        // the printer output from the source `caixa.lisp`, or a per-
17582        // cluster WIT-alias rewrite that didn't land on the peer field-
17583        // access sites. Five values sweep the shape-dispatch accept-set
17584        // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
17585        // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
17586        // `wasi:keyvalue/`).
17587        for (wit, endpoint, subject, slot) in [
17588            ("wasi:http/proxy", Some("/lookup"), None, None),
17589            ("http:proxy", Some("/health"), None, None),
17590            ("nats:pub-sub", None, Some("orders.paid"), None),
17591            ("kafka:events", None, Some("checkout-events"), None),
17592            ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
17593        ] {
17594            let c = WitContract {
17595                de: "cart".into(),
17596                para: "downstream".into(),
17597                wit: wit.into(),
17598                endpoint: endpoint.map(str::to_string),
17599                subject: subject.map(str::to_string),
17600                slot: slot.map(str::to_string),
17601            };
17602            assert_eq!(
17603                c.world_ref(),
17604                wit,
17605                "WitContract::world_ref must return :contratos :wit \
17606                 verbatim (got {:?}, expected {wit:?})",
17607                c.world_ref(),
17608            );
17609            assert_eq!(
17610                c.world_ref(),
17611                c.wit.as_str(),
17612                "WitContract::world_ref must byte-equal the .wit field \
17613                 access",
17614            );
17615        }
17616    }
17617
17618    #[test]
17619    fn wit_contract_world_ref_borrows_from_wit_storage() {
17620        // The borrow-not-copy pin: [`WitContract::world_ref`] must
17621        // return a `&str` slice that borrows from the typed slot's own
17622        // [`String`] storage — same-address invariant with
17623        // `c.wit.as_str()`. Pins against a future silent detour that
17624        // allocated a fresh `String` (`self.wit.clone()` in the body
17625        // would type-check but silently drop the borrow, and every
17626        // downstream consumer that assumed the returned slice outlives
17627        // `&self` would break on a stale-reference use-after-free — the
17628        // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
17629        // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
17630        // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
17631        // / [`is_pubsub`][WitContract::is_pubsub] /
17632        // [`is_store`][WitContract::is_store] methods route through —
17633        // each borrow from the WitContract's own storage and each would
17634        // silently misbehave if this accessor produced a detached copy).
17635        // Peer of the sibling per-`:contratos` [`WitContract::source`] /
17636        // [`WitContract::destination`] and per-`:entrada`
17637        // [`Entrada::destination`] / [`Entrada::hostname`] and
17638        // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
17639        // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
17640        let c = WitContract {
17641            de: "cart".into(),
17642            para: "catalog".into(),
17643            wit: "wasi:http/proxy".into(),
17644            endpoint: Some("/lookup".into()),
17645            subject: None,
17646            slot: None,
17647        };
17648        let world = c.world_ref();
17649        let wit_slice = c.wit.as_str();
17650        assert_eq!(
17651            world.as_ptr(),
17652            wit_slice.as_ptr(),
17653            "WitContract::world_ref must borrow from the .wit String's \
17654             backing storage — a fresh allocation here means the \
17655             accessor no longer names the substrate-primitive typed \
17656             dispatch and every downstream consumer would silently carry \
17657             a detached copy",
17658        );
17659        assert_eq!(
17660            world.len(),
17661            wit_slice.len(),
17662            "WitContract::world_ref and .wit.as_str() must byte-equal in \
17663             length as well as in address",
17664        );
17665    }
17666
17667    #[test]
17668    fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
17669        // Sibling-triple invariant pin composing all three per-`:contratos`
17670        // substrate-primitive typed dispatches — [`WitContract::source`]
17671        // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
17672        // [`WitContract::world_ref`] — at the joint
17673        // `(source(), destination(), world_ref())` call shape every
17674        // renderer that fans on per-edge caller-callee-shape identity
17675        // keys off. The invariant, evaluated per-contract:
17676        //
17677        //   (c.source(), c.destination(), c.world_ref())
17678        //   == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
17679        //
17680        // Closes the last unlifted per-`:contratos` scalar axis — every
17681        // downstream consumer that reads the triple now routes through
17682        // exactly three typed dispatches on the substrate primitive,
17683        // not two typed + one open-coded field access. A future refactor
17684        // that silently split any one accessor's projection (an
17685        // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
17686        // canonicalization that didn't reach the peer `source`/
17687        // `destination` arms, an accidental `source()` per-cluster
17688        // caller-alias rewrite that didn't land on the `world_ref` peer)
17689        // surfaces at caixa-core build time. Peer of the sibling per-
17690        // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
17691        // per-`:entrada` `(hostname(), destination())` (6db982c /
17692        // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
17693        // axes, extended to the per-`:contratos` triple.
17694        for (de, para, wit, endpoint, subject, slot) in [
17695            (
17696                "cart",
17697                "catalog",
17698                "wasi:http/proxy",
17699                Some("/lookup"),
17700                None,
17701                None,
17702            ),
17703            (
17704                "checkout",
17705                "orders",
17706                "nats:pub-sub",
17707                None,
17708                Some("orders.paid"),
17709                None,
17710            ),
17711            (
17712                "cart",
17713                "kv",
17714                "wasi:keyvalue/store",
17715                None,
17716                None,
17717                Some("carts/{cart_id}"),
17718            ),
17719            (
17720                "orders-v2",
17721                "inventory-v3",
17722                "http:proxy",
17723                Some("/reserve"),
17724                None,
17725                None,
17726            ),
17727        ] {
17728            let c = WitContract {
17729                de: de.into(),
17730                para: para.into(),
17731                wit: wit.into(),
17732                endpoint: endpoint.map(str::to_string),
17733                subject: subject.map(str::to_string),
17734                slot: slot.map(str::to_string),
17735            };
17736            assert_eq!(
17737                (c.source(), c.destination(), c.world_ref()),
17738                (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
17739                "(WitContract::source, ::destination, ::world_ref) must \
17740                 project (.de, .para, .wit) verbatim across every author-\
17741                 declared triple (got ({:?}, {:?}, {:?}), expected \
17742                 ({de:?}, {para:?}, {wit:?}))",
17743                c.source(),
17744                c.destination(),
17745                c.world_ref(),
17746            );
17747        }
17748    }
17749
17750    #[test]
17751    fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
17752        // The canonical per-`:contratos` owned-form caller-callee-pair
17753        // pin: [`WitContract::edge_pair`] must return the
17754        // `(source(), destination())` tuple in owned form byte-for-byte,
17755        // projected through the lifted [`WitContract::source`] /
17756        // [`WitContract::destination`] scalar accessors. Pins the
17757        // composite-projection invariant on the per-`:contratos`
17758        // mesh-slot atom — every author-declared `(de, para)` pair must
17759        // round-trip verbatim through the substrate primitive's typed
17760        // dispatch, so the nine [`AplicacaoError`] diagnostic-
17761        // construction sites the accessor now feeds
17762        // ([`AplicacaoError::EmptyWit`],
17763        // [`AplicacaoError::ContratoEndpointEmpty`],
17764        // [`AplicacaoError::ContratoEndpointNotAbsolute`],
17765        // [`AplicacaoError::ContratoEndpointInvalid`],
17766        // [`AplicacaoError::ContratoSubjectEmpty`],
17767        // [`AplicacaoError::ContratoSubjectInvalid`],
17768        // [`AplicacaoError::ContratoSlotEmpty`],
17769        // [`AplicacaoError::ContratoSlotInvalid`],
17770        // [`AplicacaoError::ContratoDuplicate`]) all read the same
17771        // `(de, para)` label pair every author sees at the source
17772        // `caixa.lisp`. Pins against a future silent detour that swapped
17773        // the `.0` / `.1` arms (an accidental `(destination(),
17774        // source())` re-order in the body would silently invert every
17775        // downstream diagnostic's `de:` / `para:` label pair, silently
17776        // reversing the direction of every operator-facing typed error
17777        // arrow), a fresh-allocation shape drift (an accidental
17778        // `.to_string()` on one arm but not the other would leave the
17779        // owned/borrowed pair mismatched vs. the sibling `source()` /
17780        // `destination()` returns), or an M4 per-cluster caller/callee-
17781        // alias rewrite that landed on `source()` without reaching
17782        // `destination()` (or vice versa). Peer of the sibling per-
17783        // `:contratos` `(source, destination, world_ref)` triple
17784        // pin above on the mesh-slot-atom scalar-value axes, extended
17785        // to the owned-form pair-projection axis.
17786        for (de, para, wit, endpoint, subject, slot) in [
17787            (
17788                "cart",
17789                "catalog",
17790                "wasi:http/proxy",
17791                Some("/lookup"),
17792                None,
17793                None,
17794            ),
17795            (
17796                "checkout",
17797                "orders",
17798                "nats:pub-sub",
17799                None,
17800                Some("orders.paid"),
17801                None,
17802            ),
17803            (
17804                "cart",
17805                "kv",
17806                "wasi:keyvalue/store",
17807                None,
17808                None,
17809                Some("carts/{cart_id}"),
17810            ),
17811            (
17812                "orders-v2",
17813                "inventory-v3",
17814                "http:proxy",
17815                Some("/reserve"),
17816                None,
17817                None,
17818            ),
17819        ] {
17820            let c = WitContract {
17821                de: de.into(),
17822                para: para.into(),
17823                wit: wit.into(),
17824                endpoint: endpoint.map(str::to_string),
17825                subject: subject.map(str::to_string),
17826                slot: slot.map(str::to_string),
17827            };
17828            assert_eq!(
17829                c.edge_pair(),
17830                (de.to_string(), para.to_string()),
17831                "WitContract::edge_pair must return (:contratos :de, \
17832                 :contratos :para) as an owned tuple verbatim (got {:?}, \
17833                 expected ({de:?}, {para:?}))",
17834                c.edge_pair(),
17835            );
17836        }
17837    }
17838
17839    #[test]
17840    fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
17841        // The composition pin: [`WitContract::edge_pair`] must return
17842        // exactly `(source().to_string(), destination().to_string())` —
17843        // the owned form of the sibling accessor pair — so any future
17844        // refactor that silently re-authored the caller-arm / callee-arm
17845        // projection to bypass the lifted scalar accessors (an accidental
17846        // `(self.de.clone(), self.para.clone())` regression back to the
17847        // raw field-access shape, an M4-typed-caller-enum `Display`
17848        // re-canonicalization on `source()` that didn't reach
17849        // `edge_pair()`, a per-cluster alias rewrite the operator lands
17850        // on `destination()` without reaching this composite projection)
17851        // trips at caixa-core build time. Pins the "typed dispatch
17852        // composes with typed dispatch, not with raw field access"
17853        // discipline every downstream diagnostic-construction site now
17854        // routes through — a `de:` / `para:` label pair whose
17855        // projection silently drifted off the substrate primitive's
17856        // scalar accessors would silently split the diagnostic's self-
17857        // locating signal from the source `caixa.lisp` author's view.
17858        // Peer of the sibling per-`:politicas` `is_empty` /
17859        // `validate_politicas` accessor-routing-pin family on the M3
17860        // mesh-slot family (18575, 18739, 18918, 19140, 19371).
17861        let c = WitContract {
17862            de: "cart".into(),
17863            para: "catalog".into(),
17864            wit: "wasi:http/proxy".into(),
17865            endpoint: Some("/lookup".into()),
17866            subject: None,
17867            slot: None,
17868        };
17869        assert_eq!(
17870            c.edge_pair(),
17871            (c.source().to_string(), c.destination().to_string()),
17872            "WitContract::edge_pair must compose exactly \
17873             (source().to_string(), destination().to_string()) — a \
17874             bypass of either sibling accessor here would silently \
17875             decouple the composite-projection axis from the \
17876             substrate-primitive scalar accessors every downstream \
17877             consumer routes through",
17878        );
17879    }
17880
17881    #[test]
17882    fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
17883     {
17884        // The canonical per-`:contratos` owned-form
17885        // caller-callee-world-ref-triple pin:
17886        // [`WitContract::edge_triple`] must return the
17887        // `(source(), destination(), world_ref())` tuple in owned form
17888        // byte-for-byte, projected through the lifted
17889        // [`WitContract::source`] / [`WitContract::destination`] /
17890        // [`WitContract::world_ref`] scalar accessors. Pins the
17891        // composite-projection invariant on the per-`:contratos`
17892        // mesh-slot atom — every author-declared `(de, para, wit)`
17893        // triple must round-trip verbatim through the substrate
17894        // primitive's typed dispatch, so the nine
17895        // [`AplicacaoError`] diagnostic-construction sites the
17896        // accessor now feeds (the [`WitTarget`]-dispatch's eight
17897        // wrong-target / missing-target / invalid-wit / capability-
17898        // with-payload arms in [`WitContract::target`], plus the
17899        // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
17900        // diagnostic constructor in [`AplicacaoSpec::validate`]) all
17901        // read the same `(de, para, wit)` triple every author sees at
17902        // the source `caixa.lisp`. Pins against a future silent
17903        // detour that swapped any two arms (an accidental `(destination(),
17904        // source(), world_ref())` re-order in the body would silently
17905        // invert every downstream diagnostic's `de:` / `para:` label
17906        // pair, silently reversing the direction of every operator-
17907        // facing typed error arrow), a fresh-allocation shape drift
17908        // (an accidental `.to_string()` skipped on one arm would leave
17909        // the owned/borrowed triple mismatched vs. the sibling
17910        // `source()` / `destination()` / `world_ref()` returns), or an
17911        // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
17912        // canonicalization pass that landed on one accessor without
17913        // reaching the peers. Peer of the sibling per-`:contratos`
17914        // caller-callee-pair
17915        // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
17916        // pin on the mesh-slot-atom composite-projection axis,
17917        // extended to the triple-projection axis.
17918        for (de, para, wit, endpoint, subject, slot) in [
17919            (
17920                "cart",
17921                "catalog",
17922                "wasi:http/proxy",
17923                Some("/lookup"),
17924                None,
17925                None,
17926            ),
17927            (
17928                "checkout",
17929                "orders",
17930                "nats:pub-sub",
17931                None,
17932                Some("orders.paid"),
17933                None,
17934            ),
17935            (
17936                "cart",
17937                "kv",
17938                "wasi:keyvalue/store",
17939                None,
17940                None,
17941                Some("carts/{cart_id}"),
17942            ),
17943            (
17944                "orders-v2",
17945                "inventory-v3",
17946                "http:proxy",
17947                Some("/reserve"),
17948                None,
17949                None,
17950            ),
17951        ] {
17952            let c = WitContract {
17953                de: de.into(),
17954                para: para.into(),
17955                wit: wit.into(),
17956                endpoint: endpoint.map(str::to_string),
17957                subject: subject.map(str::to_string),
17958                slot: slot.map(str::to_string),
17959            };
17960            assert_eq!(
17961                c.edge_triple(),
17962                (de.to_string(), para.to_string(), wit.to_string()),
17963                "WitContract::edge_triple must return (:contratos :de, \
17964                 :contratos :para, :contratos :wit) as an owned triple \
17965                 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
17966                c.edge_triple(),
17967            );
17968        }
17969    }
17970
17971    #[test]
17972    fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
17973        // The composition pin: [`WitContract::edge_triple`] must return
17974        // exactly `(source().to_string(), destination().to_string(),
17975        // world_ref().to_string())` — the owned form of the sibling
17976        // scalar-accessor triple — so any future refactor that silently
17977        // re-authored one arm's projection to bypass the lifted scalar
17978        // accessors (an accidental `(self.de.clone(), self.para.clone(),
17979        // self.wit.clone())` regression back to the raw field-access
17980        // shape the internal `edge` closure and the ContratoDuplicate
17981        // diagnostic both carried before this lift landed, an
17982        // M4-typed-caller-enum `Display` re-canonicalization on
17983        // `source()` that didn't reach `edge_triple()`, a per-cluster
17984        // alias rewrite the operator lands on `destination()` /
17985        // `world_ref()` without reaching this composite projection)
17986        // trips at caixa-core build time. Pins the "typed dispatch
17987        // composes with typed dispatch, not with raw field access"
17988        // discipline every downstream diagnostic-construction site now
17989        // routes through — a `de:` / `para:` / `wit:` triple whose
17990        // projection silently drifted off the substrate primitive's
17991        // scalar accessors would silently split the diagnostic's self-
17992        // locating signal from the source `caixa.lisp` author's view.
17993        // Peer of the sibling per-`:contratos` edge_pair composition-
17994        // pin above on the mesh-slot-atom composite-projection axis.
17995        let c = WitContract {
17996            de: "cart".into(),
17997            para: "catalog".into(),
17998            wit: "wasi:http/proxy".into(),
17999            endpoint: Some("/lookup".into()),
18000            subject: None,
18001            slot: None,
18002        };
18003        assert_eq!(
18004            c.edge_triple(),
18005            (
18006                c.source().to_string(),
18007                c.destination().to_string(),
18008                c.world_ref().to_string(),
18009            ),
18010            "WitContract::edge_triple must compose exactly \
18011             (source().to_string(), destination().to_string(), \
18012             world_ref().to_string()) — a bypass of any sibling accessor \
18013             here would silently decouple the composite-projection axis \
18014             from the substrate-primitive scalar accessors every \
18015             downstream consumer routes through",
18016        );
18017    }
18018
18019    #[test]
18020    fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
18021        // The canonical semantics-pin: [`WitContract::edge_triple`] must
18022        // project the full `(de, para, wit)` identity of a `:contratos`
18023        // edge — the sub-triple every triple-carrying
18024        // [`AplicacaoError::Contrato*`] diagnostic weaves into its
18025        // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
18026        // missing-target, capability-with-payload, invalid-wit, and the
18027        // duplicate-gate). Rejects a drift in shape (an accidental
18028        // silent detour that returned a `(de, para)` pair or added an
18029        // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
18030        // would trip here because the return type would no longer
18031        // pattern-match the eight `let (de, para, wit) = edge();`
18032        // destructures the [`WitContract::target`] dispatch feeds off
18033        // + the paired duplicate-gate `let (de, para, wit) =
18034        // c.edge_triple();` destructure in
18035        // [`AplicacaoSpec::validate`]). Peer of the sibling per-
18036        // `:contratos` caller-callee-pair pin above extended to the
18037        // triple projection surface: closes the "one composite
18038        // accessor per typed diagnostic-construction sub-tuple"
18039        // discipline on the per-`:contratos` mesh-slot-atom axis.
18040        let c = WitContract {
18041            de: "checkout".into(),
18042            para: "orders".into(),
18043            wit: "nats:pub-sub".into(),
18044            endpoint: None,
18045            subject: Some("orders.paid".into()),
18046            slot: None,
18047        };
18048        let (de, para, wit) = c.edge_triple();
18049        assert_eq!(de, "checkout");
18050        assert_eq!(para, "orders");
18051        assert_eq!(wit, "nats:pub-sub");
18052    }
18053
18054    #[test]
18055    fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
18056     {
18057        // The composition pin: [`WitContract::identity`] must return
18058        // exactly `(source(), destination(), world_ref(), endpoint(),
18059        // subject(), slot())` — the borrowed form of the six-scalar-
18060        // accessor identity axis. Any future refactor that silently
18061        // re-authored one arm's projection to bypass a scalar accessor
18062        // (a `self.de.as_str()` regression back to raw field access on
18063        // any of the three required arms, a `self.endpoint.as_deref()`
18064        // regression on any of the three optional arms, an M4 per-
18065        // cluster caller/callee-alias rewrite the operator lands on
18066        // `source()` / `destination()` without reaching this composite
18067        // projection) trips at caixa-core build time. Sweeps four
18068        // permutations of the WIT-shape × payload lattice — HTTP with
18069        // endpoint, pub-sub with subject, store with slot, payload-less
18070        // capability — so every payload arm is exercised. Peer of the
18071        // sibling per-`:contratos`
18072        // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
18073        // composition pin on the mesh-slot-atom composite-projection
18074        // axis; extends the discipline from the (de, para, wit) prefix
18075        // onto the full-identity axis carrying the three payload arms.
18076        for (de, para, wit, endpoint, subject, slot) in [
18077            (
18078                "cart",
18079                "catalog",
18080                "wasi:http/proxy",
18081                Some("/lookup"),
18082                None,
18083                None,
18084            ),
18085            (
18086                "checkout",
18087                "orders",
18088                "nats:pub-sub",
18089                None,
18090                Some("orders.paid"),
18091                None,
18092            ),
18093            (
18094                "cart",
18095                "kv",
18096                "wasi:keyvalue/store",
18097                None,
18098                None,
18099                Some("carts/{cart_id}"),
18100            ),
18101            ("audit", "sink", "wasi:logging", None, None, None),
18102        ] {
18103            let c = WitContract {
18104                de: de.into(),
18105                para: para.into(),
18106                wit: wit.into(),
18107                endpoint: endpoint.map(str::to_owned),
18108                subject: subject.map(str::to_owned),
18109                slot: slot.map(str::to_owned),
18110            };
18111            assert_eq!(
18112                c.identity(),
18113                (
18114                    c.source(),
18115                    c.destination(),
18116                    c.world_ref(),
18117                    c.endpoint(),
18118                    c.subject(),
18119                    c.slot(),
18120                ),
18121                "WitContract::identity must compose exactly \
18122                 (source(), destination(), world_ref(), endpoint(), \
18123                 subject(), slot()) — a bypass of any sibling accessor \
18124                 here would silently decouple the identity-projection \
18125                 axis from the substrate-primitive scalar accessors \
18126                 every dedup-key consumer routes through",
18127            );
18128        }
18129    }
18130
18131    #[test]
18132    fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
18133        // The canonical semantics-pin: [`WitContract::identity`] must
18134        // project the six-axis (de, para, wit, endpoint, subject, slot)
18135        // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
18136        // gate keys off — two `WitContract`s that agree on all six axes
18137        // are the same typed edge declared twice, the graph-edge
18138        // analogue of duplicate `:membros` / `:placement :clusters` /
18139        // `:entrada :paths` entries. Rejects a shape drift (an
18140        // accidental silent detour that returned a prefix tuple or
18141        // added an extra field) by pattern-matching the six-arm shape.
18142        // Peer of the sibling per-`:contratos`
18143        // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
18144        // pin extended from the (de, para, wit) prefix onto the full
18145        // six-axis identity that the dedup key rides.
18146        let c = WitContract {
18147            de: "cart".into(),
18148            para: "catalog".into(),
18149            wit: "wasi:http/proxy".into(),
18150            endpoint: Some("/products/:id".into()),
18151            subject: None,
18152            slot: None,
18153        };
18154        let (de, para, wit, endpoint, subject, slot) = c.identity();
18155        assert_eq!(de, "cart");
18156        assert_eq!(para, "catalog");
18157        assert_eq!(wit, "wasi:http/proxy");
18158        assert_eq!(endpoint, Some("/products/:id"));
18159        assert_eq!(subject, None);
18160        assert_eq!(slot, None);
18161
18162        // Two byte-identical contracts must produce equal identities —
18163        // the dedup key's foundational invariant.
18164        let c2 = c.clone();
18165        assert_eq!(c.identity(), c2.identity());
18166
18167        // Any change on any of the six axes must break the identity —
18168        // sweeps by mutating one axis at a time.
18169        let mut mutated = c.clone();
18170        mutated.de = "search".into();
18171        assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
18172        let mut mutated = c.clone();
18173        mutated.para = "warehouse".into();
18174        assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
18175        let mut mutated = c.clone();
18176        mutated.wit = "http:legacy".into();
18177        assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
18178        let mut mutated = c.clone();
18179        mutated.endpoint = Some("/search".into());
18180        assert_ne!(
18181            c.identity(),
18182            mutated.identity(),
18183            "endpoint axis must partition"
18184        );
18185        let mut mutated = c.clone();
18186        mutated.subject = Some("orders.paid".into());
18187        assert_ne!(
18188            c.identity(),
18189            mutated.identity(),
18190            "subject axis must partition"
18191        );
18192        let mut mutated = c;
18193        mutated.slot = Some("carts/{id}".into());
18194        assert_ne!(mutated.identity().5, None, "slot axis must partition");
18195    }
18196
18197    #[test]
18198    fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
18199        // The canonical per-`:contratos` structural-self-edge pin:
18200        // [`WitContract::is_self_loop`] must return `true` when the
18201        // `:de` and `:para` fields agree byte-for-byte, across every
18202        // WIT-shape variant the per-edge shape family carries. Pins
18203        // the shape-agnostic identity-space partition the
18204        // [`AplicacaoSpec::validate`] self-edge gate at
18205        // caixa-core/src/aplicacao.rs:5559 fires against — all four
18206        // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
18207        // under the same one predicate. Four permutations sweep the
18208        // accept-set: HTTP with endpoint, pub-sub with subject, KV
18209        // store with slot, and payload-less capability.
18210        for (nome, wit, endpoint, subject, slot) in [
18211            ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
18212            ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
18213            (
18214                "kv",
18215                "wasi:keyvalue/store",
18216                None,
18217                None,
18218                Some("carts/{cart_id}"),
18219            ),
18220            ("audit", "wasi:logging", None, None, None),
18221        ] {
18222            let c = WitContract {
18223                de: nome.into(),
18224                para: nome.into(),
18225                wit: wit.into(),
18226                endpoint: endpoint.map(str::to_string),
18227                subject: subject.map(str::to_string),
18228                slot: slot.map(str::to_string),
18229            };
18230            assert!(
18231                c.is_self_loop(),
18232                "WitContract::is_self_loop must return true when \
18233                 :contratos :de == :contratos :para (got false on \
18234                 {nome:?} under {wit:?})",
18235            );
18236        }
18237    }
18238
18239    #[test]
18240    fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
18241        // The complement pin: [`WitContract::is_self_loop`] must return
18242        // `false` on every well-shaped inter-Servico contract (the
18243        // author-intended `:contratos` shape MESH-COMPOSITION §III.1
18244        // names — "Servico A calls Servico B" between two distinct
18245        // graph nodes). Pins against a future silent detour that
18246        // inverted the predicate (an accidental `!= ` swap for `==`
18247        // would silently reject every legitimate inter-Servico edge
18248        // and admit every self-edge — the exact inversion of the
18249        // author-intended shape). Four permutations sweep the same
18250        // WIT-shape accept-set the sibling positive-arm test carries.
18251        for (de, para, wit, endpoint, subject, slot) in [
18252            (
18253                "cart",
18254                "catalog",
18255                "wasi:http/proxy",
18256                Some("/lookup"),
18257                None,
18258                None,
18259            ),
18260            (
18261                "checkout",
18262                "orders",
18263                "nats:pub-sub",
18264                None,
18265                Some("orders.paid"),
18266                None,
18267            ),
18268            (
18269                "cart",
18270                "kv",
18271                "wasi:keyvalue/store",
18272                None,
18273                None,
18274                Some("carts/{cart_id}"),
18275            ),
18276            ("audit", "sink", "wasi:logging", None, None, None),
18277        ] {
18278            let c = WitContract {
18279                de: de.into(),
18280                para: para.into(),
18281                wit: wit.into(),
18282                endpoint: endpoint.map(str::to_string),
18283                subject: subject.map(str::to_string),
18284                slot: slot.map(str::to_string),
18285            };
18286            assert!(
18287                !c.is_self_loop(),
18288                "WitContract::is_self_loop must return false when \
18289                 :contratos :de differs from :contratos :para (got true \
18290                 on {de:?} → {para:?} under {wit:?})",
18291            );
18292        }
18293    }
18294
18295    #[test]
18296    fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
18297        // The composition pin: [`WitContract::is_self_loop`] must
18298        // resolve to exactly `self.source() == self.destination()` —
18299        // the equality probe of the sibling scalar-accessor pair — so
18300        // any future refactor that silently re-authored the predicate
18301        // to bypass the lifted scalar accessors (an accidental
18302        // `self.de == self.para` regression back to the raw field-
18303        // access shape, an M4-typed-caller-enum identity-comparison
18304        // rule that landed on `source()` without reaching
18305        // `destination()`, a per-cluster alias rewrite the operator
18306        // pins on `destination()` without reaching this predicate)
18307        // trips at caixa-core build time. Pins the "typed dispatch
18308        // composes with typed dispatch, not with raw field access"
18309        // discipline the sibling [`WitContract::edge_pair`] /
18310        // [`WitContract::edge_triple`] composite-projection accessors
18311        // already carry, extended onto the per-edge endpoint-equality
18312        // predicate axis. Positive and complement arms both fire.
18313        let self_edge = WitContract {
18314            de: "cart".into(),
18315            para: "cart".into(),
18316            wit: "wasi:http/proxy".into(),
18317            endpoint: Some("/lookup".into()),
18318            subject: None,
18319            slot: None,
18320        };
18321        assert_eq!(
18322            self_edge.is_self_loop(),
18323            self_edge.source() == self_edge.destination(),
18324            "WitContract::is_self_loop must compose exactly \
18325             `source() == destination()` — a bypass of either sibling \
18326             accessor here would silently decouple the endpoint-\
18327             equality predicate from the substrate-primitive scalar \
18328             accessors every downstream consumer routes through",
18329        );
18330        let inter_edge = WitContract {
18331            de: "cart".into(),
18332            para: "catalog".into(),
18333            wit: "wasi:http/proxy".into(),
18334            endpoint: Some("/lookup".into()),
18335            subject: None,
18336            slot: None,
18337        };
18338        assert_eq!(
18339            inter_edge.is_self_loop(),
18340            inter_edge.source() == inter_edge.destination(),
18341            "WitContract::is_self_loop must compose exactly \
18342             `source() == destination()` on the complement arm too",
18343        );
18344    }
18345
18346    #[test]
18347    fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
18348        // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
18349        // pin: [`WitContract::endpoint`] must return the `:contratos
18350        // :endpoint` field byte-for-byte, borrowed from the typed slot's
18351        // own `Option<String>` storage. Peer of the sibling
18352        // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
18353        // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
18354        // mesh-slot `Option<String>` optional-scalar axes — same "the
18355        // substrate-primitive accessor must byte-equal the raw field
18356        // access verbatim across every author-declared value" discipline
18357        // extended to the per-`:contratos` HTTP-payload-carrier arm.
18358        // Pins against a future silent detour that re-canonicalized the
18359        // endpoint (an accidental percent-encoding pass that didn't
18360        // reach the peer field-access site at the dedup key, a per-CR
18361        // fully-qualified prefix rewrite the operator authors on one
18362        // consumer without the other, or an M4 typed-path-template
18363        // `Display` re-canonicalization that silently drifted the
18364        // printer output from the source `caixa.lisp`). Four values
18365        // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
18366        // gate upstream admits (short root-path, dashed, param-shaped,
18367        // deep-hierarchy).
18368        for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
18369            let c = WitContract {
18370                de: "cart".into(),
18371                para: "catalog".into(),
18372                wit: "wasi:http/proxy".into(),
18373                endpoint: Some(endpoint.into()),
18374                subject: None,
18375                slot: None,
18376            };
18377            assert_eq!(
18378                c.endpoint(),
18379                Some(endpoint),
18380                "WitContract::endpoint must return :contratos :endpoint \
18381                 verbatim (got {:?}, expected Some({endpoint:?}))",
18382                c.endpoint(),
18383            );
18384            assert_eq!(
18385                c.endpoint(),
18386                c.endpoint.as_deref(),
18387                "WitContract::endpoint must byte-equal the .endpoint \
18388                 field's `.as_deref()` projection",
18389            );
18390        }
18391    }
18392
18393    #[test]
18394    fn wit_contract_endpoint_none_when_field_is_none() {
18395        // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
18396        // payload-carrier accessor pin: when the typed slot is absent —
18397        // the canonical shape under a non-HTTP `:wit` world per the
18398        // [`WitContract::target`]-enforced shape ↔ target partition
18399        // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
18400        // carries `:slot`, [`WitTarget::Capability`] carries none) —
18401        // [`WitContract::endpoint`] must return `None`. Pins against a
18402        // future silent detour that projected the absent slot to a
18403        // `Some("")` empty-string default (the canonical `Option<String>`
18404        // → `String` collapse footgun the sibling M2
18405        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
18406        // emptiness predicates already guard on the peer M2 typed-slot
18407        // surfaces), a `Some("None")` stringified-None round-trip, or a
18408        // `Some` arm whose contents were derived from a sibling slot (an
18409        // accidental fallback to the `:subject` / `:slot` payload that
18410        // read the pub-sub / store payload into the endpoint axis).
18411        // Three contracts sweep the accept-set every non-HTTP `:wit`
18412        // world lands on — pub-sub NATS, key/value, and payload-less
18413        // capability.
18414        for (wit, subject, slot) in [
18415            ("nats:pub-sub", Some("orders.paid"), None),
18416            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
18417            ("wasi:cli/environment", None, None),
18418        ] {
18419            let c = WitContract {
18420                de: "cart".into(),
18421                para: "downstream".into(),
18422                wit: wit.into(),
18423                endpoint: None,
18424                subject: subject.map(str::to_string),
18425                slot: slot.map(str::to_string),
18426            };
18427            assert!(
18428                c.endpoint().is_none(),
18429                "WitContract::endpoint must return None when the typed \
18430                 slot is absent under :wit {wit:?} (got {:?})",
18431                c.endpoint(),
18432            );
18433            assert_eq!(
18434                c.endpoint(),
18435                c.endpoint.as_deref(),
18436                "WitContract::endpoint must byte-equal the .endpoint \
18437                 field's `.as_deref()` projection in the absent arm",
18438            );
18439        }
18440    }
18441
18442    #[test]
18443    fn wit_contract_endpoint_borrows_from_endpoint_storage() {
18444        // The borrow-not-copy pin: [`WitContract::endpoint`] must return
18445        // an `Option<&str>` whose `Some` arm borrows from the typed
18446        // slot's own [`String`] storage — same-address invariant with
18447        // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
18448        // detour that allocated a fresh `String`
18449        // (`self.endpoint.clone().map(...)` in the body would type-check
18450        // but silently drop the borrow, and every downstream consumer
18451        // that assumed the returned slice outlives `&self` would break
18452        // on a stale-reference use-after-free — the [`WitContract::target`]
18453        // Http-arm payload extraction rebinds the returned `Option<&str>`
18454        // through `.ok_or_else(...)` and threads the `&str` payload into
18455        // [`WitTarget::Http { endpoint: &'a str }`], the
18456        // [`AplicacaoSpec::validate`] duplicate-`:contratos`
18457        // [`ContratoIdentity`] dedup key threads the returned
18458        // `Option<&str>` into the six-tuple's HTTP arm — each borrow
18459        // from the WitContract's own storage and each would silently
18460        // misbehave if this accessor produced a detached copy). Peer of
18461        // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
18462        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
18463        // shaped optional-scalar axes — first extension of the
18464        // `Option<&str>` borrow-not-copy discipline onto the
18465        // per-`:contratos` HTTP-shaped payload-carrier axis.
18466        let c = WitContract {
18467            de: "cart".into(),
18468            para: "catalog".into(),
18469            wit: "wasi:http/proxy".into(),
18470            endpoint: Some("/lookup".into()),
18471            subject: None,
18472            slot: None,
18473        };
18474        let ep = c.endpoint().expect("Some arm");
18475        let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
18476        assert_eq!(
18477            ep.as_ptr(),
18478            storage_slice.as_ptr(),
18479            "WitContract::endpoint must borrow from the .endpoint \
18480             String's backing storage — a fresh allocation here means \
18481             the accessor no longer names the substrate-primitive typed \
18482             dispatch and every downstream consumer would silently \
18483             carry a detached copy",
18484        );
18485        assert_eq!(
18486            ep.len(),
18487            storage_slice.len(),
18488            "WitContract::endpoint and .endpoint.as_deref() must byte-\
18489             equal in length as well as in address",
18490        );
18491    }
18492
18493    #[test]
18494    fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
18495        // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
18496        // pin: [`WitContract::subject`] must return the `:contratos
18497        // :subject` field byte-for-byte, borrowed from the typed slot's
18498        // own `Option<String>` storage. Peer of the sibling per-`:contratos`
18499        // [`WitContract::endpoint`] (7020470) accessor pin on the M3
18500        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
18501        // optional-scalar axis — same "the substrate-primitive accessor
18502        // must byte-equal the raw field access verbatim across every
18503        // author-declared value" discipline extended to the pub-sub arm.
18504        // Pins against a future silent detour that re-canonicalized the
18505        // subject (an accidental `.to_lowercase()` normalization that
18506        // didn't reach the peer field-access site at the dedup key, a
18507        // per-CR fully-qualified prefix rewrite the operator authors on
18508        // one consumer without the other, or an M4 typed-subject-template
18509        // `Display` re-canonicalization that silently drifted the printer
18510        // output from the source `caixa.lisp`). Four values sweep the
18511        // NATS accept-set every pub-sub author-declared subject lands on
18512        // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
18513        for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
18514            let c = WitContract {
18515                de: "cart".into(),
18516                para: "notifier".into(),
18517                wit: "nats:pub-sub".into(),
18518                endpoint: None,
18519                subject: Some(subject.into()),
18520                slot: None,
18521            };
18522            assert_eq!(
18523                c.subject(),
18524                Some(subject),
18525                "WitContract::subject must return :contratos :subject \
18526                 verbatim (got {:?}, expected Some({subject:?}))",
18527                c.subject(),
18528            );
18529            assert_eq!(
18530                c.subject(),
18531                c.subject.as_deref(),
18532                "WitContract::subject must byte-equal the .subject \
18533                 field's `.as_deref()` projection",
18534            );
18535        }
18536    }
18537
18538    #[test]
18539    fn wit_contract_subject_none_when_field_is_none() {
18540        // The absent-`:subject` arm of the per-`:contratos` pub-sub-
18541        // shaped payload-carrier accessor pin: when the typed slot is
18542        // absent — the canonical shape under a non-pub-sub `:wit` world
18543        // per the [`WitContract::target`]-enforced shape ↔ target
18544        // partition ([`WitTarget::Http`] carries `:endpoint`,
18545        // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
18546        // carries none) — [`WitContract::subject`] must return `None`.
18547        // Pins against a future silent detour that projected the absent
18548        // slot to a `Some("")` empty-string default (the canonical
18549        // `Option<String>` → `String` collapse footgun the sibling M2
18550        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
18551        // emptiness predicates already guard on the peer M2 typed-slot
18552        // surfaces), a `Some("None")` stringified-None round-trip, or a
18553        // `Some` arm whose contents were derived from a sibling slot (an
18554        // accidental fallback to the `:endpoint` / `:slot` payload that
18555        // read the HTTP / store payload into the subject axis). Three
18556        // contracts sweep the accept-set every non-pub-sub `:wit` world
18557        // lands on — HTTP proxy, key/value store, and payload-less
18558        // capability.
18559        for (wit, endpoint, slot) in [
18560            ("wasi:http/proxy", Some("/lookup"), None),
18561            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
18562            ("wasi:cli/environment", None, None),
18563        ] {
18564            let c = WitContract {
18565                de: "cart".into(),
18566                para: "downstream".into(),
18567                wit: wit.into(),
18568                endpoint: endpoint.map(str::to_string),
18569                subject: None,
18570                slot: slot.map(str::to_string),
18571            };
18572            assert!(
18573                c.subject().is_none(),
18574                "WitContract::subject must return None when the typed \
18575                 slot is absent under :wit {wit:?} (got {:?})",
18576                c.subject(),
18577            );
18578            assert_eq!(
18579                c.subject(),
18580                c.subject.as_deref(),
18581                "WitContract::subject must byte-equal the .subject \
18582                 field's `.as_deref()` projection in the absent arm",
18583            );
18584        }
18585    }
18586
18587    #[test]
18588    fn wit_contract_subject_borrows_from_subject_storage() {
18589        // The borrow-not-copy pin: [`WitContract::subject`] must return
18590        // an `Option<&str>` whose `Some` arm borrows from the typed
18591        // slot's own [`String`] storage — same-address invariant with
18592        // `c.subject.as_deref().unwrap()`. Pins against a future silent
18593        // detour that allocated a fresh `String`
18594        // (`self.subject.clone().map(...)` in the body would type-check
18595        // but silently drop the borrow, and every downstream consumer
18596        // that assumed the returned slice outlives `&self` would break
18597        // on a stale-reference use-after-free — the [`WitContract::target`]
18598        // PubSub-arm payload extraction rebinds the returned
18599        // `Option<&str>` through `.ok_or_else(...)` and threads the
18600        // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
18601        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
18602        // [`ContratoIdentity`] dedup key threads the returned
18603        // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
18604        // from the WitContract's own storage and each would silently
18605        // misbehave if this accessor produced a detached copy). Peer of
18606        // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
18607        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
18608        // shaped optional-scalar axis — second extension of the
18609        // `Option<&str>` borrow-not-copy discipline onto the
18610        // per-`:contratos` payload-carrier family, this time on the
18611        // pub-sub arm.
18612        let c = WitContract {
18613            de: "cart".into(),
18614            para: "notifier".into(),
18615            wit: "nats:pub-sub".into(),
18616            endpoint: None,
18617            subject: Some("orders.paid".into()),
18618            slot: None,
18619        };
18620        let sub = c.subject().expect("Some arm");
18621        let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
18622        assert_eq!(
18623            sub.as_ptr(),
18624            storage_slice.as_ptr(),
18625            "WitContract::subject must borrow from the .subject \
18626             String's backing storage — a fresh allocation here means \
18627             the accessor no longer names the substrate-primitive typed \
18628             dispatch and every downstream consumer would silently \
18629             carry a detached copy",
18630        );
18631        assert_eq!(
18632            sub.len(),
18633            storage_slice.len(),
18634            "WitContract::subject and .subject.as_deref() must byte-\
18635             equal in length as well as in address",
18636        );
18637    }
18638
18639    #[test]
18640    fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
18641        // The canonical per-`:contratos` key/value-store-shaped
18642        // `:slot`-scalar pin: [`WitContract::slot`] must return the
18643        // `:contratos :slot` field byte-for-byte, borrowed from the
18644        // typed slot's own `Option<String>` storage. Peer of the
18645        // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
18646        // [`WitContract::subject`] (90de675) accessor pins on the M3
18647        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
18648        // optional-scalar axis — same "the substrate-primitive
18649        // accessor must byte-equal the raw field access verbatim
18650        // across every author-declared value" discipline extended to
18651        // the store arm. Pins against a future silent detour that
18652        // re-canonicalized the slot template (an accidental
18653        // `.to_lowercase()` bucket-prefix normalization that didn't
18654        // reach the peer field-access site at the dedup key, a per-CR
18655        // fully-qualified prefix rewrite the operator authors on one
18656        // consumer without the other, or an M4 typed-key-template
18657        // `Display` re-canonicalization that silently drifted the
18658        // printer output from the source `caixa.lisp`). Four values
18659        // sweep the wasi:keyvalue accept-set every store-shaped
18660        // author-declared slot lands on (flat bucket, single-param
18661        // template, multi-param template, nested-hierarchy template).
18662        for slot in [
18663            "sessions",
18664            "carts/{cart_id}",
18665            "orders/{tenant}/{order_id}",
18666            "cache/tenant-a/orders/{id}",
18667        ] {
18668            let c = WitContract {
18669                de: "cart".into(),
18670                para: "kv".into(),
18671                wit: "wasi:keyvalue/store".into(),
18672                endpoint: None,
18673                subject: None,
18674                slot: Some(slot.into()),
18675            };
18676            assert_eq!(
18677                c.slot(),
18678                Some(slot),
18679                "WitContract::slot must return :contratos :slot \
18680                 verbatim (got {:?}, expected Some({slot:?}))",
18681                c.slot(),
18682            );
18683            assert_eq!(
18684                c.slot(),
18685                c.slot.as_deref(),
18686                "WitContract::slot must byte-equal the .slot field's \
18687                 `.as_deref()` projection",
18688            );
18689        }
18690    }
18691
18692    #[test]
18693    fn wit_contract_slot_none_when_field_is_none() {
18694        // The absent-`:slot` arm of the per-`:contratos` store-shaped
18695        // payload-carrier accessor pin: when the typed slot is absent —
18696        // the canonical shape under a non-store `:wit` world per the
18697        // [`WitContract::target`]-enforced shape ↔ target partition
18698        // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
18699        // carries `:subject`, [`WitTarget::Capability`] carries none) —
18700        // [`WitContract::slot`] must return `None`. Pins against a
18701        // future silent detour that projected the absent slot to a
18702        // `Some("")` empty-string default (the canonical
18703        // `Option<String>` → `String` collapse footgun the sibling M2
18704        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
18705        // emptiness predicates already guard on the peer M2 typed-slot
18706        // surfaces), a `Some("None")` stringified-None round-trip, or
18707        // a `Some` arm whose contents were derived from a sibling
18708        // slot (an accidental fallback to the `:endpoint` / `:subject`
18709        // payload that read the HTTP / pub-sub payload into the store
18710        // axis). Three contracts sweep the accept-set every non-store
18711        // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
18712        // payload-less capability.
18713        for (wit, endpoint, subject) in [
18714            ("wasi:http/proxy", Some("/lookup"), None),
18715            ("nats:pub-sub", None, Some("orders.paid")),
18716            ("wasi:cli/environment", None, None),
18717        ] {
18718            let c = WitContract {
18719                de: "cart".into(),
18720                para: "downstream".into(),
18721                wit: wit.into(),
18722                endpoint: endpoint.map(str::to_string),
18723                subject: subject.map(str::to_string),
18724                slot: None,
18725            };
18726            assert!(
18727                c.slot().is_none(),
18728                "WitContract::slot must return None when the typed \
18729                 slot is absent under :wit {wit:?} (got {:?})",
18730                c.slot(),
18731            );
18732            assert_eq!(
18733                c.slot(),
18734                c.slot.as_deref(),
18735                "WitContract::slot must byte-equal the .slot field's \
18736                 `.as_deref()` projection in the absent arm",
18737            );
18738        }
18739    }
18740
18741    #[test]
18742    fn wit_contract_slot_borrows_from_slot_storage() {
18743        // The borrow-not-copy pin: [`WitContract::slot`] must return
18744        // an `Option<&str>` whose `Some` arm borrows from the typed
18745        // slot's own [`String`] storage — same-address invariant with
18746        // `c.slot.as_deref().unwrap()`. Pins against a future silent
18747        // detour that allocated a fresh `String`
18748        // (`self.slot.clone().map(...)` in the body would type-check
18749        // but silently drop the borrow, and every downstream consumer
18750        // that assumed the returned slice outlives `&self` would
18751        // break on a stale-reference use-after-free — the
18752        // [`WitContract::target`] Store-arm payload extraction rebinds
18753        // the returned `Option<&str>` through `.ok_or_else(...)` and
18754        // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
18755        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
18756        // [`ContratoIdentity`] dedup key threads the returned
18757        // `Option<&str>` into the six-tuple's store arm — each borrow
18758        // from the WitContract's own storage and each would silently
18759        // misbehave if this accessor produced a detached copy). Peer
18760        // of the sibling per-`:contratos` [`WitContract::endpoint`]
18761        // (7020470) / [`WitContract::subject`] (90de675)
18762        // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
18763        // shaped optional-scalar axis — third and final extension of
18764        // the `Option<&str>` borrow-not-copy discipline onto the
18765        // per-`:contratos` payload-carrier family, this time on the
18766        // store arm.
18767        let c = WitContract {
18768            de: "cart".into(),
18769            para: "kv".into(),
18770            wit: "wasi:keyvalue/store".into(),
18771            endpoint: None,
18772            subject: None,
18773            slot: Some("carts/{cart_id}".into()),
18774        };
18775        let slot = c.slot().expect("Some arm");
18776        let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
18777        assert_eq!(
18778            slot.as_ptr(),
18779            storage_slice.as_ptr(),
18780            "WitContract::slot must borrow from the .slot String's \
18781             backing storage — a fresh allocation here means the \
18782             accessor no longer names the substrate-primitive typed \
18783             dispatch and every downstream consumer would silently \
18784             carry a detached copy",
18785        );
18786        assert_eq!(
18787            slot.len(),
18788            storage_slice.len(),
18789            "WitContract::slot and .slot.as_deref() must byte-equal \
18790             in length as well as in address",
18791        );
18792    }
18793
18794    #[test]
18795    fn membro_nome_returns_caixa_byte_equal_across_permutations() {
18796        // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
18797        // [`Membro::nome`] must return the `:membros :caixa` field
18798        // byte-for-byte, borrowed from the typed slot's own [`String`]
18799        // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
18800        // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
18801        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
18802        // slot-atom scalar-value axes — same "the substrate-primitive
18803        // accessor must byte-equal the raw field access verbatim across
18804        // every author-declared value" discipline extended to the
18805        // per-`:membros` member-identity arm. Pins against a future
18806        // silent detour that re-normalized the member identity (an
18807        // accidental `.to_lowercase()` — every `:membros :caixa` is
18808        // validated as a DNS-1123 label upstream via
18809        // [`validate_membro_caixa`], so any re-normalization is
18810        // redundant + a drift surface between the validator and the
18811        // accessor), a namespace-prefix rewrite (an accidental
18812        // `format!("{namespace}/{caixa}")` per-CR fully-qualified
18813        // rewrite that didn't land on the peer axes), or a per-cluster
18814        // alias stamp the operator authors on one consumer without the
18815        // other. Four values sweep the accept-set the DNS-1123 gate
18816        // upstream admits (short single-word / dashed / v-suffixed
18817        // member names).
18818        for name in ["cart", "checkout", "catalog", "orders-v2"] {
18819            let m = Membro {
18820                caixa: name.into(),
18821                versao: "^0.1".into(),
18822            };
18823            assert_eq!(
18824                m.nome(),
18825                name,
18826                "Membro::nome must return :membros :caixa verbatim \
18827                 (got {:?}, expected {name:?})",
18828                m.nome(),
18829            );
18830            assert_eq!(
18831                m.nome(),
18832                m.caixa.as_str(),
18833                "Membro::nome must byte-equal the .caixa field access",
18834            );
18835        }
18836    }
18837
18838    #[test]
18839    fn membro_nome_borrows_from_caixa_storage() {
18840        // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
18841        // slice that borrows from the typed slot's own [`String`]
18842        // storage — same-address invariant with `m.caixa.as_str()`. Pins
18843        // against a future silent detour that allocated a fresh `String`
18844        // (`self.caixa.clone()` in the body would type-check but
18845        // silently drop the borrow, and every downstream consumer that
18846        // assumed the returned slice outlives `&self` would break on a
18847        // stale-reference use-after-free — the `HashSet<&str>` collector
18848        // at [`AplicacaoSpec::validate`]'s `names` seed, the
18849        // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
18850        // [`AplicacaoSpec::detect_sync_cycles`], the
18851        // [`crate::render::insert_first_seen`] dedup key at
18852        // [`AplicacaoSpec::validate_membros`] — each borrow from the
18853        // Membro's own storage and each would silently misbehave if
18854        // this accessor produced a detached copy). Peer of the sibling
18855        // per-`:contratos` [`WitContract::source`] /
18856        // [`WitContract::destination`] and per-`:entrada`
18857        // [`Entrada::destination`] borrow-invariant pins on the mesh-
18858        // slot-atom scalar-value axes.
18859        let m = Membro {
18860            caixa: "checkout".into(),
18861            versao: "^0.1".into(),
18862        };
18863        let name = m.nome();
18864        let caixa_slice = m.caixa.as_str();
18865        assert_eq!(
18866            name.as_ptr(),
18867            caixa_slice.as_ptr(),
18868            "Membro::nome must borrow from the .caixa String's backing \
18869             storage — a fresh allocation here means the accessor no \
18870             longer names the substrate-primitive typed dispatch and \
18871             every downstream consumer would silently carry a detached \
18872             copy",
18873        );
18874        assert_eq!(
18875            name.len(),
18876            caixa_slice.len(),
18877            "Membro::nome and .caixa.as_str() must byte-equal in length \
18878             as well as in address",
18879        );
18880    }
18881
18882    #[test]
18883    fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
18884        // The canonical per-`:membros` member-`:versao`-scalar pin:
18885        // [`Membro::versao_requirement`] must return the
18886        // `:membros :versao` field byte-for-byte, borrowed from the typed
18887        // slot's own [`String`] storage. Sibling of the peer
18888        // `membro_nome_returns_caixa_byte_equal_across_permutations`
18889        // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
18890        // — same "the substrate-primitive accessor must byte-equal the
18891        // raw field access verbatim across every author-declared value"
18892        // discipline extended to the per-`:membros` member-`:versao`
18893        // requirement-string arm. Pins against a future silent detour
18894        // that re-canonicalized the requirement (an accidental
18895        // `.to_string()` via [`parse_requirement`] → [`Display`] round-
18896        // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
18897        // drifted the printer output away from the source `caixa.lisp`,
18898        // an accidental whitespace trim on `"^ 0.1"` that no consumer
18899        // ever produced from the field-access side, an accidental
18900        // per-cluster lacre-projected concrete-version rewrite that
18901        // didn't land on the peer field-access sites). Five values sweep
18902        // the accept-set the shared
18903        // [`crate::render::require_valid_versao_requirement`] gate
18904        // admits (caret / tilde / exact / wildcard / bare-major).
18905        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
18906            let m = Membro {
18907                caixa: "cart".into(),
18908                versao: req.into(),
18909            };
18910            assert_eq!(
18911                m.versao_requirement(),
18912                req,
18913                "Membro::versao_requirement must return :membros :versao \
18914                 verbatim (got {:?}, expected {req:?})",
18915                m.versao_requirement(),
18916            );
18917            assert_eq!(
18918                m.versao_requirement(),
18919                m.versao.as_str(),
18920                "Membro::versao_requirement must byte-equal the .versao \
18921                 field access",
18922            );
18923        }
18924    }
18925
18926    #[test]
18927    fn membro_versao_requirement_borrows_from_versao_storage() {
18928        // The borrow-not-copy pin: [`Membro::versao_requirement`] must
18929        // return a `&str` slice that borrows from the typed slot's own
18930        // [`String`] storage — same-address invariant with
18931        // `m.versao.as_str()`. Pins against a future silent detour that
18932        // allocated a fresh `String` (`self.versao.clone()` in the body
18933        // would type-check but silently drop the borrow, and every
18934        // downstream consumer that assumed the returned slice outlives
18935        // `&self` would break on a stale-reference use-after-free). Peer
18936        // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
18937        // per-`:contratos` [`WitContract::source`] /
18938        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
18939        // [`Entrada::destination`] (6db982c) borrow-invariant pins on
18940        // the mesh-slot-atom scalar-value axes.
18941        let m = Membro {
18942            caixa: "checkout".into(),
18943            versao: "^0.1".into(),
18944        };
18945        let req = m.versao_requirement();
18946        let versao_slice = m.versao.as_str();
18947        assert_eq!(
18948            req.as_ptr(),
18949            versao_slice.as_ptr(),
18950            "Membro::versao_requirement must borrow from the .versao \
18951             String's backing storage — a fresh allocation here means \
18952             the accessor no longer names the substrate-primitive typed \
18953             dispatch and every downstream consumer would silently carry \
18954             a detached copy",
18955        );
18956        assert_eq!(
18957            req.len(),
18958            versao_slice.len(),
18959            "Membro::versao_requirement and .versao.as_str() must byte-\
18960             equal in length as well as in address",
18961        );
18962    }
18963
18964    #[test]
18965    fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
18966        // Sibling-pair invariant pin composing both per-`:membros`
18967        // substrate-primitive typed dispatches — [`Membro::nome`]
18968        // (4a32abf) and [`Membro::versao_requirement`] — at the joint
18969        // `(nome(), versao_requirement())` call shape every renderer
18970        // that fans on per-member identity + version pin keys off. The
18971        // invariant, evaluated per-member:
18972        //
18973        //   (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
18974        //
18975        // Closes the last unlifted per-`:membros` scalar axis — every
18976        // downstream consumer that reads the pair now routes through
18977        // exactly two typed dispatches on the substrate primitive, not
18978        // one typed + one open-coded field access. A future refactor
18979        // that silently split either accessor's projection (an
18980        // accidental `nome()` namespace-prefix rewrite that didn't
18981        // reach the peer, an accidental `versao_requirement()` lacre-
18982        // projected concrete-version rewrite that didn't land on the
18983        // `nome()` peer) surfaces at caixa-core build time. Peer of the
18984        // sibling per-`:entrada` `(hostname(), destination())` and
18985        // per-`:contratos` `(source(), destination())` pair invariants
18986        // on the mesh-slot-atom scalar-value axes.
18987        for (caixa, versao) in [
18988            ("cart", "^0.1"),
18989            ("checkout", "~0.1.2"),
18990            ("catalog", "0.1.0"),
18991            ("orders-v2", "*"),
18992        ] {
18993            let m = Membro {
18994                caixa: caixa.into(),
18995                versao: versao.into(),
18996            };
18997            assert_eq!(
18998                (m.nome(), m.versao_requirement()),
18999                (m.caixa.as_str(), m.versao.as_str()),
19000                "(Membro::nome, Membro::versao_requirement) must project \
19001                 (.caixa, .versao) verbatim across every author-declared \
19002                 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
19003                m.nome(),
19004                m.versao_requirement(),
19005            );
19006        }
19007    }
19008
19009    #[test]
19010    fn validate_membros_empty_gate_routes_through_nome_accessor() {
19011        // Composition pin: [`AplicacaoSpec::validate_membros`]'s
19012        // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
19013        // not the raw `.caixa` field access. Structurally: setting
19014        // ONLY the `.caixa` field to `""` on an otherwise-well-formed
19015        // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
19016        // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
19017        // (i.e. the empty string) — so the emptiness predicate the
19018        // refusal arm reaches under is the accessor-projected value,
19019        // not a peer field that would silently drift under a future
19020        // accessor-side rewrite.
19021        //
19022        // Pins against a future silent detour that (a) re-derived the
19023        // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
19024        // instead of `self.nome().is_empty()`, silently disagreeing with
19025        // every peer consumer (the `validate_membro_caixa(m.nome())`
19026        // call one line below, the dedup-key `insert_first_seen(&mut
19027        // seen, m.nome(), …)` two lines below, the emit-side per-
19028        // `programs[]` entry-`name:` at caixa-mesh/src/lib.rs:133),
19029        // (b) accessor-side introduced a per-tenant alias arm the
19030        // caller was unaware of, silently rewriting an author-declared
19031        // `:caixa "checkout"` to `""` — the raw-field-access gate
19032        // would fail-open while the accessor-routed peer consumers
19033        // would fail-closed, splitting the diagnostic from the actual
19034        // failure surface.
19035        //
19036        // Peer of the sibling
19037        // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
19038        // (c0110f1) composition pin — same "the shape-gate predicate
19039        // must route through the substrate-primitive typed dispatch"
19040        // discipline extended onto the per-`:membros` empty-`:caixa`
19041        // refusal-arm axis. Closes the last unlifted `.caixa` production-
19042        // code read site on `Membro` — after this converge every
19043        // caixa-core `.caixa` field access outside the accessor's own
19044        // body is either a test-side field-setter (in-module tests
19045        // constructing invalid-shape inputs) or a doc-comment reference.
19046        let mut s = three_member_spec();
19047        s.membros[1].caixa = String::new();
19048        assert!(
19049            s.membros[1].nome().is_empty(),
19050            "Membro::nome must byte-equal the .caixa field access — an \
19051             accessor-side detour that no longer projects the raw field \
19052             would silently split this drift-detection test from the \
19053             validate() refusal arm",
19054        );
19055        assert_eq!(
19056            s.membros[1].nome(),
19057            s.membros[1].caixa.as_str(),
19058            "Membro::nome and .caixa.as_str() must byte-equal on an \
19059             empty-`:caixa` entry — the emptiness gate keys off the \
19060             accessor by construction",
19061        );
19062        assert_eq!(
19063            s.validate().unwrap_err(),
19064            AplicacaoError::MembroCaixaEmpty,
19065            "validate_membros' emptiness gate must fire MembroCaixaEmpty \
19066             on an entry whose accessor-projected `nome()` is empty",
19067        );
19068    }
19069
19070    #[test]
19071    fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
19072        // The canonical per-`:placement` Akka-cluster-sharding
19073        // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
19074        // the `:placement :shard-key` field byte-for-byte, borrowed
19075        // from the typed slot's own `Option<String>` storage. Peer of
19076        // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
19077        // per-`:contratos` [`WitContract::source`] /
19078        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
19079        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
19080        // slot-atom scalar-value axes — same "the substrate-primitive
19081        // accessor must byte-equal the raw field access verbatim across
19082        // every author-declared value" discipline extended to the
19083        // per-`:placement` Akka-cluster-sharding key extractor arm.
19084        // Pins against a future silent detour that re-normalized the
19085        // key (an accidental `.to_lowercase()` — every non-empty
19086        // `:shard-key` is validated as a printable-ASCII single-token
19087        // reference upstream via [`validate_placement_shard_key`], so
19088        // any re-normalization is redundant + a drift surface between
19089        // the validator and the accessor), a per-cluster alias rewrite
19090        // the operator authors on one consumer without the other, or an
19091        // accidental variable-prefix strip (`$tenantId` → `tenantId`)
19092        // that didn't land on the peer field-access sites. Four values
19093        // sweep the accept-set the shape gate admits — bare identifier,
19094        // `$`-prefixed variable, dotted path, `${}`-quoted variable —
19095        // the four canonical Akka-style entity-id extractor shapes the
19096        // future M4 cluster-sharding reconciler hashes.
19097        for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
19098            let p = Placement {
19099                estrategia: PlacementStrategy::Sharded,
19100                clusters: vec!["rio".into()],
19101                affinity: None,
19102                shard_key: Some(key.into()),
19103            };
19104            assert_eq!(
19105                p.shard_key(),
19106                Some(key),
19107                "Placement::shard_key must return :placement :shard-key \
19108                 verbatim (got {:?}, expected Some({key:?}))",
19109                p.shard_key(),
19110            );
19111            assert_eq!(
19112                p.shard_key(),
19113                p.shard_key.as_deref(),
19114                "Placement::shard_key must byte-equal the .shard_key \
19115                 field's `.as_deref()` projection",
19116            );
19117        }
19118    }
19119
19120    #[test]
19121    fn placement_shard_key_none_when_field_is_none() {
19122        // The absent-`:shard-key` arm of the per-`:placement`
19123        // Akka-cluster-sharding accessor pin: when the typed slot is
19124        // absent — the canonical shape under `:estrategia Replicated` /
19125        // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
19126        // enforced `shard_key.is_some() == matches!(estrategia,
19127        // Sharded)` partition — [`Placement::shard_key`] must return
19128        // `None`. Pins against a future silent detour that projected
19129        // the absent slot to a `Some("")` empty-string default (the
19130        // canonical `Option<String>` → `String` collapse footgun the
19131        // sibling M2 [`crate::LimitsSpec::is_empty`] /
19132        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
19133        // already guard on the peer M2 typed-slot surfaces), a
19134        // `Some("None")` stringified-None round-trip, or a `Some` arm
19135        // whose contents were derived from a sibling slot (an
19136        // accidental fallback to `estrategia.as_str()` that read the
19137        // strategy discriminator into the key axis). Two placements
19138        // sweep the accept-set every `validate`-passing non-`Sharded`
19139        // shape lands on — `Replicated` (Erlang/OTP distributed-app
19140        // takeover) and `SingleNode` (single-node hosting).
19141        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
19142            let p = Placement {
19143                estrategia,
19144                clusters: vec!["rio".into()],
19145                affinity: None,
19146                shard_key: None,
19147            };
19148            assert!(
19149                p.shard_key().is_none(),
19150                "Placement::shard_key must return None when the typed \
19151                 slot is absent under :estrategia {estrategia:?} (got {:?})",
19152                p.shard_key(),
19153            );
19154            assert_eq!(
19155                p.shard_key(),
19156                p.shard_key.as_deref(),
19157                "Placement::shard_key must byte-equal the .shard_key \
19158                 field's `.as_deref()` projection in the absent arm",
19159            );
19160        }
19161    }
19162
19163    #[test]
19164    fn placement_shard_key_borrows_from_shard_key_storage() {
19165        // The borrow-not-copy pin: [`Placement::shard_key`] must return
19166        // an `Option<&str>` whose `Some` arm borrows from the typed
19167        // slot's own [`String`] storage — same-address invariant with
19168        // `p.shard_key.as_deref().unwrap()`. Pins against a future
19169        // silent detour that allocated a fresh `String`
19170        // (`self.shard_key.clone().map(...)` in the body would type-
19171        // check but silently drop the borrow, and every downstream
19172        // consumer that assumed the returned slice outlives `&self`
19173        // would break on a stale-reference use-after-free — the
19174        // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
19175        // gate's `Some(k)`-bound match arm reads `k: &str` under the
19176        // accessor's return type and would silently misbehave if this
19177        // accessor produced a detached copy). Peer of the sibling
19178        // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
19179        // [`WitContract::source`] / [`WitContract::destination`]
19180        // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
19181        // (6db982c) borrow-invariant pins on the mesh-slot-atom
19182        // scalar-value axes — first extension of the discipline onto
19183        // an `Option<String>`-shaped optional-scalar axis.
19184        let p = Placement {
19185            estrategia: PlacementStrategy::Sharded,
19186            clusters: vec!["rio".into()],
19187            affinity: None,
19188            shard_key: Some("tenantId".into()),
19189        };
19190        let key = p.shard_key().expect("Some arm");
19191        let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
19192        assert_eq!(
19193            key.as_ptr(),
19194            storage_slice.as_ptr(),
19195            "Placement::shard_key must borrow from the .shard_key \
19196             String's backing storage — a fresh allocation here means \
19197             the accessor no longer names the substrate-primitive typed \
19198             dispatch and every downstream consumer would silently \
19199             carry a detached copy",
19200        );
19201        assert_eq!(
19202            key.len(),
19203            storage_slice.len(),
19204            "Placement::shard_key and .shard_key.as_deref() must byte-\
19205             equal in length as well as in address",
19206        );
19207    }
19208
19209    #[test]
19210    fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
19211        // The canonical per-`:placement` M3-Adaptive-compression-hint
19212        // scalar pin: [`Placement::affinity`] must return the
19213        // `:placement :affinity` field byte-for-byte, borrowed from the
19214        // typed slot's own `Option<String>` storage. Peer of the sibling
19215        // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
19216        // pin on the sibling `Option<&str>` optional-scalar axis — same
19217        // "the substrate-primitive accessor must byte-equal the raw
19218        // field access verbatim across every author-declared value"
19219        // discipline extended to the peer per-`:placement` M3-Adaptive-
19220        // compression-hint arm. Pins against a future silent detour
19221        // that re-normalized the hint (an accidental `.to_lowercase()`
19222        // — every `:affinity` is already validated as a DNS-1123 label
19223        // upstream via [`validate_placement_affinity`], so any re-
19224        // normalization is redundant + a drift surface between the
19225        // validator and the accessor), a per-cluster alias rewrite the
19226        // operator authors on one consumer without the other, or an
19227        // accidental hint-family collapse (`low-latency` → `latency`
19228        // that dropped the qualifier prefix). Four values sweep the
19229        // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
19230        // canonical adaptive-compression-weight biases the future M4
19231        // placement engine reads.
19232        for hint in [
19233            "data-locality",
19234            "low-latency",
19235            "high-throughput",
19236            "cost-optimized",
19237        ] {
19238            let p = Placement {
19239                estrategia: PlacementStrategy::Replicated,
19240                clusters: vec!["rio".into()],
19241                affinity: Some(hint.into()),
19242                shard_key: None,
19243            };
19244            assert_eq!(
19245                p.affinity(),
19246                Some(hint),
19247                "Placement::affinity must return :placement :affinity \
19248                 verbatim (got {:?}, expected Some({hint:?}))",
19249                p.affinity(),
19250            );
19251            assert_eq!(
19252                p.affinity(),
19253                p.affinity.as_deref(),
19254                "Placement::affinity must byte-equal the .affinity \
19255                 field's `.as_deref()` projection",
19256            );
19257        }
19258    }
19259
19260    #[test]
19261    fn placement_affinity_none_when_field_is_none() {
19262        // The absent-`:affinity` arm of the per-`:placement`
19263        // M3-Adaptive-compression-hint accessor pin: when the typed
19264        // slot is absent — the canonical shape of an Aplicacao that
19265        // leaves the compression weighting up to the placement engine's
19266        // cluster-default arm — [`Placement::affinity`] must return
19267        // `None`. Pins against a future silent detour that projected
19268        // the absent slot to a `Some("")` empty-string default (the
19269        // canonical `Option<String>` → `String` collapse footgun the
19270        // sibling M2 [`crate::LimitsSpec::is_empty`] /
19271        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
19272        // already guard on the peer M2 typed-slot surfaces), a
19273        // `Some("None")` stringified-None round-trip, a `Some` arm
19274        // whose contents were derived from a sibling slot (an
19275        // accidental fallback to `estrategia.as_str()` that read the
19276        // strategy discriminator into the hint axis), or a
19277        // `Some("default")` implicit-default that would silently biases
19278        // the routing without the author having written one. Three
19279        // placements sweep the accept-set every `validate`-passing
19280        // `:affinity None` shape lands on — one per PlacementStrategy
19281        // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
19282        // with a shard-key), since `:affinity` is orthogonal to
19283        // `:estrategia` in the typed grammar.
19284        for (estrategia, shard_key) in [
19285            (PlacementStrategy::SingleNode, None),
19286            (PlacementStrategy::Replicated, None),
19287            (PlacementStrategy::Sharded, Some("tenantId".to_string())),
19288        ] {
19289            let p = Placement {
19290                estrategia,
19291                clusters: vec!["rio".into()],
19292                affinity: None,
19293                shard_key,
19294            };
19295            assert!(
19296                p.affinity().is_none(),
19297                "Placement::affinity must return None when the typed \
19298                 slot is absent under :estrategia {estrategia:?} (got {:?})",
19299                p.affinity(),
19300            );
19301            assert_eq!(
19302                p.affinity(),
19303                p.affinity.as_deref(),
19304                "Placement::affinity must byte-equal the .affinity \
19305                 field's `.as_deref()` projection in the absent arm",
19306            );
19307        }
19308    }
19309
19310    #[test]
19311    fn placement_affinity_borrows_from_affinity_storage() {
19312        // The borrow-not-copy pin: [`Placement::affinity`] must return
19313        // an `Option<&str>` whose `Some` arm borrows from the typed
19314        // slot's own [`String`] storage — same-address invariant with
19315        // `p.affinity.as_deref().unwrap()`. Pins against a future
19316        // silent detour that allocated a fresh `String`
19317        // (`self.affinity.clone().map(...)` in the body would type-
19318        // check but silently drop the borrow, and every downstream
19319        // consumer that assumed the returned slice outlives `&self`
19320        // would break on a stale-reference use-after-free — the
19321        // [`AplicacaoSpec::validate_placement`] per-hint value-shape
19322        // gate reads the accessor's `&str` return through the
19323        // [`validate_placement_affinity`] `&str` parameter and would
19324        // silently misbehave if this accessor produced a detached
19325        // copy). Peer of the sibling per-`:placement`
19326        // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
19327        // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
19328        // extends the discipline onto the sibling per-`:placement`
19329        // M3-Adaptive-compression-hint arm.
19330        let p = Placement {
19331            estrategia: PlacementStrategy::Replicated,
19332            clusters: vec!["rio".into()],
19333            affinity: Some("data-locality".into()),
19334            shard_key: None,
19335        };
19336        let hint = p.affinity().expect("Some arm");
19337        let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
19338        assert_eq!(
19339            hint.as_ptr(),
19340            storage_slice.as_ptr(),
19341            "Placement::affinity must borrow from the .affinity \
19342             String's backing storage — a fresh allocation here means \
19343             the accessor no longer names the substrate-primitive typed \
19344             dispatch and every downstream consumer would silently \
19345             carry a detached copy",
19346        );
19347        assert_eq!(
19348            hint.len(),
19349            storage_slice.len(),
19350            "Placement::affinity and .affinity.as_deref() must byte-\
19351             equal in length as well as in address",
19352        );
19353    }
19354
19355    #[test]
19356    fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
19357        // The canonical per-`:placement` distribution-strategy-scalar
19358        // pin: [`Placement::estrategia`] must return the `:placement
19359        // :estrategia` field verbatim as a [`PlacementStrategy`],
19360        // `Copy`-projected from the typed slot's own `PlacementStrategy`
19361        // storage across every variant in the closed accept-set
19362        // (`SingleNode` — Erlang/OTP distributed-app takeover;
19363        // `Replicated` — active-active across every named cluster;
19364        // `Sharded` — Akka-style hash-keyed entity distribution). Pins
19365        // against a future silent detour that re-derived the strategy
19366        // from a peer axis (an accidental fallback to
19367        // `if shard_key.is_some() { Sharded } else { Replicated }`
19368        // collapse that read the shard-key axis into the strategy
19369        // discriminator), a variant remap the operator authors on one
19370        // consumer without the other, or a stale-derive detour that
19371        // substituted [`PlacementStrategy::default`] when the field
19372        // held any explicit variant (which would silently collapse the
19373        // distinction between "author explicitly declared `:estrategia
19374        // Replicated`" and "author omitted the slot and inherited the
19375        // default" the future per-cluster override slot depends on).
19376        // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
19377        // pin on the `Copy`-return `u16` scalar axis — same "the
19378        // substrate-primitive accessor must byte-equal the raw field
19379        // access verbatim across every author-declared value" discipline
19380        // extended onto the per-`:placement` distribution-strategy
19381        // `Copy`-composite-enum scalar axis.
19382        for estrategia in [
19383            PlacementStrategy::SingleNode,
19384            PlacementStrategy::Replicated,
19385            PlacementStrategy::Sharded,
19386        ] {
19387            let shard_key = estrategia.is_sharded().then(|| "tenantId".to_string());
19388            let p = Placement {
19389                estrategia,
19390                clusters: vec!["rio".into()],
19391                affinity: None,
19392                shard_key,
19393            };
19394            assert_eq!(
19395                p.estrategia(),
19396                estrategia,
19397                "Placement::estrategia must return :placement :estrategia \
19398                 verbatim (got {:?}, expected {estrategia:?})",
19399                p.estrategia(),
19400            );
19401            assert_eq!(
19402                p.estrategia(),
19403                p.estrategia,
19404                "Placement::estrategia accessor and .estrategia field \
19405                 access must byte-equal — the accessor is the substrate-\
19406                 primitive typed dispatch every downstream distribution-\
19407                 strategy consumer must route through",
19408            );
19409        }
19410    }
19411
19412    #[test]
19413    fn validate_placement_reads_through_lifted_estrategia_accessor() {
19414        // Three-consumer coherence pin: the
19415        // [`AplicacaoSpec::validate_placement`]
19416        // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
19417        // `estrategia:` field (which reads through
19418        // [`Placement::estrategia`] to name the strategy the empty
19419        // `:clusters` list was declared against), the same method's
19420        // `Sharded ↔ non-Sharded` `match` partition dispatch (which
19421        // reads through [`Placement::estrategia`] to fan across the
19422        // shape-gate cascades), and the non-`Sharded`-arm
19423        // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
19424        // `estrategia:` field (which reads through
19425        // [`Placement::estrategia`] to name the strategy the declared-
19426        // but-inert `:shard-key` was authored under) must all key off
19427        // the lifted accessor, so any future rebrand on the typed
19428        // slot's reader shape lands at exactly one place. Pins the
19429        // three-site coherence by exercising each error surface end-
19430        // to-end and asserting the surfaced `estrategia:` field byte-
19431        // equals the accessor's return. Peer of the sibling per-
19432        // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
19433        // pin on the M3 mesh-slot `Copy`-return scalar axis.
19434
19435        // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
19436        // whose `estrategia:` field must byte-equal the accessor's return
19437        // for every variant in the closed accept-set.
19438        for estrategia in [
19439            PlacementStrategy::SingleNode,
19440            PlacementStrategy::Replicated,
19441            PlacementStrategy::Sharded,
19442        ] {
19443            let mut spec = three_member_spec();
19444            spec.placement.estrategia = estrategia;
19445            spec.placement.clusters = Vec::new();
19446            spec.placement.shard_key = estrategia.is_sharded().then(|| "tenantId".to_string());
19447            let err = spec.validate().unwrap_err();
19448            match err {
19449                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
19450                    assert_eq!(
19451                        e,
19452                        spec.placement.estrategia(),
19453                        "PlacementWithoutClusters.estrategia must byte-equal \
19454                         Placement::estrategia() — the error carrier reads \
19455                         through the lifted accessor",
19456                    );
19457                }
19458                other => panic!(
19459                    "expected PlacementWithoutClusters, got {other:?} for \
19460                     estrategia={estrategia:?}"
19461                ),
19462            }
19463        }
19464
19465        // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
19466        // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
19467        // must byte-equal the accessor's return for both non-`Sharded`
19468        // strategies.
19469        for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
19470            let mut spec = three_member_spec();
19471            spec.placement.estrategia = estrategia;
19472            spec.placement.shard_key = Some("tenantId".into());
19473            let err = spec.validate().unwrap_err();
19474            match err {
19475                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
19476                    assert_eq!(
19477                        e,
19478                        spec.placement.estrategia(),
19479                        "ShardKeyOnNonSharded.estrategia must byte-equal \
19480                         Placement::estrategia() — the non-Sharded-arm \
19481                         refusal reads through the lifted accessor",
19482                    );
19483                }
19484                other => panic!(
19485                    "expected ShardKeyOnNonSharded, got {other:?} for \
19486                     estrategia={estrategia:?}"
19487                ),
19488            }
19489        }
19490    }
19491
19492    // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
19493    //
19494    // The [`Placement::clusters`] accessor lift is the second slice-return
19495    // (`&[T]`) accessor on any typed slot — sibling to the seed M2
19496    // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
19497    // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
19498    // below cover (1) the accessor's byte-equal projection against the raw
19499    // field access across the empty / singleton / cohort fixtures the
19500    // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
19501    // and the per-cluster validate loop fan between, and (2) the two-
19502    // consumer coherence of the paired pre-flight refusal probe and the
19503    // per-cluster validate loop routing through the accessor on both arms.
19504
19505    #[test]
19506    fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
19507        // The canonical per-`:placement` cluster-pool-scalar-shape pin:
19508        // [`Placement::clusters`] must return the `:placement :clusters`
19509        // typed `Vec<String>` verbatim as a `&[String]` slice-view over
19510        // the same backing buffer the raw `self.clusters.as_slice()`
19511        // field access borrows from, byte-equal across every
19512        // representative fixture in the accept-set — the empty slice
19513        // (the pre-validation sentinel every
19514        // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
19515        // the singleton slice (the minimal `SingleNode`-shape cohort),
19516        // and multi-entry cohorts (the peer `Replicated` / `Sharded`
19517        // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
19518        //
19519        // Pins against a future silent detour that returned
19520        // `&Vec<String>` (which would type-check but leak the storage-
19521        // side `Vec`'s grow/push/reserve surface no consumer of the
19522        // typed view reaches for), a fresh-allocated `Vec<String>` copy
19523        // (which would type-check via a coercion but silently break
19524        // every downstream caller that relied on the slice sharing the
19525        // backing buffer's identity), or an out-of-order or length-
19526        // drifted projection (which would silently split the paired
19527        // pre-flight `.is_empty()` refusal probe's input from the per-
19528        // cluster validate loop's traversal input).
19529        //
19530        // Peer of the sibling M2
19531        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
19532        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
19533        // `:supervisor` static-child-list axis, extended onto the M3
19534        // per-`:placement` distribution-target-list `Vec`-carry axis.
19535        let fixtures: Vec<Vec<String>> = vec![
19536            Vec::new(),
19537            vec!["rio".into()],
19538            vec!["rio".into(), "mar".into()],
19539            vec!["rio".into(), "mar".into(), "plo".into()],
19540        ];
19541        for clusters in fixtures {
19542            let p = Placement {
19543                clusters: clusters.clone(),
19544                ..Placement::default()
19545            };
19546            assert_eq!(
19547                p.clusters(),
19548                clusters.as_slice(),
19549                "Placement::clusters must return :placement :clusters \
19550                 verbatim (got {:?}, expected {:?})",
19551                p.clusters(),
19552                clusters.as_slice(),
19553            );
19554            assert_eq!(
19555                p.clusters(),
19556                p.clusters.as_slice(),
19557                "Placement::clusters accessor and .clusters.as_slice() \
19558                 field access must byte-equal — the accessor is the \
19559                 substrate-primitive typed dispatch every downstream \
19560                 cluster-pool consumer must route through",
19561            );
19562            assert_eq!(
19563                p.clusters().len(),
19564                p.clusters.len(),
19565                "Placement::clusters().len() must byte-equal \
19566                 self.clusters.len() — a length-drift would silently \
19567                 split the paired pre-flight `.is_empty()` refusal \
19568                 probe input from the per-cluster validate loop's \
19569                 traversal input",
19570            );
19571        }
19572    }
19573
19574    #[test]
19575    fn validate_placement_reads_through_lifted_clusters_accessor() {
19576        // Two-consumer coherence pin: the
19577        // [`AplicacaoSpec::validate_placement`] pre-flight
19578        // `self.placement.clusters().is_empty()` refusal probe (which
19579        // must trip [`AplicacaoError::PlacementWithoutClusters`] when
19580        // the accessor projects the empty slice) and the per-cluster
19581        // validate loop's `for c in self.placement.clusters()`
19582        // traversal (which must reach every entry in the same order
19583        // the accessor projects, so both the per-entry value-shape
19584        // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
19585        // and the duplicate-detection HashSet insert that trips
19586        // [`AplicacaoError::PlacementClusterDuplicate`] key off the
19587        // accessor's projection) must both key off the lifted
19588        // accessor, so any future rebrand on the typed slot's reader
19589        // shape lands at exactly one place. Pins the two-site
19590        // coherence by exercising each production consumer end-to-end:
19591        // (1) the `PlacementWithoutClusters` refusal under the empty
19592        // slice, (2) the `PlacementClusterInvalid` refusal fires on
19593        // the second entry of a two-cluster cohort whose head is
19594        // valid but tail is not (which requires the loop to reach the
19595        // second entry through the accessor), and (3) the
19596        // `PlacementClusterDuplicate` refusal fires on the second
19597        // entry of a two-cluster cohort that shares a name (which
19598        // requires the loop to reach both entries — a first-entry-only
19599        // projection would silently pass since the dedup HashSet has
19600        // room for the first insert).
19601        //
19602        // Peer of the sibling M2
19603        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
19604        // (bc92bce) coherence pin on the per-`:supervisor` static-
19605        // child-list axis, extended onto the M3 per-`:placement`
19606        // distribution-target-list `Vec`-carry axis.
19607
19608        // (1) Pre-flight `.is_empty()` probe: the empty slice must
19609        // trip `PlacementWithoutClusters`.
19610        let mut spec = three_member_spec();
19611        spec.placement.clusters = Vec::new();
19612        match spec.validate().unwrap_err() {
19613            AplicacaoError::PlacementWithoutClusters { .. } => {}
19614            other => panic!("expected PlacementWithoutClusters, got {other:?}"),
19615        }
19616        assert!(
19617            spec.placement.clusters().is_empty(),
19618            "the pre-flight refusal input must be the empty slice per \
19619             the accessor's projection",
19620        );
19621
19622        // (2) Per-cluster validate loop: a two-cluster cohort with an
19623        // invalid tail entry must trip `PlacementClusterInvalid` on
19624        // the tail — the loop must reach the second entry through
19625        // the accessor.
19626        let mut spec = three_member_spec();
19627        spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
19628        match spec.validate().unwrap_err() {
19629            AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
19630                assert_eq!(
19631                    cluster, "BAD_CLUSTER",
19632                    "PlacementClusterInvalid.cluster must carry the \
19633                     tail entry the loop reached through the accessor",
19634                );
19635            }
19636            other => panic!("expected PlacementClusterInvalid, got {other:?}"),
19637        }
19638        assert_eq!(
19639            spec.placement.clusters().len(),
19640            2,
19641            "the per-cluster validate loop's traversal input must be \
19642             a two-element slice per the accessor's projection",
19643        );
19644
19645        // (3) Per-cluster validate loop: a two-cluster cohort that
19646        // shares a name must trip `PlacementClusterDuplicate` on the
19647        // second entry — the loop must reach both entries through the
19648        // accessor for the dedup HashSet's second insert to collide.
19649        let mut spec = three_member_spec();
19650        spec.placement.clusters = vec!["rio".into(), "rio".into()];
19651        match spec.validate().unwrap_err() {
19652            AplicacaoError::PlacementClusterDuplicate { cluster } => {
19653                assert_eq!(
19654                    cluster, "rio",
19655                    "PlacementClusterDuplicate.cluster must carry the \
19656                     shared cluster name verbatim",
19657                );
19658            }
19659            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
19660        }
19661        assert_eq!(
19662            spec.placement.clusters().len(),
19663            2,
19664            "the per-cluster validate loop's traversal input must be \
19665             a two-element slice per the accessor's projection",
19666        );
19667    }
19668
19669    #[test]
19670    fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
19671        // The canonical per-`:membros` member-list-slice-shape pin:
19672        // [`AplicacaoSpec::membros`] must return the `:membros` typed
19673        // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
19674        // same backing buffer the raw `self.membros.as_slice()` field
19675        // access borrows from, byte-equal across every representative
19676        // fixture in the accept-set — the empty slice (the pre-
19677        // validation sentinel every [`AplicacaoError::NoMembros`]
19678        // refusal keys off), the singleton slice (the minimal one-
19679        // Servico Aplicacao shape), and multi-entry cohorts (the peer
19680        // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
19681        // load-bearing identity of the application graph).
19682        //
19683        // Pins against a future silent detour that returned
19684        // `&Vec<Membro>` (which would type-check but leak the storage-
19685        // side `Vec`'s grow/push/reserve surface no consumer of the
19686        // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
19687        // (which would type-check via a coercion but silently break
19688        // every downstream caller that relied on the slice sharing the
19689        // backing buffer's identity), or an out-of-order or length-
19690        // drifted projection (which would silently split the paired
19691        // `HashSet<&str>` name-set seed's collect input from the
19692        // pre-flight `.is_empty()` refusal probe's input from the per-
19693        // member validate loop's traversal input from the
19694        // programs.yaml emitter's per-entry fan-out loop's input from
19695        // the `feira app graph` per-member print traversal's input).
19696        //
19697        // Peer of the sibling M2
19698        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
19699        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
19700        // `:supervisor` static-child-list axis and the sibling M3
19701        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
19702        // (a6e18d7) `&[String]` byte-equal pin on the per-
19703        // `:placement` distribution-target-list axis — extends the
19704        // slice-return-accessor byte-equal-projection discipline onto
19705        // the outermost M3 mesh-slot type's per-Aplicacao member-list
19706        // `Vec`-carry axis.
19707        let fixtures: Vec<Vec<Membro>> = vec![
19708            Vec::new(),
19709            vec![membro("catalog", "^0.1")],
19710            vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
19711            vec![
19712                membro("catalog", "^0.1"),
19713                membro("cart", "^0.1"),
19714                membro("payment", "^0.2"),
19715            ],
19716        ];
19717        for membros in fixtures {
19718            let s = AplicacaoSpec {
19719                membros: membros.clone(),
19720                contratos: Vec::new(),
19721                politicas: MeshPolicy::default(),
19722                placement: Placement::default(),
19723                entrada: None,
19724            };
19725            assert_eq!(
19726                s.membros(),
19727                membros.as_slice(),
19728                "AplicacaoSpec::membros must return :membros verbatim \
19729                 (got {:?}, expected {:?})",
19730                s.membros(),
19731                membros.as_slice(),
19732            );
19733            assert_eq!(
19734                s.membros(),
19735                s.membros.as_slice(),
19736                "AplicacaoSpec::membros accessor and .membros.as_slice() \
19737                 field access must byte-equal — the accessor is the \
19738                 substrate-primitive typed dispatch every downstream \
19739                 member-list consumer must route through",
19740            );
19741            assert_eq!(
19742                s.membros().len(),
19743                s.membros.len(),
19744                "AplicacaoSpec::membros().len() must byte-equal \
19745                 self.membros.len() — a length-drift would silently \
19746                 split the paired `HashSet<&str>` name-set seed's \
19747                 collect input from the pre-flight `.is_empty()` \
19748                 refusal probe input from the per-member validate \
19749                 loop's traversal input",
19750            );
19751        }
19752    }
19753
19754    #[test]
19755    fn validate_reads_through_lifted_membros_accessor() {
19756        // Three-consumer coherence pin: the
19757        // [`AplicacaoSpec::validate_membros`] pre-flight
19758        // `self.membros().is_empty()` refusal probe (which must trip
19759        // [`AplicacaoError::NoMembros`] when the accessor projects the
19760        // empty slice), the same method's per-member validate loop's
19761        // `for m in self.membros()` traversal (which must reach every
19762        // entry in the same order the accessor projects, so both the
19763        // per-entry empty-`:caixa` gate that trips
19764        // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
19765        // detection `insert_first_seen` that trips
19766        // [`AplicacaoError::MembroDuplicate`] key off the accessor's
19767        // projection), and the peer [`AplicacaoSpec::validate`]'s
19768        // `HashSet<&str>` name-set seed's
19769        // `self.membros().iter().map(Membro::nome).collect()` collect
19770        // input (which every `:contratos` `:de` / `:para` membership
19771        // lookup rejects an unknown name against) must all three key
19772        // off the lifted accessor, so any future rebrand on the typed
19773        // slot's reader shape lands at exactly one place. Pins the
19774        // three-site coherence by exercising each production consumer
19775        // end-to-end: (1) the `NoMembros` refusal under the empty
19776        // slice, (2) the `MembroCaixaEmpty` refusal fires on the
19777        // second entry of a two-member cohort whose head is valid but
19778        // tail has an empty `:caixa` (which requires the loop to
19779        // reach the second entry through the accessor), and (3) the
19780        // `MembroDuplicate` refusal fires on the second entry of a
19781        // two-member cohort that shares a `:caixa` name (which
19782        // requires the loop to reach both entries through the
19783        // accessor for the dedup HashSet's second insert to collide).
19784        //
19785        // Peer of the sibling M2
19786        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
19787        // (bc92bce) coherence pin on the per-`:supervisor` static-
19788        // child-list axis and the sibling M3
19789        // `validate_placement_reads_through_lifted_clusters_accessor`
19790        // (a6e18d7) coherence pin on the per-`:placement` distribution-
19791        // target-list axis — extends the slice-return-accessor
19792        // multi-consumer coherence discipline onto the outermost M3
19793        // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
19794
19795        // (1) Pre-flight `.is_empty()` probe: the empty slice must
19796        // trip `NoMembros`.
19797        let mut spec = three_member_spec();
19798        spec.membros = Vec::new();
19799        assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
19800        assert!(
19801            spec.membros().is_empty(),
19802            "the pre-flight refusal input must be the empty slice per \
19803             the accessor's projection",
19804        );
19805
19806        // (2) Per-member validate loop: a two-member cohort with an
19807        // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
19808        // the tail — the loop must reach the second entry through
19809        // the accessor.
19810        let mut spec = three_member_spec();
19811        spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
19812        assert_eq!(
19813            spec.validate().unwrap_err(),
19814            AplicacaoError::MembroCaixaEmpty,
19815        );
19816        assert_eq!(
19817            spec.membros().len(),
19818            2,
19819            "the per-member validate loop's traversal input must be \
19820             a two-element slice per the accessor's projection",
19821        );
19822
19823        // (3) Per-member validate loop: a two-member cohort that
19824        // shares a `:caixa` name must trip `MembroDuplicate` on the
19825        // second entry — the loop must reach both entries through the
19826        // accessor for the dedup HashSet's second insert to collide.
19827        let mut spec = three_member_spec();
19828        spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
19829        match spec.validate().unwrap_err() {
19830            AplicacaoError::MembroDuplicate { caixa } => {
19831                assert_eq!(
19832                    caixa, "catalog",
19833                    "MembroDuplicate.caixa must carry the shared \
19834                     member name verbatim",
19835                );
19836            }
19837            other => panic!("expected MembroDuplicate, got {other:?}"),
19838        }
19839        assert_eq!(
19840            spec.membros().len(),
19841            2,
19842            "the per-member validate loop's traversal input must be \
19843             a two-element slice per the accessor's projection",
19844        );
19845    }
19846
19847    #[test]
19848    fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
19849        // The canonical per-`:contratos` contract-list-slice-shape pin:
19850        // [`AplicacaoSpec::contratos`] must return the `:contratos`
19851        // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
19852        // slice-view over the same backing buffer the raw
19853        // `self.contratos.as_slice()` field access borrows from, byte-
19854        // equal across every representative fixture in the accept-set —
19855        // the empty slice (the pre-validation "internal-only mesh" shape
19856        // an Aplicacao whose members exchange no typed edges renders
19857        // through), the singleton slice (the minimal one-edge Aplicacao
19858        // shape), and multi-entry cohorts (the peer multi-edge shapes
19859        // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
19860        // of the application graph).
19861        //
19862        // Pins against a future silent detour that returned
19863        // `&Vec<WitContract>` (which would type-check but leak the
19864        // storage-side `Vec`'s grow/push/reserve surface no consumer of
19865        // the typed view reaches for), a fresh-allocated
19866        // `Vec<WitContract>` copy (which would type-check via a coercion
19867        // but silently break every downstream caller that relied on the
19868        // slice sharing the backing buffer's identity), or an out-of-
19869        // order or length-drifted projection (which would silently split
19870        // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
19871        // seed's traversal input from the `detect_sync_cycles` per-edge
19872        // adjacency-list seed's traversal input from the
19873        // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
19874        // BTreeMap grouping loop's traversal input from the
19875        // `feira app graph` per-contract print traversal's input).
19876        //
19877        // Peer of the immediately-adjacent sibling M3
19878        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
19879        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
19880        // node-list axis, the sibling M3
19881        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
19882        // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
19883        // distribution-target-list axis, and the sibling M2
19884        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
19885        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
19886        // `:supervisor` static-child-list axis — extends the slice-
19887        // return-accessor byte-equal-projection discipline onto the
19888        // outermost M3 mesh-slot type's per-Aplicacao contract-list
19889        // `Vec`-carry axis, closing the last unlifted per-
19890        // `AplicacaoSpec` `Vec`-carry axis.
19891        let fixtures: Vec<Vec<WitContract>> = vec![
19892            Vec::new(),
19893            vec![contract_http("cart", "catalog", "/products/:id")],
19894            vec![
19895                contract_http("cart", "catalog", "/products/:id"),
19896                contract_http("cart", "payment", "/charge"),
19897            ],
19898            vec![
19899                contract_http("cart", "catalog", "/products/:id"),
19900                contract_http("cart", "payment", "/charge"),
19901                contract_http("payment", "catalog", "/audit"),
19902            ],
19903        ];
19904        for contratos in fixtures {
19905            let s = AplicacaoSpec {
19906                membros: vec![
19907                    membro("catalog", "^0.1"),
19908                    membro("cart", "^0.1"),
19909                    membro("payment", "^0.2"),
19910                ],
19911                contratos: contratos.clone(),
19912                politicas: MeshPolicy::default(),
19913                placement: Placement::default(),
19914                entrada: None,
19915            };
19916            assert_eq!(
19917                s.contratos(),
19918                contratos.as_slice(),
19919                "AplicacaoSpec::contratos must return :contratos verbatim \
19920                 (got {:?}, expected {:?})",
19921                s.contratos(),
19922                contratos.as_slice(),
19923            );
19924            assert_eq!(
19925                s.contratos(),
19926                s.contratos.as_slice(),
19927                "AplicacaoSpec::contratos accessor and \
19928                 .contratos.as_slice() field access must byte-equal — \
19929                 the accessor is the substrate-primitive typed dispatch \
19930                 every downstream contract-list consumer must route \
19931                 through",
19932            );
19933            assert_eq!(
19934                s.contratos().len(),
19935                s.contratos.len(),
19936                "AplicacaoSpec::contratos().len() must byte-equal \
19937                 self.contratos.len() — a length-drift would silently \
19938                 split the paired per-edge validate-loop's traversal \
19939                 input from the sync-cycle adjacency-list seed's \
19940                 traversal input from the cilium_network_policies \
19941                 per-`(:de, :para)` BTreeMap grouping loop's traversal \
19942                 input from the `feira app graph` per-contract print \
19943                 traversal's input",
19944            );
19945        }
19946    }
19947
19948    #[test]
19949    fn validate_reads_through_lifted_contratos_accessor() {
19950        // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
19951        // per-`:contratos` validate-loop's `for c in self.contratos()`
19952        // traversal (which must reach every entry in the same order the
19953        // accessor projects, so both the per-entry
19954        // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
19955        // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
19956        // dedup `HashSet` insert key off the accessor's projection),
19957        // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
19958        // `for c in self.contratos()` adjacency-list seed (which drives
19959        // the sync-subgraph deadlock-detection gate via
19960        // [`AplicacaoError::SyncCycle`]), and the peer
19961        // [`caixa_mesh::cilium_network_policies`]'s
19962        // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
19963        // grouping loop (which drives the per-CNP fan-out) must all
19964        // three key off the lifted accessor, so any future rebrand on
19965        // the typed slot's reader shape lands at exactly one place. Pins
19966        // the three-site coherence by exercising the two caixa-core
19967        // production consumers end-to-end: (1) the empty-`:contratos`
19968        // slice must validate without a per-edge diagnostic (the
19969        // per-edge loop is a no-op under the empty projection), (2) the
19970        // `ContratoMemberMissing` refusal fires on the second entry of a
19971        // two-edge cohort whose head references a valid member but tail
19972        // references a phantom name (which requires the loop to reach
19973        // the second entry through the accessor), and (3) the
19974        // `SyncCycle` refusal fires on a self-referential two-edge
19975        // cohort through the sync-cycle detector's peer projection
19976        // (which requires the detector to iterate the accessor's
19977        // projection to add the back-edge to its adjacency list).
19978        //
19979        // Peer of the sibling M3
19980        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
19981        // three-consumer coherence pin on the per-`:membros` node-list
19982        // axis and the sibling M3
19983        // `validate_placement_reads_through_lifted_clusters_accessor`
19984        // (a6e18d7) coherence pin on the per-`:placement` distribution-
19985        // target-list axis — extends the slice-return-accessor multi-
19986        // consumer coherence discipline onto the outermost M3 mesh-slot
19987        // type's per-Aplicacao contract-list `Vec`-carry axis.
19988
19989        // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
19990        // and no per-edge diagnostic surfaces. Validate succeeds on
19991        // the well-formed `:membros` head.
19992        let mut spec = three_member_spec();
19993        spec.contratos = Vec::new();
19994        assert!(
19995            spec.validate().is_ok(),
19996            "empty :contratos must validate — the per-edge loop is a \
19997             no-op under the accessor's empty projection",
19998        );
19999        assert!(
20000            spec.contratos().is_empty(),
20001            "the per-edge validate loop's traversal input must be the \
20002             empty slice per the accessor's projection",
20003        );
20004
20005        // (2) Per-edge validate loop: a two-edge cohort whose tail
20006        // references a phantom `:para` member must trip
20007        // `ContratoMemberMissing` on the tail — the loop must reach
20008        // the second entry through the accessor for the membership
20009        // lookup to fail on the phantom name.
20010        let mut spec = three_member_spec();
20011        spec.contratos = vec![
20012            contract_http("cart", "catalog", "/products/:id"),
20013            contract_http("cart", "phantom", "/x"),
20014        ];
20015        let err = spec.validate().unwrap_err();
20016        assert!(
20017            matches!(
20018                err,
20019                AplicacaoError::ContratoMemberMissing { ref caixa }
20020                    if caixa == "phantom"
20021            ),
20022            "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
20023        );
20024        assert_eq!(
20025            spec.contratos().len(),
20026            2,
20027            "the per-edge validate loop's traversal input must be \
20028             a two-element slice per the accessor's projection",
20029        );
20030
20031        // (3) Sync-cycle detector: a two-edge synchronous cohort
20032        // whose second edge closes the sync-subgraph back onto the
20033        // first must trip [`AplicacaoError::ContratoCycle`] — the
20034        // detector must iterate the accessor's projection to add
20035        // both edges to its adjacency list, so a length-drift on
20036        // the accessor's projection would silently disagree with
20037        // the sync-cycle detector on which edge closes the loop.
20038        // Peer projection to the `validate` per-edge loop above:
20039        // the sync-cycle detector routes through the same lifted
20040        // accessor, so a rebrand of the reader shape lands at one
20041        // place. Uses a two-edge cohort (cart → catalog → cart)
20042        // because the per-edge `ContratoSelfLoop` gate fires before
20043        // the sync-cycle detector on a single self-referential edge
20044        // (`cart → cart`) — the cycle-detector's input must be a
20045        // multi-edge cohort for its per-edge traversal input to be
20046        // observably wider than the per-edge validate loop's input.
20047        let mut spec = three_member_spec();
20048        spec.contratos = vec![
20049            contract_http("cart", "catalog", "/products/:id"),
20050            contract_http("catalog", "cart", "/callback"),
20051        ];
20052        let err = spec.validate().unwrap_err();
20053        assert!(
20054            matches!(err, AplicacaoError::ContratoCycle { .. }),
20055            "expected ContratoCycle from the sync-cycle detector on a \
20056             two-edge back-edge cohort, got {err:?}",
20057        );
20058        assert_eq!(
20059            spec.contratos().len(),
20060            2,
20061            "the sync-cycle detector's traversal input must be a \
20062             two-element slice per the accessor's projection",
20063        );
20064    }
20065
20066    #[test]
20067    fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
20068        // The canonical per-`:politicas` outer-composite-reference-shape
20069        // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
20070        // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
20071        // the same backing storage the raw `&self.politicas` field
20072        // access borrows from, byte-equal across every representative
20073        // fixture in the accept-set — the default `MeshPolicy` (the
20074        // author-empty "no policy on any axis" shape whose
20075        // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
20076        // shapes carrying one axis at a time
20077        // (`{mtls_required, timeout, retries, circuit_breaker,
20078        // rate_limit}` — the minimal five-axis fan-out over the
20079        // per-axis lifted accessor family every downstream mesh-artifact
20080        // emitter dispatches on), and the multi-axis composite (the
20081        // canonical `three_member_spec` fixture's `{timeout, retries,
20082        // mtls_required}` triple — the load-bearing shape every
20083        // Aplicacao-scoped fixture in this suite constructs).
20084        //
20085        // Pins against a future silent detour that returned a fresh-
20086        // cloned `MeshPolicy` copy (which would type-check via a `Clone`
20087        // impl but silently break every downstream caller that relied
20088        // on the reference sharing the composite's backing identity), a
20089        // reference to an operator-resolved overlay (the future
20090        // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
20091        // acknowledges — its resolution must land at exactly this
20092        // accessor body, not silently divert the raw slot away from a
20093        // second consumer), or an axis-shuffled projection (a future
20094        // detour that swapped `timeout` and `retries` through the
20095        // accessor would silently split the paired `validate_politicas`
20096        // per-axis bracket-dispatch's traversal input from the peer
20097        // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
20098        // emitter's fan-out input from the peer
20099        // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
20100        // overlay emitter's fan-out input).
20101        //
20102        // Peer of the sibling M3
20103        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
20104        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
20105        // node-list `Vec`-carry axis and the sibling M3
20106        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
20107        // (0dcc926) `&[WitContract]` byte-equal pin on the per-
20108        // `:contratos` edge-list `Vec`-carry axis — extends the outer-
20109        // accessor byte-equal-projection discipline onto the outermost
20110        // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
20111        // reference axis, the first `&Composite`-return accessor on the
20112        // outer [`AplicacaoSpec`] type.
20113        let fixtures: Vec<MeshPolicy> = vec![
20114            MeshPolicy::default(),
20115            MeshPolicy {
20116                mtls_required: Some(true),
20117                ..MeshPolicy::default()
20118            },
20119            MeshPolicy {
20120                mtls_required: Some(false),
20121                ..MeshPolicy::default()
20122            },
20123            MeshPolicy {
20124                timeout: Some(Duration::from_secs(30)),
20125                ..MeshPolicy::default()
20126            },
20127            MeshPolicy {
20128                retries: Some(3),
20129                ..MeshPolicy::default()
20130            },
20131            MeshPolicy {
20132                circuit_breaker: Some(CircuitBreaker {
20133                    max_failures: 5,
20134                    window: Duration::from_secs(30),
20135                }),
20136                ..MeshPolicy::default()
20137            },
20138            MeshPolicy {
20139                rate_limit: Some(RateLimit {
20140                    rate: 100,
20141                    window: Duration::from_secs(1),
20142                }),
20143                ..MeshPolicy::default()
20144            },
20145            MeshPolicy {
20146                timeout: Some(Duration::from_secs(30)),
20147                retries: Some(3),
20148                mtls_required: Some(true),
20149                ..MeshPolicy::default()
20150            },
20151        ];
20152        for politicas in fixtures {
20153            let s = AplicacaoSpec {
20154                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
20155                contratos: Vec::new(),
20156                politicas: politicas.clone(),
20157                placement: Placement::default(),
20158                entrada: None,
20159            };
20160            assert_eq!(
20161                *s.politicas(),
20162                politicas,
20163                "AplicacaoSpec::politicas must return :politicas verbatim \
20164                 (got {:?}, expected {:?})",
20165                s.politicas(),
20166                politicas,
20167            );
20168            assert!(
20169                std::ptr::eq(s.politicas(), &s.politicas),
20170                "AplicacaoSpec::politicas accessor and &self.politicas \
20171                 field access must borrow the same backing storage — \
20172                 the accessor is the substrate-primitive typed dispatch \
20173                 every downstream mesh-policy composite consumer must \
20174                 route through, and a reference-identity split would \
20175                 silently break every consumer that relied on the \
20176                 borrow sharing the composite's storage",
20177            );
20178            assert_eq!(
20179                s.politicas().is_empty(),
20180                s.politicas.is_empty(),
20181                "AplicacaoSpec::politicas().is_empty() must byte-equal \
20182                 self.politicas.is_empty() — an emptiness-drift would \
20183                 silently split the paired `validate_politicas` \
20184                 per-axis bracket-dispatch's seed from the peer \
20185                 caixa-mesh CNP mTLS-overlay emitter's key from the \
20186                 peer caixa-mesh HTTPRoute timeout+retry overlay \
20187                 emitter's key",
20188            );
20189        }
20190    }
20191
20192    #[test]
20193    fn validate_politicas_reads_through_lifted_politicas_accessor() {
20194        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
20195        // per-axis bracket-dispatch seed (`let p = self.politicas();`,
20196        // followed by the per-axis fan-out `p.timeout()` /
20197        // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
20198        // the lifted axis-level accessor family) must key off the
20199        // lifted outer accessor, so any future rebrand on the typed
20200        // slot's outer-composite reader shape lands at exactly one
20201        // place. Pins the multi-axis coherence by exercising each
20202        // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
20203        // a `Some(Duration::ZERO)` timeout under the outer accessor's
20204        // reference projection, (2) `PolicyRetriesZero` fires on a
20205        // `Some(0)` retries under the same projection, and (3) an
20206        // empty [`MeshPolicy::default`] passes `validate_politicas` —
20207        // the outer accessor's reference-projection reaches every
20208        // per-axis branch without silently short-circuiting any.
20209        //
20210        // Peer of the sibling M3
20211        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
20212        // three-consumer coherence pin on the per-`:membros` node-list
20213        // axis and the sibling M3
20214        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
20215        // three-consumer coherence pin on the per-`:contratos`
20216        // edge-list axis — extends the multi-consumer coherence
20217        // discipline onto the outermost M3 mesh-slot type's per-
20218        // Aplicacao mesh-policy composite-reference axis, the first
20219        // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
20220        // type.
20221
20222        // (1) `PolicyTimeoutZero` refusal under the outer accessor's
20223        // reference projection: a `Some(Duration::ZERO)` timeout must
20224        // trip the zero-floor gate. The bracket-dispatch's first arm
20225        // reads `p.timeout()` on the reference returned by the outer
20226        // accessor.
20227        let mut spec = three_member_spec();
20228        spec.politicas.timeout = Some(Duration::ZERO);
20229        spec.politicas.retries = None;
20230        spec.politicas.circuit_breaker = None;
20231        spec.politicas.rate_limit = None;
20232        assert_eq!(
20233            spec.validate().unwrap_err(),
20234            AplicacaoError::PolicyTimeoutZero,
20235        );
20236        assert!(
20237            std::ptr::eq(spec.politicas(), &spec.politicas),
20238            "the `validate_politicas` per-axis bracket-dispatch's \
20239             traversal input must be the same backing composite the \
20240             accessor's reference projection borrows from",
20241        );
20242
20243        // (2) `PolicyRetriesZero` refusal under the outer accessor's
20244        // reference projection: a `Some(0)` retries must trip the
20245        // zero-floor gate. The bracket-dispatch's second arm reads
20246        // `p.retries()` on the reference returned by the outer accessor.
20247        let mut spec = three_member_spec();
20248        spec.politicas.timeout = None;
20249        spec.politicas.retries = Some(0);
20250        spec.politicas.circuit_breaker = None;
20251        spec.politicas.rate_limit = None;
20252        assert_eq!(
20253            spec.validate().unwrap_err(),
20254            AplicacaoError::PolicyRetriesZero,
20255        );
20256
20257        // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
20258        // — every per-axis arm short-circuits on `None`, so the outer
20259        // accessor's reference projection reaches the fall-through
20260        // `Ok(())` without any per-axis refusal firing.
20261        let mut spec = three_member_spec();
20262        spec.politicas = MeshPolicy::default();
20263        assert!(
20264            spec.validate().is_ok(),
20265            "an empty `MeshPolicy` must pass `validate_politicas` — \
20266             every per-axis arm short-circuits on `None` under the \
20267             outer accessor's reference projection",
20268        );
20269        assert!(
20270            spec.politicas().is_empty(),
20271            "the outer accessor's reference projection must be the \
20272             empty composite per the `MeshPolicy::default()` fixture",
20273        );
20274    }
20275
20276    #[test]
20277    #[allow(clippy::too_many_lines)]
20278    fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
20279        // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
20280        // per-axis bracket-dispatch's `:timeout` and `:retries` arms
20281        // must both key off the lifted axis-level accessors
20282        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
20283        // the peer `:circuit-breaker` / `:rate-limit` arms already
20284        // routing through [`MeshPolicy::circuit_breaker`] /
20285        // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
20286        // per axis on the substrate primitive" shape at the fan-out
20287        // (four axes, four accessors, no raw-field-access site
20288        // anywhere on the bracket-dispatch). Pins the per-axis
20289        // coherence at the accept-set boundaries the bracket carves:
20290        //   1. accessor byte-equal to raw field on every representative
20291        //      accept-set value (`None`, sub-cap, at-cap, past-cap
20292        //      sentinel) — a future accessor drift that no longer
20293        //      shipped the raw slot verbatim would surface here,
20294        //   2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
20295        //      routed through the accessor's projection, proving the
20296        //      first arm reads through the accessor rather than a
20297        //      silent-detour peer-axis field access,
20298        //   3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
20299        //      through the accessor's projection, proving the second
20300        //      arm reads through the accessor,
20301        //   4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
20302        //      passes validate under the accessor projection (paired
20303        //      with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
20304        //      sibling axis), pinning the upper-boundary accept-arm
20305        //      also routes through the accessor.
20306        //
20307        // Peer of the sibling M3
20308        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
20309        // outer-composite-reference coherence pin (which asserts the
20310        // `let p = self.politicas()` seed); extends the discipline onto
20311        // the per-axis fan-out layer that consumes the seed's
20312        // reference. Same shape as
20313        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
20314        // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
20315        // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
20316        // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
20317
20318        // (1) Accessor byte-equal to raw field on the `:timeout` axis
20319        // across the accept-set boundaries the bracket dispatch's
20320        // three-arm gate carves out
20321        // ([`crate::render::require_positive_canonical_bounded_duration`]
20322        // — zero-floor + canonical-form + upper-cap).
20323        for timeout in [
20324            None,
20325            Some(Duration::ZERO),
20326            Some(Duration::from_millis(1)),
20327            Some(POLICY_TIMEOUT_MAX),
20328        ] {
20329            let p = MeshPolicy {
20330                timeout,
20331                ..MeshPolicy::default()
20332            };
20333            assert_eq!(
20334                p.timeout(),
20335                p.timeout,
20336                "MeshPolicy::timeout accessor must byte-equal the raw \
20337                 .timeout field across every accept-set boundary the \
20338                 validate_politicas :timeout arm carves out — a drift \
20339                 here would silently split the validate bracket's arm \
20340                 from the peer caixa-mesh HTTPRoute timeout-overlay \
20341                 emitter's read",
20342            );
20343        }
20344
20345        // (2) Accessor byte-equal to raw field on the `:retries` axis
20346        // across the accept-set boundaries the bracket dispatch's
20347        // two-arm gate carves out
20348        // ([`crate::render::require_positive_bounded_u32`] — zero-floor
20349        // + upper-cap).
20350        for retries in [
20351            None,
20352            Some(0u32),
20353            Some(1u32),
20354            Some(POLICY_RETRIES_MAX),
20355            Some(POLICY_RETRIES_MAX + 1),
20356            Some(u32::MAX),
20357        ] {
20358            let p = MeshPolicy {
20359                retries,
20360                ..MeshPolicy::default()
20361            };
20362            assert_eq!(
20363                p.retries(),
20364                p.retries,
20365                "MeshPolicy::retries accessor must byte-equal the raw \
20366                 .retries field across every accept-set boundary the \
20367                 validate_politicas :retries arm carves out — a drift \
20368                 here would silently split the validate bracket's arm \
20369                 from the peer caixa-mesh HTTPRoute retry-overlay \
20370                 emitter's read",
20371            );
20372        }
20373
20374        // (3) `PolicyTimeoutZero` fires on the accessor-projected
20375        // zero-floor boundary. A silent detour that no longer read
20376        // through `p.timeout()` (a peer-axis field read, an accidental
20377        // Option::and-then chain that collapsed the None arm to Some,
20378        // an accessor rebrand that clamped the return through the
20379        // upper cap) would fail to refuse here.
20380        let mut spec = three_member_spec();
20381        spec.politicas.timeout = Some(Duration::ZERO);
20382        spec.politicas.retries = None;
20383        spec.politicas.circuit_breaker = None;
20384        spec.politicas.rate_limit = None;
20385        assert_eq!(
20386            spec.politicas().timeout(),
20387            Some(Duration::ZERO),
20388            "the accessor projection must reflect the fixture's \
20389             `Some(Duration::ZERO)` :timeout verbatim",
20390        );
20391        assert_eq!(
20392            spec.validate().unwrap_err(),
20393            AplicacaoError::PolicyTimeoutZero,
20394            "the validate_politicas :timeout zero-floor arm must fire \
20395             through the lifted accessor's projection — a silent \
20396             detour to a peer-axis field would fail to refuse",
20397        );
20398
20399        // (4) `PolicyRetriesZero` fires on the accessor-projected
20400        // zero-floor boundary on the sibling `:retries` axis.
20401        let mut spec = three_member_spec();
20402        spec.politicas.timeout = None;
20403        spec.politicas.retries = Some(0);
20404        spec.politicas.circuit_breaker = None;
20405        spec.politicas.rate_limit = None;
20406        assert_eq!(
20407            spec.politicas().retries(),
20408            Some(0),
20409            "the accessor projection must reflect the fixture's \
20410             `Some(0)` :retries verbatim",
20411        );
20412        assert_eq!(
20413            spec.validate().unwrap_err(),
20414            AplicacaoError::PolicyRetriesZero,
20415            "the validate_politicas :retries zero-floor arm must fire \
20416             through the lifted accessor's projection — a silent \
20417             detour to a peer-axis field would fail to refuse",
20418        );
20419
20420        // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
20421        // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
20422        // must pass validate under the accessor projection — pins the
20423        // upper-boundary accept-arm also routes through the lifted
20424        // accessor (a drift that clamped or short-circuited at the
20425        // upper boundary would fail the whole-spec validate here).
20426        let mut spec = three_member_spec();
20427        spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
20428        spec.politicas.retries = Some(POLICY_RETRIES_MAX);
20429        spec.politicas.circuit_breaker = None;
20430        spec.politicas.rate_limit = None;
20431        assert_eq!(
20432            spec.politicas().timeout(),
20433            Some(POLICY_TIMEOUT_MAX),
20434            "the accessor projection must reflect the fixture's \
20435             at-cap :timeout verbatim",
20436        );
20437        assert_eq!(
20438            spec.politicas().retries(),
20439            Some(POLICY_RETRIES_MAX),
20440            "the accessor projection must reflect the fixture's \
20441             at-cap :retries verbatim",
20442        );
20443        assert!(
20444            spec.validate().is_ok(),
20445            "at-cap :timeout + :retries must pass validate under the \
20446             accessor projection — the upper-boundary accept-arm on \
20447             both axes routes through the lifted accessor",
20448        );
20449    }
20450
20451    #[test]
20452    fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
20453        // The canonical per-`:placement` outer-composite-reference-shape
20454        // pin: [`AplicacaoSpec::placement`] must return the `:placement`
20455        // typed `Placement` verbatim as a `&Placement` reference over the
20456        // same backing storage the raw `&self.placement` field access
20457        // borrows from, byte-equal across every representative fixture in
20458        // the accept-set — the default `Placement` (the substrate seed
20459        // shape whose [`PlacementStrategy::default`] evaluates to
20460        // `SingleNode` with an empty `:clusters` pool and both
20461        // optional-scalar axes `None`), and every canonical strategy /
20462        // cluster-pool / optional-scalar combination the
20463        // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
20464        // three [`PlacementStrategy`] variants — `SingleNode`,
20465        // `Replicated`, `Sharded` — cross-projected with a non-empty
20466        // `:clusters` pool and, on the `Sharded` arm, a non-empty
20467        // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
20468        // canonical `three_member_spec` `Replicated` fixture's
20469        // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
20470        //
20471        // Pins against a future silent detour that returned a fresh-
20472        // cloned `Placement` copy (which would type-check via a `Clone`
20473        // impl but silently break every downstream caller that relied on
20474        // the reference sharing the composite's backing identity), a
20475        // reference to an operator-resolved overlay (the future per-
20476        // cluster `:placement-overrides` slot MESH-COMPOSITION §V
20477        // acknowledges — its resolution must land at exactly this
20478        // accessor body, not silently divert the raw slot away from a
20479        // second consumer), or an axis-shuffled projection (a future
20480        // detour that swapped `clusters` and `affinity` through the
20481        // accessor would silently split the paired `validate_placement`
20482        // per-axis bracket-dispatch's traversal input from the peer
20483        // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
20484        // programs.yaml distribution-annotation emitter's fan-out input
20485        // from the peer `feira app graph` per-Aplicacao print line's
20486        // input).
20487        //
20488        // Peer of the sibling M3
20489        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
20490        // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
20491        // outer mesh-policy composite-reference axis, and of the sibling
20492        // slice-return `aplicacao_spec_membros_returns_membros_slice_
20493        // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
20494        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
20495        // across_permutations` (0dcc926) `&[WitContract]` pins — extends
20496        // the outer-accessor byte-equal-projection discipline onto the
20497        // outermost M3 mesh-slot type's per-Aplicacao distribution
20498        // composite-reference axis, the second `&Composite`-return
20499        // accessor on the outer [`AplicacaoSpec`] type.
20500        let fixtures: Vec<Placement> = vec![
20501            Placement::default(),
20502            Placement {
20503                estrategia: PlacementStrategy::SingleNode,
20504                clusters: vec!["rio".into()],
20505                affinity: None,
20506                shard_key: None,
20507            },
20508            Placement {
20509                estrategia: PlacementStrategy::Replicated,
20510                clusters: vec!["rio".into(), "mar".into()],
20511                affinity: None,
20512                shard_key: None,
20513            },
20514            Placement {
20515                estrategia: PlacementStrategy::Replicated,
20516                clusters: vec!["rio".into(), "mar".into()],
20517                affinity: Some("data-locality".into()),
20518                shard_key: None,
20519            },
20520            Placement {
20521                estrategia: PlacementStrategy::Sharded,
20522                clusters: vec!["rio".into(), "mar".into()],
20523                affinity: None,
20524                shard_key: Some("tenantId".into()),
20525            },
20526            Placement {
20527                estrategia: PlacementStrategy::Sharded,
20528                clusters: vec!["rio".into(), "mar".into(), "sol".into()],
20529                affinity: Some("low-latency".into()),
20530                shard_key: Some("metadata.tenantId".into()),
20531            },
20532        ];
20533        for placement in fixtures {
20534            let s = AplicacaoSpec {
20535                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
20536                contratos: Vec::new(),
20537                politicas: MeshPolicy::default(),
20538                placement: placement.clone(),
20539                entrada: None,
20540            };
20541            assert_eq!(
20542                *s.placement(),
20543                placement,
20544                "AplicacaoSpec::placement must return :placement verbatim \
20545                 (got {:?}, expected {:?})",
20546                s.placement(),
20547                placement,
20548            );
20549            assert!(
20550                std::ptr::eq(s.placement(), &s.placement),
20551                "AplicacaoSpec::placement accessor and &self.placement \
20552                 field access must borrow the same backing storage — the \
20553                 accessor is the substrate-primitive typed dispatch every \
20554                 downstream distribution-composite consumer must route \
20555                 through, and a reference-identity split would silently \
20556                 break every consumer that relied on the borrow sharing \
20557                 the composite's storage",
20558            );
20559            assert_eq!(
20560                s.placement().estrategia(),
20561                s.placement.estrategia,
20562                "AplicacaoSpec::placement().estrategia() must byte-equal \
20563                 self.placement.estrategia — a strategy-drift would \
20564                 silently split the paired `validate_placement` \
20565                 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
20566                 peer caixa-mesh programs.yaml `placement.estrategia` \
20567                 emitter's key from the peer `feira app graph` printer's \
20568                 strategy label",
20569            );
20570            assert_eq!(
20571                s.placement().clusters(),
20572                s.placement.clusters.as_slice(),
20573                "AplicacaoSpec::placement().clusters() must byte-equal \
20574                 self.placement.clusters — a cluster-pool drift would \
20575                 silently split the paired `validate_placement` \
20576                 pre-flight `.is_empty()` refusal probe's traversal from \
20577                 the peer caixa-mesh programs.yaml `placement.clusters` \
20578                 emitter's fan-out from the peer `feira app graph` \
20579                 printer's cluster list",
20580            );
20581        }
20582    }
20583
20584    #[test]
20585    fn validate_placement_reads_through_lifted_placement_accessor() {
20586        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
20587        // per-axis bracket-dispatch seed (`let p = self.placement();`,
20588        // followed by the per-axis fan-out `p.clusters()` /
20589        // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
20590        // lifted axis-level accessor family) must key off the lifted
20591        // outer accessor, so any future rebrand on the typed slot's
20592        // outer-composite reader shape lands at exactly one place. Pins
20593        // the multi-axis coherence by exercising each per-axis refusal
20594        // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
20595        // `:clusters` pool under the outer accessor's reference
20596        // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
20597        // strategy with a `None` `:shard-key` under the same projection,
20598        // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
20599        // with a `Some` `:shard-key` under the same projection, and
20600        // (4) the canonical `three_member_spec` `Replicated` fixture
20601        // passes `validate_placement` under the outer accessor's
20602        // reference projection — the accessor's reference-projection
20603        // reaches every per-axis branch (cluster-pool refusal, `Sharded`
20604        // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
20605        // without silently short-circuiting any.
20606        //
20607        // Peer of the sibling M3
20608        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
20609        // (534dc21) multi-axis coherence pin on the per-`:politicas`
20610        // outer mesh-policy composite-reference axis — extends the
20611        // multi-consumer coherence discipline onto the outermost M3
20612        // mesh-slot type's per-Aplicacao distribution composite-
20613        // reference axis, the second `&Composite`-return accessor on
20614        // the outer [`AplicacaoSpec`] type.
20615
20616        // (1) `PlacementWithoutClusters` refusal under the outer
20617        // accessor's reference projection: an empty `:clusters` pool
20618        // must trip the pre-flight refusal probe. The bracket-dispatch's
20619        // first arm reads `p.clusters()` on the reference returned by
20620        // the outer accessor.
20621        let mut spec = three_member_spec();
20622        spec.placement.clusters = Vec::new();
20623        assert_eq!(
20624            spec.validate().unwrap_err(),
20625            AplicacaoError::PlacementWithoutClusters {
20626                estrategia: PlacementStrategy::Replicated,
20627            },
20628        );
20629        assert!(
20630            std::ptr::eq(spec.placement(), &spec.placement),
20631            "the `validate_placement` per-axis bracket-dispatch's \
20632             traversal input must be the same backing composite the \
20633             accessor's reference projection borrows from",
20634        );
20635
20636        // (2) `ShardedWithoutKey` refusal under the outer accessor's
20637        // reference projection: a `Sharded` strategy with a `None`
20638        // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
20639        // The bracket-dispatch's third arm reads `p.estrategia()` for
20640        // the match scrutinee then `p.shard_key()` for the cascade
20641        // scrutinee, both on the reference returned by the outer
20642        // accessor.
20643        let mut spec = three_member_spec();
20644        spec.placement.estrategia = PlacementStrategy::Sharded;
20645        spec.placement.shard_key = None;
20646        assert_eq!(
20647            spec.validate().unwrap_err(),
20648            AplicacaoError::ShardedWithoutKey,
20649        );
20650
20651        // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
20652        // reference projection: a non-`Sharded` strategy with a `Some`
20653        // `:shard-key` must trip the declared-but-inert refusal. The
20654        // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
20655        // + `p.estrategia()` for the diagnostic on the reference
20656        // returned by the outer accessor.
20657        let mut spec = three_member_spec();
20658        spec.placement.estrategia = PlacementStrategy::Replicated;
20659        spec.placement.shard_key = Some("tenantId".into());
20660        assert_eq!(
20661            spec.validate().unwrap_err(),
20662            AplicacaoError::ShardKeyOnNonSharded {
20663                estrategia: PlacementStrategy::Replicated,
20664                shard_key: "tenantId".into(),
20665            },
20666        );
20667
20668        // (4) Canonical `three_member_spec` `Replicated` fixture passes
20669        // `validate_placement` — every per-axis arm reaches the fall-
20670        // through `Ok(())` without any per-axis refusal firing under the
20671        // outer accessor's reference projection.
20672        let spec = three_member_spec();
20673        assert!(
20674            spec.validate().is_ok(),
20675            "the canonical Replicated placement fixture must pass \
20676             `validate_placement` — every per-axis arm short-circuits on \
20677             valid input under the outer accessor's reference projection",
20678        );
20679        assert_eq!(
20680            spec.placement().estrategia(),
20681            PlacementStrategy::Replicated,
20682            "the outer accessor's reference projection must be the \
20683             canonical Replicated fixture's strategy",
20684        );
20685        assert_eq!(
20686            spec.placement().clusters(),
20687            &["rio", "mar"],
20688            "the outer accessor's reference projection must be the \
20689             canonical Replicated fixture's cluster pool",
20690        );
20691    }
20692
20693    #[test]
20694    fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
20695        // The canonical per-`:entrada` outer-composite-optional-
20696        // reference-shape pin: [`AplicacaoSpec::entrada`] must return
20697        // the `:entrada` typed `Option<Entrada>` verbatim as an
20698        // `Option<&Entrada>` reference over the same backing storage
20699        // the raw `self.entrada.as_ref()` field access borrows from,
20700        // byte-equal across every representative fixture in the
20701        // accept-set — the author-omitted `None` shape (the
20702        // "internal-only mesh" partition every downstream external-
20703        // gateway emitter treats as "emit nothing"), the minimal
20704        // singleton `:entrada` composite (host + destination + empty
20705        // paths + default port), the paths-carrying composite (the
20706        // canonical `three_member_spec` fixture's ["/api" "/health"]
20707        // path-list shape every HTTPRoute per-rule fan-out emitter
20708        // reads), and the non-default port composite (the canonical
20709        // custom-port shape the port-fallback resolver reads).
20710        //
20711        // Pins against a future silent detour that returned a fresh-
20712        // cloned `Entrada` copy (which would type-check via a `Clone`
20713        // impl but silently break every downstream caller that
20714        // relied on the reference sharing the composite's backing
20715        // identity), a reference to an operator-resolved overlay
20716        // (the future per-cluster `:entrada-overrides` slot the
20717        // MESH-COMPOSITION §V federation roadmap acknowledges — its
20718        // resolution must land at exactly this accessor body, not
20719        // silently divert the raw slot away from a second consumer),
20720        // a `None` → `Some(Entrada::default)` cluster-default
20721        // projection (which would collapse the load-bearing
20722        // "author-omitted `:entrada` ⇒ internal-only mesh" partition
20723        // the peer `gateway_routes` early-return + `feira app graph`
20724        // internal-only-mesh partition both read), or an axis-
20725        // shuffled projection (a future detour that swapped
20726        // `host` and `para` through the accessor would silently
20727        // split the paired `validate` per-`:entrada` shape-and-
20728        // membership gate's traversal input from the peer
20729        // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
20730        // fan-out input from the peer `feira app graph` external-
20731        // gateway summary line).
20732        //
20733        // Peer of the sibling M3
20734        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
20735        // (534dc21) `&MeshPolicy` byte-equal pin on the per-
20736        // `:politicas` outer mesh-policy composite-reference axis
20737        // and of the sibling M3
20738        // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
20739        // (9abb8f0) `&Placement` byte-equal pin on the per-
20740        // `:placement` outer distribution-composite composite-
20741        // reference axis — extends the outer-accessor byte-equal-
20742        // projection discipline onto the last unlifted outermost M3
20743        // mesh-slot type's per-Aplicacao external-gateway composite-
20744        // reference axis, the third and final `&Composite`-return
20745        // accessor on the outer [`AplicacaoSpec`] type.
20746        let fixtures: Vec<Option<Entrada>> = vec![
20747            None,
20748            Some(Entrada {
20749                host: "checkout.quero.cloud".into(),
20750                para: "cart".into(),
20751                paths: Vec::new(),
20752                port: DEFAULT_SERVICO_PORT,
20753            }),
20754            Some(Entrada {
20755                host: "checkout.quero.cloud".into(),
20756                para: "cart".into(),
20757                paths: vec!["/api".into(), "/health".into()],
20758                port: DEFAULT_SERVICO_PORT,
20759            }),
20760            Some(Entrada {
20761                host: "checkout.quero.cloud".into(),
20762                para: "cart".into(),
20763                paths: vec!["/api".into()],
20764                port: 9443,
20765            }),
20766        ];
20767        for entrada in fixtures {
20768            let s = AplicacaoSpec {
20769                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
20770                contratos: Vec::new(),
20771                politicas: MeshPolicy::default(),
20772                placement: Placement::default(),
20773                entrada: entrada.clone(),
20774            };
20775            assert_eq!(
20776                s.entrada(),
20777                entrada.as_ref(),
20778                "AplicacaoSpec::entrada must return :entrada verbatim \
20779                 (got {:?}, expected {:?})",
20780                s.entrada(),
20781                entrada.as_ref(),
20782            );
20783            match (s.entrada(), s.entrada.as_ref()) {
20784                (Some(a), Some(b)) => assert!(
20785                    std::ptr::eq(a, b),
20786                    "AplicacaoSpec::entrada accessor and \
20787                     self.entrada.as_ref() field access must borrow \
20788                     the same backing storage — the accessor is the \
20789                     substrate-primitive typed dispatch every \
20790                     downstream external-gateway composite consumer \
20791                     must route through, and a reference-identity \
20792                     split would silently break every consumer that \
20793                     relied on the borrow sharing the composite's \
20794                     storage",
20795                ),
20796                (None, None) => {}
20797                _ => panic!(
20798                    "AplicacaoSpec::entrada presence bit must byte-\
20799                     equal self.entrada.is_some() — a presence-bit \
20800                     drift would silently split the paired `validate` \
20801                     per-`:entrada` shape-and-membership gate's \
20802                     traversal head from the peer \
20803                     caixa-mesh gateway_routes early-return partition \
20804                     from the peer `feira app graph` internal-only-\
20805                     mesh partition",
20806                ),
20807            }
20808            assert_eq!(
20809                s.entrada().is_some(),
20810                s.entrada.is_some(),
20811                "AplicacaoSpec::entrada().is_some() must byte-equal \
20812                 self.entrada.is_some() — a presence-bit drift would \
20813                 silently split every downstream `Option<&Entrada>` \
20814                 consumer's partition on the internal-only-mesh arm",
20815            );
20816        }
20817    }
20818
20819    #[test]
20820    fn validate_reads_through_lifted_entrada_accessor() {
20821        // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
20822        // per-`:entrada` shape-and-membership gate (`if let Some(e) =
20823        // self.entrada() { … }`, followed by the per-axis fan-out
20824        // `validate_entrada_para(&e.para)` /
20825        // `EntradaMemberMissing` membership lookup /
20826        // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
20827        // per-`e.paths` `validate_entrada_path` traversal) must key
20828        // off the lifted outer accessor, so any future rebrand on
20829        // the typed slot's outer-composite reader shape lands at
20830        // exactly one place. Pins the multi-axis coherence by
20831        // exercising each per-axis refusal end-to-end: (1) the
20832        // author-omitted `None` shape short-circuits past every
20833        // per-`:entrada` refusal (the internal-only mesh partition
20834        // the accessor's `None` arm names), (2) `EntradaMemberMissing`
20835        // fires on a well-shaped but phantom `:para` under the outer
20836        // accessor's reference projection, and (3) the canonical
20837        // `three_member_spec` `:entrada` fixture passes `validate`
20838        // under the outer accessor's reference projection.
20839        //
20840        // Peer of the sibling M3
20841        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
20842        // (534dc21) multi-axis coherence pin on the per-`:politicas`
20843        // outer mesh-policy composite-reference axis and the sibling
20844        // M3
20845        // [`validate_placement_reads_through_lifted_placement_accessor`]
20846        // (9abb8f0) multi-axis coherence pin on the per-`:placement`
20847        // outer distribution-composite composite-reference axis —
20848        // extends the multi-consumer coherence discipline onto the
20849        // last unlifted outermost M3 mesh-slot type's per-Aplicacao
20850        // external-gateway composite-reference axis, the third and
20851        // final `&Composite`-return accessor on the outer
20852        // [`AplicacaoSpec`] type.
20853
20854        // (1) `None` :entrada — the internal-only-mesh partition
20855        // short-circuits past every per-`:entrada` refusal. The outer
20856        // accessor's reference projection reaches the fall-through
20857        // `Ok(())` on the `None` arm without any per-axis refusal
20858        // firing.
20859        let mut spec = three_member_spec();
20860        spec.entrada = None;
20861        assert!(
20862            spec.validate().is_ok(),
20863            "an author-omitted `:entrada` must pass `validate` — the \
20864             internal-only-mesh partition short-circuits past every \
20865             per-`:entrada` refusal under the outer accessor's \
20866             reference projection",
20867        );
20868        assert!(
20869            spec.entrada().is_none(),
20870            "the outer accessor's reference projection must name the \
20871             internal-only-mesh partition per the `None` fixture",
20872        );
20873
20874        // (2) `EntradaMemberMissing` refusal under the outer accessor's
20875        // reference projection: a well-shaped but phantom `:para` must
20876        // trip the membership-lookup refusal. The gate's second arm
20877        // reads `e.para` on the reference returned by the outer
20878        // accessor.
20879        let mut spec = three_member_spec();
20880        if let Some(e) = spec.entrada.as_mut() {
20881            e.para = "phantom".into();
20882        }
20883        assert_eq!(
20884            spec.validate().unwrap_err(),
20885            AplicacaoError::EntradaMemberMissing {
20886                para: "phantom".into(),
20887            },
20888        );
20889        match (spec.entrada(), spec.entrada.as_ref()) {
20890            (Some(a), Some(b)) => assert!(
20891                std::ptr::eq(a, b),
20892                "the `validate` per-`:entrada` gate's traversal head \
20893                 must be the same backing composite the accessor's \
20894                 reference projection borrows from",
20895            ),
20896            _ => panic!("fixture must carry Some(:entrada)"),
20897        }
20898
20899        // (3) Canonical `three_member_spec` `:entrada` fixture passes
20900        // `validate` — every per-axis arm reaches the fall-through
20901        // `Ok(())` without any per-axis refusal firing under the
20902        // outer accessor's reference projection.
20903        let spec = three_member_spec();
20904        assert!(
20905            spec.validate().is_ok(),
20906            "the canonical `:entrada` fixture must pass `validate` — \
20907             every per-axis arm short-circuits on valid input under \
20908             the outer accessor's reference projection",
20909        );
20910        assert!(
20911            spec.entrada().is_some(),
20912            "the outer accessor's reference projection must be the \
20913             canonical `:entrada` fixture's composite",
20914        );
20915    }
20916
20917    #[test]
20918    fn port_for_destination_reads_through_lifted_entrada_accessor() {
20919        // Peer coherence pin: the
20920        // [`AplicacaoSpec::port_for_destination`] per-destination
20921        // L4-port fallback resolver's composite-projection seed
20922        // (`self.entrada().filter(…).map_or(…)`) must key off the
20923        // lifted outer accessor. Pins the coherence by exercising
20924        // the resolver end-to-end: (1) the `None` `:entrada` shape
20925        // falls through to `DEFAULT_SERVICO_PORT` under the outer
20926        // accessor's reference projection, (2) a non-matching
20927        // destination falls through to `DEFAULT_SERVICO_PORT` under
20928        // the outer accessor's reference projection, and (3) the
20929        // matching destination resolves to the `:entrada :port`
20930        // value under the outer accessor's reference projection.
20931        //
20932        // Peer of the sibling
20933        // [`validate_reads_through_lifted_entrada_accessor`] multi-
20934        // consumer coherence pin on the same per-`:entrada` outer-
20935        // composite axis — extends the multi-consumer coherence
20936        // discipline onto the second per-`:entrada` production
20937        // consumer, the L4-port fallback resolver.
20938
20939        // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
20940        // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
20941        // arm under the outer accessor's reference projection.
20942        let mut spec = three_member_spec();
20943        spec.entrada = None;
20944        assert_eq!(
20945            spec.port_for_destination("cart"),
20946            DEFAULT_SERVICO_PORT,
20947            "the port-fallback resolver must fall through to \
20948             DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
20949             under the outer accessor's reference projection",
20950        );
20951
20952        // (2) Non-matching destination — the resolver's `filter(…)`
20953        // arm rejects a mismatched destination and falls through
20954        // to `DEFAULT_SERVICO_PORT` under the outer accessor's
20955        // reference projection.
20956        let mut spec = three_member_spec();
20957        if let Some(e) = spec.entrada.as_mut() {
20958            e.para = "cart".into();
20959            e.port = 9443;
20960        }
20961        assert_eq!(
20962            spec.port_for_destination("catalog"),
20963            DEFAULT_SERVICO_PORT,
20964            "the port-fallback resolver must fall through to \
20965             DEFAULT_SERVICO_PORT on a non-matching destination \
20966             under the outer accessor's reference projection",
20967        );
20968
20969        // (3) Matching destination — the resolver's `map_or(…)` arm
20970        // returns the `:entrada :port` value under the outer
20971        // accessor's reference projection.
20972        let mut spec = three_member_spec();
20973        if let Some(e) = spec.entrada.as_mut() {
20974            e.para = "cart".into();
20975            e.port = 9443;
20976        }
20977        assert_eq!(
20978            spec.port_for_destination("cart"),
20979            9443,
20980            "the port-fallback resolver must return the \
20981             `:entrada :port` value on a matching destination \
20982             under the outer accessor's reference projection",
20983        );
20984    }
20985
20986    #[test]
20987    fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
20988        // The canonical per-`:politicas` `:mtls-required` mTLS-
20989        // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
20990        // must return the `:politicas :mtls-required` typed bool
20991        // verbatim as an `Option<bool>`, byte-equal to the raw field
20992        // access across every value in the three-way accept-set —
20993        // `None` (cluster default applies), `Some(true)` (mTLS
20994        // handshake enforced — the sandboxing-by-default arm the
20995        // MeshPolicy's docstring names), `Some(false)` (handshake
20996        // skipped — the explicit debug-edge opt-out).
20997        //
20998        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
20999        // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
21000        // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
21001        // shape — first `Option<Copy-T>`-return accessor on the M3
21002        // mesh-slot family. Pins against a future silent detour that
21003        // re-derived the toggle from a peer axis (an accidental
21004        // `.circuit_breaker.is_some()` collapse that assumed mTLS on
21005        // whenever a breaker is set), a `None` → `Some(false)` cluster-
21006        // default projection (the canonical `Option<bool>` → `bool`
21007        // collapse footgun the surrounding `is_empty()` predicate
21008        // guards on the peer emptiness axis), or a `Some(true)` /
21009        // `Some(false)` variant swap that landed on one consumer
21010        // without the other.
21011        for required in [None, Some(true), Some(false)] {
21012            let p = MeshPolicy {
21013                mtls_required: required,
21014                ..MeshPolicy::default()
21015            };
21016            assert_eq!(
21017                p.mtls_required(),
21018                required,
21019                "MeshPolicy::mtls_required must return :politicas \
21020                 :mtls-required verbatim (got {:?}, expected {required:?})",
21021                p.mtls_required(),
21022            );
21023            assert_eq!(
21024                p.mtls_required(),
21025                p.mtls_required,
21026                "MeshPolicy::mtls_required must byte-equal the raw \
21027                 .mtls_required field access across every value in the \
21028                 three-way accept-set",
21029            );
21030        }
21031    }
21032
21033    #[test]
21034    fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
21035        // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
21036        // arm must key off [`MeshPolicy::mtls_required`], not the raw
21037        // `.mtls_required` field access. Structurally: toggling ONLY
21038        // the `mtls_required` slot on an otherwise-default MeshPolicy
21039        // must flip `is_empty()` from `true` (all-`None`) to `false`
21040        // (one axis carries a value); the flip must be observed for
21041        // both `Some(true)` and `Some(false)` since the emptiness
21042        // semantic reads "any axis carries a value" — not "any axis
21043        // carries a truthy value" — the same non-collapsing shape the
21044        // sibling M2 [`crate::LimitsSpec::is_empty`] /
21045        // [`crate::BehaviorSpec::is_empty`] predicates carry on their
21046        // peer `Option<T>`-typed slot surfaces.
21047        //
21048        // Pins against a future silent detour that re-derived the
21049        // emptiness predicate off a peer axis (an accidental
21050        // `.rate_limit.is_none()`-only chain that dropped the
21051        // `mtls_required` arm entirely), a `mtls_required == Some(_)`
21052        // collapse to a truthy-only check (which would silently
21053        // classify `Some(false)` as empty), or an accessor-side
21054        // detour that no longer names the substrate-primitive typed
21055        // dispatch (an accidental `self.mtls_required.unwrap_or(false)
21056        // == false` fallback in the accessor that would silently
21057        // classify both `None` and `Some(false)` as the same value).
21058        //
21059        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
21060        // (7cd2a28) accessor-composition pin on the sibling optional-
21061        // scalar axis — same "the emptiness / shape-gate predicate
21062        // must route through the substrate-primitive typed dispatch"
21063        // discipline extended onto the peer per-`:politicas` emptiness
21064        // predicate.
21065        let empty = MeshPolicy::default();
21066        assert!(
21067            empty.is_empty(),
21068            "MeshPolicy::default() must be is_empty() — every axis \
21069             defaults to None",
21070        );
21071        for required in [Some(true), Some(false)] {
21072            let p = MeshPolicy {
21073                mtls_required: required,
21074                ..MeshPolicy::default()
21075            };
21076            assert!(
21077                !p.is_empty(),
21078                "MeshPolicy::is_empty must return false when \
21079                 :mtls-required is {required:?} — the emptiness \
21080                 predicate reads \"any axis carries a value\", not \
21081                 \"any axis carries a truthy value\"",
21082            );
21083            assert_eq!(
21084                p.mtls_required().is_none(),
21085                p.is_empty(),
21086                "when :mtls-required is the only set axis, \
21087                 is_empty() must equal mtls_required().is_none() — \
21088                 the accessor and the emptiness predicate must \
21089                 route through the same substrate-primitive typed \
21090                 dispatch on the :mtls-required arm",
21091            );
21092        }
21093    }
21094
21095    #[test]
21096    fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
21097        // The by-copy pin: [`MeshPolicy::mtls_required`] returns
21098        // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
21099        // accessor must return by value, not by reference. Peer of the
21100        // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
21101        // borrow-invariant pin on the sibling `Option<String>` slot,
21102        // but extended onto the peer `Option<bool>` copy-invariant
21103        // shape — the accessor's returned `Option<bool>` must outlive
21104        // `&self` (multiple calls must return equal values from a
21105        // dropped-`&self` copy, since the returned Option carries no
21106        // borrow), and calling the accessor twice on the same
21107        // MeshPolicy must yield the same `Option<bool>` verbatim
21108        // (idempotent, no side effects on `&self`).
21109        //
21110        // Pins against a future silent detour that returned
21111        // `Option<&bool>` (which would type-check but silently break
21112        // every downstream caller — [`single_field_overlay`]'s first
21113        // parameter is `Option<T: Clone>`, and `&bool` would fold to a
21114        // detached copy at the call site), an accidental
21115        // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
21116        // would also type-check but return `Option<&bool>`), or a
21117        // one-arm-only accessor that reads `Some(*b)` in the Some arm
21118        // but reads a fresh Default::default() in the None arm.
21119        for required in [None, Some(true), Some(false)] {
21120            let p = MeshPolicy {
21121                mtls_required: required,
21122                ..MeshPolicy::default()
21123            };
21124            let first = p.mtls_required();
21125            let second = p.mtls_required();
21126            assert_eq!(
21127                first, second,
21128                "MeshPolicy::mtls_required must be idempotent — two \
21129                 successive calls on the same &self must return the \
21130                 same Option<bool>",
21131            );
21132            assert_eq!(
21133                first, required,
21134                "MeshPolicy::mtls_required must return :politicas \
21135                 :mtls-required verbatim by copy — got {first:?}, \
21136                 expected {required:?}",
21137            );
21138        }
21139    }
21140
21141    #[test]
21142    fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
21143        // The canonical per-`:politicas` `:retries` transient-failure-
21144        // retry-budget scalar pin: [`MeshPolicy::retries`] must return
21145        // the `:politicas :retries` typed `u32` verbatim as an
21146        // `Option<u32>`, byte-equal to the raw field access across every
21147        // representative value in the accept-set — `None` (cluster
21148        // default applies — typically "no retries beyond a single
21149        // dispatch attempt" the caixa-mesh `retry_overlay` builder
21150        // documents), `Some(1)` (the lower boundary of the
21151        // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
21152        // `AplicacaoSpec::validate_politicas` gate carves out on the
21153        // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
21154        // (the upper boundary the same gate carves out on the sibling
21155        // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
21156        // past-the-guard sentinel that pins the accessor doesn't perform
21157        // a silent bounds-collapse at the return path).
21158        //
21159        // Sibling of the peer per-`:politicas`
21160        // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
21161        // sibling `Option<Copy-T>` optional-scalar axis, extended to the
21162        // peer per-`:politicas` `Option<u32>` shape — second
21163        // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
21164        // Pins against a future silent detour that re-derived the retry
21165        // cap from a peer axis (an accidental `.circuit_breaker
21166        // .as_ref().map(|b| b.max_failures)` collapse that read the
21167        // breaker's max-failure count as a retry budget), a
21168        // `None → Some(0)` cluster-default projection (which would
21169        // silently re-introduce the `PolicyRetriesZero` refusal case at
21170        // the emit boundary), or a bounds-collapsing accessor that
21171        // clamped the return through `POLICY_RETRIES_MAX` (the
21172        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
21173        // must ship the raw slot verbatim so a validate-time gate
21174        // regression surfaces at the emit boundary rather than being
21175        // silently absorbed).
21176        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
21177            let p = MeshPolicy {
21178                retries,
21179                ..MeshPolicy::default()
21180            };
21181            assert_eq!(
21182                p.retries(),
21183                retries,
21184                "MeshPolicy::retries must return :politicas :retries \
21185                 verbatim (got {:?}, expected {retries:?})",
21186                p.retries(),
21187            );
21188            assert_eq!(
21189                p.retries(),
21190                p.retries,
21191                "MeshPolicy::retries must byte-equal the raw .retries \
21192                 field access across every value in the accept-set",
21193            );
21194        }
21195    }
21196
21197    #[test]
21198    fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
21199        // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
21200        // must key off [`MeshPolicy::retries`], not the raw `.retries`
21201        // field access. Structurally: toggling ONLY the `retries` slot
21202        // on an otherwise-default MeshPolicy must flip `is_empty()`
21203        // from `true` (all-`None`) to `false` (one axis carries a
21204        // value); the flip must be observed for every value in the
21205        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
21206        // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
21207        // the emptiness semantic reads "any axis carries a value" —
21208        // not "any axis carries a value the validate gate accepts" —
21209        // the same non-collapsing shape the peer M2
21210        // [`crate::LimitsSpec::is_empty`] /
21211        // [`crate::BehaviorSpec::is_empty`] predicates carry.
21212        //
21213        // Pins against a future silent detour that re-derived the
21214        // emptiness predicate off a peer axis (an accidental
21215        // `.rate_limit.is_none()`-only chain that dropped the
21216        // `retries` arm entirely), a `retries == Some(_)` collapse
21217        // that key-off a validate-gate-clamped bounds check (which
21218        // would silently classify a past-the-guard `Some(u32::MAX)`
21219        // as empty because it fails the `1..=POLICY_RETRIES_MAX`
21220        // check), or an accessor-side detour that no longer names the
21221        // substrate-primitive typed dispatch.
21222        //
21223        // Sibling of the peer per-`:politicas`
21224        // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
21225        // pin on the sibling `Option<Copy-T>` optional-scalar axis —
21226        // same "the emptiness predicate must route through the
21227        // substrate-primitive typed dispatch" discipline extended onto
21228        // the peer per-`:politicas` `Option<u32>` axis.
21229        let empty = MeshPolicy::default();
21230        assert!(
21231            empty.is_empty(),
21232            "MeshPolicy::default() must be is_empty() — every axis \
21233             defaults to None",
21234        );
21235        for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
21236            let p = MeshPolicy {
21237                retries,
21238                ..MeshPolicy::default()
21239            };
21240            assert!(
21241                !p.is_empty(),
21242                "MeshPolicy::is_empty must return false when \
21243                 :retries is {retries:?} — the emptiness \
21244                 predicate reads \"any axis carries a value\", not \
21245                 \"any axis carries a value the validate gate \
21246                 accepts\"",
21247            );
21248            assert_eq!(
21249                p.retries().is_none(),
21250                p.is_empty(),
21251                "when :retries is the only set axis, is_empty() \
21252                 must equal retries().is_none() — the accessor and \
21253                 the emptiness predicate must route through the same \
21254                 substrate-primitive typed dispatch on the :retries \
21255                 arm",
21256            );
21257        }
21258    }
21259
21260    #[test]
21261    fn mesh_policy_retries_projects_option_u32_by_copy() {
21262        // The by-copy pin: [`MeshPolicy::retries`] returns
21263        // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
21264        // accessor must return by value, not by reference. Sibling of
21265        // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
21266        // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
21267        // extended onto the sibling `Option<u32>` copy-invariant
21268        // shape — the accessor's returned `Option<u32>` must outlive
21269        // `&self` (multiple calls must return equal values from a
21270        // dropped-`&self` copy, since the returned Option carries no
21271        // borrow), and calling the accessor twice on the same
21272        // MeshPolicy must yield the same `Option<u32>` verbatim
21273        // (idempotent, no side effects on `&self`).
21274        //
21275        // Pins against a future silent detour that returned
21276        // `Option<&u32>` (which would type-check but silently break
21277        // every downstream caller — [`crate::render::single_field_overlay`]'s
21278        // first parameter is `Option<T: Clone>`, and `&u32` would
21279        // fold to a detached copy at the call site), an accidental
21280        // `Option::as_ref()` projection (`self.retries.as_ref()` would
21281        // also type-check but return `Option<&u32>`), or a one-arm-
21282        // only accessor that reads `Some(*n)` in the Some arm but
21283        // reads a fresh `Default::default()` (`0_u32`) in the None
21284        // arm.
21285        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
21286            let p = MeshPolicy {
21287                retries,
21288                ..MeshPolicy::default()
21289            };
21290            let first = p.retries();
21291            let second = p.retries();
21292            assert_eq!(
21293                first, second,
21294                "MeshPolicy::retries must be idempotent — two \
21295                 successive calls on the same &self must return the \
21296                 same Option<u32>",
21297            );
21298            assert_eq!(
21299                first, retries,
21300                "MeshPolicy::retries must return :politicas :retries \
21301                 verbatim by copy — got {first:?}, expected {retries:?}",
21302            );
21303        }
21304    }
21305
21306    #[test]
21307    fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
21308        // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
21309        // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
21310        // return the `:politicas :timeout` typed [`Duration`] verbatim
21311        // as an `Option<Duration>`, byte-equal to the raw field access
21312        // across every representative value in the accept-set — `None`
21313        // (cluster default applies — typically the gateway class's
21314        // implementation-side per-request wall-clock cap the caixa-mesh
21315        // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
21316        // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
21317        // set the surrounding `AplicacaoSpec::validate_politicas` gate
21318        // carves out on the sibling `PolicyTimeoutZero` /
21319        // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
21320        // (the upper boundary the same gate carves out on the sibling
21321        // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
21322        // (a past-the-guard sentinel that pins the accessor doesn't
21323        // perform a silent bounds-collapse into `None` on the zero-
21324        // Duration arm — validate rejects zero but the accessor must
21325        // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
21326        // past-the-guard sentinel that pins the accessor doesn't
21327        // perform a silent bounds-collapse at the return path).
21328        //
21329        // Sibling of the peer per-`:politicas`
21330        // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
21331        // `Option<u32>` optional-scalar axis and the peer per-
21332        // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
21333        // pin on the sibling `Option<bool>` optional-scalar axis,
21334        // extended onto the peer per-`:politicas` `Option<Duration>`
21335        // shape — third `Option<Copy-T>`-return accessor on the M3
21336        // mesh-slot family. Pins against a future silent detour that
21337        // re-derived the per-call cap from a peer axis (an accidental
21338        // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
21339        // read the breaker's rolling-window duration as a per-call
21340        // deadline), a `None → Some(Duration::MAX)` cluster-default
21341        // projection (which would silently re-introduce the
21342        // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
21343        // blocking" arm at the emit boundary), or a bounds-collapsing
21344        // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
21345        // (the `AplicacaoSpec::validate` gate owns the bounds; the
21346        // accessor must ship the raw slot verbatim so a validate-time
21347        // gate regression surfaces at the emit boundary rather than
21348        // being silently absorbed).
21349        for timeout in [
21350            None,
21351            Some(Duration::from_millis(1)),
21352            Some(POLICY_TIMEOUT_MAX),
21353            Some(Duration::ZERO),
21354            Some(Duration::MAX),
21355        ] {
21356            let p = MeshPolicy {
21357                timeout,
21358                ..MeshPolicy::default()
21359            };
21360            assert_eq!(
21361                p.timeout(),
21362                timeout,
21363                "MeshPolicy::timeout must return :politicas :timeout \
21364                 verbatim (got {:?}, expected {timeout:?})",
21365                p.timeout(),
21366            );
21367            assert_eq!(
21368                p.timeout(),
21369                p.timeout,
21370                "MeshPolicy::timeout must byte-equal the raw .timeout \
21371                 field access across every value in the accept-set",
21372            );
21373        }
21374    }
21375
21376    #[test]
21377    fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
21378        // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
21379        // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
21380        // field access. Structurally: toggling ONLY the `timeout` slot
21381        // on an otherwise-default MeshPolicy must flip `is_empty()`
21382        // from `true` (all-`None`) to `false` (one axis carries a
21383        // value); the flip must be observed for every value in the
21384        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
21385        // gate accepts (`Some(Duration::from_millis(1))`,
21386        // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
21387        // reads "any axis carries a value" — not "any axis carries a
21388        // value the validate gate accepts" — the same non-collapsing
21389        // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
21390        // [`crate::BehaviorSpec::is_empty`] predicates carry.
21391        //
21392        // Pins against a future silent detour that re-derived the
21393        // emptiness predicate off a peer axis (an accidental
21394        // `.rate_limit.is_none()`-only chain that dropped the
21395        // `timeout` arm entirely), a `timeout == Some(_)` collapse
21396        // that key-off a validate-gate-clamped bounds check (which
21397        // would silently classify a past-the-guard `Some(Duration::MAX)`
21398        // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
21399        // check), or an accessor-side detour that no longer names the
21400        // substrate-primitive typed dispatch.
21401        //
21402        // Sibling of the peer per-`:politicas`
21403        // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
21404        // the sibling `Option<u32>` optional-scalar axis and the peer
21405        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
21406        // accessor-composition pin on the sibling `Option<bool>`
21407        // optional-scalar axis — same "the emptiness predicate must
21408        // route through the substrate-primitive typed dispatch"
21409        // discipline extended onto the peer per-`:politicas`
21410        // `Option<Duration>` axis.
21411        let empty = MeshPolicy::default();
21412        assert!(
21413            empty.is_empty(),
21414            "MeshPolicy::default() must be is_empty() — every axis \
21415             defaults to None",
21416        );
21417        for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
21418            let p = MeshPolicy {
21419                timeout,
21420                ..MeshPolicy::default()
21421            };
21422            assert!(
21423                !p.is_empty(),
21424                "MeshPolicy::is_empty must return false when \
21425                 :timeout is {timeout:?} — the emptiness \
21426                 predicate reads \"any axis carries a value\", not \
21427                 \"any axis carries a value the validate gate \
21428                 accepts\"",
21429            );
21430            assert_eq!(
21431                p.timeout().is_none(),
21432                p.is_empty(),
21433                "when :timeout is the only set axis, is_empty() \
21434                 must equal timeout().is_none() — the accessor and \
21435                 the emptiness predicate must route through the same \
21436                 substrate-primitive typed dispatch on the :timeout \
21437                 arm",
21438            );
21439        }
21440    }
21441
21442    #[test]
21443    fn mesh_policy_timeout_projects_option_duration_by_copy() {
21444        // The by-copy pin: [`MeshPolicy::timeout`] returns
21445        // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
21446        // and the accessor must return by value, not by reference.
21447        // Sibling of the peer per-`:politicas`
21448        // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
21449        // sibling `Option<u32>` optional-scalar axis and the peer
21450        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
21451        // by-copy pin on the sibling `Option<bool>` optional-scalar
21452        // axis, extended onto the peer per-`:politicas`
21453        // `Option<Duration>` copy-invariant shape — the accessor's
21454        // returned `Option<Duration>` must outlive `&self` (multiple
21455        // calls must return equal values from a dropped-`&self`
21456        // copy, since the returned Option carries no borrow), and
21457        // calling the accessor twice on the same MeshPolicy must
21458        // yield the same `Option<Duration>` verbatim (idempotent, no
21459        // side effects on `&self`).
21460        //
21461        // Pins against a future silent detour that returned
21462        // `Option<&Duration>` (which would type-check but silently
21463        // break every downstream caller — [`crate::render::single_field_overlay`]'s
21464        // first parameter is `Option<T: Clone>`, and `&Duration`
21465        // would fold to a detached copy at the call site), an
21466        // accidental `Option::as_ref()` projection
21467        // (`self.timeout.as_ref()` would also type-check but return
21468        // `Option<&Duration>`), or a one-arm-only accessor that
21469        // reads `Some(*d)` in the Some arm but reads a fresh
21470        // `Default::default()` (`Duration::ZERO`) in the None arm
21471        // (which would silently re-classify every unset `:timeout`
21472        // as the `PolicyTimeoutZero`-refused zero-Duration value at
21473        // the accessor boundary).
21474        for timeout in [
21475            None,
21476            Some(Duration::from_millis(1)),
21477            Some(POLICY_TIMEOUT_MAX),
21478            Some(Duration::ZERO),
21479            Some(Duration::MAX),
21480        ] {
21481            let p = MeshPolicy {
21482                timeout,
21483                ..MeshPolicy::default()
21484            };
21485            let first = p.timeout();
21486            let second = p.timeout();
21487            assert_eq!(
21488                first, second,
21489                "MeshPolicy::timeout must be idempotent — two \
21490                 successive calls on the same &self must return the \
21491                 same Option<Duration>",
21492            );
21493            assert_eq!(
21494                first, timeout,
21495                "MeshPolicy::timeout must return :politicas :timeout \
21496                 verbatim by copy — got {first:?}, expected {timeout:?}",
21497            );
21498        }
21499    }
21500
21501    #[test]
21502    fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
21503        // The canonical per-`:politicas` `:rate-limit` Envoy-
21504        // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
21505        // [`MeshPolicy::rate_limit`] must return the `:politicas
21506        // :rate-limit` typed [`RateLimit`] verbatim as an
21507        // `Option<RateLimit>`, byte-equal to the raw field access
21508        // across every representative value in the accept-set — `None`
21509        // (cluster default applies — no per-Aplicacao rate declaration,
21510        // the gateway-class per-listener default arm the future caixa-
21511        // mesh `local_rate_limit_overlay` emitter documents),
21512        // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
21513        // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
21514        // accept-set the surrounding
21515        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
21516        // sibling `PolicyRateLimitZero` refusal, paired with the
21517        // canonical-window "1 second" arm of the three-unit
21518        // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
21519        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
21520        // (the upper boundary the same gate carves out on the sibling
21521        // `PolicyRateLimitExceedsCap` refusal, paired with the
21522        // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
21523        // (a past-the-guard sentinel that pins the accessor doesn't
21524        // perform a silent bounds-collapse into `None` on the
21525        // zero-rate/zero-window arm — validate rejects zero but the
21526        // accessor must ship the raw slot verbatim so a validate-time
21527        // gate regression surfaces at the emit boundary rather than
21528        // being silently absorbed), and
21529        // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
21530        // (a past-the-guard sentinel that pins the accessor doesn't
21531        // perform a silent bounds-collapse at the return path).
21532        //
21533        // First `Option<Copy-composite-T>`-return accessor pin on the
21534        // M3 mesh-slot family (peer of the sibling per-`:politicas`
21535        // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
21536        // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
21537        // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
21538        // Copy accessor pins, extended onto the peer per-`:politicas`
21539        // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
21540        // and the accessor returns by value). Pins against a future
21541        // silent detour that re-derived the rate declaration from a
21542        // peer axis (an accidental
21543        // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
21544        // collapse that read the breaker's trip threshold + rolling
21545        // window as a rate declaration), a `None → Some(default())`
21546        // cluster-default projection (which would silently re-
21547        // introduce a "cluster default is 0/s" arm the emit boundary
21548        // would take as "declared but inert" — the canonical
21549        // declared-but-inert footgun the sibling
21550        // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
21551        // amplification-shape axis), a bounds-collapsing accessor
21552        // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
21553        // clamped `rl.window` through [`is_canonical_rate_limit_window`]
21554        // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
21555        // accessor must ship the raw slot verbatim), or a
21556        // by-reference detour (`Option<&RateLimit>`) that broke every
21557        // downstream consumer keying off `Option<RateLimit>` by-copy.
21558        for rl in [
21559            None,
21560            Some(RateLimit {
21561                rate: 1,
21562                window: Duration::from_secs(1),
21563            }),
21564            Some(RateLimit {
21565                rate: POLICY_RATE_LIMIT_MAX,
21566                window: Duration::from_secs(3600),
21567            }),
21568            Some(RateLimit {
21569                rate: 0,
21570                window: Duration::ZERO,
21571            }),
21572            Some(RateLimit {
21573                rate: u32::MAX,
21574                window: Duration::MAX,
21575            }),
21576        ] {
21577            let p = MeshPolicy {
21578                rate_limit: rl,
21579                ..MeshPolicy::default()
21580            };
21581            assert_eq!(
21582                p.rate_limit(),
21583                rl,
21584                "MeshPolicy::rate_limit must return :politicas :rate-limit \
21585                 verbatim (got {:?}, expected {rl:?})",
21586                p.rate_limit(),
21587            );
21588            assert_eq!(
21589                p.rate_limit(),
21590                p.rate_limit,
21591                "MeshPolicy::rate_limit must byte-equal the raw \
21592                 .rate_limit field access across every value in the \
21593                 accept-set",
21594            );
21595        }
21596    }
21597
21598    #[test]
21599    fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
21600        // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
21601        // must key off [`MeshPolicy::rate_limit`], not the raw
21602        // `.rate_limit` field access. Structurally: toggling ONLY the
21603        // `rate_limit` slot on an otherwise-default MeshPolicy must
21604        // flip `is_empty()` from `true` (all-`None`) to `false` (one
21605        // axis carries a value); the flip must be observed for every
21606        // representative value in the accept-set the surrounding
21607        // [`AplicacaoSpec::validate_politicas`] gate accepts
21608        // (`Some(RateLimit { rate: 1, window: 1s })`,
21609        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
21610        // since the emptiness semantic reads "any axis carries a
21611        // value" — not "any axis carries a value the validate gate
21612        // accepts" — the same non-collapsing shape the peer M2
21613        // [`crate::LimitsSpec::is_empty`] /
21614        // [`crate::BehaviorSpec::is_empty`] predicates carry.
21615        //
21616        // Pins against a future silent detour that re-derived the
21617        // emptiness predicate off a peer axis (an accidental
21618        // `.timeout.is_none()`-only chain that dropped the
21619        // `rate_limit` arm entirely — the last unlifted inline field
21620        // access on `is_empty` before this lift), a `rate_limit ==
21621        // Some(_)` collapse that key-off a validate-gate-clamped
21622        // bounds check (which would silently classify a past-the-
21623        // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
21624        // because it fails the value-shape gate), or an accessor-
21625        // side detour that no longer names the substrate-primitive
21626        // typed dispatch.
21627        //
21628        // Fourth "the emptiness predicate must route through the
21629        // substrate-primitive typed dispatch" composition pin on the
21630        // M3 mesh-slot family — closes the last unlifted composition
21631        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
21632        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
21633        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
21634        // 7073d0f is_empty-composition pins on the sibling primitive-
21635        // Copy axes, extended onto the peer per-`:politicas`
21636        // composite-Copy `Option<RateLimit>` axis).
21637        let empty = MeshPolicy::default();
21638        assert!(
21639            empty.is_empty(),
21640            "MeshPolicy::default() must be is_empty() — every axis \
21641             defaults to None",
21642        );
21643        for rl in [
21644            RateLimit {
21645                rate: 1,
21646                window: Duration::from_secs(1),
21647            },
21648            RateLimit {
21649                rate: POLICY_RATE_LIMIT_MAX,
21650                window: Duration::from_secs(3600),
21651            },
21652        ] {
21653            let p = MeshPolicy {
21654                rate_limit: Some(rl),
21655                ..MeshPolicy::default()
21656            };
21657            assert!(
21658                !p.is_empty(),
21659                "MeshPolicy::is_empty must return false when \
21660                 :rate-limit is {rl:?} — the emptiness predicate \
21661                 reads \"any axis carries a value\", not \"any axis \
21662                 carries a value the validate gate accepts\"",
21663            );
21664            assert_eq!(
21665                p.rate_limit().is_none(),
21666                p.is_empty(),
21667                "when :rate-limit is the only set axis, is_empty() \
21668                 must equal rate_limit().is_none() — the accessor \
21669                 and the emptiness predicate must route through the \
21670                 same substrate-primitive typed dispatch on the \
21671                 :rate-limit arm",
21672            );
21673        }
21674    }
21675
21676    #[test]
21677    fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
21678        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
21679        // `:rate-limit` value-shape gate must key off
21680        // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
21681        // field bind. Structurally: a `MeshPolicy` whose only set
21682        // axis is a `Some(RateLimit { rate: 0, .. })` must surface
21683        // the `PolicyRateLimitZero` refusal exactly, and the same
21684        // MeshPolicy with the rate at the canonical lower boundary
21685        // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
21686        // The pair jointly pins the accessor + validate-gate
21687        // composition: any future silent detour that had the accessor
21688        // omit the `Some(RateLimit { rate: 0, .. })` arm (a
21689        // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
21690        // silently absorb the `PolicyRateLimitZero` refusal at the
21691        // accessor boundary — the composition pin catches that at
21692        // caixa-core build time.
21693        //
21694        // Sibling of the peer [`validate_politicas`]
21695        // `:mtls-required` / `:retries` / `:timeout` composition pins
21696        // on the sibling primitive-Copy optional-scalar axes — same
21697        // "the validate / shape-gate predicate must route through the
21698        // substrate-primitive typed dispatch" discipline extended
21699        // onto the peer per-`:politicas` composite-Copy
21700        // `Option<RateLimit>` axis. Second composition-with-accessor
21701        // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
21702        // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
21703        let mut spec = three_member_spec();
21704        spec.politicas = MeshPolicy {
21705            rate_limit: Some(RateLimit {
21706                rate: 0,
21707                window: Duration::from_secs(1),
21708            }),
21709            ..MeshPolicy::default()
21710        };
21711        assert!(
21712            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
21713            "validate_politicas must reject rate == 0 with \
21714             PolicyRateLimitZero — the accessor and the validate gate \
21715             must route through the same substrate-primitive typed \
21716             dispatch on the :rate-limit zero-floor arm",
21717        );
21718        spec.politicas = MeshPolicy {
21719            rate_limit: Some(RateLimit {
21720                rate: 1,
21721                window: Duration::from_secs(1),
21722            }),
21723            ..MeshPolicy::default()
21724        };
21725        assert!(
21726            spec.validate().is_ok(),
21727            "validate_politicas must accept rate == 1 (the canonical \
21728             lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
21729             set) with a canonical 1s window",
21730        );
21731    }
21732
21733    #[test]
21734    fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
21735        // The canonical per-`:politicas` `:circuit-breaker` Envoy-
21736        // `outlier_detection`-mesh consecutive-failure-ejection scalar
21737        // pin: [`MeshPolicy::circuit_breaker`] must return the
21738        // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
21739        // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
21740        // raw field access across every representative value in the
21741        // accept-set — `None` (cluster default applies — no
21742        // per-Aplicacao breaker declaration, the gateway-class per-
21743        // listener default arm the future caixa-mesh
21744        // `outlier_detection_overlay` emitter documents),
21745        // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
21746        // (the lower boundary of the accept-set the surrounding
21747        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
21748        // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
21749        // refusals),
21750        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
21751        // (the upper boundary the same gate carves out on the sibling
21752        // `PolicyBreakerMaxFailuresExceedsCap` /
21753        // `PolicyBreakerWindowExceedsCap` refusals),
21754        // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
21755        // (a past-the-guard sentinel that pins the accessor doesn't
21756        // perform a silent bounds-collapse into `None` on the
21757        // zero-failures/zero-window arm — validate rejects zero but
21758        // the accessor must ship the raw slot verbatim so a validate-
21759        // time gate regression surfaces at the emit boundary rather
21760        // than being silently absorbed), and
21761        // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
21762        // (a past-the-guard sentinel that pins the accessor doesn't
21763        // perform a silent bounds-collapse at the return path).
21764        //
21765        // Second `Option<Copy-composite-T>`-return accessor pin on the
21766        // M3 mesh-slot family (peer of the sibling per-`:politicas`
21767        // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
21768        // composite-Copy accessor pin, and of the sibling per-
21769        // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
21770        // [`MeshPolicy::retries`] bdfb399 /
21771        // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
21772        // accessor pins). Pins against a future silent detour that
21773        // re-derived the breaker declaration from a peer axis (an
21774        // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
21775        // collapse that read the rate-limit's bucket capacity + refill
21776        // period as a breaker declaration), a `None → Some(default())`
21777        // cluster-default projection (which would silently re-
21778        // introduce the `PolicyBreakerZeroFailures` /
21779        // `PolicyBreakerZeroWindow` refusal cases at the emit
21780        // boundary), a bounds-collapsing accessor that clamped
21781        // `cb.max_failures` through
21782        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
21783        // through [`POLICY_BREAKER_WINDOW_MAX`] (the
21784        // [`AplicacaoSpec::validate`] gate owns the bounds; the
21785        // accessor must ship the raw slot verbatim), or a
21786        // by-reference detour (`Option<&CircuitBreaker>`) that broke
21787        // every downstream consumer keying off `Option<CircuitBreaker>`
21788        // by-copy.
21789        for cb in [
21790            None,
21791            Some(CircuitBreaker {
21792                max_failures: 1,
21793                window: Duration::from_millis(1),
21794            }),
21795            Some(CircuitBreaker {
21796                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
21797                window: POLICY_BREAKER_WINDOW_MAX,
21798            }),
21799            Some(CircuitBreaker {
21800                max_failures: 0,
21801                window: Duration::ZERO,
21802            }),
21803            Some(CircuitBreaker {
21804                max_failures: u32::MAX,
21805                window: Duration::MAX,
21806            }),
21807        ] {
21808            let p = MeshPolicy {
21809                circuit_breaker: cb,
21810                ..MeshPolicy::default()
21811            };
21812            assert_eq!(
21813                p.circuit_breaker(),
21814                cb,
21815                "MeshPolicy::circuit_breaker must return :politicas \
21816                 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
21817                p.circuit_breaker(),
21818            );
21819            assert_eq!(
21820                p.circuit_breaker(),
21821                p.circuit_breaker,
21822                "MeshPolicy::circuit_breaker must byte-equal the raw \
21823                 .circuit_breaker field access across every value in \
21824                 the accept-set",
21825            );
21826        }
21827    }
21828
21829    #[test]
21830    fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
21831        // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
21832        // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
21833        // `.circuit_breaker` field access. Structurally: toggling ONLY
21834        // the `circuit_breaker` slot on an otherwise-default MeshPolicy
21835        // must flip `is_empty()` from `true` (all-`None`) to `false`
21836        // (one axis carries a value); the flip must be observed for
21837        // every representative value in the accept-set the surrounding
21838        // [`AplicacaoSpec::validate_politicas`] gate accepts
21839        // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
21840        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
21841        // since the emptiness semantic reads "any axis carries a
21842        // value" — not "any axis carries a value the validate gate
21843        // accepts" — the same non-collapsing shape the peer M2
21844        // [`crate::LimitsSpec::is_empty`] /
21845        // [`crate::BehaviorSpec::is_empty`] predicates carry.
21846        //
21847        // Pins against a future silent detour that re-derived the
21848        // emptiness predicate off a peer axis (an accidental
21849        // `.rate_limit.is_none()`-only chain that dropped the
21850        // `circuit_breaker` arm entirely — the last unlifted inline
21851        // field access on `is_empty` before this lift), a
21852        // `circuit_breaker == Some(_)` collapse that key-off a
21853        // validate-gate-clamped bounds check (which would silently
21854        // classify a past-the-guard `Some(CircuitBreaker { max_failures:
21855        // 0, window: 0s })` as empty because it fails the value-shape
21856        // gate), or an accessor-side detour that no longer names the
21857        // substrate-primitive typed dispatch.
21858        //
21859        // Fifth "the emptiness predicate must route through the
21860        // substrate-primitive typed dispatch" composition pin on the
21861        // M3 mesh-slot family — closes the last unlifted composition
21862        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
21863        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
21864        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
21865        // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
21866        // composition pins on the sibling primitive-Copy + composite-
21867        // Copy axes, extended onto the peer per-`:politicas`
21868        // composite-Copy `Option<CircuitBreaker>` axis).
21869        let empty = MeshPolicy::default();
21870        assert!(
21871            empty.is_empty(),
21872            "MeshPolicy::default() must be is_empty() — every axis \
21873             defaults to None",
21874        );
21875        for cb in [
21876            CircuitBreaker {
21877                max_failures: 1,
21878                window: Duration::from_millis(1),
21879            },
21880            CircuitBreaker {
21881                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
21882                window: POLICY_BREAKER_WINDOW_MAX,
21883            },
21884        ] {
21885            let p = MeshPolicy {
21886                circuit_breaker: Some(cb),
21887                ..MeshPolicy::default()
21888            };
21889            assert!(
21890                !p.is_empty(),
21891                "MeshPolicy::is_empty must return false when \
21892                 :circuit-breaker is {cb:?} — the emptiness predicate \
21893                 reads \"any axis carries a value\", not \"any axis \
21894                 carries a value the validate gate accepts\"",
21895            );
21896            assert_eq!(
21897                p.circuit_breaker().is_none(),
21898                p.is_empty(),
21899                "when :circuit-breaker is the only set axis, \
21900                 is_empty() must equal circuit_breaker().is_none() — \
21901                 the accessor and the emptiness predicate must route \
21902                 through the same substrate-primitive typed dispatch \
21903                 on the :circuit-breaker arm",
21904            );
21905        }
21906    }
21907
21908    #[test]
21909    fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
21910        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
21911        // `:circuit-breaker` value-shape gate must key off
21912        // [`MeshPolicy::circuit_breaker`], not the raw
21913        // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
21914        // whose only set axis is a `Some(CircuitBreaker { max_failures:
21915        // 0, .. })` must surface the `PolicyBreakerZeroFailures`
21916        // refusal exactly, and the same MeshPolicy with the breaker at
21917        // the canonical lower boundary
21918        // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
21919        // pass validate. The pair jointly pins the accessor +
21920        // validate-gate composition: any future silent detour that had
21921        // the accessor omit the `Some(CircuitBreaker { max_failures:
21922        // 0, .. })` arm (a
21923        // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
21924        // collapse) would silently absorb the
21925        // `PolicyBreakerZeroFailures` refusal at the accessor
21926        // boundary — the composition pin catches that at caixa-core
21927        // build time.
21928        //
21929        // Sibling of the peer [`validate_politicas`]
21930        // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
21931        // composition pins on the sibling primitive-Copy + composite-
21932        // Copy optional-scalar axes — same "the validate / shape-gate
21933        // predicate must route through the substrate-primitive typed
21934        // dispatch" discipline extended onto the peer per-`:politicas`
21935        // composite-Copy `Option<CircuitBreaker>` axis. Second
21936        // composition-with-accessor pin on the M3 mesh-slot
21937        // `Option<CircuitBreaker>` arm alongside the
21938        // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
21939        let mut spec = three_member_spec();
21940        spec.politicas = MeshPolicy {
21941            circuit_breaker: Some(CircuitBreaker {
21942                max_failures: 0,
21943                window: Duration::from_millis(1),
21944            }),
21945            ..MeshPolicy::default()
21946        };
21947        assert!(
21948            matches!(
21949                spec.validate(),
21950                Err(AplicacaoError::PolicyBreakerZeroFailures)
21951            ),
21952            "validate_politicas must reject max_failures == 0 with \
21953             PolicyBreakerZeroFailures — the accessor and the validate \
21954             gate must route through the same substrate-primitive \
21955             typed dispatch on the :circuit-breaker zero-floor arm",
21956        );
21957        spec.politicas = MeshPolicy {
21958            circuit_breaker: Some(CircuitBreaker {
21959                max_failures: 1,
21960                window: Duration::from_millis(1),
21961            }),
21962            ..MeshPolicy::default()
21963        };
21964        assert!(
21965            spec.validate().is_ok(),
21966            "validate_politicas must accept a CircuitBreaker at the \
21967             canonical lower boundary (max_failures = 1, window = \
21968             1ms) — the accessor and the validate gate must route \
21969             through the same substrate-primitive typed dispatch on \
21970             the :circuit-breaker arm",
21971        );
21972    }
21973
21974    #[test]
21975    fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
21976        // The canonical per-`:politicas :circuit-breaker` `:max-failures`
21977        // Envoy-outlier-detection trip-threshold scalar pin:
21978        // [`CircuitBreaker::max_failures`] must return the
21979        // `:politicas :circuit-breaker :max-failures` typed `u32`
21980        // verbatim, byte-equal to the raw field access across every
21981        // representative value in the accept-set — `1` (the lower
21982        // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
21983        // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
21984        // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
21985        // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
21986        // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
21987        // refusal), `0` (a past-the-guard sentinel that pins the accessor
21988        // doesn't perform a silent bounds-collapse into `1` on the zero
21989        // arm — validate rejects zero but the accessor must ship the
21990        // raw slot verbatim so a validate-time gate regression surfaces
21991        // at the emit boundary rather than being silently absorbed),
21992        // `u32::MAX` (a past-the-guard sentinel that pins the accessor
21993        // doesn't perform a silent bounds-collapse through
21994        // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
21995        //
21996        // First sub-struct required-scalar accessor pin on the M3
21997        // mesh-slot family — sibling in shape to the peer per-`:membros`
21998        // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
21999        // (a40b0e3) required-`String`-carry accessor pins and the peer
22000        // per-`:contratos` [`WitContract::source`] /
22001        // [`WitContract::destination`] (7f0fd43) required-`String`-carry
22002        // accessor pins, extended onto the peer per-`CircuitBreaker`
22003        // required-`u32` scalar-value axis. Pins against a future silent
22004        // detour that re-derived the trip threshold from a peer axis (an
22005        // accidental `self.window.as_secs() as u32` collapse that read
22006        // the breaker's rolling-window duration as a failure count), a
22007        // `0 → 1` cluster-default projection (which would silently absorb
22008        // the `PolicyBreakerZeroFailures` refusal case at the accessor
22009        // boundary), or a bounds-collapsing accessor that clamped the
22010        // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
22011        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
22012        // must ship the raw slot verbatim).
22013        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
22014            let cb = CircuitBreaker {
22015                max_failures,
22016                window: Duration::from_secs(60),
22017            };
22018            assert_eq!(
22019                cb.max_failures(),
22020                max_failures,
22021                "CircuitBreaker::max_failures must return :politicas \
22022                 :circuit-breaker :max-failures verbatim (got {}, \
22023                 expected {max_failures})",
22024                cb.max_failures(),
22025            );
22026            assert_eq!(
22027                cb.max_failures(),
22028                cb.max_failures,
22029                "CircuitBreaker::max_failures must byte-equal the raw \
22030                 .max_failures field access across every value in the \
22031                 u32 accept-set",
22032            );
22033        }
22034    }
22035
22036    #[test]
22037    fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
22038        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
22039        // `:circuit-breaker :max-failures` zero-floor arm must key off
22040        // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
22041        // field access. Structurally: a `CircuitBreaker { max_failures:
22042        // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
22043        // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
22044        // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
22045        // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
22046        // pass validate. The pair jointly pins the accessor +
22047        // validate-gate composition: any future silent detour that had
22048        // the accessor return a fresh `1` on the zero arm (a
22049        // `.max_failures().max(1)` collapse) would silently absorb the
22050        // `PolicyBreakerZeroFailures` refusal at the accessor boundary
22051        // and the validate gate would accept a struct-literal
22052        // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
22053        // catches that at caixa-core build time.
22054        //
22055        // Peer of the sibling per-`:politicas`
22056        // [`MeshPolicy::mtls_required`] (c0110f1) /
22057        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
22058        // (7073d0f) accessor-composition pins on the sibling optional-
22059        // scalar axes — same "the validate / shape-gate predicate must
22060        // route through the substrate-primitive typed dispatch"
22061        // discipline extended onto the peer per-`CircuitBreaker`
22062        // required-scalar composition axis.
22063        let mut spec = three_member_spec();
22064        spec.politicas = MeshPolicy {
22065            circuit_breaker: Some(CircuitBreaker {
22066                max_failures: 0,
22067                window: Duration::from_secs(60),
22068            }),
22069            ..MeshPolicy::default()
22070        };
22071        assert!(
22072            matches!(
22073                spec.validate(),
22074                Err(AplicacaoError::PolicyBreakerZeroFailures)
22075            ),
22076            "validate_politicas must reject max_failures == 0 with \
22077             PolicyBreakerZeroFailures — the accessor and the validate \
22078             gate must route through the same substrate-primitive typed \
22079             dispatch on the :max-failures zero-floor arm",
22080        );
22081        spec.politicas = MeshPolicy {
22082            circuit_breaker: Some(CircuitBreaker {
22083                max_failures: 1,
22084                window: Duration::from_secs(60),
22085            }),
22086            ..MeshPolicy::default()
22087        };
22088        assert!(
22089            spec.validate().is_ok(),
22090            "validate_politicas must accept max_failures == 1 (the \
22091             lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
22092             accept-set)",
22093        );
22094    }
22095
22096    #[test]
22097    fn circuit_breaker_max_failures_projects_u32_by_copy() {
22098        // The by-copy pin: [`CircuitBreaker::max_failures`] returns
22099        // `u32` by copy — `u32` is `Copy` and the accessor must return
22100        // by value, not by reference. Peer of the sibling
22101        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
22102        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
22103        // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
22104        // optional-scalar axes, extended onto the peer
22105        // per-`CircuitBreaker` required-`u32` copy-invariant shape —
22106        // the accessor's returned `u32` must outlive `&self` (multiple
22107        // calls must return equal values from a dropped-`&self` copy,
22108        // since the returned scalar carries no borrow), and calling
22109        // the accessor twice on the same CircuitBreaker must yield the
22110        // same `u32` verbatim (idempotent, no side effects on `&self`).
22111        //
22112        // Pins against a future silent detour that returned `&u32`
22113        // (which would type-check but silently break every downstream
22114        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
22115        // first parameter is `u32`, and `&u32` would fold to a detached
22116        // copy at the call site with a `*` deref the sibling accessors
22117        // don't need), an accidental `.max_failures.wrapping_add(0)`
22118        // detour that returned a fresh copy through an arithmetic
22119        // no-op (breaking a future `const fn` regression), or a
22120        // one-arm-only accessor that returned a saturating value on
22121        // some sentinel input (breaking the pass-through invariant the
22122        // sibling required-scalar accessors carry).
22123        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
22124            let cb = CircuitBreaker {
22125                max_failures,
22126                window: Duration::from_secs(60),
22127            };
22128            let first = cb.max_failures();
22129            let second = cb.max_failures();
22130            assert_eq!(
22131                first, second,
22132                "CircuitBreaker::max_failures must be idempotent — two \
22133                 successive calls on the same &self must return the \
22134                 same u32",
22135            );
22136            assert_eq!(
22137                first, max_failures,
22138                "CircuitBreaker::max_failures must return :politicas \
22139                 :circuit-breaker :max-failures verbatim by copy — \
22140                 got {first}, expected {max_failures}",
22141            );
22142        }
22143    }
22144
22145    #[test]
22146    fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
22147        // The canonical per-`:politicas :circuit-breaker` `:window`
22148        // Envoy-outlier-detection rolling-observation-interval scalar
22149        // pin: [`CircuitBreaker::window`] must return the
22150        // `:politicas :circuit-breaker :window` typed `Duration`
22151        // verbatim, byte-equal to the raw field access across every
22152        // representative value in the accept-set — `Duration::from_millis(1)`
22153        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
22154        // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
22155        // gate carves out on the sibling `PolicyBreakerZeroWindow`
22156        // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
22157        // same gate carves out on the sibling
22158        // `PolicyBreakerWindowExceedsCap` refusal),
22159        // `Duration::ZERO` (a past-the-guard sentinel that pins the
22160        // accessor doesn't perform a silent bounds-collapse into
22161        // `Duration::from_millis(1)` on the zero arm — validate rejects
22162        // zero but the accessor must ship the raw slot verbatim so a
22163        // validate-time gate regression surfaces at the emit boundary
22164        // rather than being silently absorbed),
22165        // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
22166        // far above the 1h cap — that pins the accessor doesn't perform
22167        // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
22168        // at the return path).
22169        //
22170        // Second sub-struct required-scalar accessor pin on the M3
22171        // mesh-slot family — sibling in shape to the just-landed
22172        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
22173        // (3a74062) required-`u32` accessor pin on the peer
22174        // per-`CircuitBreaker` required-axis, extended onto the
22175        // per-sub-struct required-`Duration` axis. Pins against a
22176        // future silent detour that re-derived the observation window
22177        // from a peer axis (an accidental
22178        // `Duration::from_secs(self.max_failures as u64)` collapse that
22179        // read the breaker's trip count as an observation-interval
22180        // duration), a `Duration::ZERO → Duration::from_millis(1)`
22181        // cluster-default projection (which would silently absorb the
22182        // `PolicyBreakerZeroWindow` refusal case at the accessor
22183        // boundary), or a bounds-collapsing accessor that clamped the
22184        // return through `POLICY_BREAKER_WINDOW_MAX` (the
22185        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
22186        // must ship the raw slot verbatim).
22187        for window in [
22188            Duration::from_millis(1),
22189            POLICY_BREAKER_WINDOW_MAX,
22190            Duration::ZERO,
22191            Duration::from_secs(86_400),
22192        ] {
22193            let cb = CircuitBreaker {
22194                max_failures: 5,
22195                window,
22196            };
22197            assert_eq!(
22198                cb.window(),
22199                window,
22200                "CircuitBreaker::window must return :politicas \
22201                 :circuit-breaker :window verbatim (got {:?}, \
22202                 expected {window:?})",
22203                cb.window(),
22204            );
22205            assert_eq!(
22206                cb.window(),
22207                cb.window,
22208                "CircuitBreaker::window must byte-equal the raw \
22209                 .window field access across every value in the \
22210                 Duration accept-set",
22211            );
22212        }
22213    }
22214
22215    #[test]
22216    fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
22217        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
22218        // `:circuit-breaker :window` zero-floor arm must key off
22219        // [`CircuitBreaker::window`], not the raw `.window` field
22220        // access. Structurally: a `CircuitBreaker { window:
22221        // Duration::ZERO, .. }` embedded in a
22222        // `:politicas :circuit-breaker` slot must surface the
22223        // `PolicyBreakerZeroWindow` refusal exactly, and a
22224        // `CircuitBreaker { window: Duration::from_millis(1), .. }`
22225        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
22226        // accept-set) must pass validate. The pair jointly pins the
22227        // accessor + validate-gate composition: any future silent
22228        // detour that had the accessor return a fresh
22229        // `Duration::from_millis(1)` on the zero arm (a
22230        // `.window().max(Duration::from_millis(1))` collapse) would
22231        // silently absorb the `PolicyBreakerZeroWindow` refusal at the
22232        // accessor boundary and the validate gate would accept a
22233        // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
22234        // — the composition pin catches that at caixa-core build time.
22235        //
22236        // Peer of the sibling per-`CircuitBreaker`
22237        // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
22238        // pin on the peer required-scalar `:max-failures` axis — same
22239        // "the validate / shape-gate predicate must route through the
22240        // substrate-primitive typed dispatch" discipline extended onto
22241        // the peer per-`CircuitBreaker` required-`Duration` composition
22242        // axis.
22243        let mut spec = three_member_spec();
22244        spec.politicas = MeshPolicy {
22245            circuit_breaker: Some(CircuitBreaker {
22246                max_failures: 5,
22247                window: Duration::ZERO,
22248            }),
22249            ..MeshPolicy::default()
22250        };
22251        assert!(
22252            matches!(
22253                spec.validate(),
22254                Err(AplicacaoError::PolicyBreakerZeroWindow)
22255            ),
22256            "validate_politicas must reject window == Duration::ZERO \
22257             with PolicyBreakerZeroWindow — the accessor and the \
22258             validate gate must route through the same substrate-\
22259             primitive typed dispatch on the :window zero-floor arm",
22260        );
22261        spec.politicas = MeshPolicy {
22262            circuit_breaker: Some(CircuitBreaker {
22263                max_failures: 5,
22264                window: Duration::from_millis(1),
22265            }),
22266            ..MeshPolicy::default()
22267        };
22268        assert!(
22269            spec.validate().is_ok(),
22270            "validate_politicas must accept window == \
22271             Duration::from_millis(1) (the lower boundary of the \
22272             1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
22273        );
22274    }
22275
22276    #[test]
22277    fn circuit_breaker_window_projects_duration_by_copy() {
22278        // The by-copy pin: [`CircuitBreaker::window`] returns
22279        // `Duration` by copy — `Duration` is `Copy` and the accessor
22280        // must return by value, not by reference. Peer of the sibling
22281        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
22282        // (3a74062) by-copy pin on the peer required-scalar
22283        // `:max-failures` axis, extended onto the peer
22284        // per-`CircuitBreaker` required-`Duration` copy-invariant shape
22285        // — the accessor's returned `Duration` must outlive `&self`
22286        // (multiple calls must return equal values from a
22287        // dropped-`&self` copy, since the returned scalar carries no
22288        // borrow), and calling the accessor twice on the same
22289        // CircuitBreaker must yield the same `Duration` verbatim
22290        // (idempotent, no side effects on `&self`).
22291        //
22292        // Pins against a future silent detour that returned
22293        // `&Duration` (which would type-check but silently break every
22294        // downstream `Duration`-by-value consumer —
22295        // [`crate::render::require_positive_canonical_bounded_duration`]'s
22296        // first parameter is `Duration`, and `&Duration` would fold to
22297        // a detached copy at the call site with a `*` deref the sibling
22298        // accessors don't need), an accidental `.window + Duration::ZERO`
22299        // detour that returned a fresh copy through an arithmetic
22300        // no-op (breaking a future `const fn` regression), or a
22301        // one-arm-only accessor that returned a saturating value on
22302        // some sentinel input (breaking the pass-through invariant the
22303        // sibling required-scalar accessors carry).
22304        for window in [
22305            Duration::from_millis(1),
22306            POLICY_BREAKER_WINDOW_MAX,
22307            Duration::ZERO,
22308            Duration::from_secs(86_400),
22309        ] {
22310            let cb = CircuitBreaker {
22311                max_failures: 5,
22312                window,
22313            };
22314            let first = cb.window();
22315            let second = cb.window();
22316            assert_eq!(
22317                first, second,
22318                "CircuitBreaker::window must be idempotent — two \
22319                 successive calls on the same &self must return the \
22320                 same Duration",
22321            );
22322            assert_eq!(
22323                first, window,
22324                "CircuitBreaker::window must return :politicas \
22325                 :circuit-breaker :window verbatim by copy — \
22326                 got {first:?}, expected {window:?}",
22327            );
22328        }
22329    }
22330
22331    #[test]
22332    fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
22333        // Apex-identity pair-invariant pin composing both substrate-
22334        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
22335        // and [`WitContract::destination`] — at the emit-side call shape
22336        // every per-`(:de, :para)` CNP L4 port reader now takes. The
22337        // invariant, evaluated per-edge:
22338        //
22339        //   spec.port_for_destination(c.destination()) == expected_port
22340        //
22341        // where `expected_port` is `entrada.port` when
22342        // `c.destination() == entrada.destination()` and
22343        // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
22344        // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
22345        // pin on the per-`:entrada` axis — that pin encodes the apex
22346        // ingress L4 identity via `entrada.destination()`; this pin
22347        // encodes the per-edge L4 identity via `c.destination()`, and
22348        // both compose on the same substrate-primitive resolver so a
22349        // future refactor that silently split either accessor's apex
22350        // behavior surfaces at caixa-core build time.
22351        let mut spec = three_member_spec();
22352        if let Some(e) = spec.entrada.as_mut() {
22353            e.para = "cart".into();
22354            e.port = 8443;
22355        }
22356        let apex_contract = WitContract {
22357            de: "checkout".into(),
22358            para: "cart".into(),
22359            wit: "wasi:http/proxy".into(),
22360            endpoint: Some("/hello".into()),
22361            subject: None,
22362            slot: None,
22363        };
22364        assert_eq!(
22365            spec.port_for_destination(apex_contract.destination()),
22366            8443,
22367            "`spec.port_for_destination(c.destination())` must equal \
22368             `entrada.port` when the contract callee names the ingress \
22369             apex — the CNP per-edge L4 port and the HTTPRoute apex \
22370             backendRef port share this substrate-primitive resolver.",
22371        );
22372        let non_apex_contract = WitContract {
22373            de: "cart".into(),
22374            para: "payment".into(),
22375            wit: "wasi:http/proxy".into(),
22376            endpoint: Some("/charge".into()),
22377            subject: None,
22378            slot: None,
22379        };
22380        assert_eq!(
22381            spec.port_for_destination(non_apex_contract.destination()),
22382            DEFAULT_SERVICO_PORT,
22383            "`spec.port_for_destination(c.destination())` must fall back \
22384             to the substrate-canonical port floor when the contract \
22385             callee is not the ingress apex — the resolver's non-apex \
22386             arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
22387        );
22388    }
22389
22390    #[test]
22391    fn membro_key_consts_are_lower_camel_case_shape() {
22392        // Shape-pin: every `MEMBRO_KEY_*` const must be a
22393        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
22394        // `kebab-case` hyphens, no leading colon, no `PascalCase`
22395        // leading capital, no whitespace / dots) — the canonical shape
22396        // the `#[serde(rename_all = "camelCase")]` derive produces on
22397        // [`Membro`]. A future flip to a non-camelCase attribute at
22398        // the derive surfaces both here (this test fails on the
22399        // stale-constant shape) and at
22400        // `membro_serde_keys_match_lifted_membro_key_consts` (that test
22401        // fails on the mismatch between const and derive). Peer with
22402        // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
22403        // on the sibling `SupervisorSpec` top-level axis.
22404        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
22405            assert!(
22406                !key.is_empty(),
22407                "MEMBRO_KEY_* must be non-empty (got {key:?})"
22408            );
22409            let first = key.chars().next().unwrap();
22410            assert!(
22411                first.is_ascii_lowercase(),
22412                "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
22413                 (got {key:?}, leads with {first:?})",
22414            );
22415            assert!(
22416                key.chars().all(|c| c.is_ascii_alphanumeric()),
22417                "MEMBRO_KEY_* must be ASCII-alphanumeric only \
22418                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
22419            );
22420        }
22421    }
22422
22423    // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
22424
22425    #[test]
22426    fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
22427        // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
22428        // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
22429        // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
22430        // keys the `#[serde(rename_all = "camelCase")]` attribute on
22431        // [`WitContract`] emits for the required-triad. The three
22432        // sibling payload-arm keys already pin under
22433        // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
22434        // `STORE_FIELD_NAME` — pin all six alongside so a future
22435        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
22436        // verbatim-field-name flip at the derive attribute (any of which
22437        // would silently break every downstream JSON consumer that
22438        // reaches for one of the six via `Value::get(...)`) surfaces
22439        // here as a build-time test failure at `aplicacao.rs`, not as an
22440        // apply-time `.get(<stale-canonical-const>)` returning `None`
22441        // far from the derive-attr drift's commit. Peer with the sibling
22442        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
22443        // pin on the M3 `:membros` per-entry axis — same discipline the
22444        // `Membro` per-entry lift established, extended here to the
22445        // sibling M3 `WitContract` per-`:contratos` entry axis, the last
22446        // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
22447        // axis on the Aplicacao surface without a lifted serde-key peer.
22448        let c = WitContract {
22449            de: "cart".into(),
22450            para: "catalog".into(),
22451            wit: "wasi:http/proxy".into(),
22452            endpoint: Some("/lookup".into()),
22453            subject: None,
22454            slot: None,
22455        };
22456        let json = serde_json::to_string(&c).unwrap();
22457        for key in [
22458            crate::CONTRATO_KEY_DE,
22459            crate::CONTRATO_KEY_PARA,
22460            crate::CONTRATO_KEY_WIT,
22461            WitTarget::HTTP_FIELD_NAME,
22462        ] {
22463            let quoted = format!("\"{key}\"");
22464            assert!(
22465                json.contains(&quoted),
22466                "serialized WitContract must carry the lifted \
22467                 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
22468                 {quoted} verbatim in the JSON emission (got: {json})",
22469            );
22470        }
22471
22472        // Pin the two remaining payload-arm keys by round-tripping a
22473        // `WitContract` under each payload-shape (pub-sub, store) — the
22474        // required-triad appears on every emission but the payload arms
22475        // only surface when their `Option<String>` field is `Some`.
22476        let pubsub = WitContract {
22477            de: "cart".into(),
22478            para: "events".into(),
22479            wit: "nats:pub-sub".into(),
22480            endpoint: None,
22481            subject: Some("orders.placed".into()),
22482            slot: None,
22483        };
22484        let pubsub_json = serde_json::to_string(&pubsub).unwrap();
22485        let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
22486        assert!(
22487            pubsub_json.contains(&pubsub_quoted),
22488            "serialized pub-sub WitContract must carry the lifted \
22489             WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
22490             verbatim in the JSON emission (got: {pubsub_json})",
22491        );
22492        let store = WitContract {
22493            de: "cart".into(),
22494            para: "sessions".into(),
22495            wit: "wasi:keyvalue/store".into(),
22496            endpoint: None,
22497            subject: None,
22498            slot: Some("cart/$id".into()),
22499        };
22500        let store_json = serde_json::to_string(&store).unwrap();
22501        let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
22502        assert!(
22503            store_json.contains(&store_quoted),
22504            "serialized store WitContract must carry the lifted \
22505             WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
22506             verbatim in the JSON emission (got: {store_json})",
22507        );
22508    }
22509
22510    #[test]
22511    fn contrato_key_consts_are_pairwise_distinct() {
22512        // Cross-axis drift-detection pin: a future collapse of the six
22513        // canonical [`WitContract`] per-entry byte-strings onto the same
22514        // value (e.g. an accidental copy-paste flip of
22515        // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
22516        // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
22517        // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
22518        // every downstream probe on one axis onto the sibling axis's
22519        // overlay entry and pass every propagation-probe test that
22520        // expected only the stale axis's value. Peer of the sibling
22521        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
22522        // widened here to the six-way axis the `WitContract`
22523        // required-triad + `WitTarget` payload-triad jointly cover.
22524        let all = [
22525            crate::CONTRATO_KEY_DE,
22526            crate::CONTRATO_KEY_PARA,
22527            crate::CONTRATO_KEY_WIT,
22528            WitTarget::HTTP_FIELD_NAME,
22529            WitTarget::PUBSUB_FIELD_NAME,
22530            WitTarget::STORE_FIELD_NAME,
22531        ];
22532        for (i, a) in all.iter().enumerate() {
22533            for b in all.iter().skip(i + 1) {
22534                assert_ne!(
22535                    a, b,
22536                    "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
22537                     must be pairwise-distinct canonical byte-sequences \
22538                     — got `{a}` == `{b}`",
22539                );
22540            }
22541        }
22542    }
22543
22544    #[test]
22545    fn contrato_key_consts_are_lower_camel_case_shape() {
22546        // Shape-pin: every `CONTRATO_KEY_*` (and every peer
22547        // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
22548        // byte-sequence (no `snake_case` underscores, no `kebab-case`
22549        // hyphens, no leading colon, no `PascalCase` leading capital, no
22550        // whitespace / dots) — the canonical shape the
22551        // `#[serde(rename_all = "camelCase")]` derive produces on
22552        // [`WitContract`]. A future flip to a non-camelCase attribute at
22553        // the derive surfaces both here (this test fails on the
22554        // stale-constant shape) and at
22555        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
22556        // (that test fails on the mismatch between const and derive).
22557        // Peer with `membro_key_consts_are_lower_camel_case_shape`
22558        // (ce80ca0) on the sibling `Membro` per-entry axis.
22559        for key in [
22560            crate::CONTRATO_KEY_DE,
22561            crate::CONTRATO_KEY_PARA,
22562            crate::CONTRATO_KEY_WIT,
22563            WitTarget::HTTP_FIELD_NAME,
22564            WitTarget::PUBSUB_FIELD_NAME,
22565            WitTarget::STORE_FIELD_NAME,
22566        ] {
22567            assert!(
22568                !key.is_empty(),
22569                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
22570                 non-empty (got {key:?})"
22571            );
22572            let first = key.chars().next().unwrap();
22573            assert!(
22574                first.is_ascii_lowercase(),
22575                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
22576                 with an ASCII-lowercase byte (got {key:?}, leads with \
22577                 {first:?})",
22578            );
22579            assert!(
22580                key.chars().all(|c| c.is_ascii_alphanumeric()),
22581                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
22582                 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
22583                 whitespace (got {key:?})",
22584            );
22585        }
22586    }
22587
22588    // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
22589
22590    #[test]
22591    fn entrada_serde_keys_match_lifted_entrada_key_consts() {
22592        // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
22593        // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
22594        // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
22595        // name the exact camelCase JSON keys the
22596        // `#[serde(rename_all = "camelCase")]` attribute on
22597        // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
22598        // pin that each canonical byte-sequence appears verbatim in the
22599        // JSON — a future accidental `rename_all = "snake_case"` /
22600        // `"kebab-case"` / verbatim-field-name flip at the derive
22601        // attribute (any of which would silently break every downstream
22602        // JSON consumer that reaches for one of the four consts via
22603        // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
22604        // emitter's per-Aplicacao hostname/paths/port projection, the
22605        // future `app-operator` reconciler's per-Aplicacao ingress
22606        // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
22607        // materializer's admission-time cross-check) surfaces here as
22608        // a build-time test failure at `aplicacao.rs`, not as an
22609        // apply-time `.get(<stale-canonical-const>)` returning `None`
22610        // far from the derive-attr drift's commit. Peer with the
22611        // sibling
22612        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
22613        // (ca463a4) and
22614        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
22615        // pins on the M3 collection-slot atom axes — same discipline
22616        // both collection-slot lifts established, extended here to the
22617        // singleton `:entrada` mesh-slot atom axis, the last M3
22618        // typed-struct top-level `#[serde(rename_all = "camelCase")]`
22619        // axis on the Aplicacao surface without a lifted serde-key
22620        // peer.
22621        let e = Entrada {
22622            host: "checkout.quero.cloud".into(),
22623            para: "cart".into(),
22624            paths: vec!["/cart".into()],
22625            port: 8080,
22626        };
22627        let json = serde_json::to_string(&e).unwrap();
22628        for key in [
22629            crate::ENTRADA_KEY_HOST,
22630            crate::ENTRADA_KEY_PARA,
22631            crate::ENTRADA_KEY_PATHS,
22632            crate::ENTRADA_KEY_PORT,
22633        ] {
22634            let quoted = format!("\"{key}\"");
22635            assert!(
22636                json.contains(&quoted),
22637                "serialized Entrada must carry the lifted ENTRADA_KEY_* \
22638                 byte-sequence {quoted} verbatim in the JSON emission \
22639                 (got: {json})",
22640            );
22641        }
22642    }
22643
22644    #[test]
22645    fn entrada_key_consts_are_pairwise_distinct() {
22646        // Cross-axis drift-detection pin: a future collapse of the four
22647        // canonical [`Entrada`] singleton byte-strings onto the same
22648        // value (e.g. an accidental copy-paste flip of
22649        // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
22650        // silently reroute every downstream probe on one axis onto the
22651        // sibling axis's overlay entry and pass every propagation-probe
22652        // test that expected only the stale axis's value — the
22653        // Gateway/HTTPRoute emitter would read the hostname string
22654        // where the destination-Servico name was expected (or vice
22655        // versa), the admission-webhook cross-check would compare the
22656        // wrong pair of values, and the resulting Gateway resource
22657        // would either be admitted with garbage or rejected at the
22658        // controller far from the rebrand commit's source. Peer of the
22659        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
22660        // tetrad (40cc4e5), the two-way distinct pin on the
22661        // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
22662        // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
22663        // triad (ca463a4).
22664        let all = [
22665            crate::ENTRADA_KEY_HOST,
22666            crate::ENTRADA_KEY_PARA,
22667            crate::ENTRADA_KEY_PATHS,
22668            crate::ENTRADA_KEY_PORT,
22669        ];
22670        for (i, a) in all.iter().enumerate() {
22671            for b in all.iter().skip(i + 1) {
22672                assert_ne!(
22673                    a, b,
22674                    "ENTRADA_KEY_* consts must be pairwise-distinct \
22675                     canonical byte-sequences — got `{a}` == `{b}`",
22676                );
22677            }
22678        }
22679    }
22680
22681    #[test]
22682    fn entrada_key_consts_are_lower_camel_case_shape() {
22683        // Shape-pin: every `ENTRADA_KEY_*` const must be a
22684        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
22685        // `kebab-case` hyphens, no leading colon, no `PascalCase`
22686        // leading capital, no whitespace / dots) — the canonical shape
22687        // the `#[serde(rename_all = "camelCase")]` derive produces on
22688        // [`Entrada`]. A future flip to a non-camelCase attribute at
22689        // the derive surfaces both here (this test fails on the
22690        // stale-constant shape) and at
22691        // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
22692        // test fails on the mismatch between const and derive). Peer
22693        // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
22694        // and `contrato_key_consts_are_lower_camel_case_shape`
22695        // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
22696        // entry axes.
22697        for key in [
22698            crate::ENTRADA_KEY_HOST,
22699            crate::ENTRADA_KEY_PARA,
22700            crate::ENTRADA_KEY_PATHS,
22701            crate::ENTRADA_KEY_PORT,
22702        ] {
22703            assert!(
22704                !key.is_empty(),
22705                "ENTRADA_KEY_* must be non-empty (got {key:?})"
22706            );
22707            let first = key.chars().next().unwrap();
22708            assert!(
22709                first.is_ascii_lowercase(),
22710                "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
22711                 (got {key:?}, leads with {first:?})",
22712            );
22713            assert!(
22714                key.chars().all(|c| c.is_ascii_alphanumeric()),
22715                "ENTRADA_KEY_* must be ASCII-alphanumeric only \
22716                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
22717            );
22718        }
22719    }
22720
22721    // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
22722
22723    #[test]
22724    fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
22725        // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
22726        // ([`crate::POLITICAS_KEY_TIMEOUT`] /
22727        // [`crate::POLITICAS_KEY_RETRIES`] /
22728        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
22729        // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
22730        // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
22731        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
22732        // on [`MeshPolicy`] emits. Three of the five axes
22733        // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
22734        // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
22735        // camelCase transforms — the derive-attribute is load-bearing
22736        // on those, unlike the sibling `Entrada` / `Membro` /
22737        // `WitContract` structs whose fields are all lowercase-single-
22738        // word and where the derive is a no-op on every axis.
22739        // Serialize a fully-populated [`MeshPolicy`] (every axis
22740        // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
22741        // on none of the five slots) and pin that each canonical
22742        // byte-sequence appears verbatim in the JSON — a future
22743        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
22744        // verbatim-field-name flip at the derive attribute (any of
22745        // which would silently break every downstream JSON consumer
22746        // that reaches for one of the five consts via
22747        // `Value::get(...)` — the future M4 per-edge `:politicas`
22748        // overlay projection onto Cilium `L7Rules` and Gateway API
22749        // `HTTPRoute` backend timeouts, the future
22750        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
22751        // admission-time mesh-policy cross-check, the future
22752        // `feira lint` per-`:politicas` bound-check gate) surfaces here
22753        // as a build-time test failure at `aplicacao.rs`, not as an
22754        // apply-time `.get(<stale-canonical-const>)` returning `None`
22755        // far from the derive-attr drift's commit. Peer with the
22756        // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
22757        // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
22758        // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
22759        // (ce80ca0) pins on the M3 collection-slot / singleton-slot
22760        // atom axes — same discipline every M3 sibling lift
22761        // established, extended here to the singleton `:politicas`
22762        // mesh-slot atom axis, closing the last M3 typed-struct
22763        // top-level `#[serde(rename_all = "camelCase")]` axis on the
22764        // Aplicacao surface without a lifted serde-key peer.
22765        let p = MeshPolicy {
22766            timeout: Some(Duration::from_secs(30)),
22767            retries: Some(3),
22768            circuit_breaker: Some(CircuitBreaker {
22769                max_failures: 5,
22770                window: Duration::from_secs(60),
22771            }),
22772            mtls_required: Some(true),
22773            rate_limit: Some(RateLimit {
22774                rate: 100,
22775                window: Duration::from_secs(1),
22776            }),
22777        };
22778        let json = serde_json::to_string(&p).unwrap();
22779        for key in [
22780            crate::POLITICAS_KEY_TIMEOUT,
22781            crate::POLITICAS_KEY_RETRIES,
22782            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
22783            crate::POLITICAS_KEY_MTLS_REQUIRED,
22784            crate::POLITICAS_KEY_RATE_LIMIT,
22785        ] {
22786            let quoted = format!("\"{key}\"");
22787            assert!(
22788                json.contains(&quoted),
22789                "serialized MeshPolicy must carry the lifted \
22790                 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
22791                 JSON emission (got: {json})",
22792            );
22793        }
22794    }
22795
22796    #[test]
22797    fn politicas_key_consts_are_pairwise_distinct() {
22798        // Cross-axis drift-detection pin: a future collapse of the five
22799        // canonical [`MeshPolicy`] singleton byte-strings onto the same
22800        // value (e.g. an accidental copy-paste flip of
22801        // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
22802        // would silently reroute every downstream probe on one axis
22803        // onto the sibling axis's overlay entry and pass every
22804        // propagation-probe test that expected only the stale axis's
22805        // value — the M4 per-edge `:politicas` overlay projection would
22806        // read the retry-count string where the timeout duration was
22807        // expected (or vice versa), the CR materializer's admission
22808        // cross-check would compare the wrong pair of values, and the
22809        // resulting mesh reconciler would either bind the wrong axis
22810        // or reject the resource at reconcile far from the rebrand
22811        // commit's source. Peer of the sibling four-way distinct pin
22812        // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
22813        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
22814        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
22815        // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
22816        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
22817        let all = [
22818            crate::POLITICAS_KEY_TIMEOUT,
22819            crate::POLITICAS_KEY_RETRIES,
22820            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
22821            crate::POLITICAS_KEY_MTLS_REQUIRED,
22822            crate::POLITICAS_KEY_RATE_LIMIT,
22823        ];
22824        for (i, a) in all.iter().enumerate() {
22825            for b in all.iter().skip(i + 1) {
22826                assert_ne!(
22827                    a, b,
22828                    "POLITICAS_KEY_* consts must be pairwise-distinct \
22829                     canonical byte-sequences — got `{a}` == `{b}`",
22830                );
22831            }
22832        }
22833    }
22834
22835    #[test]
22836    fn politicas_key_consts_are_lower_camel_case_shape() {
22837        // Shape-pin: every `POLITICAS_KEY_*` const must be a
22838        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
22839        // `kebab-case` hyphens, no leading colon, no `PascalCase`
22840        // leading capital, no whitespace / dots) — the canonical shape
22841        // the `#[serde(rename_all = "camelCase")]` derive produces on
22842        // [`MeshPolicy`]. A future flip to a non-camelCase attribute
22843        // at the derive surfaces both here (this test fails on the
22844        // stale-constant shape) and at
22845        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
22846        // (that test fails on the mismatch between const and derive).
22847        // Peer with `entrada_key_consts_are_lower_camel_case_shape`
22848        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
22849        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
22850        // (ca463a4) on the sibling M3 typed-struct axes.
22851        for key in [
22852            crate::POLITICAS_KEY_TIMEOUT,
22853            crate::POLITICAS_KEY_RETRIES,
22854            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
22855            crate::POLITICAS_KEY_MTLS_REQUIRED,
22856            crate::POLITICAS_KEY_RATE_LIMIT,
22857        ] {
22858            assert!(
22859                !key.is_empty(),
22860                "POLITICAS_KEY_* must be non-empty (got {key:?})"
22861            );
22862            let first = key.chars().next().unwrap();
22863            assert!(
22864                first.is_ascii_lowercase(),
22865                "POLITICAS_KEY_* must lead with an ASCII-lowercase \
22866                 byte (got {key:?}, leads with {first:?})",
22867            );
22868            assert!(
22869                key.chars().all(|c| c.is_ascii_alphanumeric()),
22870                "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
22871                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
22872            );
22873        }
22874    }
22875
22876    // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
22877
22878    #[test]
22879    fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
22880        // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
22881        // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
22882        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
22883        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
22884        // [`CircuitBreaker`] emits inside the
22885        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
22886        // two axes (`max_failures` → `maxFailures`) is a non-trivial
22887        // camelCase transform — the derive-attribute is load-bearing on
22888        // that axis, unlike the sibling `window` field where the derive
22889        // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
22890        // pin that each canonical byte-sequence appears verbatim in the
22891        // JSON — a future accidental `rename_all = "snake_case"` /
22892        // `"kebab-case"` / verbatim-field-name flip at the derive
22893        // attribute (any of which would silently break every downstream
22894        // JSON consumer that reaches for one of the two consts via
22895        // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
22896        // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
22897        // per-edge `:politicas` overlay projection onto the mesh's
22898        // per-backend consecutive-failure-counter tripping threshold, the
22899        // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
22900        // admission-time breaker cross-check, the future `feira lint`
22901        // per-`:politicas :circuit-breaker` bound-check gate) surfaces
22902        // here as a build-time test failure at `aplicacao.rs`, not as an
22903        // apply-time `.get(<stale-canonical-const>)` returning `None`
22904        // far from the derive-attr drift's commit. Peer with the sibling
22905        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
22906        // (b55cca7) parent-axis pin — that test pins the outer
22907        // sub-block key the derive on [`MeshPolicy`] emits, this test
22908        // pins the inner keys the derive on the payload type emits, so
22909        // the two together lock the whole [`MeshPolicy`] breaker-tuning
22910        // shape end-to-end at build time.
22911        let cb = CircuitBreaker {
22912            max_failures: 5,
22913            window: Duration::from_secs(60),
22914        };
22915        let json = serde_json::to_string(&cb).unwrap();
22916        for key in [
22917            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
22918            crate::CIRCUIT_BREAKER_KEY_WINDOW,
22919        ] {
22920            let quoted = format!("\"{key}\"");
22921            assert!(
22922                json.contains(&quoted),
22923                "serialized CircuitBreaker must carry the lifted \
22924                 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
22925                 in the JSON emission (got: {json})",
22926            );
22927        }
22928    }
22929
22930    #[test]
22931    fn circuit_breaker_key_consts_are_pairwise_distinct() {
22932        // Cross-axis drift-detection pin: a future collapse of the two
22933        // canonical [`CircuitBreaker`] sub-block byte-strings onto the
22934        // same value (e.g. an accidental copy-paste flip of
22935        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
22936        // `"maxFailures"`) would silently reroute every downstream
22937        // probe on one axis onto the sibling axis's overlay entry and
22938        // pass every propagation-probe test that expected only the
22939        // stale axis's value — the M4 per-edge `:politicas` overlay
22940        // projection would read the failure-count where the window
22941        // duration was expected (or vice versa), the CR materializer's
22942        // admission cross-check would compare the wrong pair of values,
22943        // and the resulting mesh reconciler would either bind the wrong
22944        // axis or reject the resource at reconcile far from the rebrand
22945        // commit's source. Peer of the sibling five-way distinct pin on
22946        // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
22947        // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
22948        // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
22949        // six-way distinct pin on the `CONTRATO_KEY_*` triad +
22950        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
22951        let all = [
22952            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
22953            crate::CIRCUIT_BREAKER_KEY_WINDOW,
22954        ];
22955        for (i, a) in all.iter().enumerate() {
22956            for b in all.iter().skip(i + 1) {
22957                assert_ne!(
22958                    a, b,
22959                    "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
22960                     canonical byte-sequences — got `{a}` == `{b}`",
22961                );
22962            }
22963        }
22964    }
22965
22966    #[test]
22967    fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
22968        // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
22969        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
22970        // `kebab-case` hyphens, no leading colon, no `PascalCase`
22971        // leading capital, no whitespace / dots) — the canonical shape
22972        // the `#[serde(rename_all = "camelCase")]` derive produces on
22973        // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
22974        // at the derive surfaces both here (this test fails on the
22975        // stale-constant shape) and at
22976        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
22977        // (that test fails on the mismatch between const and derive).
22978        // Peer with `politicas_key_consts_are_lower_camel_case_shape`
22979        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
22980        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
22981        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
22982        // (ca463a4) on the sibling M3 typed-struct axes.
22983        for key in [
22984            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
22985            crate::CIRCUIT_BREAKER_KEY_WINDOW,
22986        ] {
22987            assert!(
22988                !key.is_empty(),
22989                "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
22990            );
22991            let first = key.chars().next().unwrap();
22992            assert!(
22993                first.is_ascii_lowercase(),
22994                "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
22995                 byte (got {key:?}, leads with {first:?})",
22996            );
22997            assert!(
22998                key.chars().all(|c| c.is_ascii_alphanumeric()),
22999                "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
23000                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
23001            );
23002        }
23003    }
23004
23005    // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
23006
23007    #[test]
23008    fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
23009        // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
23010        // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
23011        // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
23012        // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
23013        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
23014        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
23015        // [`Placement`] emits. One of the four axes (`shard_key` →
23016        // `shardKey`) is a non-trivial camelCase transform — the
23017        // derive-attribute is load-bearing on that axis, unlike the
23018        // sibling `estrategia` / `clusters` / `affinity` axes whose
23019        // source-side field names carry no `_` and where the derive is a
23020        // no-op. Serialize a fully-populated [`Placement`] (both
23021        // `Option`-carrying axes `Some(_)` so
23022        // `skip_serializing_if = "Option::is_none"` fires on neither of
23023        // the two optional slots) and pin that each canonical
23024        // byte-sequence appears verbatim in the JSON — a future
23025        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
23026        // verbatim-field-name flip at the derive attribute (any of which
23027        // would silently break every downstream consumer that reaches
23028        // for one of the four consts via
23029        // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
23030        // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
23031        // aggregator's per-cluster fanout filter keying off
23032        // `placement.clusters`, the M3 shard-pool dispatch materializer
23033        // keying off `placement.shardKey`, the M3 Adaptive compression
23034        // pass weighting off `placement.affinity`, every downstream
23035        // dispatcher branching on `placement.estrategia`, the future
23036        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
23037        // admission-time placement cross-check, the future `feira lint`
23038        // per-`:placement` bound-check gate) surfaces here as a
23039        // build-time test failure at `aplicacao.rs`, not as an
23040        // apply-time `.get(<stale-canonical-const>)` returning `None`
23041        // far from the derive-attr drift's commit. Peer with the sibling
23042        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
23043        // (b55cca7),
23044        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
23045        // (468e959),
23046        // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
23047        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
23048        // (ca463a4), and
23049        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
23050        // pins on the M3 collection-slot / singleton-slot atom axes —
23051        // closes the last M3 typed-struct top-level
23052        // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
23053        // surface without a drift-detection pin.
23054        let p = Placement {
23055            estrategia: PlacementStrategy::Sharded,
23056            clusters: vec!["rio".into(), "mar".into()],
23057            affinity: Some("data-locality".into()),
23058            shard_key: Some("$tenantId".into()),
23059        };
23060        let json = serde_json::to_string(&p).unwrap();
23061        for key in [
23062            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
23063            crate::M3_PLACEMENT_KEY_CLUSTERS,
23064            crate::M3_PLACEMENT_KEY_AFFINITY,
23065            crate::M3_PLACEMENT_KEY_SHARD_KEY,
23066        ] {
23067            let quoted = format!("\"{key}\"");
23068            assert!(
23069                json.contains(&quoted),
23070                "serialized Placement must carry the lifted \
23071                 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
23072                 the JSON emission (got: {json})",
23073            );
23074        }
23075    }
23076
23077    #[test]
23078    fn m3_placement_key_consts_are_pairwise_distinct() {
23079        // Cross-axis drift-detection pin: a future collapse of the four
23080        // canonical [`Placement`] sub-block byte-strings onto the same
23081        // value (e.g. an accidental copy-paste flip of
23082        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
23083        // `"affinity"`) would silently reroute every downstream probe on
23084        // one axis onto the sibling axis's overlay entry and pass every
23085        // propagation-probe test that expected only the stale axis's
23086        // value — the M3 shard-pool dispatch materializer would read the
23087        // affinity placement-hint where the shard-selection template was
23088        // expected (or vice versa), the M3 Adaptive compression pass's
23089        // cross-check would compare the wrong pair of values, and the
23090        // resulting placement engine would either bind the wrong axis or
23091        // reject the resource at reconcile far from the rebrand commit's
23092        // source. Peer of the sibling two-way distinct pin on the
23093        // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
23094        // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
23095        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
23096        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
23097        // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
23098        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
23099        let all = [
23100            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
23101            crate::M3_PLACEMENT_KEY_CLUSTERS,
23102            crate::M3_PLACEMENT_KEY_AFFINITY,
23103            crate::M3_PLACEMENT_KEY_SHARD_KEY,
23104        ];
23105        for (i, a) in all.iter().enumerate() {
23106            for b in all.iter().skip(i + 1) {
23107                assert_ne!(
23108                    a, b,
23109                    "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
23110                     canonical byte-sequences — got `{a}` == `{b}`",
23111                );
23112            }
23113        }
23114    }
23115
23116    #[test]
23117    fn m3_placement_key_consts_are_lower_camel_case_shape() {
23118        // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
23119        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
23120        // `kebab-case` hyphens, no leading colon, no `PascalCase`
23121        // leading capital, no whitespace / dots) — the canonical shape
23122        // the `#[serde(rename_all = "camelCase")]` derive produces on
23123        // [`Placement`]. A future flip to a non-camelCase attribute at
23124        // the derive surfaces both here (this test fails on the stale-
23125        // constant shape) and at
23126        // `placement_serde_keys_match_lifted_m3_placement_key_consts`
23127        // (that test fails on the mismatch between const and derive).
23128        // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
23129        // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
23130        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
23131        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
23132        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
23133        // (ca463a4) on the sibling M3 typed-struct axes.
23134        for key in [
23135            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
23136            crate::M3_PLACEMENT_KEY_CLUSTERS,
23137            crate::M3_PLACEMENT_KEY_AFFINITY,
23138            crate::M3_PLACEMENT_KEY_SHARD_KEY,
23139        ] {
23140            assert!(
23141                !key.is_empty(),
23142                "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
23143            );
23144            let first = key.chars().next().unwrap();
23145            assert!(
23146                first.is_ascii_lowercase(),
23147                "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
23148                 byte (got {key:?}, leads with {first:?})",
23149            );
23150            assert!(
23151                key.chars().all(|c| c.is_ascii_alphanumeric()),
23152                "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
23153                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
23154            );
23155        }
23156    }
23157
23158    // ── AplicacaoSpec::port_for_destination — the substrate-canonical
23159    //    destination-facing L4 port resolver every per-Aplicacao renderer
23160    //    reaching for a per-destination Servico TCP port axis routes
23161    //    through. The four pin tests below fix the four-way accept-set
23162    //    the resolver must always honor: (:entrada-para-matches,
23163    //    :entrada-para-mismatches, :entrada-none-so-fallback,
23164    //    :entrada-port-non-default-honored) — drift on any arm surfaces
23165    //    at caixa-core build time rather than at cluster-apply time.
23166
23167    #[test]
23168    fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
23169        // The typed `:entrada` block's `:para "cart"` matches the
23170        // queried destination, so the resolver returns the author-
23171        // declared `:port` scalar verbatim — the canonical "the
23172        // destination Servico IS the ingress apex, honor the typed
23173        // listener port" arm of the port-resolution dispatch.
23174        let mut spec = three_member_spec();
23175        if let Some(e) = spec.entrada.as_mut() {
23176            e.para = "cart".into();
23177            e.port = 9090;
23178        }
23179        assert_eq!(
23180            spec.port_for_destination("cart"),
23181            9090,
23182            "port_for_destination(entrada.para) must return entrada.port \
23183             verbatim, not the DEFAULT_SERVICO_PORT fallback"
23184        );
23185    }
23186
23187    #[test]
23188    fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
23189        // The typed `:entrada` block names `:para "cart"`, but the
23190        // queried destination is `"payment"` — a Servico that
23191        // participates in the mesh graph but is not the ingress apex.
23192        // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
23193        // canonical port floor, closing the "non-apex destination reads
23194        // the substrate default" arm. Same fixture the peer
23195        // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
23196        // pin at caixa-mesh exercises through the CNP emit-side path;
23197        // this pin exercises the shared underlying resolver directly.
23198        let spec = three_member_spec();
23199        assert_eq!(
23200            spec.port_for_destination("payment"),
23201            DEFAULT_SERVICO_PORT,
23202            "port_for_destination(non-apex-destination) must route \
23203             through the lifted DEFAULT_SERVICO_PORT canonical port floor"
23204        );
23205    }
23206
23207    #[test]
23208    fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
23209        // Internal-only Aplicacao — no `:entrada` block declared. Every
23210        // per-destination port query falls back to the lifted
23211        // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
23212        // the Aplicacao surface admits `:entrada None` (internal mesh
23213        // with no external gateway); every downstream renderer's per-
23214        // destination port axis must still resolve to a well-defined
23215        // scalar even without an ingress apex.
23216        let mut spec = three_member_spec();
23217        spec.entrada = None;
23218        assert_eq!(
23219            spec.port_for_destination("cart"),
23220            DEFAULT_SERVICO_PORT,
23221            "port_for_destination on an internal-only Aplicacao must \
23222             fall back to the lifted DEFAULT_SERVICO_PORT floor for \
23223             every destination"
23224        );
23225        assert_eq!(
23226            spec.port_for_destination("payment"),
23227            DEFAULT_SERVICO_PORT,
23228            "port_for_destination on an internal-only Aplicacao must \
23229             fall back uniformly across every destination — the fallback \
23230             is not entrada-shape-conditional"
23231        );
23232    }
23233
23234    #[test]
23235    fn port_for_destination_honors_non_default_entrada_port_verbatim() {
23236        // Structural pin against a hypothetical future refactor that
23237        // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
23238        // the resolver (a "normalize to the default when the author's
23239        // port matches the substrate default" collapse) — that would
23240        // break renderer sites that carry meaning on the emitted port
23241        // value beyond bare equality (a future per-cluster listener-
23242        // audit that keys off the author-declared port, not the
23243        // resolved-with-fallback port). Pin that a non-default
23244        // entrada.port is returned verbatim so drift here surfaces at
23245        // caixa-core build time.
23246        let mut spec = three_member_spec();
23247        if let Some(e) = spec.entrada.as_mut() {
23248            e.para = "cart".into();
23249            e.port = 8443;
23250        }
23251        assert_ne!(
23252            8443, DEFAULT_SERVICO_PORT,
23253            "test fixture must probe a port distinct from \
23254             DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
23255        );
23256        assert_eq!(
23257            spec.port_for_destination("cart"),
23258            8443,
23259            "port_for_destination(entrada.para) must return entrada.port \
23260             verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
23261        );
23262    }
23263
23264    #[test]
23265    fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
23266        // Apex-identity pair-invariant pin composing both substrate-
23267        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
23268        // and [`Entrada::destination`] — at the emit-side call shape
23269        // every per-Aplicacao renderer's ingress-apex L4 port reader
23270        // now takes. The invariant:
23271        //
23272        //   spec.port_for_destination(entrada.destination()) == entrada.port
23273        //
23274        // holds by construction under today's single-destination
23275        // `:entrada` slot (`destination()` returns `entrada.para`, and
23276        // the resolver's apex arm matches `para == destination` and
23277        // returns `entrada.port`), and every downstream consumer that
23278        // composes the two accessors at the ingress apex — the
23279        // `caixa_mesh::gateway_routes` HTTPRoute per-rule
23280        // `backendRefs[0].port` emit-site path, the peer future M4 CR
23281        // materializer's admission-webhook that promotes the scalar to
23282        // a per-CR override overlay, every future per-Aplicacao snapshot
23283        // renderer's apex-facing L4 port reader — reaches through the
23284        // same composition. Pin the identity across four permutations
23285        // (`:para` × `:port` including a non-default port to exercise
23286        // the honor-verbatim arm and a non-cart `:para` to exercise
23287        // destination-agnostic identity) so a future refactor that
23288        // silently split either accessor's apex behavior surfaces at
23289        // caixa-core build time — a subtle `destination()` renaming
23290        // that returned `entrada.host.as_str()` instead of
23291        // `entrada.para.as_str()` would blow this pin loudly, closing
23292        // the last quiet failure mode the two lifts admit in composition.
23293        //
23294        // Peer discipline with the sibling caixa-mesh cross-crate pin
23295        // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
23296        // on the two-renderer pair-invariant axis; this pin encodes the
23297        // same two-consumer coherence rule at the substrate-primitive
23298        // level so the invariant survives even if every renderer is
23299        // deleted.
23300        for (para, port) in [
23301            ("cart", DEFAULT_SERVICO_PORT),
23302            ("cart", 8443u16),
23303            ("payment", 9090u16),
23304            ("catalog", 443u16),
23305        ] {
23306            let mut spec = three_member_spec();
23307            if let Some(e) = spec.entrada.as_mut() {
23308                e.para = para.into();
23309                e.port = port;
23310            }
23311            let expected_port = spec
23312                .entrada
23313                .as_ref()
23314                .expect("three_member_spec carries a typed `:entrada` block")
23315                .port;
23316            let composed_port = {
23317                let entrada = spec.entrada.as_ref().expect("entrada present");
23318                spec.port_for_destination(entrada.destination())
23319            };
23320            assert_eq!(
23321                composed_port, expected_port,
23322                "`spec.port_for_destination(entrada.destination())` must \
23323                 equal `entrada.port` under today's single-destination \
23324                 `:entrada` slot — this is the apex-identity contract \
23325                 every downstream ingress-apex L4 port reader relies on. \
23326                 Input :entrada :para: {para:?}, :entrada :port: {port}"
23327            );
23328        }
23329    }
23330
23331    #[test]
23332    fn port_for_destination_apex_arm_routes_through_destination_accessor() {
23333        // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
23334        // per-`:entrada` apex-arm membership probe must key off
23335        // [`Entrada::destination`], not the raw `.para` field access.
23336        // Structurally: setting ONLY the `:entrada :para` field to a
23337        // fresh non-cart destination on an otherwise-well-formed
23338        // Aplicacao must (1) leave `e.destination()` byte-equal to
23339        // `e.para.as_str()` (the accessor is byte-projective by
23340        // definition), and (2) cause the resolver's apex arm to fire
23341        // and return `entrada.port` at exactly that new destination
23342        // while every other destination string falls through to
23343        // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
23344        // membership check. Pins against a future silent detour that
23345        // (a) re-derived the apex-arm membership probe off
23346        // `e.para == destination` in `port_for_destination` instead of
23347        // `e.destination() == destination`, silently disagreeing with
23348        // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
23349        // consumers (`entrada.destination()` at
23350        // caixa-mesh/src/lib.rs:3173, `c.destination()` at
23351        // caixa-mesh/src/lib.rs:2739) that already reach through the
23352        // accessor, (b) accessor-side introduced a per-tenant alias
23353        // arm the caller was unaware of, silently rewriting an
23354        // author-declared `:para "cart"` value to a canary-aliased
23355        // form — the raw-field-access resolver would fall through to
23356        // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
23357        // while the peer emit-site consumers landed on the aliased
23358        // destination, splitting the ingress-apex L4 port at
23359        // cluster-apply time.
23360        //
23361        // Peer of the sibling
23362        // [`validate_membros_empty_gate_routes_through_nome_accessor`]
23363        // (d0de220) composition pin on the per-`:membros` refusal-arm
23364        // axis — same "the shape-gate predicate must route through the
23365        // substrate-primitive typed dispatch" discipline extended onto
23366        // the per-`:entrada` apex-arm membership-probe axis. Closes
23367        // the last unlifted `.para` production-code read site on
23368        // `Entrada` in `caixa-core` — after this converge every
23369        // `caixa-core` `.para` field access outside the accessor's own
23370        // body and outside the `WitContract` per-`:contratos` sibling
23371        // axis is either a test-side field-setter or a doc-comment
23372        // reference.
23373        for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
23374            let mut spec = three_member_spec();
23375            if let Some(e) = spec.entrada.as_mut() {
23376                e.para = para.into();
23377                e.port = port;
23378            }
23379            let e = spec
23380                .entrada
23381                .as_ref()
23382                .expect("three_member_spec carries a typed `:entrada` block");
23383            assert_eq!(
23384                e.destination(),
23385                e.para.as_str(),
23386                "Entrada::destination must byte-equal the .para field \
23387                 access — an accessor-side detour that no longer \
23388                 projects the raw field would silently split this \
23389                 drift-detection test from the port_for_destination \
23390                 apex-arm membership probe",
23391            );
23392            assert_eq!(
23393                spec.port_for_destination(para),
23394                port,
23395                "port_for_destination must key off the accessor-projected \
23396                 destination and return `entrada.port` on the apex arm — \
23397                 input :entrada :para: {para:?}, :entrada :port: {port}",
23398            );
23399            assert_eq!(
23400                spec.port_for_destination("ghost-destination-never-a-member"),
23401                DEFAULT_SERVICO_PORT,
23402                "port_for_destination must fall through to \
23403                 DEFAULT_SERVICO_PORT on a non-matching destination \
23404                 under the accessor-projected membership check — input \
23405                 :entrada :para: {para:?}, :entrada :port: {port}",
23406            );
23407        }
23408    }
23409
23410    #[test]
23411    fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
23412        // The canonical per-`:politicas :rate-limit` `:rate`
23413        // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
23414        // [`RateLimit::rate`] must return the `:politicas :rate-limit`
23415        // typed `u32` verbatim, byte-equal to the raw field access
23416        // across every representative value in the accept-set — `1` (the
23417        // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
23418        // the surrounding [`AplicacaoSpec::validate_politicas`] gate
23419        // carves out on the sibling `PolicyRateLimitZero` refusal),
23420        // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
23421        // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
23422        // `0` (a past-the-guard sentinel that pins the accessor doesn't
23423        // perform a silent bounds-collapse into `1` on the zero arm —
23424        // validate rejects zero but the accessor must ship the raw slot
23425        // verbatim so a validate-time gate regression surfaces at the
23426        // emit boundary rather than being silently absorbed), `u32::MAX`
23427        // (a past-the-guard sentinel that pins the accessor doesn't
23428        // perform a silent bounds-collapse through
23429        // `POLICY_RATE_LIMIT_MAX` at the return path).
23430        //
23431        // First sub-struct required-scalar accessor pin on the
23432        // `RateLimit` axis — sibling in shape to the peer
23433        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
23434        // required-`u32` accessor pin on the peer per-sub-struct
23435        // required-axis. Pins against a future silent detour that
23436        // re-derived the token capacity from a peer axis (an accidental
23437        // `self.window.as_secs() as u32` collapse that read the
23438        // rate-limit window duration as a token count), a `0 → 1`
23439        // cluster-default projection (which would silently absorb the
23440        // `PolicyRateLimitZero` refusal case at the accessor boundary),
23441        // or a bounds-collapsing accessor that clamped the return
23442        // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
23443        // gate owns the bounds; the accessor must ship the raw slot
23444        // verbatim).
23445        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
23446            let rl = RateLimit {
23447                rate,
23448                window: Duration::from_secs(1),
23449            };
23450            assert_eq!(
23451                rl.rate(),
23452                rate,
23453                "RateLimit::rate must return :politicas :rate-limit :rate \
23454                 verbatim (got {}, expected {rate})",
23455                rl.rate(),
23456            );
23457            assert_eq!(
23458                rl.rate(),
23459                rl.rate,
23460                "RateLimit::rate must byte-equal the raw .rate field \
23461                 access across every value in the u32 accept-set",
23462            );
23463        }
23464    }
23465
23466    #[test]
23467    fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
23468        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
23469        // `:rate-limit :rate` zero-floor arm must key off
23470        // [`RateLimit::rate`], not the raw `.rate` field access.
23471        // Structurally: a `RateLimit { rate: 0, window:
23472        // Duration::from_secs(1) }` embedded in a `:politicas
23473        // :rate-limit` slot must surface the `PolicyRateLimitZero`
23474        // refusal exactly, and a `RateLimit { rate: 1, window:
23475        // Duration::from_secs(1) }` (the lower boundary of the
23476        // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
23477        // The pair jointly pins the accessor + validate-gate composition:
23478        // any future silent detour that had the accessor return a fresh
23479        // `1` on the zero arm (a `.rate().max(1)` collapse) would
23480        // silently absorb the `PolicyRateLimitZero` refusal at the
23481        // accessor boundary and the validate gate would accept a
23482        // struct-literal `RateLimit { rate: 0, .. }` — the composition
23483        // pin catches that at caixa-core build time.
23484        //
23485        // Peer of the sibling per-`CircuitBreaker`
23486        // [`CircuitBreaker::max_failures`] (3a74062) /
23487        // [`CircuitBreaker::window`] (373957f) accessor-composition
23488        // pins on the peer required-scalar axes — same "the validate /
23489        // shape-gate predicate must route through the substrate-primitive
23490        // typed dispatch" discipline extended onto the peer
23491        // per-`RateLimit` required-`u32` composition axis.
23492        let mut spec = three_member_spec();
23493        spec.politicas = MeshPolicy {
23494            rate_limit: Some(RateLimit {
23495                rate: 0,
23496                window: Duration::from_secs(1),
23497            }),
23498            ..MeshPolicy::default()
23499        };
23500        assert!(
23501            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
23502            "validate_politicas must reject rate == 0 with \
23503             PolicyRateLimitZero — the accessor and the validate gate \
23504             must route through the same substrate-primitive typed \
23505             dispatch on the :rate zero-floor arm",
23506        );
23507        spec.politicas = MeshPolicy {
23508            rate_limit: Some(RateLimit {
23509                rate: 1,
23510                window: Duration::from_secs(1),
23511            }),
23512            ..MeshPolicy::default()
23513        };
23514        assert!(
23515            spec.validate().is_ok(),
23516            "validate_politicas must accept rate == 1 (the lower \
23517             boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
23518        );
23519    }
23520
23521    #[test]
23522    fn rate_limit_rate_projects_u32_by_copy() {
23523        // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
23524        // `u32` is `Copy` and the accessor must return by value, not by
23525        // reference. Peer of the sibling per-`CircuitBreaker`
23526        // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
23527        // peer required-scalar `:max-failures` axis, extended onto the
23528        // peer per-`RateLimit` required-`u32` copy-invariant shape —
23529        // the accessor's returned `u32` must outlive `&self` (multiple
23530        // calls must return equal values from a dropped-`&self` copy,
23531        // since the returned scalar carries no borrow), and calling the
23532        // accessor twice on the same RateLimit must yield the same
23533        // `u32` verbatim (idempotent, no side effects on `&self`).
23534        //
23535        // Pins against a future silent detour that returned `&u32`
23536        // (which would type-check but silently break every downstream
23537        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
23538        // first parameter is `u32`, and `&u32` would fold to a detached
23539        // copy at the call site with a `*` deref the sibling accessors
23540        // don't need), an accidental `.rate.wrapping_add(0)` detour that
23541        // returned a fresh copy through an arithmetic no-op (breaking a
23542        // future `const fn` regression), or a one-arm-only accessor
23543        // that returned a saturating value on some sentinel input
23544        // (breaking the pass-through invariant the sibling required-
23545        // scalar accessors carry).
23546        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
23547            let rl = RateLimit {
23548                rate,
23549                window: Duration::from_secs(1),
23550            };
23551            let first = rl.rate();
23552            let second = rl.rate();
23553            assert_eq!(
23554                first, second,
23555                "RateLimit::rate must be idempotent — two successive \
23556                 calls on the same &self must return the same u32",
23557            );
23558            assert_eq!(
23559                first, rate,
23560                "RateLimit::rate must return :politicas :rate-limit :rate \
23561                 verbatim by copy — got {first}, expected {rate}",
23562            );
23563        }
23564    }
23565
23566    #[test]
23567    fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
23568        // The canonical per-`:politicas :rate-limit` `:window`
23569        // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
23570        // pin: [`RateLimit::window`] must return the
23571        // `:politicas :rate-limit :window` typed `Duration` verbatim,
23572        // byte-equal to the raw field access across every
23573        // representative value in the accept-set — `Duration::from_secs(1)`
23574        // (the `"s"` canonical window, the lower row of
23575        // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
23576        // [`AplicacaoSpec::validate_politicas`] gate accepts via
23577        // [`is_canonical_rate_limit_window`]),
23578        // `Duration::from_secs(60)` (the `"m"` canonical window, the
23579        // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
23580        // window, the upper row), `Duration::ZERO` (a past-the-guard
23581        // sentinel that pins the accessor doesn't perform a silent
23582        // bounds-collapse into `Duration::from_secs(1)` on the zero
23583        // arm — validate rejects an off-set window through
23584        // `PolicyRateLimitWindowNotCanonical` but the accessor must
23585        // ship the raw slot verbatim so a validate-time gate
23586        // regression surfaces at the emit boundary rather than being
23587        // silently absorbed), `Duration::from_millis(500)` (a
23588        // sub-canonical past-the-guard sentinel that pins the accessor
23589        // doesn't silently normalize a non-canonical fractional
23590        // magnitude onto the nearest canonical row).
23591        //
23592        // Second sub-struct required-scalar accessor pin on the
23593        // `RateLimit` axis — sibling in shape to the just-landed
23594        // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
23595        // accessor pin on the peer per-sub-struct required-axis,
23596        // extended onto the per-`RateLimit` required-`Duration` axis.
23597        // Pins against a future silent detour that re-derived the
23598        // refill period from a peer axis (an accidental
23599        // `Duration::from_secs(self.rate as u64)` collapse that read
23600        // the rate-limit token capacity as a refill-interval
23601        // duration), a `Duration::ZERO → Duration::from_secs(1)`
23602        // canonical-default projection (which would silently absorb
23603        // the `PolicyRateLimitWindowNotCanonical` refusal case at the
23604        // accessor boundary), or a canonical-set-collapsing accessor
23605        // that clamped the return through [`rate_limit_window_unit`]
23606        // (the `AplicacaoSpec::validate` gate owns the canonical-set
23607        // membership; the accessor must ship the raw slot verbatim).
23608        for window in [
23609            Duration::from_secs(1),
23610            Duration::from_secs(60),
23611            Duration::from_secs(3600),
23612            Duration::ZERO,
23613            Duration::from_millis(500),
23614        ] {
23615            let rl = RateLimit { rate: 100, window };
23616            assert_eq!(
23617                rl.window(),
23618                window,
23619                "RateLimit::window must return :politicas :rate-limit :window \
23620                 verbatim (got {:?}, expected {window:?})",
23621                rl.window(),
23622            );
23623            assert_eq!(
23624                rl.window(),
23625                rl.window,
23626                "RateLimit::window must byte-equal the raw .window field \
23627                 access across every value in the Duration accept-set",
23628            );
23629        }
23630    }
23631
23632    #[test]
23633    fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
23634        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
23635        // `:rate-limit :window` canonical-set arm must key off
23636        // [`RateLimit::window`], not the raw `.window` field access.
23637        // Structurally: a `RateLimit { window: Duration::from_millis(500),
23638        // .. }` embedded in a `:politicas :rate-limit` slot must
23639        // surface the `PolicyRateLimitWindowNotCanonical` refusal
23640        // exactly (with the sub-canonical `Duration::from_millis(500)`
23641        // magnitude carried through verbatim), and a `RateLimit
23642        // { window: Duration::from_secs(1), .. }` (the lower row of
23643        // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
23644        // The pair jointly pins the accessor + validate-gate
23645        // composition: any future silent detour that had the accessor
23646        // normalize the off-set window to the nearest canonical row
23647        // (a `.window().max(Duration::from_secs(1))` collapse, or a
23648        // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
23649        // collapse) would silently absorb the
23650        // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
23651        // boundary — including a drift in the error's `window` payload
23652        // (the emit-side diagnostic reader keys off the offending
23653        // magnitude verbatim, so a normalization at the accessor
23654        // boundary would silently pin the wrong magnitude in the
23655        // refusal). The composition pin catches that at caixa-core
23656        // build time.
23657        //
23658        // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
23659        // (7f81a60) accessor-composition pin on the peer required-
23660        // scalar `:rate` axis — same "the validate / shape-gate
23661        // predicate must route through the substrate-primitive typed
23662        // dispatch, and the error payload must project through the
23663        // same accessor" discipline extended onto the peer
23664        // per-`RateLimit` required-`Duration` composition axis.
23665        let mut spec = three_member_spec();
23666        spec.politicas = MeshPolicy {
23667            rate_limit: Some(RateLimit {
23668                rate: 100,
23669                window: Duration::from_millis(500),
23670            }),
23671            ..MeshPolicy::default()
23672        };
23673        match spec.validate() {
23674            Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
23675                assert_eq!(
23676                    window,
23677                    Duration::from_millis(500),
23678                    "PolicyRateLimitWindowNotCanonical must carry the \
23679                     offending :window magnitude verbatim through the \
23680                     accessor — got {window:?}, expected 500ms",
23681                );
23682            }
23683            other => panic!(
23684                "validate_politicas must reject non-canonical :window \
23685                 with PolicyRateLimitWindowNotCanonical — the accessor \
23686                 and the validate gate must route through the same \
23687                 substrate-primitive typed dispatch on the :window \
23688                 canonical-set arm; got {other:?}",
23689            ),
23690        }
23691        spec.politicas = MeshPolicy {
23692            rate_limit: Some(RateLimit {
23693                rate: 100,
23694                window: Duration::from_secs(1),
23695            }),
23696            ..MeshPolicy::default()
23697        };
23698        assert!(
23699            spec.validate().is_ok(),
23700            "validate_politicas must accept window == Duration::from_secs(1) \
23701             (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
23702        );
23703    }
23704
23705    #[test]
23706    fn rate_limit_window_projects_duration_by_copy() {
23707        // The by-copy pin: [`RateLimit::window`] returns `Duration`
23708        // by copy — `Duration` is `Copy` and the accessor must return
23709        // by value, not by reference. Peer of the sibling per-`RateLimit`
23710        // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
23711        // required-scalar `:rate` axis, extended onto the peer
23712        // per-`RateLimit` required-`Duration` copy-invariant shape —
23713        // the accessor's returned `Duration` must outlive `&self`
23714        // (multiple calls must return equal values from a
23715        // dropped-`&self` copy, since the returned scalar carries no
23716        // borrow), and calling the accessor twice on the same
23717        // RateLimit must yield the same `Duration` verbatim
23718        // (idempotent, no side effects on `&self`).
23719        //
23720        // Pins against a future silent detour that returned
23721        // `&Duration` (which would type-check but silently break every
23722        // downstream `Duration`-by-value consumer —
23723        // [`is_canonical_rate_limit_window`]'s first parameter is
23724        // `Duration`, and `&Duration` would fold to a detached copy at
23725        // the call site with a `*` deref the sibling accessors don't
23726        // need), an accidental `.window + Duration::ZERO` detour that
23727        // returned a fresh copy through an arithmetic no-op (breaking
23728        // a future `const fn` regression), or a one-arm-only accessor
23729        // that returned a canonical fallback on some sentinel input
23730        // (breaking the pass-through invariant the sibling required-
23731        // scalar accessors carry).
23732        for window in [
23733            Duration::from_secs(1),
23734            Duration::from_secs(60),
23735            Duration::from_secs(3600),
23736            Duration::ZERO,
23737            Duration::from_millis(500),
23738        ] {
23739            let rl = RateLimit { rate: 100, window };
23740            let first = rl.window();
23741            let second = rl.window();
23742            assert_eq!(
23743                first, second,
23744                "RateLimit::window must be idempotent — two successive \
23745                 calls on the same &self must return the same Duration",
23746            );
23747            assert_eq!(
23748                first, window,
23749                "RateLimit::window must return :politicas :rate-limit :window \
23750                 verbatim by copy — got {first:?}, expected {window:?}",
23751            );
23752        }
23753    }
23754}