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    /// True when this contract targets an HTTP-shaped WIT world.
748    #[must_use]
749    pub fn is_http(&self) -> bool {
750        wit_shape_is_http(self.world_ref())
751    }
752
753    /// True when this contract targets a pub-sub-shaped WIT world.
754    #[must_use]
755    pub fn is_pubsub(&self) -> bool {
756        wit_shape_is_pubsub(self.world_ref())
757    }
758
759    /// True when this contract targets a key/value-shaped WIT world.
760    #[must_use]
761    pub fn is_store(&self) -> bool {
762        wit_shape_is_store(self.world_ref())
763    }
764
765    /// True when this contract's caller equals its callee — a
766    /// structurally degenerate typed edge that no `:contratos` entry can
767    /// legitimately carry (MESH-COMPOSITION §III.1 — "Servico A calls
768    /// Servico B" is an *inter*-Servico contract between two distinct
769    /// graph nodes). A Servico contracting with itself resolves to an
770    /// in-process call the wasm-engine never routes through the mesh at
771    /// all, so no rendered `CiliumNetworkPolicy` / `HTTPRoute` /
772    /// per-edge policy can express the intended shape — the pub-sub
773    /// path silently rendered a self-allow rule that is a no-op (intra-
774    /// pod traffic bypasses the mesh entirely), and the synchronous
775    /// paths surfaced as a misleading `ContratoCycle` whose path was
776    /// `["cart", "cart"]` — framing a self-edge as a multi-node
777    /// deadlock. Every downstream consumer that must reject the shape
778    /// (the [`AplicacaoSpec::validate`] per-`:contratos` self-loop
779    /// gate at caixa-core/src/aplicacao.rs:5559, every future
780    /// per-`:contratos`-edge policy resolver on the M4 CR materializer
781    /// axis, every future adjacency-graph builder that must skip self-
782    /// edges rather than fold them into an incidental cycle) now keys
783    /// off exactly one typed dispatch on the substrate primitive, so
784    /// any future rebrand on the axis (an M4-typed-caller enum whose
785    /// identity comparison rule the accessor could route through, an
786    /// operator-side per-cluster caller/callee-alias table the
787    /// materializer resolves per-CR before the equality probe, a
788    /// promotion of the pointwise `==` to a set-membership check once
789    /// SimpleOneForOne-shaped dynamic replicas come into typed scope
790    /// so a per-replica self-edge is rejected under the same predicate)
791    /// migrates as a single caixa-core edit rather than a coordinated
792    /// rewrite of every downstream self-edge consumer. Composes
793    /// byte-for-byte through the lifted [`Self::source`] /
794    /// [`Self::destination`] scalar accessors — the accessor pair every
795    /// per-`:contratos` scalar-value axis already routes through — so
796    /// any future rebrand of the underlying `:de` / `:para` storage
797    /// (a lift from `String` to a typed `ServicoName(String)` newtype,
798    /// a per-Aplicacao interning arena the M4 CR materializer authors,
799    /// a `smol_str::SmolStr` inline-buffer swap) flows through the
800    /// same one body without a coordinated per-consumer rewrite.
801    ///
802    /// Sibling in shape to the peer per-`:contratos` shape-predicate
803    /// family [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
804    /// on the `:wit` world-ref axis — extended onto the per-edge
805    /// endpoint-equality axis: `is_http` / `is_pubsub` / `is_store`
806    /// partition the WIT-shape-space; `is_self_loop` partitions the
807    /// caller-callee identity-space. Named `is_self_loop()` to reflect
808    /// the graph-theoretic identity of the shape (a loop from a graph
809    /// node to itself, distinct from the sibling multi-node
810    /// `ContratoCycle` shape [`Self::detect_sync_cycles`] rejects) and
811    /// to match the [`AplicacaoError::ContratoSelfLoop`] diagnostic
812    /// variant already carrying the term.
813    #[must_use]
814    pub fn is_self_loop(&self) -> bool {
815        self.source() == self.destination()
816    }
817
818    /// Typed view of the contract's payload target. Enforces that the
819    /// `:wit` shape and the carried `:endpoint`/`:subject`/`:slot`
820    /// fields agree, and that each carried value is itself
821    /// value-shape valid:
822    ///
823    ///   - HTTP world (`wasi:http/*`, `http:*`) ⇒ exactly `:endpoint`,
824    ///     non-empty, leading-`/` (Cilium L7 `path` + Gateway API
825    ///     `PathPrefix` invariant — same shape required of `:entrada
826    ///     :paths`)
827    ///   - `PubSub` world (`nats:*`, `kafka:*`) ⇒ exactly `:subject`,
828    ///     non-empty (NATS / Kafka publish without a subject is a
829    ///     no-op subscribe, never the author's intent)
830    ///   - Store world (`wasi:keyvalue/*`, `kv:*`) ⇒ exactly `:slot`,
831    ///     non-empty (an empty slot template addresses the bucket
832    ///     root, defeating the per-key isolation the slot exists for)
833    ///   - Anything else ⇒ none of the three; the contract is a pure
834    ///     typed capability edge with no payload selector.
835    ///
836    /// Translates the Apollo Federation discipline ("conflicts are
837    /// errors at compile time, not warnings at runtime";
838    /// MESH-COMPOSITION §II.3) onto pleme-io's typed Aplicacao surface:
839    /// a contract whose WIT shape disagrees with its target field, or
840    /// whose target field carries a value-shape-invalid string, is a
841    /// build error — not a silent renderer drop. The returned
842    /// [`WitTarget`] view's `&str` payload is therefore guaranteed
843    /// non-empty (and absolute, for `Http`); every downstream consumer
844    /// (caixa-mesh's L7 emission, the M3 Gateway/HTTPRoute renderer,
845    /// the M4 per-edge policy resolver) can rely on that without
846    /// re-checking.
847    pub fn target(&self) -> Result<WitTarget<'_>, AplicacaoError> {
848        // Route the HTTP-shaped payload-target extraction through the
849        // lifted [`WitContract::endpoint`] accessor rather than the raw
850        // `self.endpoint.as_deref()` field access — the two production
851        // consumers of the per-`:contratos :endpoint` HTTP-shaped
852        // payload-carrier scalar (this method's Http-arm payload
853        // extraction, the [`AplicacaoSpec::validate`] duplicate-
854        // `:contratos` [`ContratoIdentity`] dedup-key HTTP arm) now key
855        // off exactly one typed dispatch on the substrate primitive, so
856        // any future rebrand on the axis (an M4 per-cluster endpoint-
857        // alias rewrite, a per-CR fully-qualified path prefix the M4
858        // materializer applies per-tenant, an M4 promotion from
859        // `Option<String>` to a typed HTTP path-template enum) migrates
860        // as a single caixa-core edit rather than a coordinated rewrite
861        // of the two call sites — peer of the sibling M3 per-`:placement`
862        // [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
863        // (74ec2d3) `Option<&str>` typed-dispatch discipline extended
864        // onto the per-`:contratos` HTTP-shaped payload-carrier axis.
865        let endpoint = self.endpoint();
866        let subject = self.subject();
867        // Route the store-arm payload-carrier scalar through the
868        // lifted [`WitContract::slot`] accessor rather than the raw
869        // `self.slot.as_deref()` field access — the two production
870        // consumers of the per-`:contratos :slot` key/value-store-
871        // shaped payload-carrier scalar (this method's Store-arm
872        // payload extraction, the [`AplicacaoSpec::validate`]
873        // duplicate-`:contratos` [`ContratoIdentity`] dedup-key store
874        // arm) now key off exactly one typed dispatch on the substrate
875        // primitive. Closes the last unlifted per-`:contratos`
876        // `Option<String>` axis, completing the payload-carrier
877        // accessor family peer of the sibling per-`:contratos`
878        // [`WitContract::endpoint`] (7020470) / [`WitContract::subject`]
879        // (90de675) lifts across the HTTP / pub-sub arms.
880        let slot = self.slot();
881        // Route the local `(de, para, wit)` triple-projection closure
882        // through the lifted [`WitContract::edge_triple`] typed accessor
883        // rather than re-inlining `(self.de.clone(), self.para.clone(),
884        // self.wit.clone())` — the eight [`AplicacaoError::Contrato*`]
885        // triple-carrying diagnostic constructors below (wrong-target /
886        // missing-target on all three payload arms + capability-with-
887        // payload + invalid-wit) now key off exactly one typed dispatch
888        // on the substrate-primitive composite projection, sibling to
889        // the peer [`WitContract::edge_pair`]-routed
890        // [`AplicacaoError::Empty*`]/`ContratoEndpointEmpty`/
891        // `ContratoSubjectEmpty`/`ContratoSlotEmpty` pair-carrying
892        // diagnostic constructors on the same per-`:contratos`
893        // diagnostic-construction surface.
894        let edge = || self.edge_triple();
895
896        // The `:wit` value drives every downstream dispatch — the
897        // is_http/is_pubsub/is_store prefix matchers below, the
898        // caixa-mesh L7-vs-L4 emission, the cycle-detector's pub-sub
899        // exclusion. Until this gate landed `target()` accepted any
900        // non-empty string and silently demoted unrecognized shapes to
901        // a capability-only edge (`:wit "WASI:HTTP/proxy"` — uppercase
902        // typo, `:wit "wasi-http/proxy"` — hyphen-instead-of-colon typo,
903        // `:wit "wasi:http proxy"` — whitespace, `:wit "wasi:"` — empty
904        // package, the paste-from-binary footgun a multi-line blob
905        // accidentally landing in the slot, the un-percent-encoded
906        // non-ASCII byte) — the canonical "I thought I had L7 HTTP
907        // routing, got L4-only" footgun. Empty is still pre-checked at
908        // the [`AplicacaoSpec::validate`] call site via the narrower
909        // [`AplicacaoError::EmptyWit`] variant (and fires first at the
910        // validate layer); the value-shape gate here picks up the
911        // structurally-invalid non-empty cases the empty check misses,
912        // and remains correct under direct `target()` calls outside
913        // validate (the predicate's defensive empty arm returns a
914        // parser-shaped reason rather than silently falling through to
915        // the Capability arm). Same trajectory as c4213a4 (WitContract
916        // endpoint/subject/slot value-shape gates lifted into
917        // `target()`) on the peer payload axes.
918        if let Err(reason) = crate::render::is_wit_world_ref(&self.wit) {
919            let (de, para, wit) = edge();
920            return Err(AplicacaoError::ContratoWitInvalid {
921                de,
922                para,
923                wit,
924                reason,
925            });
926        }
927
928        if self.is_http() {
929            if subject.is_some() || slot.is_some() {
930                let (de, para, wit) = edge();
931                return Err(AplicacaoError::ContratoWrongTarget {
932                    de,
933                    para,
934                    wit,
935                    expected: WitTarget::HTTP_FIELD_NAME,
936                });
937            }
938            let ep = endpoint.ok_or_else(|| {
939                let (de, para, wit) = edge();
940                AplicacaoError::ContratoMissingTarget {
941                    de,
942                    para,
943                    wit,
944                    expected: WitTarget::HTTP_FIELD_NAME,
945                }
946            })?;
947            if ep.is_empty() {
948                let (de, para) = self.edge_pair();
949                return Err(AplicacaoError::ContratoEndpointEmpty { de, para });
950            }
951            if !ep.starts_with('/') {
952                let (de, para) = self.edge_pair();
953                return Err(AplicacaoError::ContratoEndpointNotAbsolute {
954                    de,
955                    para,
956                    endpoint: ep.to_string(),
957                });
958            }
959            // The `:endpoint` lands verbatim as a Cilium L7 `path:` rule
960            // (caixa-mesh/src/lib.rs:311) and shares the K8s Gateway
961            // API v1 HTTPPathMatch.value admission grammar with the
962            // sibling `:entrada :paths` axis. Until this gate landed
963            // `target()` only refused the empty string + the missing-
964            // leading-`/` form; a structurally invalid endpoint
965            // (`"/charge?token=X"` — query in path slot, `"/foo bar"` —
966            // un-percent-encoded whitespace, `"/api/café"` — non-ASCII,
967            // `"/api//bar"` — consecutive slash, `"/api/../etc"` —
968            // path-traversal segment, the >1024-byte slug) silently
969            // passed validate and the failure surfaced at apply time
970            // as a Cilium policy rejection / silent traffic drop, far
971            // from the source caixa.lisp. Same Gateway API HTTPPathMatch
972            // grammar `:entrada :paths` already gates (55410e4), now
973            // shared with `:contratos :endpoint` through the lifted
974            // `crate::render::is_gateway_api_http_path` predicate.
975            if let Err(reason) = crate::render::is_gateway_api_http_path(ep) {
976                let (de, para) = self.edge_pair();
977                return Err(AplicacaoError::ContratoEndpointInvalid {
978                    de,
979                    para,
980                    endpoint: ep.to_string(),
981                    reason,
982                });
983            }
984            return Ok(WitTarget::Http { endpoint: ep });
985        }
986        if self.is_pubsub() {
987            if endpoint.is_some() || slot.is_some() {
988                let (de, para, wit) = edge();
989                return Err(AplicacaoError::ContratoWrongTarget {
990                    de,
991                    para,
992                    wit,
993                    expected: WitTarget::PUBSUB_FIELD_NAME,
994                });
995            }
996            let s = subject.ok_or_else(|| {
997                let (de, para, wit) = edge();
998                AplicacaoError::ContratoMissingTarget {
999                    de,
1000                    para,
1001                    wit,
1002                    expected: WitTarget::PUBSUB_FIELD_NAME,
1003                }
1004            })?;
1005            if s.is_empty() {
1006                let (de, para) = self.edge_pair();
1007                return Err(AplicacaoError::ContratoSubjectEmpty { de, para });
1008            }
1009            // The `:subject` lands at runtime as the NATS subject the
1010            // producer publishes to and the consumer subscribes from.
1011            // Until this gate landed `target()` only refused the
1012            // empty string; a structurally invalid subject
1013            // (`"foo..bar"` — empty token between separators,
1014            // `"foo.>.bar"` — non-trailing `>` wildcard the NATS
1015            // server's subject parser rejects, `"foo bar"` —
1016            // un-percent-encoded whitespace, `"foo.café"` —
1017            // un-percent-encoded non-ASCII, `".foo"` / `"foo."` —
1018            // empty leading/trailing tokens, the >256-byte
1019            // paste-from-binary slug) silently passed validate and
1020            // the failure surfaced at runtime as a NATS server-side
1021            // `-ERR 'Invalid Subject'` on publish / subscribe, or as
1022            // a silent message drop, far from the source caixa.lisp.
1023            // Same Gateway API HTTPPathMatch / WIT-IDL grammar
1024            // trajectory `:contratos :endpoint` (4f0390b) and
1025            // `:contratos :wit` (6226bf4) already gate, now shared
1026            // with `:contratos :subject` through the lifted
1027            // `crate::render::is_nats_subject` predicate.
1028            if let Err(reason) = crate::render::is_nats_subject(s) {
1029                let (de, para) = self.edge_pair();
1030                return Err(AplicacaoError::ContratoSubjectInvalid {
1031                    de,
1032                    para,
1033                    subject: s.to_string(),
1034                    reason,
1035                });
1036            }
1037            return Ok(WitTarget::PubSub { subject: s });
1038        }
1039        if self.is_store() {
1040            if endpoint.is_some() || subject.is_some() {
1041                let (de, para, wit) = edge();
1042                return Err(AplicacaoError::ContratoWrongTarget {
1043                    de,
1044                    para,
1045                    wit,
1046                    expected: WitTarget::STORE_FIELD_NAME,
1047                });
1048            }
1049            let sl = slot.ok_or_else(|| {
1050                let (de, para, wit) = edge();
1051                AplicacaoError::ContratoMissingTarget {
1052                    de,
1053                    para,
1054                    wit,
1055                    expected: WitTarget::STORE_FIELD_NAME,
1056                }
1057            })?;
1058            if sl.is_empty() {
1059                let (de, para) = self.edge_pair();
1060                return Err(AplicacaoError::ContratoSlotEmpty { de, para });
1061            }
1062            // Value-shape gate on the third (and last) typed payload
1063            // axis the `WitContract::target` dispatch carries — the
1064            // peer of [`crate::render::is_gateway_api_http_path`] for
1065            // `:endpoint` (4f0390b) and [`crate::render::is_nats_subject`]
1066            // for `:subject` (63e18a0). Until this gate landed
1067            // `target()` only refused the empty string; a structurally
1068            // invalid slot (`"check out/$order"` — un-percent-encoded
1069            // whitespace whose runtime behavior varies unpredictably
1070            // across kv backends, `"checkout/\x01order"` — control
1071            // character that Redis admits but corrupts on next read
1072            // and DynamoDB rejects outright, `"chéckout/$order"` —
1073            // un-percent-encoded non-ASCII byte each backend re-encodes
1074            // differently, `"checkout\n/$order"` — embedded newline,
1075            // the 513-byte paste-from-binary slug) silently passed
1076            // validate and surfaced at runtime as a per-backend kv
1077            // write rejection (DynamoDB / etcd) or as a silent
1078            // next-read corruption (Redis-via-RESP3), far from the
1079            // source caixa.lisp with no field naming which `:contratos`
1080            // edge carried the typo. The lifted predicate makes the
1081            // kv-backend intersection-floor a substrate-level
1082            // invariant at validate time, not a runtime "this passed
1083            // validate but the kv backend rejected on first write"
1084            // surprise — closes the typed payload-axis value-shape
1085            // trajectory across all three legs of the four
1086            // [`WitTarget`] arms (HTTP / PubSub / Store / Capability)
1087            // that caixa-mesh + the future kv emitters land in.
1088            if let Err(reason) = crate::render::is_wasi_keyvalue_slot(sl) {
1089                let (de, para) = self.edge_pair();
1090                return Err(AplicacaoError::ContratoSlotInvalid {
1091                    de,
1092                    para,
1093                    slot: sl.to_string(),
1094                    reason,
1095                });
1096            }
1097            return Ok(WitTarget::Store { slot: sl });
1098        }
1099
1100        // Unrecognized WIT world — must not carry any payload target.
1101        if endpoint.is_some() || subject.is_some() || slot.is_some() {
1102            let (de, para, wit) = edge();
1103            return Err(AplicacaoError::ContratoWrongTarget {
1104                de,
1105                para,
1106                wit,
1107                expected: WitTarget::CAPABILITY_EXPECTED,
1108            });
1109        }
1110        Ok(WitTarget::Capability)
1111    }
1112}
1113
1114/// Borrowed identity key for the typed-graph duplicate-`:contratos`
1115/// gate (see [`AplicacaoSpec::validate`]): every field that
1116/// distinguishes one contract from another, in declaration order
1117/// (`(de, para, wit, endpoint, subject, slot)`). Two [`WitContract`]s
1118/// with equal [`ContratoIdentity`]s are the same typed edge declared
1119/// twice — the graph-edge analogue of duplicate `:membros` /
1120/// `:placement :clusters` / `:entrada :paths` entries. Lifted as a
1121/// type alias so the duplicate-gate's `HashSet<…>` type doesn't trip
1122/// clippy's `type_complexity` lint (and so a future axis added to
1123/// `WitContract` is one alias edit, not a coordinated rewrite of
1124/// every set instantiation).
1125type ContratoIdentity<'a> = (
1126    &'a str,
1127    &'a str,
1128    &'a str,
1129    Option<&'a str>,
1130    Option<&'a str>,
1131    Option<&'a str>,
1132);
1133
1134/// Typed view of a [`WitContract`]'s payload target. Each variant
1135/// carries the field its WIT shape requires; constructing a `Http`
1136/// view without an endpoint is impossible by the type system.
1137///
1138/// Renderers (caixa-mesh L7 rules, feira app graph) match on this
1139/// instead of probing `Option<String>` fields one by one — the
1140/// "which payload field is set?" question is answered once, at
1141/// validation time.
1142#[derive(Debug, Clone, Copy, PartialEq, Eq, gen_platform::IsVariant)]
1143pub enum WitTarget<'a> {
1144    /// HTTP-shaped WIT world. Carries the configured request path.
1145    Http { endpoint: &'a str },
1146    /// Pub-sub-shaped WIT world. Carries the event-stream subject.
1147    ///
1148    /// The `IsVariant` derive would auto-name the predicate `is_pub_sub`
1149    /// (`discriminant_to_snake("PubSub") == "pub_sub"`); the explicit
1150    /// `#[is_variant(name = "pubsub")]` override keeps the emitted
1151    /// method name byte-identical to the sibling
1152    /// [`WitContract::is_pubsub`] predicate (the paired shape-side
1153    /// arm-discriminator that routes through
1154    /// [`wit_shape_is_pubsub`] on the wit-world-ref scalar rather than
1155    /// through `matches!` on the variant), so the two arm-discriminator
1156    /// axes — target-side variant-arm and shape-side ref-prefix — reach
1157    /// every downstream consumer through the same `is_pubsub()` name.
1158    #[is_variant(name = "pubsub")]
1159    PubSub { subject: &'a str },
1160    /// Key-value-shaped WIT world. Carries the slot template.
1161    Store { slot: &'a str },
1162    /// A typed capability edge with no payload selector — the WIT
1163    /// world stands on its own (rare; reserved for plain capability
1164    /// imports or M4-and-later WIT worlds we haven't shaped yet).
1165    Capability,
1166}
1167
1168impl<'a> WitTarget<'a> {
1169    /// Canonical author-facing `:contratos` payload field name for the
1170    /// HTTP-shaped arm — the `expected: &'static str` scalar the
1171    /// [`AplicacaoError::ContratoMissingTarget`] /
1172    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1173    /// through, the `:endpoint "…"` keyword the [`WitTarget::label`]
1174    /// duplicate-edge diagnostic emits, and the `endpoint=…` prefix
1175    /// the `feira app graph` verb prints. Peer of
1176    /// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
1177    /// on the payload-field-name axis; declared as a peer const next
1178    /// to the [`WitTarget::Http`] variant so a future rename on the
1179    /// author-surface `(defcaixa … :contratos ((:de … :para … :wit …
1180    /// :endpoint …)))` field lands in exactly one place, not scattered
1181    /// across the [`WitContract::target`] gate's six `expected:`
1182    /// literals, the label template, and every downstream consumer
1183    /// that prints a per-arm prefix. Same trajectory as the peer
1184    /// [`WitTarget::label`] lift (174e96a): a single source of truth
1185    /// for the arm's shape, next to the variant declaration.
1186    pub const HTTP_FIELD_NAME: &'static str = "endpoint";
1187    /// Canonical author-facing `:contratos` payload field name for the
1188    /// pub-sub-shaped arm. Peer of [`WitTarget::HTTP_FIELD_NAME`] /
1189    /// [`WitTarget::STORE_FIELD_NAME`] on the payload-field-name axis;
1190    /// see [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1191    pub const PUBSUB_FIELD_NAME: &'static str = "subject";
1192    /// Canonical author-facing `:contratos` payload field name for the
1193    /// key/value-store-shaped arm. Peer of
1194    /// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`]
1195    /// on the payload-field-name axis; see
1196    /// [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1197    pub const STORE_FIELD_NAME: &'static str = "slot";
1198
1199    /// Canonical stable human-readable label the payload-less
1200    /// [`WitTarget::Capability`] arm renders as under [`Self::label`] —
1201    /// the byte-string every consumer that formats a payload-less
1202    /// typed capability edge as text lands on (the
1203    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` diagnostic
1204    /// naming which identical edge was declared twice, the future
1205    /// `feira app graph` verb's per-arm prefix, the future M4 per-edge
1206    /// policy resolver's audit view, the operator's mesh-graph audit).
1207    /// Peer of the payload-arm [`Self::HTTP_FIELD_NAME`] /
1208    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`]
1209    /// author-facing label-scalar consts — the same
1210    /// "one canonical declaration per arm, next to the variant, so a
1211    /// future rename lands in one place" discipline extended to the
1212    /// payload-less arm. Until this lift landed the byte-string sat
1213    /// twice — once inline in [`Self::label`]'s [`WitTarget::Capability`]
1214    /// match arm, once in the pin test asserting the label's
1215    /// [`WitTarget::Capability`] output — with no compile-time link
1216    /// between the two: a rebrand on either side (an operator-facing
1217    /// vocabulary shift, a per-consumer disambiguation like
1218    /// `"(capability — no payload; typed edge only)"`) would silently
1219    /// desynchronize until a downstream consumer surfaced the drift at
1220    /// runtime.
1221    pub const CAPABILITY_LABEL: &'static str = "(capability — no payload)";
1222
1223    /// Canonical `expected:` scalar the
1224    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1225    /// through for the payload-less [`WitTarget::Capability`] arm — the
1226    /// byte-string authors read as "this WIT world's shape is not one
1227    /// of {`HTTP`, `PubSub`, `Store`}, so it must not carry
1228    /// `:endpoint` / `:subject` / `:slot`". Peer of the payload-arm
1229    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1230    /// [`Self::STORE_FIELD_NAME`] consts on the
1231    /// `ContratoWrongTarget::expected` axis — the fourth arm of the
1232    /// same "which payload field name goes in the diagnostic" dispatch
1233    /// the three payload-arm consts cover, extended to the payload-less
1234    /// arm. Until this lift landed the byte-string sat twice — once
1235    /// inline in the [`Self::target`] Capability-arm rejection at the
1236    /// production dispatch, once in the pin test asserting the
1237    /// diagnostic's `expected:` scalar carries `"none"` verbatim — with
1238    /// no compile-time link between the two: a rebrand on either side
1239    /// (an author-facing vocabulary shift to `"capability"` /
1240    /// `"(none)"` / `"no-payload"` as the WIT registry's shape
1241    /// vocabulary sharpens, a per-consumer disambiguation as M4 splits
1242    /// [`WitTarget::Capability`] into per-shape peers) would silently
1243    /// desynchronize until a downstream consumer surfaced the drift at
1244    /// runtime. Same "one canonical declaration per arm, next to the
1245    /// variant, so a future rename lands in one place" discipline the
1246    /// peer [`Self::CAPABILITY_LABEL`] lift (7ed03a3-era) already
1247    /// established for the payload-less arm's human-readable label
1248    /// axis; this lift extends it onto the peer diagnostic-scalar axis
1249    /// so both halves of the "how does the Capability arm surface at
1250    /// its two consumer axes (human-readable label, wrong-target
1251    /// diagnostic)" pipeline route through peer consts declared next
1252    /// to the variant.
1253    ///
1254    /// Pairwise-distinctness against the three payload-arm scalars
1255    /// ([`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1256    /// [`Self::STORE_FIELD_NAME`]) is pinned by the sibling
1257    /// `wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`
1258    /// test — the 4-way closure of the 3-way
1259    /// `wit_target_field_names_are_pairwise_distinct` sibling pin onto
1260    /// the `ContratoWrongTarget::expected` axis, matching the peer
1261    /// `m3_placement_estrategia_consts_are_pairwise_distinct` closed-set
1262    /// scalar-value distinctness discipline the sibling M3 typed-enum
1263    /// discriminator axis already carries.
1264    pub const CAPABILITY_EXPECTED: &'static str = "none";
1265
1266    /// The `(author-facing field name, payload)` pair this typed target
1267    /// arm carries — `Some((HTTP_FIELD_NAME, endpoint))` for
1268    /// [`Self::Http`], `Some((PUBSUB_FIELD_NAME, subject))` for
1269    /// [`Self::PubSub`], `Some((STORE_FIELD_NAME, slot))` for
1270    /// [`Self::Store`], `None` for the payload-less
1271    /// [`Self::Capability`] arm.
1272    ///
1273    /// Lifted as the single 4-arm dispatch that both [`Self::label`]
1274    /// (formats `":{field} {payload:?}"` on `Some`, falls to
1275    /// [`Self::CAPABILITY_LABEL`] on `None`) and [`Self::field_name`]
1276    /// (returns the first component) route through, so a future
1277    /// [`WitTarget`] variant addition — the M4-and-later per-edge WIT
1278    /// registry may split [`Self::Http`] into `Rest` / `Grpc` peers,
1279    /// or extend [`Self::Store`] with a `Queue`-shaped peer — becomes
1280    /// exactly one new match-arm here (a compile-time exhaustiveness
1281    /// error otherwise), not a coordinated three-way rewrite of the
1282    /// prior [`Self::label`] template + [`Self::field_name`] dispatch
1283    /// + every downstream consumer that reaches for the pair.
1284    ///
1285    /// Until this lift landed the three payload arms sat in
1286    /// [`Self::label`] as three near-identical `format!(":{} {…:?}", …)`
1287    /// invocations (one per variant, each hand-quoting the paired
1288    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1289    /// [`Self::STORE_FIELD_NAME`] const) — the canonical
1290    /// "same shape, written N times" duplication THEORY.md §I.3.5
1291    /// ("Generation first, composition second, hand-authoring last;
1292    /// the duplication budget is zero") promotes to a build-time
1293    /// concern, with each per-arm site paired to its own const with no
1294    /// compile-time link between the format template and the arm's
1295    /// payload extraction.
1296    #[must_use]
1297    pub const fn payload_pair(&self) -> Option<(&'static str, &'a str)> {
1298        match *self {
1299            WitTarget::Http { endpoint } => Some((Self::HTTP_FIELD_NAME, endpoint)),
1300            WitTarget::PubSub { subject } => Some((Self::PUBSUB_FIELD_NAME, subject)),
1301            WitTarget::Store { slot } => Some((Self::STORE_FIELD_NAME, slot)),
1302            WitTarget::Capability => None,
1303        }
1304    }
1305
1306    /// The canonical author-facing `:contratos` payload field name
1307    /// this typed target arm carries (`Http` → `Some("endpoint")`,
1308    /// `PubSub` → `Some("subject")`, `Store` → `Some("slot")`), or
1309    /// `None` for the payload-less `Capability` arm.
1310    ///
1311    /// Routes through [`Self::payload_pair`] — the single 4-arm
1312    /// dispatch [`Self::label`] also reads — so a future variant
1313    /// addition is one match-arm edit at [`Self::payload_pair`], not a
1314    /// per-consumer rewrite. Same "exhaustive-match at one canonical
1315    /// dispatch, thin projections at each consumer" trajectory the
1316    /// peer [`PlacementStrategy::as_str`] / [`std::fmt::Display`]
1317    /// pair (0a2f653) landed on the sibling M3 typed-enum axis.
1318    #[must_use]
1319    pub const fn field_name(&self) -> Option<&'static str> {
1320        match self.payload_pair() {
1321            Some((f, _)) => Some(f),
1322            None => None,
1323        }
1324    }
1325
1326    /// Render this typed target as a stable human-readable label
1327    /// (`:endpoint "/charge"`, `:subject "events.x"`,
1328    /// `:slot "checkout/$order"`, or `(capability — no payload)` when
1329    /// the WIT world is a pure capability edge).
1330    ///
1331    /// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
1332    /// gate so the diagnostic names *which* identical edge was
1333    /// declared twice (not just which `(de, para, wit)` triple).
1334    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
1335    /// on the payload-carrying arms (`Some((field, payload)) →
1336    /// format!(":{field} {payload:?}")`) and through the lifted
1337    /// [`Self::CAPABILITY_LABEL`] const on the payload-less
1338    /// [`Self::Capability`] arm — so a future variant addition (the
1339    /// M4-and-later per-edge WIT registry may split [`Self::Http`]
1340    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
1341    /// `Queue`-shaped peer) becomes a single new match-arm on
1342    /// [`Self::payload_pair`] rather than a rewrite of this template
1343    /// (and every downstream consumer that reaches for the label
1344    /// shape: the per-edge policy resolver in M4, the `feira app
1345    /// graph` view, the operator's mesh-graph audit). Until this
1346    /// lift landed the three payload arms carried three near-identical
1347    /// per-arm `format!(":{} {…:?}", …)` invocations, and the
1348    /// [`Self::Capability`] arm carried the payload-less byte-string
1349    /// twice (once inline here, once in the pin test) — closing the
1350    /// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
1351    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
1352    /// / 4a1e490) peer-const lifts already established for the
1353    /// payload-carrying arms.
1354    #[must_use]
1355    pub fn label(&self) -> String {
1356        match self.payload_pair() {
1357            Some((field, payload)) => format!(":{field} {payload:?}"),
1358            None => Self::CAPABILITY_LABEL.to_string(),
1359        }
1360    }
1361}
1362
1363/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
1364/// pretty-printed byte-string every consumer that formats a typed
1365/// payload target as user-facing text lands on (the
1366/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
1367/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
1368/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
1369/// graph` per-`:contratos`-edge payload column that reaches the graph
1370/// verb through `format!("{target}")`, the future M4 per-edge policy
1371/// resolver's per-edge audit-log line, the operator's mesh-graph
1372/// per-edge inspection view) reaches for the same lifted
1373/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
1374/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
1375/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
1376/// routes through — extending the three-path-convergence
1377/// (`Debug` for structural inspection, `Display` for user-facing text,
1378/// per-arm typed accessor for the canonical byte-string) discipline the
1379/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
1380/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
1381/// onto the fourth (and only remaining) typed-shape-discriminator axis
1382/// on the caixa surface.
1383///
1384/// Pre-lift the two paths were structurally independent — every consumer
1385/// reaching for a payload byte-string past the [`WitTarget::label`]
1386/// helper had to pick between three paths ([`WitTarget::label`],
1387/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
1388/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
1389/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
1390/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
1391/// that reached for `format!("{target}")` — the canonical shape every
1392/// user-facing pretty-print site on the sibling typed-enum axes already
1393/// uses — would silently land on the `Debug` derive's structural output
1394/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
1395/// than the `label()` helper's stable byte-string (`:endpoint
1396/// "/charge"` — the author-facing `:contratos` keyword form) the
1397/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
1398/// already threads through. The two spellings would diverge silently in
1399/// every downstream diagnostic / graph / audit line reached through
1400/// `format!` rather than through the `label()` helper. Routing
1401/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
1402/// path: every `format!("{v}")` call reaches the same
1403/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
1404/// and the duplicate-`:contratos` gate already route through, so a
1405/// future variant addition (the M4-and-later per-edge WIT registry may
1406/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
1407/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
1408/// consumer at exactly one place — the [`WitTarget::payload_pair`]
1409/// match — rather than fanning out through hand-rolled per-arm
1410/// [`std::fmt::Display`] arms.
1411///
1412/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
1413/// is the typed view returned by [`WitContract::target`], not a
1414/// closed-set discriminator enum with a gen-platform Discriminant
1415/// registration, so the `Debug` derive's structural output (which every
1416/// `{v:?}` consumer still reaches) stays distinct from the `Display`
1417/// helper's stable pretty-printed byte-string. `Debug` reveals variant
1418/// shape for structural inspection; `Display` (via `label`) reveals the
1419/// stable author-facing payload projection.
1420///
1421/// Pin tests
1422/// [`tests::wit_target_display_routes_through_label_helper`] and
1423/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
1424/// assert the two paths agree byte-for-byte on every variant, so a
1425/// future variant addition or `label()` reimplementation that hand-rolls
1426/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
1427/// build error visible at caixa-core test time, not a silent
1428/// per-consumer dispatch miss at diagnostic / audit / graph time.
1429impl std::fmt::Display for WitTarget<'_> {
1430    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1431        f.write_str(&self.label())
1432    }
1433}
1434
1435// ── one Aplicacao member ─────────────────────────────────────────────
1436
1437/// A Servico participating in the Aplicacao. Same shape as
1438/// `crate::supervisor::ChildSpec` but without a restart policy —
1439/// supervision is per-Servico (each member has its own
1440/// `:supervisor`), the Aplicacao orchestrates *placement*.
1441#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1442#[serde(rename_all = "camelCase")]
1443pub struct Membro {
1444    /// Member caixa's `:nome`. Resolves through the same dep
1445    /// resolution path as `crate::dep::Dep`.
1446    pub caixa: String,
1447
1448    /// Semver constraint.
1449    pub versao: String,
1450}
1451
1452impl Membro {
1453    /// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
1454    /// accessor every consumer that reads the member's Servico identity
1455    /// keys off — returns the author-declared `:membros :caixa`
1456    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
1457    /// own [`String`] storage.
1458    ///
1459    /// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
1460    /// participating in the Aplicacao — validated by
1461    /// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
1462    /// (via [`validate_membro_caixa`]), unique across the Aplicacao's
1463    /// `:membros` list, distinct from the Aplicacao's own `:nome` (via
1464    /// [`validate_no_self_membership`]) — and every downstream consumer
1465    /// that fans on the member's identity keys off this scalar (the
1466    /// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
1467    /// lookup, the per-`:membros` duplicate gate's dedup key, the
1468    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
1469    /// identity, the self-membership gate, the
1470    /// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
1471    /// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
1472    /// CR materializer's per-member resolver).
1473    ///
1474    /// Prior to this lift the `.caixa` byte-string was read inline at
1475    /// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
1476    /// set collector at
1477    /// `self.membros.iter().map(|m| m.caixa.as_str())`, the
1478    /// [`validate_membros`] validation-side member-caixa gate at
1479    /// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
1480    /// per-member duplicate-gate dedup key at
1481    /// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
1482    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
1483    /// `adj.entry(m.caixa.as_str()).or_default()`, and the
1484    /// [`validate_no_self_membership`] self-loop gate at
1485    /// `m.caixa == parent_nome`) — five open-coded field-accesses that
1486    /// expressed no compile-time link back to the typed slot. Every
1487    /// caixa-mesh `metadata.name` derived from a `:membros :caixa`
1488    /// value flows through the [`caixa_mesh::fleet_programs`] per-entry
1489    /// `name:` axis, so a future extension of the `:membros :caixa`
1490    /// axis to a richer author surface — a per-cluster alias table the
1491    /// operator pins through a future `:placement`-scoped slot, a
1492    /// namespace-qualified rewrite the M4 CR materializer applies
1493    /// per-CR, a per-member overlay from the future `:membros
1494    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
1495    /// acknowledges — would have had to be threaded through every
1496    /// open-coded copy in lockstep or one consumer would silently
1497    /// disagree with the peers on which caixa a given member resolves
1498    /// to. A member-set lookup that treated the name as `"cart"` while
1499    /// the peer adjacency map treated it as `"tenant-a/cart"` would
1500    /// silently split the `:contratos` membership-lookup diagnostic from
1501    /// the cycle-detector's node identity — a two-consumer split at the
1502    /// validator far from the source `caixa.lisp` with no field naming
1503    /// the identity-drift root cause. Lifting the resolution rule to a
1504    /// typed method on the substrate primitive means every downstream
1505    /// consumer of the Aplicacao's per-`:membros` identity surface
1506    /// reaches for exactly one typed dispatch — the resolver's
1507    /// accept-set migrates as a unit on any future axis addition.
1508    ///
1509    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
1510    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
1511    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
1512    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
1513    /// destination-Servico scalar accessors — same "one typed dispatch
1514    /// on the substrate primitive, thin projections at each consumer"
1515    /// discipline extended onto the per-`:membros` member-caixa `:nome`
1516    /// byte-string axis. Named `nome()` to match the tatara-lisp
1517    /// author-surface term the field's docstring already reaches for
1518    /// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
1519    /// [`crate::dep::Dep::nome`] field-name discipline the substrate
1520    /// already carries — the accessor's name maps directly onto the
1521    /// canonical caixa-identity vocabulary rather than shadowing the
1522    /// field's storage-side `caixa` label.
1523    #[must_use]
1524    pub fn nome(&self) -> &str {
1525        self.caixa.as_str()
1526    }
1527
1528    /// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
1529    /// requirement scalar accessor every consumer that reads the
1530    /// member's version pin keys off — returns the author-declared
1531    /// `:membros :versao` byte-string verbatim as a `&str`, borrowed
1532    /// from the typed slot's own [`String`] storage.
1533    ///
1534    /// The `:membros :versao` slot carries the Cargo-shaped semver
1535    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
1536    /// pins which release of the member-caixa the Aplicacao composes
1537    /// against — the same requirement grammar the peer `:deps :versao`
1538    /// / `:children :versao` axes carry, resolved through the shared
1539    /// [`crate::render::require_valid_versao_requirement`] cascade and
1540    /// the shared [`crate::version::parse_requirement`] parser. Every
1541    /// downstream consumer that fans on the member's version pin keys
1542    /// off this scalar (the [`validate_membros`] per-member requirement
1543    /// gate at `require_valid_versao_requirement(m.versao_requirement(),
1544    /// …)`, the [`feira app graph`] per-member `println!("    - {} {}",
1545    /// m.nome(), m.versao_requirement())` line, every future per-cluster
1546    /// version-lock overlay the operator pins through a future
1547    /// `:placement`-scoped slot, the future
1548    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
1549    /// version resolver, the future `feira app deploy` pipeline's
1550    /// per-member lacre BLAKE3-closure lookup).
1551    ///
1552    /// Prior to this lift the `.versao` byte-string was accessed inline
1553    /// at two `&str`-shaped sites — the [`validate_membros`]
1554    /// requirement-gate call `require_valid_versao_requirement(&m.versao,
1555    /// …)` and the `feira app graph` per-member printer's `println!(
1556    /// "    - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
1557    /// prior to this lift) — two open-coded field-accesses that expressed
1558    /// no compile-time link back to the typed slot. A future extension of
1559    /// the `:membros :versao` axis to a richer author surface (a
1560    /// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
1561    /// flow, a lacre-projected concrete-version rewrite the operator
1562    /// materializes at CR-admission time, a future `:membros :versao-lock`
1563    /// per-cluster override slot) would have had to be threaded through
1564    /// every open-coded copy in lockstep or one consumer would silently
1565    /// disagree with the peers on which release constraint a given
1566    /// member resolves to. Lifting the resolution rule to a typed method
1567    /// on the substrate primitive means every downstream requirement-
1568    /// facing consumer reaches for exactly one typed dispatch — the
1569    /// resolver's accept-set migrates as a unit on any future axis
1570    /// addition.
1571    ///
1572    /// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
1573    /// member-caixa `:nome` scalar accessor — the pair
1574    /// `(nome(), versao_requirement())` jointly projects the
1575    /// `(caixa, versao)` field pair every renderer that fans on
1576    /// per-member identity + version pin keys off, closing the last
1577    /// unlifted per-`:membros` scalar axis so every downstream
1578    /// per-`:membros` reader now routes through a typed dispatch on the
1579    /// substrate primitive. Named `versao_requirement()` rather than
1580    /// `versao()` because the field's storage-side `.versao` label is
1581    /// already the author-surface term (`:versao`); the accessor's name
1582    /// carries the semantic role — the semver *requirement* string the
1583    /// shared [`crate::version::parse_requirement`] entry-point consumes
1584    /// — so a raw field access and a typed dispatch read differently at
1585    /// every consumer site.
1586    ///
1587    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
1588    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
1589    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
1590    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
1591    /// destination-Servico scalar accessors — same "one typed dispatch
1592    /// on the substrate primitive, thin projections at each consumer"
1593    /// discipline extended onto the per-`:membros` member-`:versao`
1594    /// semver-requirement byte-string axis.
1595    #[must_use]
1596    pub fn versao_requirement(&self) -> &str {
1597        self.versao.as_str()
1598    }
1599}
1600
1601// ── mesh-level policies ──────────────────────────────────────────────
1602
1603/// Mesh policies that apply to every `:contratos` edge unless
1604/// overridden per-edge in M4. V0 is a single global policy block.
1605#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
1606#[serde(rename_all = "camelCase")]
1607pub struct MeshPolicy {
1608    /// Per-call timeout. Authored as a duration string (`"30s"`).
1609    #[serde(
1610        default,
1611        skip_serializing_if = "Option::is_none",
1612        with = "supervisor::duration_codec"
1613    )]
1614    pub timeout: Option<Duration>,
1615
1616    /// Number of retries on transient failure. None = no retries.
1617    #[serde(default, skip_serializing_if = "Option::is_none")]
1618    pub retries: Option<u32>,
1619
1620    /// Circuit breaker config. Trips after N failures within W
1621    /// duration; closes after a cooldown.
1622    #[serde(default, skip_serializing_if = "Option::is_none")]
1623    pub circuit_breaker: Option<CircuitBreaker>,
1624
1625    /// Whether mTLS is required for every contrato. Default: true
1626    /// (sandboxing-by-default; explicit opt-out only).
1627    #[serde(default, skip_serializing_if = "Option::is_none")]
1628    pub mtls_required: Option<bool>,
1629
1630    /// Token-bucket rate limit. Authored as `"100/s"` or
1631    /// `"5000/m"`; stored as `(rate, window)`.
1632    #[serde(
1633        default,
1634        skip_serializing_if = "Option::is_none",
1635        with = "rate_limit_codec"
1636    )]
1637    pub rate_limit: Option<RateLimit>,
1638}
1639
1640impl MeshPolicy {
1641    /// True when no `:politicas` axis carries a value — every field is
1642    /// `None`. The same emptiness contract every other M2/M3 typed
1643    /// surface carries ([`crate::LimitsSpec::is_empty`],
1644    /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
1645    /// typed slot onto a cluster artifact key off this predicate to
1646    /// decide "emit the slot" vs "skip the slot entirely", so an
1647    /// authored-but-unset `:politicas (())` round-trips to a rendered
1648    /// artifact that's structurally identical to one that omits the
1649    /// slot. Lifted as a typed predicate (rather than per-renderer
1650    /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
1651    /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
1652    /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
1653    /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
1654    /// not a coordinated rewrite of every consumer that's reaching
1655    /// for the emptiness semantic.
1656    #[must_use]
1657    pub const fn is_empty(&self) -> bool {
1658        self.timeout().is_none()
1659            && self.retries().is_none()
1660            && self.circuit_breaker().is_none()
1661            && self.mtls_required().is_none()
1662            && self.rate_limit().is_none()
1663    }
1664
1665    /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
1666    /// per-call-deadline scalar accessor every consumer of the
1667    /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
1668    /// returns the author-declared `:politicas :timeout` typed
1669    /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
1670    /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
1671    /// is `Copy`, so the accessor returns by value; no borrow of
1672    /// `&self` past the call). `None` when the slot is absent (the
1673    /// "cluster default applies — typically the gateway class's
1674    /// implementation-side per-request wall-clock cap" arm caixa-mesh's
1675    /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
1676    /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
1677    /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
1678    /// round-trips to a rendered `HTTPRoute` structurally identical to
1679    /// one that omits the slot).
1680    ///
1681    /// The `:politicas :timeout` slot carries the "no infinite blocking"
1682    /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
1683    /// the typed slot's `Option<Duration>` accept-set (zero-floor
1684    /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
1685    /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
1686    /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
1687    /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
1688    /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
1689    /// Every downstream consumer that reads the per-call cap keys off
1690    /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
1691    /// renderers key off to decide "emit :politicas overlay" vs "skip
1692    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
1693    /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
1694    /// fans the deadline into every rule via
1695    /// [`crate::render::single_field_overlay`], the future M4 per-
1696    /// Aplicacao Gateway API reconciler materialization pass, the
1697    /// future per-`:contratos`-edge timeout-override overlay the
1698    /// MESH-COMPOSITION §III.2 roadmap acknowledges).
1699    ///
1700    /// Prior to this lift the `.timeout` field was accessed inline at
1701    /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
1702    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
1703    /// …)` call — two open-coded field-accesses that expressed no
1704    /// compile-time link back to the typed slot. A future extension of
1705    /// the `:politicas :timeout` axis to a richer author surface — a
1706    /// per-`:contratos`-edge timeout override the operator pins through
1707    /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
1708    /// roadmap acknowledges, a per-cluster timeout-default overlay the
1709    /// M4 CR materializer resolves per-CR, a split of the single
1710    /// per-call `Duration` into a richer `{request, backendRequest}`
1711    /// pair once the Gateway API's per-rule `timeouts` block grows the
1712    /// upstream-facing backendRequest arm alongside the client-facing
1713    /// request arm — would have had to be threaded through both open-
1714    /// coded copies in lockstep or the emptiness predicate and the
1715    /// caixa-mesh emit path would silently disagree on which per-call
1716    /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
1717    /// whose only axis is a `Some :timeout` would satisfy `is_empty()
1718    /// == false` while the renderer's overlay-emit path silently read
1719    /// a drifted other value, or vice versa: an author's `:timeout
1720    /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
1721    /// the emptiness predicate still classified the policy as non-
1722    /// empty, and every `kubectl -n tatara-system get httproute -o yaml
1723    /// | grep -A2 timeouts` audit would land on a route whose author's
1724    /// typed slot value silently vanished at the renderer layer).
1725    /// Lifting the resolution to a typed method on the substrate
1726    /// primitive means every downstream consumer of the Aplicacao's
1727    /// per-`:politicas` deadline surface reaches for exactly one typed
1728    /// dispatch — the resolver's accept-set migrates as a unit on any
1729    /// future axis addition.
1730    ///
1731    /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
1732    /// family (sibling of the peer per-`:politicas`
1733    /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
1734    /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
1735    /// `Option<bool>` accessor — same "one typed dispatch on the
1736    /// substrate primitive, thin projections at each consumer"
1737    /// discipline extended onto the peer per-`:politicas` typed-
1738    /// [`Duration`] optional-scalar axis; closes the "optional per-slot
1739    /// numeric-Copy-T scalar" projection pattern the sibling
1740    /// `Option<u32>` / `Option<bool>` lifts opened, since every
1741    /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
1742    /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
1743    /// than a scalar). Named `timeout()` to match the storage field's
1744    /// name; the accessor's identity maps onto the canonical MESH-
1745    /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
1746    #[must_use]
1747    pub const fn timeout(&self) -> Option<Duration> {
1748        self.timeout
1749    }
1750
1751    /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
1752    /// retry-budget scalar accessor every consumer of the Aplicacao's
1753    /// Gateway API v1.x per-rule retry-cap keys off — returns the
1754    /// author-declared `:politicas :retries` typed `u32` verbatim as an
1755    /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
1756    /// storage (`Option<u32>` is `Copy`, so the accessor returns by
1757    /// value; no borrow of `&self` past the call). `None` when the slot
1758    /// is absent (the "cluster default applies — typically 'no retries
1759    /// beyond a single dispatch attempt'" arm the caixa-mesh
1760    /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
1761    /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
1762    /// this predicate too, so an authored-but-unset `:politicas
1763    /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
1764    /// identical to one that omits the slot).
1765    ///
1766    /// The `:politicas :retries` slot carries the "transient failure
1767    /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
1768    /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
1769    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
1770    /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
1771    /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
1772    /// count scalar the caixa-mesh `retry_overlay` builder writes.
1773    /// Every downstream consumer that reads the retry cap keys off this
1774    /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
1775    /// renderers key off to decide "emit :politicas overlay" vs "skip
1776    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
1777    /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
1778    /// the value into every rule via [`crate::render::single_field_overlay`],
1779    /// the future M4 per-Aplicacao Gateway API reconciler
1780    /// materialization pass, the future per-`:contratos`-edge retry-
1781    /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
1782    /// acknowledges).
1783    ///
1784    /// Prior to this lift the `.retries` field was accessed inline at
1785    /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
1786    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
1787    /// …)` call — two open-coded field-accesses that expressed no
1788    /// compile-time link back to the typed slot. A future extension of
1789    /// the `:politicas :retries` axis to a richer author surface — a
1790    /// per-`:contratos`-edge retry override the operator pins through a
1791    /// future `:contratos :retries` slot, a per-cluster retry-default
1792    /// overlay the M4 CR materializer resolves per-CR, a promotion of
1793    /// the plain `u32` attempt-count to a richer `{attempts, codes,
1794    /// backoff}` sub-block once the Gateway API grows the peer
1795    /// `retry.codes` / `retry.backoff` axes — would have had to be
1796    /// threaded through both open-coded copies in lockstep or the
1797    /// emptiness predicate and the caixa-mesh emit path would silently
1798    /// disagree on which retry budget a given [`MeshPolicy`] resolves to
1799    /// (a `:politicas` block whose only axis is a `Some :retries` would
1800    /// satisfy `is_empty() == false` while the renderer's overlay-emit
1801    /// path silently read a drifted other value, or vice versa: an
1802    /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
1803    /// block while the emptiness predicate still classified the policy
1804    /// as non-empty). Lifting the resolution to a typed method on the
1805    /// substrate primitive means every downstream consumer of the
1806    /// Aplicacao's per-`:politicas` retry surface reaches for exactly
1807    /// one typed dispatch — the resolver's accept-set migrates as a
1808    /// unit on any future axis addition.
1809    ///
1810    /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
1811    /// family (sibling of the peer per-`:politicas`
1812    /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
1813    /// same "one typed dispatch on the substrate primitive, thin
1814    /// projections at each consumer" discipline extended onto the
1815    /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
1816    /// the "optional per-slot numeric-Copy-T scalar" projection pattern
1817    /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
1818    /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
1819    /// fold on). Named `retries()` to match the storage field's name;
1820    /// the accessor's identity maps onto the canonical MESH-COMPOSITION
1821    /// §III.2 vocabulary the slot's docstring already carries.
1822    #[must_use]
1823    pub const fn retries(&self) -> Option<u32> {
1824        self.retries
1825    }
1826
1827    /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
1828    /// enforcement-toggle scalar accessor every consumer of the
1829    /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
1830    /// — returns the author-declared `:politicas :mtls-required` typed
1831    /// bool verbatim as an `Option<bool>`, copied out of the typed
1832    /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
1833    /// the accessor returns by value; no borrow of `&self` past the
1834    /// call). `None` when the slot is absent (the "cluster default
1835    /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
1836    /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
1837    /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
1838    /// this predicate too, so an authored-but-unset `:politicas
1839    /// (:mtls-required ())` round-trips to a rendered
1840    /// `CiliumNetworkPolicy` structurally identical to one that omits
1841    /// the slot).
1842    ///
1843    /// The `:politicas :mtls-required` slot carries the "explicit opt-
1844    /// out only, sandboxing-by-default" mTLS-enforcement toggle
1845    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
1846    /// `{None, Some(true), Some(false)}` accept-set maps onto the
1847    /// Cilium `authentication.mode` bijection through
1848    /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
1849    /// handshake enforced), `Some(false) → "disabled"` (handshake
1850    /// skipped — the debug-edge opt-out), `None` → omit the block
1851    /// (cluster default applies). Every downstream consumer that
1852    /// reads the toggle keys off this scalar (the
1853    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
1854    /// off to decide "emit :politicas overlay" vs "skip entirely", the
1855    /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
1856    /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
1857    /// ingress rule via [`crate::render::single_field_overlay`], the
1858    /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
1859    /// materialization pass, the future per-`:contratos`-edge mTLS
1860    /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
1861    ///
1862    /// Prior to this lift the `.mtls_required` field was accessed
1863    /// inline at two sites — [`MeshPolicy::is_empty`]'s
1864    /// `self.mtls_required.is_none()` arm and caixa-mesh's
1865    /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
1866    /// two open-coded field-accesses that expressed no compile-time
1867    /// link back to the typed slot. A future extension of the
1868    /// `:politicas :mtls-required` axis to a richer author surface —
1869    /// a per-`:contratos`-edge mTLS override the operator pins through
1870    /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
1871    /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
1872    /// M4 CR materializer resolves per-CR, a three-valued
1873    /// `{None, Some(true), Some(false), Some(Optional)}` promotion
1874    /// once Cilium's `authentication.mode` grows an `"optional"` arm —
1875    /// would have had to be threaded through both open-coded copies in
1876    /// lockstep or the emptiness predicate and the caixa-mesh emit
1877    /// path would silently disagree on which toggle a given
1878    /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
1879    /// axis is a `Some`
1880    /// `:mtls-required` would satisfy `is_empty() == false` while the
1881    /// renderer's overlay-emit path silently read a drifted other
1882    /// value, or vice versa). Lifting the resolution to a typed method
1883    /// on the substrate primitive means every downstream consumer of
1884    /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
1885    /// for exactly one typed dispatch — the resolver's accept-set
1886    /// migrates as a unit on any future axis addition.
1887    ///
1888    /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
1889    /// family (peer of the sibling per-`:placement`
1890    /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
1891    /// same "one typed dispatch on the substrate primitive, thin
1892    /// projections at each consumer" discipline extended onto the
1893    /// peer per-`:politicas` typed-bool optional-scalar axis; opens
1894    /// the "optional per-slot Copy-T scalar" projection pattern the
1895    /// sibling per-`:politicas` `:retries` (Option<u32>) /
1896    /// `:timeout` (Option<Duration>) future lifts fold on). Named
1897    /// `mtls_required()` to match the storage field's name; the
1898    /// accessor's identity maps onto the canonical MESH-COMPOSITION
1899    /// §III.2 vocabulary the slot's docstring already carries.
1900    #[must_use]
1901    pub const fn mtls_required(&self) -> Option<bool> {
1902        self.mtls_required
1903    }
1904
1905    /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
1906    /// `local_rate_limit`-mesh token-bucket-declaration scalar
1907    /// accessor every consumer of the Aplicacao's per-`:politicas`
1908    /// per-`(rate, window)` rate-limit surface keys off — returns the
1909    /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
1910    /// verbatim as an `Option<RateLimit>`, copied out of the typed
1911    /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
1912    /// `Copy`, so the accessor returns by value; no borrow of `&self`
1913    /// past the call). `None` when the slot is absent (the "cluster
1914    /// default applies — typically 'no per-Aplicacao rate declaration,
1915    /// gateway-class per-listener default applies'" arm the future
1916    /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
1917    /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
1918    /// `rate_limit().is_none()` arm reads this predicate too, so an
1919    /// authored-but-unset `:politicas (:rate-limit ())` round-trips
1920    /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
1921    /// identical to one that omits the slot).
1922    ///
1923    /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
1924    /// token-bucket rate declaration" contract (MESH-COMPOSITION
1925    /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
1926    /// (rate lower-bounded by 1 through
1927    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
1928    /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
1929    /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
1930    /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
1931    /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
1932    /// bijection the future `CiliumClusterwideEnvoyConfig` per-
1933    /// `:politicas` overlay emits. Every downstream consumer that
1934    /// reads the rate declaration keys off this scalar (the
1935    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
1936    /// off to decide "emit :politicas overlay" vs "skip entirely", the
1937    /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
1938    /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
1939    /// `rl.window` against [`is_canonical_rate_limit_window`], the
1940    /// future M4 per-Aplicacao Envoy reconciler materialization pass,
1941    /// the future per-`:contratos`-edge rate-limit override the
1942    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
1943    ///
1944    /// Prior to this lift the `.rate_limit` field was accessed inline
1945    /// at two sites — [`MeshPolicy::is_empty`]'s
1946    /// `self.rate_limit.is_none()` arm and the `validate_politicas`
1947    /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
1948    /// field-accesses that expressed no compile-time link back to the
1949    /// typed slot. A future extension of the `:politicas :rate-limit`
1950    /// axis to a richer author surface — a per-`:contratos`-edge
1951    /// rate-limit override the operator pins through a future
1952    /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
1953    /// roadmap acknowledges, a per-cluster rate-limit-default overlay
1954    /// the M4 CR materializer resolves per-CR, a promotion of the
1955    /// plain `(rate, window)` scalar pair to a richer
1956    /// `{rate, window, burst, key}` sub-block once Envoy's
1957    /// `local_rate_limit` grows the peer `burst_size` /
1958    /// `descriptor_key` axes — would have had to be threaded through
1959    /// both open-coded copies in lockstep or the emptiness predicate
1960    /// and the validate gate would silently disagree on which rate
1961    /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
1962    /// block whose only axis is a `Some :rate-limit` would satisfy
1963    /// `is_empty() == false` while the validate path silently read a
1964    /// drifted other value, or vice versa: an author's
1965    /// `:rate-limit "100/s"` would omit the value-shape gate while the
1966    /// emptiness predicate still classified the policy as non-empty).
1967    /// Lifting the resolution to a typed method on the substrate
1968    /// primitive means every downstream consumer of the Aplicacao's
1969    /// per-`:politicas` rate-limit surface reaches for exactly one
1970    /// typed dispatch — the resolver's accept-set migrates as a unit
1971    /// on any future axis addition.
1972    ///
1973    /// First `Option<Copy-composite-T>`-return accessor on the M3
1974    /// mesh-slot family — closes the last un-lifted per-`:politicas`
1975    /// scalar-value axis. Peer of the sibling per-`:politicas`
1976    /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
1977    /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
1978    /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
1979    /// "one typed dispatch on the substrate primitive, thin
1980    /// projections at each consumer" discipline extended onto the
1981    /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
1982    /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
1983    /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
1984    /// sub-accessors rather than a top-level accessor because
1985    /// consumers reach for the axes not the aggregate). Named
1986    /// `rate_limit()` to match the storage field's name; the
1987    /// accessor's identity maps onto the canonical MESH-COMPOSITION
1988    /// §III.2 vocabulary the slot's docstring already carries.
1989    #[must_use]
1990    pub const fn rate_limit(&self) -> Option<RateLimit> {
1991        self.rate_limit
1992    }
1993
1994    /// Substrate-canonical per-`:politicas` `:circuit-breaker`
1995    /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
1996    /// declaration scalar accessor every consumer of the Aplicacao's
1997    /// per-`:politicas` breaker declaration keys off — returns the
1998    /// author-declared `:politicas :circuit-breaker` typed
1999    /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
2000    /// copied out of the typed slot's own `Option<CircuitBreaker>`
2001    /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
2002    /// by value; no borrow of `&self` past the call). `None` when the
2003    /// slot is absent (the "cluster default applies — typically 'no
2004    /// per-Aplicacao breaker declaration, gateway-class per-listener
2005    /// default applies'" arm the future caixa-mesh
2006    /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
2007    /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
2008    /// arm reads this predicate too, so an authored-but-unset
2009    /// `:politicas (:circuit-breaker ())` round-trips to a rendered
2010    /// `CiliumClusterwideEnvoyConfig` structurally identical to one
2011    /// that omits the slot).
2012    ///
2013    /// The `:politicas :circuit-breaker` slot carries the
2014    /// "per-Aplicacao consecutive-transient-failure trip declaration"
2015    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2016    /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
2017    /// zero-floor rejected through
2018    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2019    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
2020    /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
2021    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
2022    /// canonical-form pinned through
2023    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
2024    /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
2025    /// bijection the future `CiliumClusterwideEnvoyConfig`
2026    /// per-`:politicas` overlay emits. Every downstream consumer that
2027    /// reads the breaker declaration keys off this scalar (the
2028    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2029    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2030    /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
2031    /// that brackets `cb.max_failures()` against
2032    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
2033    /// [`POLICY_BREAKER_WINDOW_MAX`] via
2034    /// [`crate::render::require_positive_canonical_bounded_duration`],
2035    /// the future M4 per-Aplicacao Envoy reconciler materialization
2036    /// pass, the future per-`:contratos`-edge breaker override the
2037    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2038    ///
2039    /// Prior to this lift the `.circuit_breaker` field was accessed
2040    /// inline at two sites — [`MeshPolicy::is_empty`]'s
2041    /// `self.circuit_breaker.is_none()` arm and the
2042    /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
2043    /// bind — two open-coded field-accesses that expressed no
2044    /// compile-time link back to the typed slot. A future extension of
2045    /// the `:politicas :circuit-breaker` axis to a richer author
2046    /// surface — a per-`:contratos`-edge breaker override the operator
2047    /// pins through a future `:contratos :circuit-breaker` slot the
2048    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
2049    /// breaker-default overlay the M4 CR materializer resolves per-CR,
2050    /// a promotion of the plain `(max_failures, window)` scalar pair to
2051    /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
2052    /// sub-block once Envoy's `outlier_detection` grows the peer
2053    /// ejection-percentage / ejection-time axes — would have had to be
2054    /// threaded through both open-coded copies in lockstep or the
2055    /// emptiness predicate and the validate gate would silently
2056    /// disagree on which breaker declaration a given [`MeshPolicy`]
2057    /// resolves to (a `:politicas` block whose only axis is a
2058    /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
2059    /// the validate path silently read a drifted other value, or vice
2060    /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
2061    /// "60s"))` would omit the value-shape gate while the emptiness
2062    /// predicate still classified the policy as non-empty). Lifting
2063    /// the resolution to a typed method on the substrate primitive
2064    /// means every downstream consumer of the Aplicacao's
2065    /// per-`:politicas` breaker surface reaches for exactly one typed
2066    /// dispatch — the resolver's accept-set migrates as a unit on any
2067    /// future axis addition.
2068    ///
2069    /// Second `Option<Copy-composite-T>`-return accessor on the M3
2070    /// mesh-slot family (sibling of the peer per-`:politicas`
2071    /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
2072    /// on the same composite-Copy shape, and of the sibling per-
2073    /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
2074    /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
2075    /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
2076    /// `Option<bool>` accessors on the sibling primitive-Copy axes —
2077    /// same "one typed dispatch on the substrate primitive, thin
2078    /// projections at each consumer" discipline extended onto the last
2079    /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
2080    /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
2081    /// match the storage field's name; the accessor's identity maps
2082    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2083    /// docstring already carries. Closes the last unlifted
2084    /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
2085    /// reader now routes through a typed dispatch on the substrate
2086    /// primitive.
2087    #[must_use]
2088    pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
2089        self.circuit_breaker
2090    }
2091}
2092
2093#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2094#[serde(rename_all = "camelCase")]
2095pub struct CircuitBreaker {
2096    pub max_failures: u32,
2097    #[serde(with = "supervisor::duration_codec_required")]
2098    pub window: Duration,
2099}
2100
2101impl CircuitBreaker {
2102    /// Substrate-canonical per-`:politicas :circuit-breaker`
2103    /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
2104    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2105    /// breaker trip-count keys off — returns the author-declared
2106    /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
2107    /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
2108    /// so the accessor returns by value; no borrow of `&self` past the
2109    /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
2110    /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
2111    /// axis; a `CircuitBreaker` past pattern-match is definitionally
2112    /// present, and its `:max-failures` field carries the trip count as a
2113    /// required-axis scalar).
2114    ///
2115    /// The `:politicas :circuit-breaker :max-failures` axis carries the
2116    /// "consecutive-transient-failure trip threshold" contract
2117    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
2118    /// (zero-floor rejected through
2119    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2120    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
2121    /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
2122    /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
2123    /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
2124    /// Every downstream consumer that reads the trip threshold keys off
2125    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2126    /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
2127    /// canonical `require_positive_bounded_u32` helper, the future M4
2128    /// per-Aplicacao Envoy config reconciler materialization pass, the
2129    /// future per-`:contratos`-edge breaker-override overlay the
2130    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2131    ///
2132    /// Prior to this lift the `.max_failures` field was accessed inline
2133    /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
2134    /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
2135    /// open-coded field-access that expressed no compile-time link back
2136    /// to the typed sub-struct axis. A future extension of the
2137    /// `:max-failures` axis to a richer author surface — a
2138    /// per-`:contratos`-edge breaker override the operator pins through a
2139    /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
2140    /// #3 roadmap acknowledges, a per-cluster max-failures-default
2141    /// overlay the M4 CR materializer resolves per-CR, a promotion of the
2142    /// plain `u32` trip count to a richer
2143    /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
2144    /// tuple once Envoy's `outlier_detection` block's peer axes come into
2145    /// scope, a per-Envoy-cluster minimum-request-volume gate before the
2146    /// count arms — would have had to be threaded through every open-
2147    /// coded copy in lockstep or the validate gate and the future M4
2148    /// emit path would silently disagree on which trip threshold a given
2149    /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
2150    /// would satisfy validate while the emit path silently read a drifted
2151    /// other value, or vice versa: a validated typed slot would land at
2152    /// the emit boundary as a no-op breaker whose trip threshold is
2153    /// structurally never reached). Lifting the resolution to a typed
2154    /// method on the substrate primitive means every downstream consumer
2155    /// of the Aplicacao's per-`:politicas :circuit-breaker`
2156    /// trip-threshold surface reaches for exactly one typed dispatch —
2157    /// the resolver's accept-set migrates as a unit on any future axis
2158    /// addition.
2159    ///
2160    /// First sub-struct scalar accessor on the M3 mesh-slot family
2161    /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
2162    /// scalar" projection pattern the sibling `CircuitBreaker::window` /
2163    /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
2164    /// closes the last unlifted per-`:politicas` scalar-value axis after
2165    /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
2166    /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
2167    /// Same "one typed dispatch on the substrate primitive, thin
2168    /// projections at each consumer" discipline the peer
2169    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
2170    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
2171    /// [`Membro::versao_requirement`] (a40b0e3),
2172    /// [`Entrada::destination`] (6db982c) accessors carry on their
2173    /// respective per-mesh-slot-atom scalar-value axes, extended onto the
2174    /// per-sub-struct required-`u32` axis. Named `max_failures()` to
2175    /// match the storage field's name; the accessor's identity maps onto
2176    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2177    /// docstring already carries.
2178    #[must_use]
2179    pub const fn max_failures(&self) -> u32 {
2180        self.max_failures
2181    }
2182
2183    /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
2184    /// Envoy-outlier-detection rolling-observation-interval scalar
2185    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2186    /// breaker rolling-window duration keys off — returns the
2187    /// author-declared `:politicas :circuit-breaker :window` typed
2188    /// `Duration` verbatim, copied out of the typed slot's own
2189    /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
2190    /// by value; no borrow of `&self` past the call). Non-optional (the
2191    /// surrounding `Option<CircuitBreaker>` is the "slot present?"
2192    /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
2193    /// `CircuitBreaker` past pattern-match is definitionally present,
2194    /// and its `:window` field carries the rolling-observation interval
2195    /// as a required-axis scalar).
2196    ///
2197    /// The `:politicas :circuit-breaker :window` axis carries the
2198    /// "consecutive-transient-failure rolling-observation interval"
2199    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2200    /// `Duration` accept-set (zero-floor rejected through
2201    /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
2202    /// residue rejected through
2203    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
2204    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
2205    /// Envoy `outlier_detection.interval` per-cluster
2206    /// ejection-observation-interval scalar (equivalently the future
2207    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2208    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2209    /// consumer that reads the rolling-observation interval keys off
2210    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2211    /// integer-millisecond canonical-form + cap bracket at
2212    /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
2213    /// [`crate::render::require_positive_canonical_bounded_duration`]
2214    /// helper, the future M4 per-Aplicacao Envoy config reconciler
2215    /// materialization pass, the future per-`:contratos`-edge
2216    /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
2217    /// acknowledges).
2218    ///
2219    /// Prior to this lift the `.window` field was accessed inline at
2220    /// one production site — [`AplicacaoSpec::validate_politicas`]'s
2221    /// `require_positive_canonical_bounded_duration(cb.window, …)`
2222    /// call — one open-coded field-access that expressed no compile-
2223    /// time link back to the typed sub-struct axis. A future extension
2224    /// of the `:window` axis to a richer author surface — a
2225    /// per-`:contratos`-edge window override the operator pins through
2226    /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
2227    /// #3 roadmap acknowledges, a per-cluster window-default overlay
2228    /// the M4 CR materializer resolves per-CR, a promotion of the plain
2229    /// `Duration` observation interval to a richer
2230    /// `{interval, base_ejection_time, max_ejection_percent}` tuple
2231    /// once Envoy's `outlier_detection` block's peer axes come into
2232    /// scope, a per-Envoy-cluster minimum-request-volume gate before
2233    /// the window arms — would have had to be threaded through every
2234    /// open-coded copy in lockstep or the validate gate and the future
2235    /// M4 emit path would silently disagree on which observation
2236    /// interval a given [`CircuitBreaker`] resolves to (an author's
2237    /// `:window "60s"` would satisfy validate while the emit path
2238    /// silently read a drifted other value, or vice versa: a validated
2239    /// typed slot would land at the emit boundary as a breaker whose
2240    /// observation window is structurally so wide that no realistic
2241    /// failure-rate shape can trip it). Lifting the resolution to a
2242    /// typed method on the substrate primitive means every downstream
2243    /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
2244    /// observation-window surface reaches for exactly one typed
2245    /// dispatch — the resolver's accept-set migrates as a unit on any
2246    /// future axis addition.
2247    ///
2248    /// Second sub-struct scalar accessor on the M3 mesh-slot family —
2249    /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
2250    /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
2251    /// required-axis, extended onto the per-sub-struct required-`Duration`
2252    /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
2253    /// axis. Same "one typed dispatch on the substrate primitive, thin
2254    /// projections at each consumer" discipline the peer
2255    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
2256    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
2257    /// [`Membro::versao_requirement`] (a40b0e3),
2258    /// [`Entrada::destination`] (6db982c) accessors carry on their
2259    /// respective per-mesh-slot-atom scalar-value axes, extended onto
2260    /// the per-sub-struct required-`Duration` axis. Named `window()` to
2261    /// match the storage field's name; the accessor's identity maps onto
2262    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2263    /// docstring already carries.
2264    #[must_use]
2265    pub const fn window(&self) -> Duration {
2266        self.window
2267    }
2268}
2269
2270#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2271pub struct RateLimit {
2272    /// Requests per window.
2273    pub rate: u32,
2274    /// Window duration.
2275    pub window: Duration,
2276}
2277
2278impl RateLimit {
2279    /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
2280    /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
2281    /// every consumer of the Aplicacao's per-`:contratos`-edge
2282    /// rate-limit-bucket capacity keys off — returns the author-declared
2283    /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
2284    /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
2285    /// returns by value; no borrow of `&self` past the call). Non-optional
2286    /// (the surrounding `Option<RateLimit>` is the "slot present?"
2287    /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
2288    /// `RateLimit` past pattern-match is definitionally present, and its
2289    /// `:rate` field carries the token-bucket capacity as a required-axis
2290    /// scalar).
2291    ///
2292    /// The `:politicas :rate-limit` `:rate` axis carries the
2293    /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
2294    /// the typed slot's `u32` accept-set (zero-floor rejected through
2295    /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
2296    /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
2297    /// `local_rate_limit.token_bucket.max_tokens` per-cluster
2298    /// token-bucket-capacity scalar (equivalently the future
2299    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2300    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2301    /// consumer that reads the token-bucket capacity keys off this
2302    /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2303    /// cap bracket that gates on the canonical
2304    /// [`crate::render::require_positive_bounded_u32`] helper, the
2305    /// [`rate_limit_codec::render`] `Duration → unit` projection that
2306    /// emits the `<n>/<s|m|h>` author surface, the future M4
2307    /// per-Aplicacao Envoy config reconciler materialization pass, the
2308    /// future per-`:contratos`-edge rate-limit-override overlay the
2309    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2310    ///
2311    /// Prior to this lift the `.rate` field was accessed inline at three
2312    /// production sites — [`AplicacaoSpec::validate_politicas`]'s
2313    /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
2314    /// [`rate_limit_codec::render`] format-arm arms (canonical-window
2315    /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
2316    /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
2317    /// field-accesses that expressed no compile-time link back to the
2318    /// typed sub-struct axis. A future extension of the `:rate` axis
2319    /// to a richer author surface — a per-`:contratos`-edge rate
2320    /// override the operator pins through a future `:contratos :rate`
2321    /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
2322    /// per-cluster rate-default overlay the M4 CR materializer resolves
2323    /// per-CR, a promotion of the plain `u32` token capacity to a
2324    /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
2325    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
2326    /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
2327    /// before the token arms — would have had to be threaded through
2328    /// every open-coded copy in lockstep or the validate gate, the
2329    /// codec's render path, and the future M4 emit path would silently
2330    /// disagree on which token capacity a given [`RateLimit`] resolves
2331    /// to (an author's `:rate-limit "100/s"` would satisfy validate
2332    /// while the render / emit paths silently read a drifted other
2333    /// value, or vice versa: a validated typed slot would land at the
2334    /// emit boundary as a no-op limiter whose token capacity is
2335    /// structurally so high that no realistic per-edge traffic shape
2336    /// can drain it). Lifting the resolution to a typed method on the
2337    /// substrate primitive means every downstream consumer of the
2338    /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
2339    /// reaches for exactly one typed dispatch — the resolver's
2340    /// accept-set migrates as a unit on any future axis addition.
2341    ///
2342    /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
2343    /// in shape to the peer per-`CircuitBreaker`
2344    /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
2345    /// on the peer per-sub-struct required-axis, extended onto the
2346    /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
2347    /// required-axis scalar" projection pattern the sibling
2348    /// [`RateLimit::window`] future lift folds on. Same "one typed
2349    /// dispatch on the substrate primitive, thin projections at each
2350    /// consumer" discipline the peer [`WitContract::source`] /
2351    /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
2352    /// (0804823), [`Membro::nome`] (4a32abf),
2353    /// [`Membro::versao_requirement`] (a40b0e3),
2354    /// [`Entrada::destination`] (6db982c),
2355    /// [`CircuitBreaker::max_failures`] (3a74062),
2356    /// [`CircuitBreaker::window`] (373957f) accessors carry on their
2357    /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
2358    /// to match the storage field's name; the accessor's identity maps
2359    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2360    /// docstring already carries.
2361    #[must_use]
2362    pub const fn rate(&self) -> u32 {
2363        self.rate
2364    }
2365
2366    /// Substrate-canonical per-`:politicas :rate-limit` `:window`
2367    /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
2368    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2369    /// rate-limit-bucket refill period keys off — returns the
2370    /// author-declared `:politicas :rate-limit` typed `Duration`
2371    /// verbatim, copied out of the typed slot's own `Duration` storage
2372    /// (`Duration` is `Copy`, so the accessor returns by value; no
2373    /// borrow of `&self` past the call). Non-optional (the surrounding
2374    /// `Option<RateLimit>` is the "slot present?" projection at the
2375    /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
2376    /// pattern-match is definitionally present, and its `:window`
2377    /// field carries the token-bucket refill period as a required-axis
2378    /// scalar).
2379    ///
2380    /// The `:politicas :rate-limit` `:window` axis carries the
2381    /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
2382    /// — the typed slot's `Duration` accept-set (constrained to the
2383    /// three canonical windows `{1s, 60s, 3600s}` the
2384    /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
2385    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
2386    /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
2387    /// per-cluster token-bucket-refill-period scalar (equivalently the
2388    /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2389    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2390    /// consumer that reads the token-bucket refill period keys off
2391    /// this scalar (the [`AplicacaoSpec::validate_politicas`]
2392    /// canonical-window gate that keys off
2393    /// [`is_canonical_rate_limit_window`], the
2394    /// [`rate_limit_codec::render`] `Duration → unit` projection that
2395    /// emits the `<n>/<s|m|h>` author surface — canonical arm via
2396    /// [`rate_limit_window_unit`] and non-canonical fallback via
2397    /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
2398    /// reconciler materialization pass, the future per-`:contratos`-
2399    /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
2400    /// roadmap acknowledges).
2401    ///
2402    /// Prior to this lift the `.window` field was accessed inline at
2403    /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
2404    /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
2405    /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
2406    /// error-payload construction on refusal, and the two
2407    /// [`rate_limit_codec::render`] arms
2408    /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
2409    /// and non-canonical-window `rl.window.as_secs()` fallback). Three
2410    /// open-coded field-accesses that expressed no compile-time link
2411    /// back to the typed sub-struct axis. A future extension of the
2412    /// `:window` axis to a richer author surface — a per-`:contratos`-
2413    /// edge window override the operator pins through a future
2414    /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
2415    /// acknowledges, a per-cluster window-default overlay the M4 CR
2416    /// materializer resolves per-CR, a promotion of the plain
2417    /// `Duration` refill period to a richer
2418    /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
2419    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
2420    /// axis comes into scope, an addition of a `"d"` day suffix once
2421    /// Envoy's `rate_limit_action` grows daily-bucket support — would
2422    /// have had to be threaded through every open-coded copy in
2423    /// lockstep or the validate gate, the codec's render path, and
2424    /// the future M4 emit path would silently disagree on which
2425    /// refill period a given [`RateLimit`] resolves to (an author's
2426    /// `:rate-limit "100/s"` would satisfy validate while the render
2427    /// / emit paths silently read a drifted other value, or vice
2428    /// versa: a validated typed slot would land at the emit boundary
2429    /// as a limiter whose refill period is structurally so long that
2430    /// no realistic per-edge traffic shape stays inside the token
2431    /// budget). Lifting the resolution to a typed method on the
2432    /// substrate primitive means every downstream consumer of the
2433    /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
2434    /// reaches for exactly one typed dispatch — the resolver's
2435    /// accept-set migrates as a unit on any future axis addition.
2436    ///
2437    /// Second sub-struct scalar accessor on the `RateLimit` axis —
2438    /// sibling in shape to the just-landed [`RateLimit::rate`]
2439    /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
2440    /// required-axis, extended onto the per-sub-struct
2441    /// required-`Duration` axis; closes the last unlifted
2442    /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
2443    /// per-sub-struct accessor coverage is now complete across both
2444    /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
2445    /// the substrate primitive, thin projections at each consumer"
2446    /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
2447    /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
2448    /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
2449    /// (7f0fd43), [`WitContract::world_ref`] (0804823),
2450    /// [`Membro::nome`] (4a32abf),
2451    /// [`Membro::versao_requirement`] (a40b0e3),
2452    /// [`Entrada::destination`] (6db982c) accessors carry on their
2453    /// respective per-mesh-slot-atom scalar-value axes. Named
2454    /// `window()` to match the storage field's name; the accessor's
2455    /// identity maps onto the canonical MESH-COMPOSITION §III.2
2456    /// vocabulary the slot's docstring already carries.
2457    #[must_use]
2458    pub const fn window(&self) -> Duration {
2459        self.window
2460    }
2461}
2462
2463/// Canonical `(unit-suffix, seconds-per-window)` bijection every
2464/// consumer of the `:politicas :rate-limit` unit table reads from —
2465/// [`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
2466/// [`rate_limit_codec::render`]'s `Duration → unit` projection, and the
2467/// [`is_canonical_rate_limit_window`] predicate the
2468/// [`AplicacaoSpec::validate_politicas`] gate keys off. Until this table
2469/// landed the `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection was
2470/// scattered across four peer sites — the codec's `match unit` parse
2471/// arm, the codec's `if secs == 1 { "s" } else if …` render cascade,
2472/// and the predicate's `secs == 1 || secs == 60 || secs == 3600`
2473/// disjunction — each carrying its own hand-written copy of the same
2474/// three (str, u64) pairs with no compile-time link between them. A
2475/// future rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
2476/// sub-second window once Envoy's `rate_limit_action` grows fractional
2477/// support) would have to be threaded through all three sites in
2478/// lockstep or a drift would silently split the accepted-window set: a
2479/// unit accepted by parse but unknown to render would round-trip
2480/// through the codec to the fallback `<n>/<k>s` shape (breaking the
2481/// THEORY.md §V.2.7 render-determinism contract every typed slot
2482/// carries), and a unit accepted by parse but unknown to the predicate
2483/// would silently pass validate and land at the renderer as a
2484/// non-canonical fallback.
2485///
2486/// Lifting the pairs to one `const` collapses the three call sites onto
2487/// one canonical projection each ([`rate_limit_window_unit`] for the
2488/// `Duration → unit` direction, [`rate_limit_window_from_unit`] for the
2489/// inverse), so a future unit addition is exactly one row appended
2490/// here — every consumer picks it up by construction. Same
2491/// "one canonical table, thin projections at each consumer" discipline
2492/// [`PlacementStrategy::as_str`] (cc8f749) applies on the sibling M3
2493/// typed-enum axis, and [`WitTarget::payload_pair`] (6788ed6) applies
2494/// on the peer typed-contract-payload axis.
2495const RATE_LIMIT_UNIT_TABLE: &[(&str, u64)] = &[("s", 1), ("m", 60), ("h", 3600)];
2496
2497/// Canonical rate-limit unit suffix for `window`, or `None` when
2498/// `window` isn't one of the [`RATE_LIMIT_UNIT_TABLE`] entries (i.e.
2499/// carries a non-canonical magnitude the codec's round-trip would break
2500/// on). Reads the `Duration → unit` half of the lifted bijection so
2501/// [`rate_limit_codec::render`] and [`is_canonical_rate_limit_window`]
2502/// share the same projection — a future unit added to the table reaches
2503/// both consumers by construction.
2504#[must_use]
2505fn rate_limit_window_unit(window: Duration) -> Option<&'static str> {
2506    if window.subsec_nanos() != 0 {
2507        return None;
2508    }
2509    let secs = window.as_secs();
2510    RATE_LIMIT_UNIT_TABLE
2511        .iter()
2512        .find_map(|(unit, s)| (*s == secs).then_some(*unit))
2513}
2514
2515/// Canonical rate-limit `Duration` for a unit suffix, or `None` when
2516/// the suffix isn't one of the [`RATE_LIMIT_UNIT_TABLE`] entries. Reads
2517/// the `unit → Duration` half of the lifted bijection so
2518/// [`rate_limit_codec::parse`] shares the same projection — a future
2519/// unit added to the table reaches parse by construction.
2520#[must_use]
2521fn rate_limit_window_from_unit(unit: &str) -> Option<Duration> {
2522    RATE_LIMIT_UNIT_TABLE
2523        .iter()
2524        .find_map(|(u, secs)| (*u == unit).then_some(Duration::from_secs(*secs)))
2525}
2526
2527/// True when `window` is exactly one of the three canonical rate-limit
2528/// windows the [`rate_limit_codec`] round-trips losslessly: 1 second
2529/// (`"<n>/s"`), 1 minute (`"<n>/m"`), or 1 hour (`"<n>/h"`). Routes
2530/// through [`rate_limit_window_unit`] — the single `Duration → unit`
2531/// projection [`rate_limit_codec::render`] also consumes — so the
2532/// canonical-window set lives in one lifted [`RATE_LIMIT_UNIT_TABLE`]
2533/// entry per unit, drift between the codec's accepted unit set and the
2534/// validate gate's accepted window set is a build error visible at the
2535/// table, not a silent round-trip break at the codec layer. Same shape
2536/// every other predicate-on-the-typed-slot helper carries
2537/// ([`MeshPolicy::is_empty`], [`crate::LimitsSpec::is_empty`],
2538/// [`crate::BehaviorSpec::is_empty`]).
2539#[must_use]
2540fn is_canonical_rate_limit_window(window: Duration) -> bool {
2541    rate_limit_window_unit(window).is_some()
2542}
2543
2544/// Upper-bound ceiling on the `:politicas :timeout` axis — every
2545/// validated [`MeshPolicy::timeout`] past
2546/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
2547/// (inclusive on both ends, integer-millisecond magnitudes by the
2548/// canonical-form gate immediately preceding).
2549///
2550/// The typed field is `Option<Duration>` (the zero-floor arm
2551/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
2552/// `Duration::ZERO`, and the canonical-form arm
2553/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
2554/// sub-millisecond residue), so a programmatic struct literal
2555/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
2556/// 24h) and the equivalent author-surface form
2557/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
2558/// integer-hour magnitude) both round-trip cleanly through serde — a
2559/// structurally unbounded `Duration` ceiling. A `:timeout` value far
2560/// above the documented production-playbook band (Envoy default `15s`,
2561/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
2562/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
2563/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
2564/// at `~3600s`) silently degenerates the mesh-policy contract: the
2565/// per-call deadline is structurally so long that no realistic
2566/// synchronous-`:contratos` traversal can reach it, so the typed slot
2567/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
2568/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
2569/// blocking" degenerates to a nominal-only contract on the
2570/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
2571/// the sibling `:politicas :retries` axis and the
2572/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
2573/// `:politicas :circuit-breaker :max-failures` axis — all three close
2574/// the "structurally unbounded ceiling on a typed `:politicas` axis"
2575/// footgun the prior zero-floor-and-canonical-form-only checks left
2576/// open.
2577///
2578/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
2579/// shared duration codec emits (`"<n>h"` for any integer-hour
2580/// magnitude) — every value in the canonical authoring form's
2581/// `<integer><unit>` grammar at or below this cap renders to a clean
2582/// canonical string. The cap sits an order of magnitude above every
2583/// documented production-playbook recommendation band (Envoy default
2584/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
2585/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
2586/// configured maximum (`proxy_read_timeout` typical max `3600s`),
2587/// below the clearly-pathological "effectively no timeout" floor
2588/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
2589/// want for a long-running synchronous workflow, but a hard wall above
2590/// which the mesh-level deadline is structurally a non-deadline.
2591/// Lifted as a typed `pub const` so the bound has exactly one source
2592/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
2593/// materializer's admission webhook and the caixa-mesh-side
2594/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2595/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
2596/// other typed upper bound in this crate carries
2597/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
2598/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2599/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2600/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2601pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
2602
2603/// Upper-bound ceiling on the `:politicas :retries` axis — every
2604/// validated [`MeshPolicy::retries`] past
2605/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
2606///
2607/// The typed slot is `Option<u32>` (`None` = no retries on transient
2608/// failure; `Some(0)` already rejected by the
2609/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
2610/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
2611/// .. }`) and the equivalent author-surface form
2612/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
2613/// serde / the codec — a structurally unbounded `u32` ceiling. The
2614/// runtime substrate that consumes the value (Envoy's
2615/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
2616/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
2617/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
2618/// admission cap is 10) translates a four-billion-retry policy into a
2619/// thundering-herd amplification vector on transient failure — the
2620/// caller's one request fans out to `retries` server-side calls per
2621/// edge per traversal, multiplying load by `(retries+1)^depth` across
2622/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
2623/// invariant "no infinite blocking" pairs with a no-runaway-amplification
2624/// invariant on the retry axis; both belong at the typed-slot layer.
2625///
2626/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
2627/// upstream mesh-policy schema that documents one) and sits above the
2628/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
2629/// every documented production playbook): a value the author can
2630/// plausibly want, but a hard wall above which the policy is
2631/// structurally a footgun. Lifted as a typed `pub const` so the bound
2632/// has exactly one source of truth — a future axis reaching for the
2633/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
2634/// materializer's admission webhook, the caixa-mesh-side
2635/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
2636/// one place. Same shape every other typed upper bound in this crate
2637/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2638/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2639/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
2640/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2641pub const POLICY_RETRIES_MAX: u32 = 10;
2642
2643/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
2644/// axis — every validated [`CircuitBreaker::max_failures`] past
2645/// [`AplicacaoSpec::validate_politicas`] lies in
2646/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
2647///
2648/// The typed field is `u32` (the zero-floor arm
2649/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
2650/// `0` — a breaker that trips on the first call), so a programmatic
2651/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
2652/// and the equivalent author-surface form
2653/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
2654/// cleanly through serde — a structurally unbounded `u32` ceiling. A
2655/// `max_failures` value far above the documented production-playbook
2656/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
2657/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
2658/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
2659/// typical 5–50) silently disables the breaker's protection role:
2660/// the threshold is structurally so high that no realistic
2661/// failures-per-`:window` traffic shape can reach it, so the breaker
2662/// never trips and the typed slot becomes a no-op carried on every
2663/// emitted Envoy / Cilium L7 overlay. Pairs with the
2664/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
2665/// axis — both close the "structurally unbounded `u32` ceiling on a
2666/// typed policy axis" footgun the prior zero-floor-only checks left
2667/// open.
2668///
2669/// The `1000` ceiling sits an order of magnitude above every
2670/// documented upstream production-playbook recommendation band (the
2671/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
2672/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
2673/// the clearly-pathological "effectively no protection"
2674/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
2675/// plausibly want at hyperscale, but a hard wall above which the
2676/// policy is structurally a no-op. Lifted as a typed `pub const` so
2677/// the bound has exactly one source of truth — the future M4
2678/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
2679/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
2680/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
2681/// one place. Same shape every other typed upper bound in this crate
2682/// carries ([`POLICY_RETRIES_MAX`],
2683/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2684/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2685/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2686pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
2687
2688/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
2689/// every validated [`CircuitBreaker::window`] past
2690/// [`AplicacaoSpec::validate_politicas`] lies in
2691/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
2692/// integer-millisecond magnitudes by the canonical-form gate
2693/// immediately preceding).
2694///
2695/// The typed field is `Duration` (the zero-floor arm
2696/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
2697/// `Duration::ZERO`, and the canonical-form arm
2698/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
2699/// sub-millisecond residue), so a programmatic struct literal
2700/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
2701/// and the equivalent author-surface form
2702/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
2703/// integer-hour magnitude) both round-trip cleanly through serde — a
2704/// structurally unbounded `Duration` ceiling. A `:window` value far
2705/// above the documented production-playbook band (Hystrix
2706/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
2707/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
2708/// Istio `outlierDetection.interval` default `10s`, Envoy
2709/// `outlier_detection.interval` default `10s`, AWS App Mesh
2710/// circuit-breaker time-window typical `30s..=300s`) degenerates the
2711/// breaker's role: a rolling-window failure counter whose window is
2712/// hours long is operationally a lifetime counter, the breaker's
2713/// "recent failures" memory is structurally so long that transient
2714/// failures are never forgotten, and the typed slot becomes a no-op
2715/// trigger that trips once and stays tripped for the lifetime of the
2716/// component carried on every emitted Envoy / Cilium L7 overlay.
2717///
2718/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
2719/// shared duration codec emits (`"<n>h"` for any integer-hour
2720/// magnitude) — every value in the canonical authoring form's
2721/// `<integer><unit>` grammar at or below this cap renders to a clean
2722/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
2723/// cap on the first typed-`Duration` `:politicas` axis: the two
2724/// duration-typed `:politicas` axes now share a single uniform top
2725/// edge so the next typed-slot wiring (the future caixa-mesh
2726/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
2727/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
2728/// admission webhook) reaches for either field knowing the value is
2729/// in `1ms..=1h` without re-validating at the renderer layer. The cap
2730/// sits two orders of magnitude above every documented upstream
2731/// production-playbook recommendation band (Hystrix / resilience4j /
2732/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
2733/// and below the clearly-pathological "rolling window degenerates to
2734/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
2735/// author can plausibly want for a very-low-traffic long-tail
2736/// failure-detection window, but a hard wall above which the breaker's
2737/// rolling-window contract is structurally a lifetime-counter contract.
2738/// Lifted as a typed `pub const` so the bound has exactly one source
2739/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
2740/// materializer's admission webhook and the caixa-mesh-side
2741/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2742/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
2743/// other typed upper bound in this crate carries
2744/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
2745/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
2746/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2747/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2748/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2749pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
2750
2751/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
2752/// every validated [`RateLimit::rate`] past
2753/// [`AplicacaoSpec::validate_politicas`] lies in
2754/// `1..=POLICY_RATE_LIMIT_MAX`.
2755///
2756/// The typed field is `u32` (the zero-floor arm
2757/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
2758/// zero-rate limit denies every request, the canonical "I forgot
2759/// that 0 means deny-everything" footgun), so a programmatic struct
2760/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
2761/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
2762/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
2763/// round-trip cleanly through serde — a structurally unbounded `u32`
2764/// ceiling. The runtime substrate consuming the value (Envoy's
2765/// `local_rate_limit.token_bucket.max_tokens`, the future
2766/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2767/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
2768/// rate-limit into a no-op rate-limiter: the bucket capacity is
2769/// structurally so high no realistic per-edge traffic shape can
2770/// drain it, the limiter never trips, and the typed slot becomes a
2771/// "rate-limit declared, no enforcement" footgun — the canonical
2772/// declared-but-inert shape every other `:politicas` cap arm
2773/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
2774/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
2775///
2776/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
2777/// above every documented upstream production-playbook recommendation
2778/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
2779/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
2780/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
2781/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
2782/// `limit_req_zone` typical `1..=1_000` RPS) and below the
2783/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
2784/// `u32::MAX`): a value the author can plausibly want at hyperscale
2785/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
2786/// /h-window arm), but a hard wall above which the policy is
2787/// structurally a no-op carried verbatim on every emitted Envoy /
2788/// Cilium L7 overlay. The cap brackets all three canonical windows
2789/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
2790/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
2791/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
2792/// per-endpoint API band). Lifted as a typed `pub const` so the bound
2793/// has exactly one source of truth — the future M4
2794/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
2795/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
2796/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
2797/// one place. Same shape every other typed upper bound in this crate
2798/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
2799/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
2800/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2801/// [`crate::LIMITS_WALL_CLOCK_MAX`],
2802/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2803/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2804pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
2805
2806// `:entrada :host` total-length and per-label cap axes route through
2807// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
2808// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
2809// pair of aplicacao-private aliases the previous `validate_entrada_host`
2810// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
2811// = 63`) were structurally the same K8s Gateway API v1 Hostname
2812// admission-schema bounds — the total-length cap on the OpenAPI
2813// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
2814// same regex — that the peer axes at the caixa-core::render level pin,
2815// so hoisting both readers onto the shared lifted constants closes the
2816// third-occurrence duplication threshold structurally: the M4
2817// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
2818// label validator, the future per-`Certificate` SAN emitter, and every
2819// other per-Gateway-API-Hostname landing site reach the same one place
2820// as the `:entrada :host` gate does — no per-axis alias drift surface
2821// between them, by construction.
2822
2823/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
2824/// extractor expression — the upper bound `validate_placement_shard_key`
2825/// enforces on every well-shaped shard-key past validate. The realistic
2826/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
2827/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
2828/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
2829/// `:placement :affinity` / `:placement :clusters` identifier-shaped
2830/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
2831/// in `:shard-key`" footgun at validate time rather than at the future
2832/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
2833const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
2834
2835/// Reject `:membros :caixa` values the K8s apiserver would refuse at
2836/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
2837/// that maps the shared parser-shaped reason into the
2838/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
2839/// is self-locating (the offending `caixa:` is named verbatim) and
2840/// the author can grep their caixa.lisp for `:caixa "<name>"` and
2841/// fix it in one edit. Same diagnostic shape as
2842/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
2843/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
2844fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
2845    // Empty is already gated by `MembroCaixaEmpty` at the call site;
2846    // re-checking here keeps the predicate usable from any future
2847    // call site (the M4 CR materializer) without an empty-check
2848    // footgun. The shared
2849    // [`crate::render::require_valid_dns_1123_label`] helper brackets
2850    // the empty-first + shape cascade every peer name axis
2851    // (`:placement :clusters`, `:placement :affinity`, `:contratos
2852    // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
2853    // `:upgrade-from :module`) routes through, so drift between the
2854    // eight axes' accepted DNS-1123-label sets is structurally
2855    // impossible.
2856    crate::render::require_valid_dns_1123_label(
2857        caixa,
2858        || AplicacaoError::MembroCaixaEmpty,
2859        |reason| AplicacaoError::MembroCaixaInvalid {
2860            caixa: caixa.to_string(),
2861            reason,
2862        },
2863    )
2864}
2865
2866/// Reject `:placement :clusters` entries the K8s apiserver would refuse
2867/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
2868/// that maps the shared parser-shaped reason into the
2869/// [`AplicacaoError::PlacementClusterInvalid`] variant.
2870///
2871/// Cluster names land in DNS-1123-label territory across every consumer:
2872/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
2873/// the `lareira-fleet-programs` aggregator applies to scope programs to
2874/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
2875/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
2876/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
2877/// cluster identity the M4 CR materializer round-trips. Each apiserver-
2878/// side schema enforces the DNS-1123 label rule on admission; a
2879/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
2880/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
2881/// mistaken-identity slug) silently passes the prior empty-/duplicate-
2882/// only gate and the failure surfaces as a no-match at filter time —
2883/// the workload doesn't land in the named cluster, with no diagnostic
2884/// naming the offending `:clusters` entry. Lifting the gate to caixa-
2885/// build time mirrors the `:membros :caixa` value-shape trajectory
2886/// (3f9d7a0) on the peer name axis.
2887///
2888/// The diagnostic carries the offending `cluster:` verbatim plus a
2889/// parser-shaped `reason:` naming the specific violation, so the
2890/// author can grep their caixa.lisp for `:clusters` and fix it in
2891/// one edit. Same diagnostic shape as
2892/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
2893fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
2894    // Empty is already gated by `PlacementClusterEmpty` at the call
2895    // site; re-checking here keeps the predicate usable from any
2896    // future call site (the M4 CR materializer's per-cluster validator)
2897    // without an empty-check footgun. Routes through the shared
2898    // [`crate::render::require_valid_dns_1123_label`] gate the peer
2899    // name axes each land on.
2900    crate::render::require_valid_dns_1123_label(
2901        cluster,
2902        || AplicacaoError::PlacementClusterEmpty,
2903        |reason| AplicacaoError::PlacementClusterInvalid {
2904            cluster: cluster.to_string(),
2905            reason,
2906        },
2907    )
2908}
2909
2910/// Reject `:placement :affinity` hints whose shape can never legitimately
2911/// land in any downstream selector or label-keyed routing axis. Thin
2912/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
2913/// shared parser-shaped reason into the
2914/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
2915/// diagnostic is self-locating (the offending `:affinity` is named
2916/// verbatim) and the author can grep their caixa.lisp for
2917/// `:affinity "<hint>"` and fix it in one edit.
2918///
2919/// The `:affinity` slot carries a placement-engine hint — canonical
2920/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
2921/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
2922/// compression overlay and the future M4 placement-engine's per-hint
2923/// routing axis. Each downstream consumer (caixa-mesh's
2924/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
2925/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
2926/// `spec.placement.affinity` admission rule, the future M4 per-hint
2927/// node-affinity / pod-affinity rule generator keying off the same
2928/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
2929/// selector) requires the value to be a DNS-1123 label — K8s label
2930/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
2931/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
2932/// admission rule the apiserver enforces.
2933///
2934/// Until this gate landed an `:affinity "DataLocality"` (the canonical
2935/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
2936/// Python-module-name leak), `:affinity "data.locality"` (the
2937/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
2938/// `:affinity "data-locality-"` (boundary-hyphen violation),
2939/// `:affinity "data locality"` (paste-from-doc whitespace),
2940/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
2941/// 64-byte over-cap slug silently passed the empty-only check and the
2942/// failure surfaced as a no-match at the M3 Adaptive compression
2943/// overlay's filter time (`placement.affinity` carried a malformed
2944/// value, no node matched, the workload landed on the default
2945/// heuristic) — the canonical "declared-but-inert" footgun mirroring
2946/// the empty-:affinity / empty-shard-key / zero-:politicas /
2947/// empty-:contratos-target gates already close on every other
2948/// declare-but-no-opinion axis. Lifting the rejection to a build-time
2949/// gate closes the fifth typed slot on the Aplicacao surface to land
2950/// on the canonical DNS-1123 label floor (after the four Servico-name
2951/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
2952/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
2953/// b0e8748).
2954///
2955/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
2956/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
2957/// validated values are guaranteed-accepted by the apiserver without
2958/// re-validation at any downstream renderer or admission layer.
2959fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
2960    // Empty is gated separately at the call site for a self-locating
2961    // diagnostic; re-checking here keeps the predicate usable from any
2962    // future call site (the M4 CR materializer's per-affinity
2963    // validator) without an empty-check footgun. Routes through the
2964    // shared [`crate::render::require_valid_dns_1123_label`] gate the
2965    // peer name axes each land on.
2966    crate::render::require_valid_dns_1123_label(
2967        affinity,
2968        || AplicacaoError::PlacementAffinityEmpty,
2969        |reason| AplicacaoError::PlacementAffinityInvalid {
2970            affinity: affinity.to_string(),
2971            reason,
2972        },
2973    )
2974}
2975
2976/// Reject `:placement :shard-key` extractor expressions whose shape can
2977/// never legitimately drive the future M4 Akka-style cluster-sharding
2978/// reconciler's hash-extractor pass. Maps the per-byte / length checks
2979/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
2980/// diagnostic is self-locating (the offending `:shard-key` value is
2981/// named verbatim alongside the parser-shaped reason) and the author can
2982/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
2983/// edit.
2984///
2985/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
2986/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
2987/// expression naming the message property to hash on. The realistic
2988/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
2989/// property name; `$tenantId` — Akka entity-id placeholder;
2990/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
2991/// `${tenant}` — interpolation-style template) all sit in the printable
2992/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
2993/// multi-line blob landing in `:shard-key`, an embedded space from a
2994/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
2995/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
2996/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
2997/// check and the failure surfaces at the future M4 reconciler's hash
2998/// pass as a runtime extractor-evaluation error far from the source
2999/// `caixa.lisp`, with no field naming which member's `:shard-key`
3000/// carried the offending value.
3001///
3002/// The contract — the printable ASCII single-token intersection-floor
3003/// every Akka-style entity-id extractor implementation admits:
3004///
3005///   - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
3006///     peer DNS-1123-label-shaped `:placement :affinity` /
3007///     `:placement :clusters` identifier axes; realistic shard-keys sit
3008///     well under 32 bytes, the cap surfaces paste-from-doc multi-line
3009///     blob footguns at validate time;
3010///   - every byte in the printable ASCII range `0x21..=0x7E` —
3011///     rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
3012///     `"$tenantId\n"` from paste-from-aligned-doc /
3013///     paste-from-shell-heredoc), control characters (`\x00..\x1F`,
3014///     `\x7F` — the canonical "embedded null from a copy-paste-binary
3015///     footgun"), and non-ASCII bytes (`"$tenàntId"` —
3016///     un-Punycode-encoded IDN that round-trips inconsistently across
3017///     NFC/NFD normalization).
3018///
3019/// The accepted set is broader than the DNS-1123 label floor the peer
3020/// `:placement :clusters` / `:placement :affinity` axes use because the
3021/// `:shard-key` value is not a K8s `metadata.name` / label-selector
3022/// landing site; it's an extractor expression the future Akka-style
3023/// reconciler reads as a property reference. The realistic forms
3024/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
3025/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
3026/// but every Akka-style entity-id extractor parses. The
3027/// printable-ASCII-token floor accepts every shape any such extractor
3028/// would accept while rejecting the cross-implementation footguns
3029/// (whitespace breaks token boundaries; non-ASCII round-trips
3030/// inconsistently across YAML emitters and NFC/NFD normalization;
3031/// control characters silently corrupt the next read).
3032///
3033/// Until this gate landed `validate_placement` only refused the
3034/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
3035/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
3036/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
3037/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
3038/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
3039/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
3040/// control character from paste-from-binary, the 64-byte over-cap
3041/// paste-from-doc multi-line slug) silently passed validate. The future
3042/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
3043/// would then surface the malformed value either as a runtime
3044/// extractor-evaluation error (whitespace breaks the extractor's token
3045/// boundary, no match) or as a silently-different shard assignment
3046/// across YAML emitters (non-ASCII normalizes differently between the
3047/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
3048/// parser, the same entity ID maps to two distinct shards on a
3049/// re-render). Lifting the shape gate to caixa-build time makes the
3050/// extractor-floor invariant a structural property of every validated
3051/// `Placement`: every `Sharded` placement past `validate_placement` has
3052/// a `:shard-key` the future M4 reconciler can hash without
3053/// re-validating at the runtime layer.
3054///
3055/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
3056/// [`AplicacaoError::ContratoSubjectInvalid`] /
3057/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
3058/// on the peer `:contratos` payload axes — each lifts the
3059/// runtime-side parser's intersection-floor to a caixa-build-time gate,
3060/// closing the canonical "this passed validate but the runtime parser
3061/// rejected it" surprise.
3062fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
3063    // Empty is gated separately at the call site via the more
3064    // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
3065    // re-checking here keeps the predicate usable from any future call
3066    // site (the M4 CR materializer's per-shard-key validator) without
3067    // an empty-check footgun.
3068    if key.is_empty() {
3069        return Err(AplicacaoError::ShardedKeyEmpty);
3070    }
3071    if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
3072        return Err(AplicacaoError::ShardKeyInvalid {
3073            shard_key: key.to_string(),
3074            reason: format!(
3075                "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
3076                 (got {} bytes; realistic Akka-style entity-id extractor expressions \
3077                 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
3078                 well under 32 bytes, this length suggests a paste-from-doc \
3079                 multi-line blob landed in `:shard-key` instead of a single-token \
3080                 extractor expression)",
3081                key.len()
3082            ),
3083        });
3084    }
3085    for &b in key.as_bytes() {
3086        if (0x21..=0x7E).contains(&b) {
3087            continue;
3088        }
3089        let reason = if b == b' ' {
3090            "contains a space (Akka-style entity-id extractor expressions are \
3091             single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
3092             whitespace breaks the extractor's token boundary at the runtime layer, \
3093             and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
3094             a multi-token blob in one `:shard-key` slot)"
3095                .to_string()
3096        } else if b == b'\t' {
3097            "contains a tab character (paste-from-aligned-doc footgun; the \
3098             Akka-style entity-id extractor reads `:shard-key` as a single-token \
3099             reference, embedded whitespace breaks the token boundary at the \
3100             runtime hash-extractor pass)"
3101                .to_string()
3102        } else if b == b'\n' || b == b'\r' {
3103            format!(
3104                "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
3105                 paste-from-multiline-doc footgun; the Akka-style entity-id \
3106                 extractor reads `:shard-key` as a single-token reference, embedded \
3107                 newlines either truncate the value at the YAML emitter layer or \
3108                 break the token boundary at the runtime hash-extractor pass)"
3109            )
3110        } else if b < 0x20 || b == 0x7F {
3111            format!(
3112                "contains control character 0x{b:02x} (the canonical \
3113                 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
3114                 control characters silently corrupt round-trip serialization \
3115                 across YAML emitters and break the runtime hash-extractor's \
3116                 single-token parser)"
3117            )
3118        } else {
3119            format!(
3120                "contains non-ASCII byte 0x{b:02x} (the canonical \
3121                 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
3122                 inconsistently across NFC/NFD normalization on APFS / ext4 / \
3123                 across YAML emitter implementations — the same entity ID can \
3124                 silently map to two distinct shards on a re-render. Use a \
3125                 printable-ASCII extractor expression like `tenantId`, \
3126                 `$tenantId`, or `metadata.tenantId`)"
3127            )
3128        };
3129        return Err(AplicacaoError::ShardKeyInvalid {
3130            shard_key: key.to_string(),
3131            reason,
3132        });
3133    }
3134    Ok(())
3135}
3136
3137/// Reject `:contratos :de` / `:contratos :para` values whose shape
3138/// can never legitimately match a validated `:membros :caixa`. Thin
3139/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
3140/// shared parser-shaped reason into the
3141/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
3142/// diagnostic is self-locating (which slot — `:de` or `:para` — and
3143/// the offending value verbatim) and the author can grep their
3144/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
3145/// one edit.
3146///
3147/// Until this gate landed an empty or DNS-1123-malformed `:de` /
3148/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
3149/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
3150/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
3151/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
3152/// un-Punycode-encoded IDN) silently passed the per-axis check and
3153/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
3154/// membership lookup — diagnostic-framed as "this caixa is not in
3155/// `:membros`" when the root cause is "this `:de` value is not a
3156/// well-shaped Servico-name identifier and could never legitimately
3157/// match any validated member". Because every `:membros :caixa` is
3158/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
3159/// `names` HashSet structurally never contains an empty / malformed
3160/// string, so the membership lookup arm misframes every empty /
3161/// malformed input. Lifting the shape arm ahead of the lookup
3162/// preserves the legitimate `ContratoMemberMissing` arm (a
3163/// well-shaped `:de` that simply isn't in `:membros` — a phantom
3164/// reference) while routing every structurally-impossible-to-match
3165/// input through the narrower self-locating shape diagnostic.
3166///
3167/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
3168/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
3169/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
3170/// to land on the canonical [`crate::render::is_dns_1123_label`]
3171/// floor. The `slot: &'static str` field carries the kebab-case
3172/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
3173/// per-callback-slot diagnostic shape and the
3174/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
3175/// (85f102c) cross-list-tag pattern.
3176fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
3177    // Routes through the shared
3178    // [`crate::render::require_valid_dns_1123_label`] gate the peer
3179    // name axes each land on. The `slot: &'static str` field flows
3180    // through both error variants so the diagnostic names which
3181    // per-edge axis (`:de` vs `:para`) the offending value came from.
3182    crate::render::require_valid_dns_1123_label(
3183        caixa,
3184        || AplicacaoError::ContratoCaixaEmpty { slot },
3185        |reason| AplicacaoError::ContratoCaixaInvalid {
3186            slot,
3187            caixa: caixa.to_string(),
3188            reason,
3189        },
3190    )
3191}
3192
3193/// Reject `:entrada :para` values whose shape can never legitimately
3194/// match a validated `:membros :caixa`. Thin wrapper around
3195/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
3196/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
3197/// variant, so the diagnostic is self-locating (the offending
3198/// `:entrada :para` value is named verbatim) and the author can grep
3199/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
3200///
3201/// Until this gate landed an empty or DNS-1123-malformed `:entrada
3202/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
3203/// ADR typo, `:para "my_cart"` the Python-module-name leak,
3204/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
3205/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
3206/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
3207/// silently passed the per-axis check and surfaced as
3208/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
3209/// — diagnostic-framed as "this caixa is not in `:membros`" when the
3210/// root cause is "this `:entrada :para` value is not a well-shaped
3211/// Servico-name identifier and could never legitimately match any
3212/// validated member". Because every `:membros :caixa` is shape-
3213/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
3214/// `HashSet` structurally never contains an empty / malformed string,
3215/// so the membership lookup arm misframes every empty / malformed
3216/// input. Lifting the shape arm ahead of the lookup preserves the
3217/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
3218/// simply isn't in `:membros` — a phantom reference) while routing
3219/// every structurally-impossible-to-match input through the narrower
3220/// self-locating shape diagnostic.
3221///
3222/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
3223/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
3224/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
3225/// fourth and last Aplicacao-level Servico-name reference axis to
3226/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
3227/// No `slot: &'static str` field because there is only one axis
3228/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
3229/// the simpler shape mirrors [`validate_membro_caixa`] and
3230/// [`validate_placement_cluster`].
3231fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
3232    // Empty is gated separately at the call site for a self-locating
3233    // diagnostic; re-checking here keeps the predicate usable from any
3234    // future call site (the M4 CR materializer's per-`:entrada`
3235    // validator) without an empty-check footgun. Routes through the
3236    // shared [`crate::render::require_valid_dns_1123_label`] gate the
3237    // peer name axes each land on.
3238    crate::render::require_valid_dns_1123_label(
3239        para,
3240        || AplicacaoError::EntradaParaEmpty,
3241        |reason| AplicacaoError::EntradaParaInvalid {
3242            para: para.to_string(),
3243            reason,
3244        },
3245    )
3246}
3247
3248/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
3249/// would refuse at admission time. The contract — exactly the regex
3250/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
3251/// and `HTTPRoute.spec.hostnames[]`,
3252/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
3253/// (max length 253; per-label max length 63):
3254///
3255///   - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
3256///     uppercase, no underscore, no Unicode/IDN — IDN must be
3257///     pre-encoded as Punycode `xn--…` by the author);
3258///   - exactly one optional leading wildcard label (`*.`); a wildcard
3259///     in any non-leading label position is rejected;
3260///   - each `.`-separated label is 1..=63 bytes, with non-hyphen
3261///     alphanumeric at both boundaries (no `-foo`, no `foo-`);
3262///   - total length 1..=253 bytes;
3263///   - no IPv4 literal (Gateway API forbids IP literals);
3264///   - no scheme (`https://`, `http://`), no port (`:8080`), no
3265///     whitespace, no path (`/`).
3266///
3267/// Lifted as a typed gate (rather than an inline cascade in
3268/// `validate()`) so the contract lives in one place — every future
3269/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3270/// materializer's host validator, the future per-`:entrada` SAN
3271/// emission for cert-manager Certificates, the multi-`:entrada`
3272/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
3273/// for the same predicate, not its own. Same compounding shape as
3274/// `is_canonical_rate_limit_window` (808017c) and
3275/// [`WitTarget::label`] (previously the free `contrato_target_label`
3276/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
3277/// per-variant label match is compiler-checked-exhaustive).
3278///
3279/// The diagnostic carries the offending `host:` verbatim plus a
3280/// parser-shaped `reason:` naming the specific violation, so the
3281/// author can grep their caixa.lisp for `:host "<host>"` and fix it
3282/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
3283/// (9888b13).
3284fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
3285    // Empty is already gated by `EmptyEntradaHost` at the call site;
3286    // re-checking here keeps the predicate usable from any future
3287    // call site (M4 CR materializer) without an empty-check footgun.
3288    if host.is_empty() {
3289        return Err(AplicacaoError::EmptyEntradaHost);
3290    }
3291    if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
3292        return Err(AplicacaoError::EntradaHostInvalid {
3293            host: host.to_string(),
3294            reason: format!(
3295                "exceeds Gateway API v1 Hostname max length of {cap} bytes \
3296                 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
3297                host.len(),
3298                cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
3299            ),
3300        });
3301    }
3302    if host.contains("://") {
3303        return Err(AplicacaoError::EntradaHostInvalid {
3304            host: host.to_string(),
3305            reason: "must not carry a scheme (drop the `https://` or `http://` prefix; \
3306                     Gateway API takes the bare hostname)"
3307                .to_string(),
3308        });
3309    }
3310    if host.contains('/') {
3311        return Err(AplicacaoError::EntradaHostInvalid {
3312            host: host.to_string(),
3313            reason: "must not carry a path (drop the `/…` suffix; Gateway API path \
3314                     matching is in `:entrada :paths`)"
3315                .to_string(),
3316        });
3317    }
3318    // After the `://` scheme-prefix and `/` path arms have ruled out the
3319    // two `:`-bearing shapes the Gateway API actively rejects with
3320    // location-shaped diagnostics, any remaining `:` in the host body is
3321    // either the canonical "I put the port in the `:host` slot"
3322    // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
3323    // slot lives one axis away on the same `:entrada` block) or an
3324    // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
3325    // Hostname forbids identically to the IPv4-literal arm below. Both
3326    // shapes silently fell through the `://` and `/` arms before this
3327    // lift and surfaced as a deep `label "<rest>:<port>" contains
3328    // invalid character ':'` diagnostic from the per-byte loop near the
3329    // bottom of this predicate, which named the offending byte but not
3330    // the canonical authoring fix — for the port case the author has to
3331    // know the `:entrada` block carries a separate `:port u16` slot
3332    // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
3333    // move the value over; for the IPv6 case the author has to know
3334    // Gateway API v1 forbids IP literals across the board. The contract
3335    // doc-comment above already promises "no port (`:8080`)" verbatim
3336    // in the rejected-shape enumeration but the predicate's
3337    // implementation refused the `:` only as a side-effect of the
3338    // per-label `[a-z0-9-]` character-class loop; this arm brings the
3339    // implementation in line with the documented contract by surfacing
3340    // the canonical fix at the top-level shape gate, peer with how the
3341    // `://` arm names the scheme prefix and the `/` arm names the
3342    // `:entrada :paths` axis. Same compounding trajectory the recent
3343    // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
3344    // — the typed slot's rejected set matches the apiserver's rejected
3345    // set, structurally, with a self-locating diagnostic at the
3346    // offending axis instead of a deep parser-shape leak.
3347    if host.contains(':') {
3348        return Err(AplicacaoError::EntradaHostInvalid {
3349            host: host.to_string(),
3350            reason: "must not contain `:` (the port belongs in the `:entrada :port` \
3351                     slot — a separate `u16` axis on the same `:entrada` block, \
3352                     defaulting to 8080 — not in the host body; drop the `:<port>` \
3353                     suffix and author the bare hostname. If you intended an IPv6 \
3354                     literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
3355                     Hostname forbids IP literals identically to the IPv4-literal \
3356                     arm — use a DNS name)"
3357                .to_string(),
3358        });
3359    }
3360    // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
3361    // predicate — the same single source of truth every peer
3362    // ASCII-whitespace scan in caixa-core flows through: the four
3363    // typed-magnitude codec sites (`limits::parse_byte_size` backing
3364    // `:limits :memory`, `limits::parse_duration` backing `:limits
3365    // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
3366    // `aplicacao::rate_limit_codec::parse` backing `:politicas
3367    // :rate-limit`) and the shared duration codec
3368    // (`supervisor::duration_codec::parse`) backing `:supervisor
3369    // :restart-window` / `:politicas :timeout` / `:politicas
3370    // :circuit-breaker :window`. This landing closes the last string-typed
3371    // slot in caixa-core still calling `.bytes().any(|b|
3372    // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
3373    // across every typed slot now shares one predicate, so a future
3374    // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
3375    // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
3376    // deliberately excluded from the peer non-ASCII predicate) can
3377    // extend at this shared site in one edit rather than seven
3378    // independent scans diverging over time. Naming the offending byte
3379    // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
3380    // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
3381    // the offending byte verbatim" discipline every peer codec site
3382    // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
3383    // / `supervisor.rs:823` / `aplicacao.rs:1640`).
3384    if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
3385        return Err(AplicacaoError::EntradaHostInvalid {
3386            host: host.to_string(),
3387            reason: format!(
3388                "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
3389                 Hostname is a single-token DNS name — leading, trailing, \
3390                 or embedded whitespace breaks the K8s apiserver's Hostname \
3391                 regex at admission time; the paste-from-aligned-doc / \
3392                 paste-from-shell-history / paste-from-CSV footgun silently \
3393                 lands a multi-token blob in `:entrada :host`. Strip every \
3394                 whitespace byte and author the bare hostname — space \
3395                 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
3396                 refuse identically)"
3397            ),
3398        });
3399    }
3400    // Peer of the ASCII-whitespace scan above: route the non-ASCII
3401    // subset of Unicode `White_Space` through the shared
3402    // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
3403    // single source of truth every peer non-ASCII-whitespace scan in
3404    // caixa-core flows through: `limits::parse_byte_size` (`:limits
3405    // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
3406    // `limits::parse_millicores` (`:limits :cpu`),
3407    // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
3408    // and `supervisor::duration_codec::parse` (`:supervisor
3409    // :restart-window` / `:politicas :timeout` / `:politicas
3410    // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
3411    // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
3412    // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
3413    // paste-from-web-doc), or an EM-SPACE-split host
3414    // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
3415    // survived this predicate's ASCII byte-scan (none of the UTF-8
3416    // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
3417    // `u8::is_ascii_whitespace`), then landed on the per-label
3418    // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
3419    // predicate with the generic `label "…" must start and end with an
3420    // alphanumeric` diagnostic — a "far from source at build-time"
3421    // leak that names the label-shape violation but not the
3422    // paste-from-typography origin the author actually needs to fix.
3423    // Peer with the four codec sites the 1b75b38 landing pinned: the
3424    // typed slot's diagnostic axis names the offending codepoint
3425    // (`U+XXXX`) verbatim rather than laundering the value through a
3426    // downstream label-shape arm, so the author can grep their
3427    // caixa.lisp for the invisible codepoint at the surfaced position
3428    // rather than eyeball a multi-byte host for embedded NBSP / LINE
3429    // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
3430    // discipline the peer ASCII-whitespace arm (720ac3b) carries:
3431    // drift between any two typed-slot sites' non-ASCII-whitespace
3432    // rejection set becomes a single-edit fix at the shared predicate
3433    // rather than N independent inline scans diverging over time, and
3434    // a future stricter classification (BOM `\u{FEFF}` / ZWSP
3435    // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
3436    // `char::is_whitespace`" class the peer non-ASCII predicate's
3437    // doc-comment names as the follow-up trajectory) extends at the
3438    // shared predicate in one edit rather than seven.
3439    if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
3440        return Err(AplicacaoError::EntradaHostInvalid {
3441            host: host.to_string(),
3442            reason: format!(
3443                "contains non-ASCII Unicode whitespace character {ch:?} \
3444                 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
3445                 single-token DNS name limited to `[a-z0-9-]` labels; \
3446                 the paste-from-typography footgun silently lands an \
3447                 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
3448                 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
3449                 `U+3000`, and every other member of the Unicode \
3450                 `White_Space` property outside the ASCII byte range) \
3451                 in `:entrada :host`, which the K8s apiserver's \
3452                 Hostname regex refuses at admission time far from the \
3453                 caixa.lisp source line. Strip every non-ASCII \
3454                 whitespace character and author the bare hostname \
3455                 with only ASCII bytes (write \"checkout.quero.cloud\" \
3456                 verbatim)",
3457                codepoint = ch as u32,
3458            ),
3459        });
3460    }
3461
3462    // Strip the optional single leading wildcard label *before* the
3463    // trailing-dot check so the bare `"*."` form surfaces the more
3464    // self-locating "wildcard without domain" diagnostic instead of
3465    // the generic "trailing dot" one.
3466    let (had_wildcard, rest) = match host.strip_prefix("*.") {
3467        Some(r) => (true, r),
3468        None => (false, host),
3469    };
3470    if had_wildcard && rest.is_empty() {
3471        return Err(AplicacaoError::EntradaHostInvalid {
3472            host: host.to_string(),
3473            reason: "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)".to_string(),
3474        });
3475    }
3476    if rest.contains('*') {
3477        return Err(AplicacaoError::EntradaHostInvalid {
3478            host: host.to_string(),
3479            reason: "wildcard `*` is allowed only as the first label (`*.example.com`); \
3480                     no inner or trailing `*` labels"
3481                .to_string(),
3482        });
3483    }
3484    if rest.ends_with('.') {
3485        return Err(AplicacaoError::EntradaHostInvalid {
3486            host: host.to_string(),
3487            reason: "must not have a trailing `.` (Gateway API hostnames are not \
3488                     fully-qualified with a root dot; the apiserver regex rejects \
3489                     trailing dots)"
3490                .to_string(),
3491        });
3492    }
3493
3494    // Reject pure IPv4 literals: four dot-separated labels, every
3495    // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
3496    // literals as Hostnames.
3497    let labels: Vec<&str> = rest.split('.').collect();
3498    if labels.len() == 4
3499        && labels
3500            .iter()
3501            .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
3502    {
3503        return Err(AplicacaoError::EntradaHostInvalid {
3504            host: host.to_string(),
3505            reason: "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
3506                     literals; use a DNS name)"
3507                .to_string(),
3508        });
3509    }
3510
3511    // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
3512    // hyphen, with non-hyphen at both boundaries.
3513    for label in &labels {
3514        if label.is_empty() {
3515            return Err(AplicacaoError::EntradaHostInvalid {
3516                host: host.to_string(),
3517                reason: "has an empty label (consecutive `..` or a leading `.`)".to_string(),
3518            });
3519        }
3520        if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
3521            return Err(AplicacaoError::EntradaHostInvalid {
3522                host: host.to_string(),
3523                reason: format!(
3524                    "label {label:?} exceeds DNS-1123 label max length of \
3525                     {cap} bytes (got {} bytes)",
3526                    label.len(),
3527                    cap = crate::render::DNS_1123_LABEL_MAX_LEN,
3528                ),
3529            });
3530        }
3531        let bytes = label.as_bytes();
3532        if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
3533            return Err(AplicacaoError::EntradaHostInvalid {
3534                host: host.to_string(),
3535                reason: format!(
3536                    "label {label:?} must start and end with an alphanumeric \
3537                     (no leading or trailing `-`)"
3538                ),
3539            });
3540        }
3541        for &b in bytes {
3542            let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
3543            if !valid {
3544                let msg = if b.is_ascii_uppercase() {
3545                    format!(
3546                        "label {label:?} contains uppercase character {ch:?} \
3547                         (Gateway API hostnames are lowercase-only; use {lower:?})",
3548                        ch = b as char,
3549                        lower = label.to_ascii_lowercase()
3550                    )
3551                } else if b == b'_' {
3552                    format!(
3553                        "label {label:?} contains `_` (Gateway API hostnames \
3554                         allow only `[a-z0-9-]`; use `-` instead)"
3555                    )
3556                } else {
3557                    format!(
3558                        "label {label:?} contains invalid character {ch:?} \
3559                         (Gateway API hostnames allow only `[a-z0-9-]`)",
3560                        ch = b as char
3561                    )
3562                };
3563                return Err(AplicacaoError::EntradaHostInvalid {
3564                    host: host.to_string(),
3565                    reason: msg,
3566                });
3567            }
3568        }
3569    }
3570    Ok(())
3571}
3572
3573/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
3574/// would refuse at admission time. Thin wrapper around
3575/// [`crate::render::is_gateway_api_http_path`] that maps the shared
3576/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
3577/// variant, preserving the more self-locating
3578/// [`AplicacaoError::EntradaPathEmpty`] /
3579/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
3580/// path fails those narrower invariants first.
3581///
3582/// The contract is the canonical HTTP-path grammar — `1..=
3583/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
3584/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
3585/// whitespace/control/non-ASCII bytes — shared with the
3586/// `:contratos :endpoint` axis through the lifted predicate so drift
3587/// between either landing site and the K8s apiserver-side
3588/// HTTPPathMatch.value OpenAPI schema is a build error visible at
3589/// the predicate, not a per-renderer "this passed validate but failed
3590/// admission" surprise. The diagnostic carries the offending `path:`
3591/// verbatim plus a parser-shaped `reason:` naming the specific
3592/// violation, so the author can grep their caixa.lisp for `:paths`
3593/// and fix it in one edit. Same diagnostic shape as
3594/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
3595/// axis.
3596fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
3597    // Empty and missing-leading-`/` are already gated at the call
3598    // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
3599    // checking here keeps the per-axis narrower diagnostics in force
3600    // when the predicate is reached directly (and `is_gateway_api_http_path`
3601    // itself defends against `bytes[0]`-style indexing on empty
3602    // input).
3603    if path.is_empty() {
3604        return Err(AplicacaoError::EntradaPathEmpty);
3605    }
3606    if !path.starts_with('/') {
3607        return Err(AplicacaoError::EntradaPathNotAbsolute {
3608            path: path.to_string(),
3609        });
3610    }
3611    crate::render::is_gateway_api_http_path(path).map_err(|reason| {
3612        AplicacaoError::EntradaPathInvalid {
3613            path: path.to_string(),
3614            reason,
3615        }
3616    })
3617}
3618
3619mod rate_limit_codec {
3620    // `Duration` is no longer named here — the codec routes through
3621    // the module-scope [`super::rate_limit_window_from_unit`] /
3622    // [`super::rate_limit_window_unit`] projections that carry the
3623    // canonical typed `Duration` unit-table axis on their signatures.
3624    use super::RateLimit;
3625    use serde::{Deserialize, Deserializer, Serializer};
3626
3627    pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
3628        match v {
3629            Some(rl) => s.serialize_str(&render(*rl)),
3630            None => s.serialize_none(),
3631        }
3632    }
3633
3634    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
3635        let opt: Option<String> = Option::deserialize(d)?;
3636        match opt {
3637            None => Ok(None),
3638            Some(s) => parse(&s).map(Some).map_err(serde::de::Error::custom),
3639        }
3640    }
3641
3642    fn parse(s: &str) -> Result<RateLimit, String> {
3643        // Whitespace-rejection arm — peer with the leading-`+`
3644        // (`"+100/s"`) and leading-zero (`"0100/s"`) arms below on the
3645        // same canonical-form render-determinism axis. Until this gate
3646        // landed the parser silently tolerated leading / trailing /
3647        // internal whitespace via the top-level `s.trim()` and the
3648        // per-part `rate_str.trim()` / `unit.trim()` calls, so every
3649        // whitespace-carrying shape (`" 100/s"`, `"100/s "`,
3650        // `"100 /s"`, `"100/ s"`, `"100 / s"`, `"100/s\n"`,
3651        // `"\t100/s"`) parsed to the same `RateLimit { 100, 1s }` and
3652        // serde silently round-tripped to `"100/s"` on the next emit
3653        // (a *different* canonical string) — breaking the THEORY.md
3654        // Part V render-determinism contract on the same
3655        // canonical-form-drift axis the leading-`+` arm below (the
3656        // 4eeae98 predecessor) and the leading-zero arm below (the
3657        // 4f46830 predecessor) already close.
3658        //
3659        // The canonical author shape is `<integer>/<s|m|h>` with no
3660        // whitespace bytes anywhere — every string [`render`] emits
3661        // carries none, so the parser's accepted set must match for
3662        // serialize / deserialize to round-trip losslessly. This gate
3663        // makes the pre-existing `s.trim()` / `rate_str.trim()` /
3664        // `unit.trim()` calls below strict no-ops on the accepted set
3665        // (every byte-position match they would perform is now already
3666        // trimmed away by the accepted set itself), while the arm
3667        // surfaces every rejected whitespace-carrying shape with a
3668        // self-locating diagnostic naming the offending byte and the
3669        // canonical form the author intended, peer with every prior
3670        // canonical-form-drift arm on this codec.
3671        //
3672        // Routed through the lifted
3673        // [`crate::render::find_ascii_whitespace_byte`] predicate — the
3674        // same source of truth the four peer typed-magnitude codec
3675        // sites (`limits::parse_byte_size`, `limits::parse_duration`,
3676        // `limits::parse_millicores`, `supervisor::duration_codec`)
3677        // share. `u8::is_ascii_whitespace()` at the predicate covers
3678        // the five WhatWG-conformant ASCII whitespace bytes (space,
3679        // tab, LF, FF, CR); the "single lifted predicate" discipline
3680        // the peer non-ASCII arm below carries on the strictly-
3681        // complementary Unicode `White_Space` class extends here to
3682        // the ASCII byte set as well.
3683        if let Some(b) = crate::render::find_ascii_whitespace_byte(s) {
3684            return Err(format!(
3685                "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
3686                 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
3687                 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
3688                 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
3689                 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
3690                 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
3691                 on first serialize — breaking the THEORY.md Part V render-determinism \
3692                 contract every typed slot carries. Strip every whitespace byte (write \
3693                 `\"100/s\"` verbatim)"
3694            ));
3695        }
3696        // Non-ASCII Unicode `White_Space` arm — the strictly-
3697        // complementary class the ASCII arm above cannot see.
3698        // `str::trim` at the top of every peer codec uses
3699        // `char::is_whitespace` (Unicode `White_Space`, strictly
3700        // wider than the ASCII byte set), so an NBSP (`\u{00A0}`) /
3701        // LINE SEPARATOR (`\u{2028}`) / EM-SPACE (`\u{2003}`)
3702        // survives the byte-scan (its UTF-8 bytes are not in
3703        // `is_ascii_whitespace`), gets silently stripped by the
3704        // top-level `s.trim()` below, and the value round-trips
3705        // through `render` to a *different* canonical form
3706        // (`\"100/s\"`) on next emit — breaking the THEORY.md Part V
3707        // render-determinism contract every typed slot carries.
3708        // Closed here (`:politicas :rate-limit`) and at the three
3709        // peer codec sites (`limits::parse_byte_size`,
3710        // `limits::parse_duration`, `supervisor::duration_codec`)
3711        // through the shared
3712        // [`crate::render::find_non_ascii_whitespace_char`] predicate
3713        // — the "single lifted predicate across all four codec sites
3714        // in one follow-up run" the 24a8ad4 commit body's `Forward
3715        // compounding` bullet named as the next compounding step.
3716        if let Some(ch) = crate::render::find_non_ascii_whitespace_char(s) {
3717            return Err(format!(
3718                "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
3719                 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
3720                 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
3721                 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
3722                 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
3723                 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
3724                 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
3725                 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
3726                 silently strips it at parse entry, and the value round-trips through \
3727                 `render` to a *different* canonical form (`\"100/s\"`) on first \
3728                 serialize — breaking the THEORY.md Part V render-determinism contract \
3729                 every typed slot carries. Strip every non-ASCII whitespace character \
3730                 (write `\"100/s\"` verbatim with only ASCII bytes)",
3731                cp = ch as u32
3732            ));
3733        }
3734        let s = s.trim();
3735        let (rate_str, unit) = s
3736            .split_once('/')
3737            .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
3738        let rate_trim = rate_str.trim();
3739        // The canonical authoring form for `:politicas :rate-limit` is
3740        // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
3741        // non-negative integer with no decimal point and no leading
3742        // sign, so the parser's accepted set must match for
3743        // serialize/deserialize to round-trip without canonical-form
3744        // drift. Until this gate landed the parser accepted any
3745        // `u32::from_str`-shaped magnitude — and current Rust
3746        // `u32::from_str` permissively accepts a leading `+` (`"+100"`
3747        // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
3748        // serde silently round-tripped to `"100/s"` on the next emit
3749        // (a *different* canonical string) — breaking the THEORY.md
3750        // Part V render-determinism contract on the fifth typed-codec
3751        // surface in caixa-core (peer with the four duration codecs the
3752        // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
3753        // already covered: `supervisor::duration_codec` backing three
3754        // typed-duration slots, `limits::parse_duration` backing
3755        // `:limits :wall-clock`, `limits::parse_byte_size` backing
3756        // `:limits :memory`). The fractional / decimal-shaped sibling
3757        // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
3758        // existing rejection arm, but the diagnostic is value-laundered
3759        // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
3760        // doesn't name the canonical-form remediation or the round-trip
3761        // drift the next emit would produce); this gate lifts the
3762        // fractional arm onto the same canonical-form diagnostic the
3763        // peer codecs carry.
3764        //
3765        // Strict canonical form: every byte of the magnitude is an
3766        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
3767        // inputs the gate distinguishes "non-canonical-but-numeric"
3768        // (parses as f64 or i64 — surfaced with a self-locating
3769        // diagnostic naming the canonical authoring form and the
3770        // round-trip drift the rejected shape would produce on first
3771        // serialize) from "garbage" (parses as neither — surfaced with
3772        // the existing narrower `"not a u32"` wording so its
3773        // diagnostic shape remains stable for the parser-shape footgun
3774        // case).
3775        //
3776        // Routed through the lifted
3777        // [`crate::render::is_digit_only_magnitude`] predicate — the
3778        // same source of truth the four peer typed-magnitude codec
3779        // sites share.
3780        let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
3781        if !digit_only {
3782            let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
3783            if numeric {
3784                return Err(format!(
3785                    "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
3786                     canonical authoring form for `:politicas :rate-limit` is \
3787                     `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
3788                     with no decimal point and no leading `+` / `-` sign. A fractional / \
3789                     signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
3790                     through `render` to a *different* canonical form (`\"1/s\"`, \
3791                     `\"100/s\"`, parser-reject) on first serialize — breaking the \
3792                     THEORY.md Part V render-determinism contract every typed slot \
3793                     carries. Pick an integer rate that fits the desired window \
3794                     (write `\"6000/m\"` instead of `\"1.66/s\"`)"
3795                ));
3796            }
3797            return Err(format!("rate-limit rate {rate_str:?} not a u32"));
3798        }
3799        // Leading-zero arm — peer with the prior `"+100/s"` arm above
3800        // (4eeae98's predecessor) on the same canonical-form
3801        // render-determinism axis. The digit-only gate accepts
3802        // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
3803        // them losslessly (= 100, 0, 7), but `render` emits the
3804        // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
3805        // a *different* canonical string on the next emit, breaking
3806        // the THEORY.md Part V render-determinism contract the same
3807        // way `"+100/s"` did before the leading-`+` arm landed. The
3808        // single-byte magnitude `"0"` itself round-trips losslessly
3809        // through `render` (`render(0)` emits `"0/s"`) — the
3810        // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
3811        // what refuses rate-zero authoring, so `"0/s"` stays in the
3812        // accepted set at this codec layer and the diagnostic
3813        // partitioning between canonical-form drift (this arm) and
3814        // semantic-zero (the downstream gate) remains stable.
3815        // Peer with the future leading-zero arms on the three peer
3816        // typed-magnitude codecs the trajectory acknowledges:
3817        // `supervisor::duration_codec`, `limits::parse_duration`,
3818        // `limits::parse_byte_size` — each carries the same
3819        // canonical-form-drift class today; this gate lands the
3820        // discipline on the fourth typed-magnitude codec in
3821        // caixa-core first because the peer `"+100/s"` arm above is
3822        // the closest predecessor on the trajectory.
3823        //
3824        // Routed through the lifted
3825        // [`crate::render::is_leading_zero_padded_magnitude`]
3826        // predicate — the same source of truth the four peer
3827        // typed-magnitude codec sites share.
3828        if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
3829            return Err(format!(
3830                "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
3831                 canonical authoring form for `:politicas :rate-limit` is \
3832                 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
3833                 with no leading-zero padding on the magnitude. A leading-zero magnitude \
3834                 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
3835                 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
3836                 first serialize — breaking the THEORY.md Part V render-determinism \
3837                 contract every typed slot carries. Strip the leading zeros (write \
3838                 `\"100/s\"` instead of `\"0100/s\"`)"
3839            ));
3840        }
3841        // The digit-only gate guarantees every byte is `[0-9]`, and
3842        // the leading-zero arm above guarantees the magnitude is
3843        // either the single byte `"0"` or starts with `[1-9]`, so
3844        // the only way `u32::from_str` can fail here is overflow
3845        // (the magnitude exceeds `u32::MAX`). Surface that with an
3846        // overflow-shaped wording so the diagnostic names the
3847        // offending magnitude verbatim rather than collapsing onto
3848        // the non-canonical arm. Same shape
3849        // `supervisor::duration_codec` (1c55a2a) carries on the peer
3850        // duration-codec axis.
3851        let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
3852            format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
3853        })?;
3854        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
3855        // module scope as the lifted [`super::RATE_LIMIT_UNIT_TABLE`]
3856        // const; this parse arm now consumes only the `unit → Duration`
3857        // projection [`super::rate_limit_window_from_unit`], so a future
3858        // rate-limit-unit addition (a `"d"` day suffix once Envoy's
3859        // `rate_limit_action` grows daily-bucket support) is one row
3860        // appended to the table — parse, render, and
3861        // `is_canonical_rate_limit_window` all pick it up by construction.
3862        let unit = unit.trim();
3863        let window = super::rate_limit_window_from_unit(unit)
3864            .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
3865        Ok(RateLimit { rate, window })
3866    }
3867
3868    fn render(rl: RateLimit) -> String {
3869        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
3870        // module scope as the lifted [`super::RATE_LIMIT_UNIT_TABLE`]
3871        // const; this render arm now consumes only the `Duration → unit`
3872        // projection [`super::rate_limit_window_unit`], which returns
3873        // `None` on every non-canonical window (the sub-second /
3874        // non-`{1, 60, 3600}` shapes the validate gate rejects). Same
3875        // helper the sibling [`super::is_canonical_rate_limit_window`]
3876        // predicate reads — so a future rate-limit-unit addition
3877        // (a `"d"` day suffix once Envoy's `rate_limit_action` grows
3878        // daily-bucket support) is one row appended to the table and
3879        // both consumers pick it up by construction.
3880        if let Some(unit) = super::rate_limit_window_unit(rl.window()) {
3881            format!("{}/{unit}", rl.rate())
3882        } else {
3883            // Defensive fallback for non-canonical windows. Note:
3884            // [`AplicacaoSpec::validate_politicas`] rejects any
3885            // non-canonical `:rate-limit :window` via
3886            // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
3887            // a validated `RateLimit` never reaches this branch. The
3888            // emitted `<n>/<k>s` form is *not* round-trippable through
3889            // [`parse`] (which accepts only the [`super::RATE_LIMIT_UNIT_TABLE`]
3890            // suffixes, not `<k>s` with an explicit count) — the
3891            // validate gate is what makes the round-trip a structural
3892            // property; this branch exists only so a programmatic
3893            // non-validated serialize doesn't panic.
3894            format!("{}/{}s", rl.rate(), rl.window().as_secs())
3895        }
3896    }
3897}
3898
3899// ── placement strategy ───────────────────────────────────────────────
3900
3901/// How the Aplicacao distributes across clusters. Three options:
3902///
3903/// - `SingleNode` — one cluster runs the app at a time; takeover on
3904///   death (Erlang/OTP distributed-app semantics).
3905/// - `Replicated` — every named cluster runs an instance (active-active).
3906/// - `Sharded` — entities distribute by hash key across clusters
3907///   (Akka cluster sharding).
3908#[derive(
3909    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
3910)]
3911pub enum PlacementStrategy {
3912    SingleNode,
3913    Replicated,
3914    Sharded,
3915}
3916
3917impl Default for PlacementStrategy {
3918    fn default() -> Self {
3919        Self::Replicated
3920    }
3921}
3922
3923impl PlacementStrategy {
3924    /// Canonical camelCase-schema discriminator scalar this variant
3925    /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
3926    /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
3927    /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
3928    /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
3929    /// every substrate consumer that dispatches on the strategy (the
3930    /// `lareira-fleet-programs` aggregator, the future `app-operator`
3931    /// reconciler, the M3 Adaptive compression pass) reads the same
3932    /// byte-string the `Serialize` derive emits — the pin test in
3933    /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
3934    /// asserts the two paths agree.
3935    #[must_use]
3936    pub const fn as_str(self) -> &'static str {
3937        match self {
3938            Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
3939            Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
3940            Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
3941        }
3942    }
3943}
3944
3945/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
3946/// the pretty-printed byte-string every consumer that formats the strategy
3947/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
3948/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
3949/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
3950/// per-Aplicacao strategy line, the future M4 CR materializer's per-
3951/// admission-webhook rejection body) reaches for the same lifted
3952/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
3953/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
3954/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
3955/// `Serialize` derive already emits under
3956/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
3957/// [`PlacementStrategy::as_str`] helper already returns.
3958///
3959/// Until this lift landed the sibling OTP-shape typed enums —
3960/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
3961/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
3962/// so [`std::fmt::Display`] routes through the same discriminant string
3963/// the wire format emits) — carried a stable [`std::fmt::Display`]
3964/// surface but [`PlacementStrategy`] did not; every consumer reaching
3965/// for a strategy byte-string past the wire format had to pick between
3966/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
3967/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
3968/// derive), any two of which a future variant rename or
3969/// `#[serde(rename_all = "kebab-case")]` attribute would silently
3970/// desynchronize — with the failure surfacing as a downstream renderer /
3971/// operator's per-strategy dispatch reading one spelling while the wire
3972/// format emitted another, far from the source rebrand commit and with
3973/// no field naming the drift. Routing `Display` through
3974/// [`PlacementStrategy::as_str`] makes the three paths
3975/// (`Debug` for structural inspection, `Display` for user-facing text,
3976/// `Serialize` for the wire format) converge on the same lifted
3977/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
3978/// the diagnostic byte-string, and the pretty-printed byte-string move
3979/// as a single unit through one canonical declaration each, by
3980/// construction. Same trajectory as [`PlacementStrategy::as_str`]
3981/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
3982/// closes the third path.
3983///
3984/// Pin tests
3985/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
3986/// and
3987/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
3988/// assert the three paths agree byte-for-byte on every variant, so a
3989/// future variant rename or per-arm serde attribute drift is a build
3990/// error visible at caixa-core test time, not a silent per-consumer
3991/// dispatch miss at apply / reconcile time.
3992impl std::fmt::Display for PlacementStrategy {
3993    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3994        f.write_str(self.as_str())
3995    }
3996}
3997
3998/// Where the Aplicacao runs.
3999#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
4000#[serde(rename_all = "camelCase")]
4001pub struct Placement {
4002    /// Distribution strategy.
4003    #[serde(default)]
4004    pub estrategia: PlacementStrategy,
4005
4006    /// Named clusters that host this Aplicacao. Required for
4007    /// `Replicated` and `SingleNode`; for `Sharded` declares the
4008    /// shard pool.
4009    #[serde(default)]
4010    pub clusters: Vec<String>,
4011
4012    /// Optional hint to the placement engine: `"data-locality"`,
4013    /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
4014    #[serde(default, skip_serializing_if = "Option::is_none")]
4015    pub affinity: Option<String>,
4016
4017    /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
4018    #[serde(default, skip_serializing_if = "Option::is_none")]
4019    pub shard_key: Option<String>,
4020}
4021
4022impl Placement {
4023    /// Substrate-canonical per-`:placement` Akka-cluster-sharding
4024    /// `:shard-key` extractor-expression scalar accessor every consumer
4025    /// of the Aplicacao's hash-keyed distribution routing keys off —
4026    /// returns the author-declared `:placement :shard-key` byte-string
4027    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
4028    /// own `Option<String>` storage; `None` when the slot is absent
4029    /// (the canonical shape under `:estrategia Replicated` /
4030    /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
4031    /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
4032    /// partition — `validate` refuses any `Placement` past this call
4033    /// that lands `Some` on a non-`Sharded` strategy or `None` on
4034    /// `Sharded`).
4035    ///
4036    /// The `:placement :shard-key` slot carries the Akka-style
4037    /// cluster-sharding entity-id extractor expression
4038    /// (MESH-COMPOSITION §II.4) — validated by
4039    /// [`validate_placement_shard_key`] to be a non-empty printable-
4040    /// ASCII single-token reference (`tenantId`, `$tenantId`,
4041    /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
4042    /// future M4 Akka-style cluster-sharding reconciler hashes without
4043    /// re-validating at the runtime layer), and every downstream
4044    /// consumer that reads the key keys off this scalar (the
4045    /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
4046    /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
4047    /// declared-but-inert refusal diagnostic, the caixa-mesh
4048    /// per-Aplicacao `placement.shardKey` emit path the substrate
4049    /// operator's per-entity hash-routing reader consumes, the future
4050    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4051    /// per-shard-key resolver).
4052    ///
4053    /// Prior to this lift the `.shard_key` field was accessed inline at
4054    /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
4055    /// `Sharded` arm's `match &self.placement.shard_key { None => …,
4056    /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
4057    /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
4058    /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
4059    /// — two open-coded field-accesses that expressed no compile-time
4060    /// link back to the typed slot. A future extension of the
4061    /// `:placement :shard-key` axis to a richer author surface — a
4062    /// per-cluster override the operator pins through a future
4063    /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
4064    /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
4065    /// alias table the M4 CR materializer resolves per-CR, a
4066    /// per-Aplicacao dynamic `:shard-key` derivation the future
4067    /// adaptive placement engine computes from `:affinity` weights —
4068    /// would have had to be threaded through both open-coded copies in
4069    /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
4070    /// arm refusal would silently disagree on which extractor
4071    /// expression a given Placement resolves to. Lifting the resolution
4072    /// rule to a typed method on the substrate primitive means every
4073    /// downstream consumer of the Aplicacao's per-`:placement`
4074    /// hash-key surface reaches for exactly one typed dispatch — the
4075    /// resolver's accept-set migrates as a unit on any future axis
4076    /// addition.
4077    ///
4078    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
4079    /// [`WitContract::destination`] / [`WitContract::world_ref`]
4080    /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
4081    /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
4082    /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
4083    /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
4084    /// typed dispatch on the substrate primitive, thin projections at
4085    /// each consumer" discipline extended onto the per-`:placement`
4086    /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
4087    /// First `Option<&str>`-return accessor on the M3 mesh-slot family
4088    /// — opens the "optional per-slot scalar" projection pattern the
4089    /// sibling per-`:placement` `:affinity`, per-`:politicas`
4090    /// `:rate-limit` future lifts fold on. Named `shard_key()` to
4091    /// match the storage field's name; the accessor's identity name
4092    /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
4093    /// slot's docstring already carries.
4094    #[must_use]
4095    pub fn shard_key(&self) -> Option<&str> {
4096        self.shard_key.as_deref()
4097    }
4098
4099    /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
4100    /// compression-hint scalar accessor every weighting-consumer of the
4101    /// Aplicacao's per-hint routing surface keys off — returns the
4102    /// author-declared `:placement :affinity` byte-string verbatim as
4103    /// an `Option<&str>`, borrowed from the typed slot's own
4104    /// `Option<String>` storage; `None` when the slot is absent (the
4105    /// canonical shape of an Aplicacao that leaves the compression
4106    /// weighting up to the placement engine's cluster-default arm — no
4107    /// author-authored `data-locality` / `low-latency` / etc. hint
4108    /// biases the routing).
4109    ///
4110    /// The `:placement :affinity` slot carries the M3 Adaptive-
4111    /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
4112    /// by [`validate_placement_affinity`] to be a DNS-1123 label
4113    /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
4114    /// K8s-conformant label-selector shape every apiserver-side pod-
4115    /// affinity / node-affinity materializer already gates on
4116    /// admission), and every downstream consumer that reads the hint
4117    /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
4118    /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
4119    /// `placement.affinity` overlay emit path the substrate operator's
4120    /// per-hint weighting-consumer reads, the future M4
4121    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
4122    /// pod-affinity / node-affinity selector resolver).
4123    ///
4124    /// Prior to this lift the `.affinity` field was accessed inline at
4125    /// the sole caixa-core site — the
4126    /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
4127    /// `if let Some(a) = &self.placement.affinity { …
4128    /// validate_placement_affinity(a)? … }` cascade — one open-coded
4129    /// field-access that expressed no compile-time link back to the
4130    /// typed slot. A future extension of the `:placement :affinity`
4131    /// axis to a richer author surface — a per-cluster override the
4132    /// operator pins through a future `:placement :affinity-overrides`
4133    /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
4134    /// tenant hint alias table the M4 CR materializer resolves per-CR,
4135    /// a per-Aplicacao dynamic `:affinity` derivation the future
4136    /// adaptive placement engine computes from `:clusters` topology —
4137    /// would have had to be threaded through the open-coded copy in
4138    /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
4139    /// materializer reader that landed on the axis, or the per-hint
4140    /// value-shape gate and its downstream weighting consumers would
4141    /// silently disagree on which hint a given Placement resolves to.
4142    /// Lifting the resolution rule to a typed method on the substrate
4143    /// primitive means every downstream consumer of the Aplicacao's
4144    /// per-`:placement` compression-hint surface reaches for exactly
4145    /// one typed dispatch — the resolver's accept-set migrates as a
4146    /// unit on any future axis addition.
4147    ///
4148    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
4149    /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
4150    /// optional-scalar axis — same "one typed dispatch on the substrate
4151    /// primitive, thin projections at each consumer" discipline extended
4152    /// onto the per-`:placement` M3-Adaptive-compression-hint
4153    /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
4154    /// return accessor on the M3 mesh-slot family; closes the last
4155    /// un-lifted per-`:placement` `Option<String>` axis. Named
4156    /// `affinity()` to match the storage field's name; the accessor's
4157    /// identity name maps onto the canonical MESH-COMPOSITION §II.4
4158    /// vocabulary the slot's docstring already carries.
4159    #[must_use]
4160    pub fn affinity(&self) -> Option<&str> {
4161        self.affinity.as_deref()
4162    }
4163
4164    /// Substrate-canonical per-`:placement` `:estrategia` distribution-
4165    /// strategy scalar accessor every consumer that dispatches on the
4166    /// Aplicacao's per-cluster distribution shape keys off — returns the
4167    /// author-declared `:placement :estrategia` variant verbatim as a
4168    /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
4169    /// `PlacementStrategy` storage.
4170    ///
4171    /// The `:placement :estrategia` slot carries the closed-set
4172    /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
4173    /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
4174    /// `Replicated` — active-active across every named cluster; `Sharded`
4175    /// — Akka-style hash-keyed entity distribution across the cluster pool
4176    /// per §II.4) that every downstream consumer of the Aplicacao's
4177    /// per-cluster fan-out shape keys off. Validated by
4178    /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
4179    /// the sibling `:shard-key` axis (`shard_key.is_some() ==
4180    /// matches!(estrategia, Sharded)` — the cross-slot partition the
4181    /// [`Placement::shard_key`] accessor's docstring pins), and every
4182    /// downstream consumer that reads the strategy keys off this scalar
4183    /// (the [`AplicacaoSpec::validate_placement`]
4184    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
4185    /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
4186    /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
4187    /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
4188    /// declared-but-inert refusal's
4189    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
4190    /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
4191    /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
4192    /// emit path the substrate operator's per-strategy fan-out reader
4193    /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4194    /// materializer's per-strategy admission-webhook resolver).
4195    ///
4196    /// Prior to this lift the `.estrategia` field was accessed inline at
4197    /// four sites — the [`AplicacaoSpec::validate_placement`]
4198    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
4199    /// `estrategia: self.placement.estrategia`, the same method's
4200    /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
4201    /// partition dispatch, the non-`Sharded`-arm
4202    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
4203    /// `estrategia: self.placement.estrategia`, and the `feira app graph`
4204    /// per-Aplicacao strategy print line at
4205    /// `println!("… {} …", spec.placement.estrategia, …)`
4206    /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
4207    /// expressed no compile-time link back to the typed slot. A future
4208    /// extension of the `:placement :estrategia` axis to a richer author
4209    /// surface (a per-cluster override the operator pins through a future
4210    /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
4211    /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
4212    /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
4213    /// derivation the future adaptive placement engine computes from
4214    /// `:affinity` + `:clusters` topology) would have had to be threaded
4215    /// through every open-coded copy in lockstep — one consumer reading
4216    /// the raw variant while a peer read the operator-resolved variant
4217    /// would silently split the `PlacementWithoutClusters` /
4218    /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
4219    /// partition-dispatch input, a two-consumer split at the validator
4220    /// far from the source `caixa.lisp` with no field naming the
4221    /// strategy-drift root cause. Lifting the resolution rule to a typed
4222    /// method on the substrate primitive means every downstream consumer
4223    /// of the Aplicacao's per-`:placement` distribution-strategy surface
4224    /// reaches for exactly one typed dispatch — the resolver's accept-set
4225    /// migrates as a unit on any future axis addition.
4226    ///
4227    /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
4228    /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
4229    /// same "one typed dispatch on the substrate primitive, thin
4230    /// projections at each consumer" discipline extended onto the
4231    /// per-`:placement` distribution-strategy `Copy`-composite-enum
4232    /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
4233    /// family; first `Copy`-return accessor on the M3 mesh-slot
4234    /// `Placement` type — companion to the sibling per-`:placement`
4235    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
4236    /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
4237    /// optional-scalar axes, closing the last unlifted per-`:placement`
4238    /// scalar-value axis (the closed-set `PlacementStrategy`
4239    /// distribution-strategy discriminator) so every downstream
4240    /// per-`:placement` reader now routes through a typed dispatch on
4241    /// the substrate primitive. Named `estrategia()` to match the storage
4242    /// field's name; the accessor's identity name maps onto the
4243    /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
4244    /// already carries.
4245    #[must_use]
4246    pub fn estrategia(&self) -> PlacementStrategy {
4247        self.estrategia
4248    }
4249
4250    /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
4251    /// per-cluster distribution-target slice accessor every consumer that
4252    /// walks the Aplicacao's declared cluster-pool keys off — returns the
4253    /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
4254    /// `&[String]` slice-view, borrowed from the typed slot's own
4255    /// `Vec<String>` storage (a zero-copy slice-view over the same
4256    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
4257    /// through). Non-optional: the empty slice is the load-bearing
4258    /// pre-validation sentinel every downstream consumer of the paired
4259    /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
4260    /// off — every strategy in the closed
4261    /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
4262    /// requires a non-empty list (`SingleNode` / `Replicated` use the
4263    /// list as hosting / takeover candidates per Erlang/OTP distributed-
4264    /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
4265    /// shard pool per Akka cluster-sharding convention, §II.4), so the
4266    /// `.is_empty()` probe is the shared pre-condition every
4267    /// [`AplicacaoSpec::validate_placement`] arm heads on.
4268    ///
4269    /// The `:placement :clusters` slot carries the K8s-conformant DNS-
4270    /// 1123-label per-cluster distribution-target list — the same
4271    /// set-not-multiset shape the sibling `:membros :caixa` /
4272    /// `:children :caixa` axes carry (`validate_placement`'s per-entry
4273    /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
4274    /// pins the shape). Every downstream consumer that fans on the list
4275    /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
4276    /// pre-flight `.is_empty()` probe that trips
4277    /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
4278    /// per-cluster value-shape + duplicate-detection fan-out loop, the
4279    /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
4280    /// that materializes the list verbatim onto every
4281    /// programs.yaml entry the substrate operator's per-cluster
4282    /// `placement.clusters | contains .Values.cluster` filter reads,
4283    /// the `feira app graph` per-Aplicacao cluster print line, the
4284    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4285    /// per-cluster admission-webhook fan-out, the future M5 adaptive-
4286    /// placement engine's cluster-topology reader).
4287    ///
4288    /// Prior to this lift the `.clusters` `Vec<String>` was accessed
4289    /// inline at three production sites — the
4290    /// [`AplicacaoSpec::validate_placement`] pre-flight
4291    /// `self.placement.clusters.is_empty()` refusal probe, the same
4292    /// method's per-cluster validate loop's
4293    /// `for c in &self.placement.clusters` traversal head, and the
4294    /// `feira app graph` per-Aplicacao print line's
4295    /// `spec.placement.clusters` `{:?}` formatter argument
4296    /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
4297    /// that expressed no compile-time link back to the typed slot. A
4298    /// future extension of the `:placement :clusters` axis to a richer
4299    /// author surface (a per-tenant cluster-pool overlay the operator
4300    /// pins through a future `:placement :clusters-overrides` slot the
4301    /// MESH-COMPOSITION §V cross-cluster-federation roadmap
4302    /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
4303    /// the future M5 adaptive-placement engine computes from
4304    /// `:affinity` weights + live cluster-topology probes, a promotion
4305    /// of the plain `Vec<String>` to a richer `{static, dynamic}`
4306    /// partition once the substrate operator's cluster-membership
4307    /// reconciler comes into typed scope) would have had to be threaded
4308    /// through all three open-coded copies in lockstep or one consumer
4309    /// would silently disagree with the peers on which cluster-pool a
4310    /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
4311    /// reading the raw slot while the peer per-cluster validate loop
4312    /// read an operator-resolved slot would silently split the paired
4313    /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
4314    /// `PlacementClusterDuplicate` refusal cascade's actual traversal
4315    /// input from the pre-flight input, a three-consumer split at the
4316    /// validator and formatter far from the source `caixa.lisp` with
4317    /// no field naming the cluster-pool-drift root cause. Lifting the
4318    /// resolution rule to a typed method on the substrate primitive
4319    /// means every downstream consumer of the Aplicacao's
4320    /// per-`:placement` cluster-pool surface reaches for exactly one
4321    /// typed dispatch — the resolver's accept-set migrates as a unit
4322    /// on any future axis addition.
4323    ///
4324    /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
4325    /// slot — sibling to the seed M2
4326    /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
4327    /// slice-return accessor on the peer per-`:supervisor` static-
4328    /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
4329    /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
4330    /// primitive, thin projections at each consumer" discipline. The
4331    /// three peer `Vec`-carry axes still unlifted at the time of this
4332    /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
4333    /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
4334    /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
4335    /// [`crate::UpgradeFromEntry::instructions`]
4336    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
4337    /// — inherit this accessor's discipline as future compounding runs
4338    /// migrate their consumers onto the shared slice-return shape.
4339    /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
4340    /// type, sibling to the two `Option<&str>`-return
4341    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
4342    /// (74ec2d3) accessors and the `Copy`-return
4343    /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
4344    /// unlifted per-`:placement` field axis (the `Vec<String>`
4345    /// distribution-target-list carrier) so every downstream
4346    /// per-`:placement` reader now routes through a typed dispatch on
4347    /// the substrate primitive. Named `clusters()` to match the storage
4348    /// field's name verbatim and the tatara-lisp author-surface term
4349    /// (`:clusters`) the field's own docstring already carries; the
4350    /// accessor's identity maps onto the canonical MESH-COMPOSITION
4351    /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
4352    /// for. Returns `&[String]` (not `&Vec<String>`) because every
4353    /// downstream consumer of the cluster list treats it as a read-only
4354    /// sequence — the slice-view is the narrowest borrow that supports
4355    /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
4356    /// `.len()`) without leaking the backing `Vec`'s
4357    /// grow/push/reserve surface that no consumer of the typed view
4358    /// reaches for (the storage-side `Vec` remains reachable through
4359    /// the `pub clusters` field for the mutation-carrying serde
4360    /// round-trip and per-test fixture-mutation paths).
4361    #[must_use]
4362    pub fn clusters(&self) -> &[String] {
4363        self.clusters.as_slice()
4364    }
4365}
4366
4367impl Default for Placement {
4368    fn default() -> Self {
4369        Self {
4370            estrategia: PlacementStrategy::default(),
4371            clusters: Vec::new(),
4372            affinity: None,
4373            shard_key: None,
4374        }
4375    }
4376}
4377
4378// ── external entry point ─────────────────────────────────────────────
4379
4380/// External entry point — what an outside caller sees. Renders to a
4381/// Gateway / Ingress + a route to the named member Servico.
4382#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
4383#[serde(rename_all = "camelCase")]
4384pub struct Entrada {
4385    /// Public hostname (e.g. `"checkout.quero.cloud"`).
4386    pub host: String,
4387
4388    /// Member Servico the gateway routes to. Must be in `:membros`.
4389    pub para: String,
4390
4391    /// Optional path filter — if set, only matching paths route to
4392    /// this Aplicacao (the rest fall through to other route rules).
4393    #[serde(default)]
4394    pub paths: Vec<String>,
4395
4396    /// Default port on the destination Servico (the trigger.service.port).
4397    #[serde(default = "default_port")]
4398    pub port: u16,
4399}
4400
4401impl Entrada {
4402    /// Substrate-canonical per-`:entrada` URL-path fallback resolver
4403    /// every HTTPRoute-aware renderer keys off — returns the author-
4404    /// declared `:entrada :paths` list verbatim when non-empty, and the
4405    /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
4406    /// all fallback otherwise (so an Aplicacao author who declares an
4407    /// external `:entrada` block but no per-path rule surface still
4408    /// gets a route whose sole `HTTPPathMatch` matches every incoming
4409    /// request under the paired
4410    /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
4411    ///
4412    /// Prior to this lift the "if `:entrada :paths` is empty use the
4413    /// substrate catch-all; else return each declared path verbatim"
4414    /// cascade lived inline at
4415    /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
4416    /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
4417    /// per-Aplicacao HTTPRoute per-rule path-list emit site the
4418    /// substrate ships today, with no typed method on the substrate
4419    /// primitive that named the rule. A future path-resolution axis
4420    /// addition — a per-cluster `:entrada :default-path` override the
4421    /// operator pins through a future `:placement`-scoped slot, an
4422    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
4423    /// admission-webhook floor that materializes the catch-all before
4424    /// the CR lands, a future per-`:entrada :paths` overlay from a
4425    /// per-cluster policy the future `feira app deploy` pipeline
4426    /// consumes — would have to be threaded through every renderer's
4427    /// inline copy of the cascade in lockstep or one consumer would
4428    /// silently disagree with the peers on which path list a given
4429    /// `:entrada` block resolves to. Lifting the rule to a typed
4430    /// method on the substrate primitive means every downstream
4431    /// HTTPRoute-aware consumer (the M4 CR materializer, the future
4432    /// per-cluster overlay resolver, every future per-Aplicacao
4433    /// snapshot renderer) reaches for exactly one typed dispatch —
4434    /// the resolver's accept-set moves as a unit on any future axis
4435    /// addition.
4436    ///
4437    /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
4438    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
4439    /// per-`:entrada` scalar-value axes — extends the "one typed
4440    /// dispatch on the substrate primitive, thin projections at each
4441    /// consumer" discipline onto the per-`:entrada` path-list
4442    /// resolution axis every HTTPRoute-aware renderer consumes. Same
4443    /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
4444    /// sibling `:politicas` primitive — one typed method on the
4445    /// substrate primitive that names the cascade every renderer
4446    /// otherwise re-inlines.
4447    #[must_use]
4448    pub fn resolved_paths(&self) -> Vec<&str> {
4449        // Route the internal cascade-head + per-entry projection reads
4450        // through the lifted [`Self::paths`] slice accessor rather than
4451        // the raw `self.paths` field access — the substrate-primitive
4452        // per-`:entrada` path-list resolver's two internal reads now
4453        // key off the canonical raw-slot surface every downstream
4454        // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
4455        // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
4456        // entrada summary line's `{:?}` Debug print) routes through, so
4457        // any future rebrand on the typed slot's raw-slot reader lands
4458        // at exactly one place. Same two-consumer coherence discipline
4459        // the sibling `Placement::clusters` (a6e18d7) accessor pins on
4460        // the peer M3 mesh-slot `Vec<String>`-carry axis.
4461        if self.paths().is_empty() {
4462            vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
4463        } else {
4464            self.paths().iter().map(String::as_str).collect()
4465        }
4466    }
4467
4468    /// Substrate-canonical per-`:entrada` DNS-hostname singular
4469    /// accessor every Gateway-API `Listener.hostname` reader keys off
4470    /// — returns the author-declared `:entrada :host` byte-string
4471    /// verbatim as a `&str`, borrowed from the typed slot's own
4472    /// [`String`] storage.
4473    ///
4474    /// Named the "singular" half of the DNS-hostname resolver pair on
4475    /// the substrate primitive: the parent-Gateway per-listener
4476    /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
4477    /// (`Listener.hostname: Option<PreciseHostname>` — at most one
4478    /// hostname per listener), and this accessor is the typed dispatch
4479    /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
4480    /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
4481    /// the per-HTTPRoute `spec.hostnames[]` list axis the same
4482    /// per-Aplicacao ingress-hostname surface projects onto.
4483    ///
4484    /// Prior to this lift the `entrada.host.clone()` byte-string was
4485    /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
4486    /// per-listener singular `hostname:` axis
4487    /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
4488    /// per-HTTPRoute plural `spec.hostnames[]` axis
4489    /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
4490    /// consumers read the same `entrada.host` field but the two-site
4491    /// duplication expressed no compile-time contract that the singular
4492    /// Gateway-listener filter and the plural `HTTPRoute` filter list
4493    /// stay in lockstep on future extensions of the `:entrada` slot to
4494    /// a multi-hostname author surface (an `:entrada :alt-hosts` list
4495    /// overlay, a per-cluster SNI fan-out the operator pins through a
4496    /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
4497    /// Aplicacao` CR materializer's per-listener virtual-host filter
4498    /// admission-webhook overlay). Any such extension would have to be
4499    /// threaded through every renderer's inline copy of the resolution
4500    /// in lockstep or the Gateway listener's `hostname:` filter would
4501    /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
4502    /// — a Gateway-API-conformance divergence whose apply-time symptom
4503    /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
4504    /// `NoMatchingParent` — the API server rejects the route because
4505    /// its `hostnames[]` filter doesn't intersect the parent listener's
4506    /// `hostname` filter) is far from the source `caixa.lisp` and never
4507    /// surfaces in the emitted YAML. Lifting the singular and plural
4508    /// resolvers to typed methods on the substrate primitive means
4509    /// every consumer of the Aplicacao's ingress-hostname surface
4510    /// reaches for exactly one typed dispatch, and the pair-invariant
4511    /// `hostnames() == vec![hostname()]` pinned by the sibling
4512    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
4513    /// keeps the two axes in lockstep by construction.
4514    ///
4515    /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
4516    /// (1449891) path-list resolver on the per-HTTPRoute per-rule
4517    /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
4518    /// the substrate primitive, thin projections at each consumer"
4519    /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
4520    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
4521    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
4522    /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
4523    /// `:entrada` scalar-value + list-value axes.
4524    #[must_use]
4525    pub fn hostname(&self) -> &str {
4526        self.host.as_str()
4527    }
4528
4529    /// Substrate-canonical per-`:entrada` DNS-hostname plural
4530    /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
4531    /// keys off — returns the singleton `[hostname()]` list under
4532    /// today's single-hostname-per-Aplicacao author surface, and the
4533    /// authoritative multi-hostname list under a future
4534    /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
4535    ///
4536    /// Plural half of the DNS-hostname resolver pair — see the
4537    /// companion [`Entrada::hostname`] docstring for the two-consumer
4538    /// lift + pair-invariant discipline (`hostnames() ==
4539    /// vec![hostname()]`, pinned load-bearing by the sibling
4540    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
4541    /// test).
4542    ///
4543    /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
4544    /// per-`:entrada` plural-list resolver on the per-HTTPRoute
4545    /// per-rule path-list axis — same `Vec<&str>` shape, same
4546    /// substrate-primitive-owns-the-resolver discipline extended to
4547    /// the per-HTTPRoute virtual-host filter-list axis.
4548    #[must_use]
4549    pub fn hostnames(&self) -> Vec<&str> {
4550        vec![self.hostname()]
4551    }
4552
4553    /// Substrate-canonical per-`:entrada` destination-Servico scalar
4554    /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
4555    /// the author-declared `:entrada :para` byte-string verbatim as a
4556    /// `&str`, borrowed from the typed slot's own [`String`] storage.
4557    ///
4558    /// The `:entrada :para` slot names the single member Servico the
4559    /// external Gateway routes to (validated by
4560    /// [`AplicacaoSpec::validate`] to be a
4561    /// [`Membro::caixa`] the Aplicacao declares — a stray
4562    /// `:para` that doesn't name a member is
4563    /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
4564    /// backend-attachment miss at cluster-apply time). Under today's
4565    /// single-destination author surface `:entrada :para` is the ingress
4566    /// apex Servico's canonical identity; under a hypothetical
4567    /// future multi-backend author surface (a `:entrada
4568    /// :split :backends` weighted-fan-out overlay for canary /
4569    /// blue-green traffic-split rollouts, per-path override for
4570    /// path-based per-Servico routing beyond the single-apex model,
4571    /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4572    /// per-CR admission-webhook that promotes the scalar to a
4573    /// weighted list) this accessor is the substrate primitive's typed
4574    /// dispatch every downstream `HTTPRoute`-aware consumer routes
4575    /// through, so the resolution shape migrates as a unit on one
4576    /// caixa-core edit rather than a coordinated rewrite across every
4577    /// renderer's inline field-access.
4578    ///
4579    /// Prior to this lift the `entrada.para` byte-string was accessed
4580    /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
4581    /// `metadata.name` composer's per-destination discriminator arg
4582    /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
4583    /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
4584    /// per-HTTPRoute per-rule `backendRefs[0].name` axis
4585    /// (`entrada.para.clone()`,
4586    /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
4587    /// consumers read the same `entrada.para` field but the two-site
4588    /// duplication expressed no compile-time contract that the HTTPRoute
4589    /// name-discriminator and the per-rule backend name stay in
4590    /// lockstep on future extensions of the `:entrada` slot to a
4591    /// multi-destination author surface. Any such extension would have
4592    /// to be threaded through every renderer's inline copy of the
4593    /// destination projection in lockstep or the HTTPRoute
4594    /// `metadata.name` would silently reference a different destination
4595    /// than its own `backendRefs[]` — an operator-side
4596    /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
4597    /// grep-by-name lookup would land on a route whose `backendRefs[]`
4598    /// silently point at a peer Servico, dropping every external
4599    /// `:entrada` flow at the gateway with the destination-drift root
4600    /// cause invisible in the emitted YAML.
4601    ///
4602    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
4603    /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
4604    /// the per-listener singular / per-HTTPRoute plural filter axes and
4605    /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
4606    /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
4607    /// typed dispatch on the substrate primitive, thin projections at
4608    /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
4609    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
4610    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
4611    /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
4612    /// sibling per-`:entrada` scalar-value + list-value axes — this
4613    /// accessor closes the last unlifted per-`:entrada` scalar axis
4614    /// (the destination-Servico byte-string) so every downstream
4615    /// per-`:entrada` reader now routes through a typed dispatch on
4616    /// the substrate primitive.
4617    #[must_use]
4618    pub fn destination(&self) -> &str {
4619        self.para.as_str()
4620    }
4621
4622    /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
4623    /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
4624    /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
4625    /// reader keys off — returns the author-declared `:entrada :port`
4626    /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
4627    /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
4628    /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
4629    /// [`AplicacaoError::EntradaPortZero`], not a silent
4630    /// admission-webhook rejection at cluster-apply time).
4631    ///
4632    /// The `:entrada :port` slot carries the destination Servico's
4633    /// canonical in-cluster L4 listener port (`trigger.service.port` on
4634    /// the `pleme-computeunit` library chart), and every downstream
4635    /// consumer that reads the port keys off this scalar (the
4636    /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
4637    /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
4638    /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
4639    /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
4640    /// CR materializer's per-Aplicacao gateway port resolver).
4641    ///
4642    /// Prior to this lift the `.port` field was accessed inline at two
4643    /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
4644    /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
4645    /// the [`AplicacaoSpec::port_for_destination`] resolver's
4646    /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
4647    /// open-coded field-accesses that expressed no compile-time link
4648    /// back to the typed slot. A future extension of the `:entrada :port`
4649    /// axis to a richer author surface — a per-cluster override the
4650    /// operator pins through a future `:placement :default-port` slot the
4651    /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
4652    /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
4653    /// heterogeneous listener ports, an M4
4654    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
4655    /// admission-webhook floor that promotes the scalar to a
4656    /// per-destination map — would have had to be threaded through both
4657    /// open-coded copies in lockstep or the structural-floor validator
4658    /// and the [`AplicacaoSpec::port_for_destination`] resolver would
4659    /// silently disagree on which port a given [`Entrada`] resolves to.
4660    /// Lifting the resolution rule to a typed method on the substrate
4661    /// primitive means every downstream consumer of the Aplicacao's
4662    /// per-`:entrada` L4-port surface reaches for exactly one typed
4663    /// dispatch — the resolver's accept-set migrates as a unit on any
4664    /// future axis addition.
4665    ///
4666    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
4667    /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
4668    /// accessors on the per-`:entrada` scalar-value axis — same "one
4669    /// typed dispatch on the substrate primitive, thin projections at
4670    /// each consumer" discipline extended onto the per-`:entrada`
4671    /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
4672    /// the M3 mesh-slot `Entrada` type — closes the last unlifted
4673    /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
4674    /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
4675    /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
4676    /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
4677    /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
4678    /// storage field's name; the accessor's identity name maps onto the
4679    /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
4680    /// already carries.
4681    #[must_use]
4682    pub fn port(&self) -> u16 {
4683        self.port
4684    }
4685
4686    /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
4687    /// slice accessor every HTTPRoute-aware renderer keys off when it
4688    /// wants the raw author-declared path-list (not the fallback-
4689    /// applied projection [`Self::resolved_paths`] returns) — returns
4690    /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
4691    /// borrowed from the typed slot's own [`Vec<String>`] storage.
4692    ///
4693    /// Named the "raw slot" half of the per-`:entrada` path-list resolver
4694    /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
4695    /// (1449891) closes the fallback-applying arm every per-Aplicacao
4696    /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
4697    /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
4698    /// catch-all; non-empty slot → per-entry verbatim projection); this
4699    /// accessor closes the raw-slot arm every consumer that must see the
4700    /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
4701    /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
4702    /// not `Err(EntradaPathEmpty)`, so it cannot route through the
4703    /// fallback-applying sibling; the `feira app graph` per-Aplicacao
4704    /// external-gateway summary line's `{:?}` Debug print — which must
4705    /// name the author's declaration, not the substrate's fallback, so
4706    /// an author reading their graph output can grep their caixa.lisp
4707    /// for the exact list they authored) routes through.
4708    ///
4709    /// Prior to this lift the `.paths` field was accessed inline at four
4710    /// production sites: the two internal reads in [`Self::resolved_paths`]
4711    /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
4712    /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
4713    /// value-shape gate's `for p in &e.paths` traversal head, and the
4714    /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
4715    /// Debug print — four open-coded field-accesses that expressed no
4716    /// compile-time link back to the typed slot. A future extension of
4717    /// the `:entrada :paths` axis to a richer author surface — a
4718    /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
4719    /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
4720    /// spec supports through `matches[].method`), a per-path per-header
4721    /// filter overlay (`matches[].headers[]`), a per-cluster override
4722    /// the operator pins through a future `:placement :path-overlay`
4723    /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4724    /// per-CR admission-webhook that normalized the list at admission
4725    /// time — would have had to be threaded through every open-coded
4726    /// copy in lockstep or the validator's per-entry gate would silently
4727    /// disagree with the renderer's per-entry emit on which list a given
4728    /// `:entrada` block resolves to. Lifting the resolution to a typed
4729    /// method on the substrate primitive means every downstream consumer
4730    /// of the Aplicacao's per-`:entrada` path-list surface reaches for
4731    /// exactly one typed dispatch — the resolver's accept-set migrates
4732    /// as a unit on any future axis addition.
4733    ///
4734    /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
4735    /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
4736    /// carry axis — same "one typed dispatch on the substrate primitive,
4737    /// thin projections at each consumer" discipline extended onto the
4738    /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
4739    /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
4740    /// carrier) so every downstream per-`:entrada` reader now routes
4741    /// through a typed dispatch on the substrate primitive. Returns
4742    /// `&[String]` (not `&Vec<String>`) because every downstream consumer
4743    /// treats the list as a read-only sequence — the slice-view is the
4744    /// narrowest borrow that supports every present + roadmapped consumer
4745    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
4746    /// `Vec`'s grow/push/reserve surface that no consumer of the typed
4747    /// view reaches for (the storage-side `Vec` remains reachable through
4748    /// the `pub paths` field for the mutation-carrying serde round-trip
4749    /// and per-test fixture-mutation paths).
4750    #[must_use]
4751    pub fn paths(&self) -> &[String] {
4752        self.paths.as_slice()
4753    }
4754}
4755
4756/// Canonical default L4 port every typed Servico exposes on its
4757/// in-cluster K8s Service (the `trigger.service.port` axis the
4758/// `pleme-computeunit` library chart emits, the `:entrada :port` author
4759/// surface defaults to when the author omits the slot, and the
4760/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
4761/// `:entrada` block matches the per-`:contratos` destination Servico).
4762/// The single source of truth all three typed-port consumers reach for:
4763///
4764///   - [`Entrada::port`]'s serde default (via the
4765///     [`default_port`] helper this constant feeds); the author surface
4766///     `(:entrada (:host … :para …))` without an explicit `:port` slot
4767///     reads back as a typed [`Entrada`] carrying this exact value;
4768///   - the
4769///     [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
4770///     emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
4771///     fallback, fired when the typed `:entrada` block doesn't name
4772///     the per-`:contratos` destination Servico — the typed
4773///     `:contratos` graph carries no per-destination port axis (the
4774///     destination port is the destination Servico's
4775///     `lareira-<nome>` chart's `trigger.service.port`, which the
4776///     Aplicacao-level renderer has no visibility into without a
4777///     resolver round-trip), so the renderer falls back to the
4778///     substrate's canonical Servico-port assumption — by
4779///     construction the same value the destination's own
4780///     `pleme-computeunit` chart emits, the same value the
4781///     destination's own typed `:entrada :port` slot defaults to;
4782///   - every future per-Servico renderer the absorption-roadmap
4783///     acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
4784///     CR materializer's per-edge port resolver, the future
4785///     per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
4786///     emitter's per-route bucket key, the future caixa-otel
4787///     collector-pipeline emitter's per-Servico scrape port).
4788///
4789/// Until this lift landed the value `8080` lived at two production-code
4790/// call-sites: the [`default_port`] helper at
4791/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
4792/// and the `.unwrap_or(8080)` literal at
4793/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
4794/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
4795/// resolver). A future Servico-port rebrand — the substrate moving the
4796/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
4797/// gateway grows direct `:80` listeners, to `8443` once the substrate
4798/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
4799/// override the operator pins through a future
4800/// `:placement :default-port` slot — without a coordinated edit on
4801/// both sides would silently emit Servicos listening on one port and
4802/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
4803/// The CNP's apply-time symptom (the policy is admitted but every L4
4804/// flow on the destination Servico's actual port silently drops because
4805/// it doesn't match the whitelisted port) is far from the rebrand
4806/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
4807/// in hubble traces, not in `kubectl describe`. Lifting the literal to
4808/// a shared constant closes the drift footgun structurally — both
4809/// consumers read from the same `u16`, so any rebrand reaches both
4810/// sites by construction.
4811///
4812/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
4813/// per-renderer canonical-K8s-axis constant — the namespace string
4814/// and the canonical Servico port both lived as duplicated literals
4815/// across caixa-core / caixa-mesh / caixa-flux before their respective
4816/// lifts. Same "the typed constant lives in one place" discipline the
4817/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
4818/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
4819/// shared-string axes.
4820///
4821/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
4822pub const DEFAULT_SERVICO_PORT: u16 = 8080;
4823
4824/// Structural floor for the typed `:entrada :port` axis — every
4825/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
4826/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
4827///
4828/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
4829/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
4830/// interprets as "let the kernel pick a free port at bind time", not a
4831/// well-defined destination the substrate's per-`:entrada` Gateway API
4832/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
4833/// carrying `port: 0` degenerates to a nominal-only routing target: the
4834/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
4835/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
4836/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
4837/// at build time rather than at `kubectl apply` time), and the
4838/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
4839/// (caixa-mesh/src/lib.rs:2657 through
4840/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
4841/// [`Entrada::port`] typed value — silently emits a policy whose
4842/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
4843/// actual listener, dropping every L4 flow at the eBPF data plane far
4844/// from the source caixa.lisp with no field naming the port-zero-drift
4845/// root cause.
4846///
4847/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
4848/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
4849/// on the top edge (unlike the peer capped-`u32` `:politicas` /
4850/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
4851/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
4852/// well below `u32::MAX` and therefore need explicit typed caps).
4853///
4854/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
4855/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
4856/// scalar every `(:entrada (:host … :para …))` slot without an explicit
4857/// `:port` inherits through the serde default hook; this constant names
4858/// the accept-set floor every declared port must satisfy. The pair is
4859/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
4860/// substrate's default must satisfy its own accept-set floor by
4861/// construction) — a future rebrand that accidentally moved
4862/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
4863/// negative-cast typo, a per-cluster override the operator pins through
4864/// a future `:placement :default-port` slot that lands out-of-range)
4865/// would silently invalidate the serde-default emission at every
4866/// author-side `(:entrada (:host … :para …))` slot — the compile-time
4867/// invariant pin
4868/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
4869/// closes the drift footgun at caixa-core build time.
4870///
4871/// Lifted as a typed `pub const` (rather than an inline `0` literal at
4872/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
4873/// has exactly one source of truth — the future M4
4874/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
4875/// gateway resolver, the future per-Servico
4876/// `computeunit.trigger.service.port` renderer's per-CR port-value
4877/// validator, and every downstream test-fixture navigator asserting
4878/// the accept-set floor all read from one place. Same shape every
4879/// other typed bracket-floor / bracket-ceiling in this crate carries
4880/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
4881/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
4882/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
4883/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
4884/// [`POLICY_RATE_LIMIT_MAX`]).
4885pub const SERVICO_PORT_MIN: u16 = 1;
4886
4887const fn default_port() -> u16 {
4888    DEFAULT_SERVICO_PORT
4889}
4890
4891// ── the typed view ───────────────────────────────────────────────────
4892
4893/// Typed composition view of the flat Aplicacao slots on
4894/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
4895/// validation + downstream renderer consumption.
4896#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
4897#[serde(rename_all = "camelCase")]
4898pub struct AplicacaoSpec {
4899    pub membros: Vec<Membro>,
4900    pub contratos: Vec<WitContract>,
4901    pub politicas: MeshPolicy,
4902    pub placement: Placement,
4903    pub entrada: Option<Entrada>,
4904}
4905
4906impl AplicacaoSpec {
4907    /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
4908    /// per-Aplicacao member-list slice-return accessor every
4909    /// per-Aplicacao member-list reader keys off — returns the author-
4910    /// declared `:membros` list verbatim as a `&[Membro]` slice-view
4911    /// over the same backing buffer the raw `self.membros.as_slice()`
4912    /// field access borrows from.
4913    ///
4914    /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
4915    /// member list — the load-bearing identity of the application graph
4916    /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
4917    /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
4918    /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
4919    /// accessor) with a `:versao` semver-requirement string (through
4920    /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
4921    /// and every downstream consumer that fans on the member-set keys
4922    /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
4923    /// membership-lookup `HashSet<&str>` seed's collect input, the
4924    /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
4925    /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
4926    /// per-member DNS-1123 / semver-requirement / duplicate-detection
4927    /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
4928    /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
4929    /// programs.yaml per-`:membros` fan-out emitter's per-entry
4930    /// mapping-composition loop, the `feira app graph` per-Aplicacao
4931    /// member-count print line and per-member tree traversal,
4932    /// every future wasm-operator (M4) per-Aplicacao CR materializer's
4933    /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
4934    /// placement engine's per-member weight-topology reader).
4935    ///
4936    /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
4937    /// inline at six production sites — the [`AplicacaoSpec::validate`]
4938    /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
4939    /// [`AplicacaoSpec::validate_membros`]'s pre-flight
4940    /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
4941    /// probe, the same method's per-member `for m in &self.membros`
4942    /// validate-loop traversal head, the
4943    /// [`AplicacaoSpec::detect_sync_cycles`]'s
4944    /// `for m in &self.membros` adjacency-list seed, the
4945    /// [`caixa_mesh::programs_for_aplicacao`] emitter's
4946    /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
4947    /// paired with the peer `for m in &spec.membros` per-entry fan-out
4948    /// loop, and the `feira app graph` per-Aplicacao print line's
4949    /// `spec.membros.len()` count formatter argument paired with the
4950    /// peer `for m in &spec.membros` per-member tree traversal — six
4951    /// open-coded field-accesses that expressed no compile-time link
4952    /// back to the typed slot. A future extension of the `:membros`
4953    /// axis to a richer author surface (a per-cluster member-set
4954    /// overlay the operator pins through a future
4955    /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
4956    /// roadmap acknowledges, a per-tenant member-alias table the M4
4957    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
4958    /// CR at admission time, a per-Aplicacao dynamic member-set
4959    /// derivation the future adaptive-placement engine computes from
4960    /// weighted membership topology, a promotion of the plain
4961    /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
4962    /// Orleans-style virtual-actor dynamic-membership comes into typed
4963    /// scope) would have had to be threaded through all six open-coded
4964    /// copies in lockstep or one consumer would silently disagree with
4965    /// the peers on which member-set a given Aplicacao resolves to —
4966    /// the `HashSet<&str>` name-set seed reading the raw slot while
4967    /// the peer `.is_empty()` refusal probe read an operator-resolved
4968    /// slot would silently split the `:contratos` membership-lookup
4969    /// input from the pre-flight-refusal input, a six-consumer split
4970    /// at the validator + programs.yaml emitter + graph printer far
4971    /// from the source `caixa.lisp` with no field naming the member-
4972    /// set-drift root cause. Lifting the resolution rule to a typed
4973    /// method on the substrate primitive means every downstream
4974    /// consumer of the Aplicacao's per-`:membros` member-list surface
4975    /// reaches for exactly one typed dispatch — the resolver's accept-
4976    /// set migrates as a unit on any future axis addition.
4977    ///
4978    /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
4979    /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
4980    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
4981    /// static-child-list `Vec`-carry axis, and to the M3
4982    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
4983    /// on the peer per-`:placement` distribution-target-list `Vec`-
4984    /// carry axis. Same "one typed dispatch on the substrate primitive,
4985    /// thin projections at each consumer" discipline. The two peer
4986    /// `Vec`-carry axes still unlifted at the time of this lift —
4987    /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
4988    /// WIT-typed edge list) and
4989    /// [`crate::UpgradeFromEntry::instructions`]
4990    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
4991    /// — inherit this accessor's discipline as future compounding runs
4992    /// migrate their consumers onto the shared slice-return shape.
4993    /// First `&[T]`-return accessor on the top-level M3 mesh-slot
4994    /// `AplicacaoSpec` type itself, extending the discipline beyond
4995    /// the inner per-slot types ([`crate::Placement`],
4996    /// [`crate::SupervisorSpec`]) onto the outermost typed composition
4997    /// view every renderer consumes. Named `membros()` to match the
4998    /// storage field's name verbatim and the tatara-lisp author-
4999    /// surface term (`:membros`) the field's own docstring already
5000    /// carries; the accessor's identity maps onto the canonical
5001    /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
5002    /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
5003    /// every downstream consumer of the member list treats it as a
5004    /// read-only sequence — the slice-view is the narrowest borrow
5005    /// that supports every present + roadmapped consumer
5006    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
5007    /// backing `Vec`'s grow/push/reserve surface that no consumer of
5008    /// the typed view reaches for (the storage-side `Vec` remains
5009    /// reachable through the `pub membros` field for the mutation-
5010    /// carrying serde round-trip and per-test fixture-mutation paths).
5011    #[must_use]
5012    pub fn membros(&self) -> &[Membro] {
5013        self.membros.as_slice()
5014    }
5015
5016    /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
5017    /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
5018    /// accessor every per-Aplicacao contract-list reader keys off —
5019    /// returns the author-declared `:contratos` list verbatim as a
5020    /// `&[WitContract]` slice-view over the same backing buffer the raw
5021    /// `self.contratos.as_slice()` field access borrows from.
5022    ///
5023    /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
5024    /// WIT-typed edge list — the load-bearing set of directed edges
5025    /// on the application graph whose nodes are the `:membros` entries
5026    /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
5027    /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
5028    /// six-tuple is the edge identity every downstream duplicate gate
5029    /// keys off). Every per-`:contratos` entry pairs a `:de` source-
5030    /// Servico caller name + a `:para` destination-Servico callee name
5031    /// (through the lifted [`WitContract::source`] +
5032    /// [`WitContract::destination`] (7f0fd43) accessor pair on the
5033    /// caller/callee-Servico axis) with a `:wit` world-reference
5034    /// (through the lifted [`WitContract::world_ref`] (0804823)
5035    /// accessor) and the target-shape-appropriate payload-carrier
5036    /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
5037    /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
5038    /// (ed22b66) accessor on the per-target-shape payload-carrier
5039    /// axis). Every downstream consumer that fans on the edge-set
5040    /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
5041    /// name-set / self-edge / target-shape / dedup fan-out loop, the
5042    /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
5043    /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
5044    /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
5045    /// grouping loop, the `feira app graph` per-Aplicacao contract-
5046    /// count print line and per-contract tree traversal, every future
5047    /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
5048    /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
5049    /// mesh-policy overlay resolver's per-contract typed-edge weight
5050    /// reader).
5051    ///
5052    /// Prior to this lift the `.contratos` `Vec<WitContract>` was
5053    /// accessed inline at four production sites — the
5054    /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
5055    /// per-edge validate-loop traversal head (which drives every
5056    /// per-edge name-set membership lookup, self-edge check,
5057    /// target-shape dispatch, and dedup `HashSet` insert), the
5058    /// [`AplicacaoSpec::detect_sync_cycles`]'s
5059    /// `for c in &self.contratos` adjacency-list seed head (which
5060    /// drives every per-edge sync-vs-pub-sub partition and per-edge
5061    /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
5062    /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
5063    /// `BTreeMap` grouping loop head (which drives every per-CNP
5064    /// fan-out emit), and the `feira app graph` per-Aplicacao print
5065    /// line's `spec.contratos.len()` count formatter argument paired
5066    /// with the peer `for c in &spec.contratos` per-contract tree
5067    /// traversal — four open-coded field-accesses that expressed no
5068    /// compile-time link back to the typed slot. A future extension
5069    /// of the `:contratos` axis to a richer author surface (a
5070    /// per-cluster contract overlay the operator pins through a
5071    /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
5072    /// federation roadmap acknowledges, a per-tenant edge-policy
5073    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5074    /// materializer resolves per-CR at admission time, a per-edge
5075    /// weight scalar the future adaptive-placement engine reads to
5076    /// bias sync-subgraph routing, a promotion of the plain
5077    /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
5078    /// once virtual-actor-style dynamic-edge composition comes into
5079    /// typed scope) would have had to be threaded through all four
5080    /// open-coded copies in lockstep or one consumer would silently
5081    /// disagree with the peers on which edge-set a given Aplicacao
5082    /// resolves to — the validator's per-edge dedup `HashSet` seed
5083    /// reading the raw slot while the peer sync-cycle adjacency-list
5084    /// seed read an operator-resolved slot would silently split the
5085    /// build-time edge-set gate from the runtime deadlock-detection
5086    /// gate, a four-consumer split at the validator, the cycle
5087    /// detector, the CNP emitter, and the graph printer far from
5088    /// the source `caixa.lisp` with no field naming the edge-set-
5089    /// drift root cause. Lifting the resolution rule to a typed method on the
5090    /// substrate primitive means every downstream consumer of the
5091    /// Aplicacao's per-`:contratos` edge-list surface reaches for
5092    /// exactly one typed dispatch — the resolver's accept-set
5093    /// migrates as a unit on any future axis addition.
5094    ///
5095    /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
5096    /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
5097    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
5098    /// static-child-list `Vec`-carry axis, to the M3
5099    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
5100    /// on the peer per-`:placement` distribution-target-list `Vec`-
5101    /// carry axis, and to the immediately-adjacent sibling M3
5102    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
5103    /// the peer per-`:membros` node-list `Vec`-carry axis — the
5104    /// per-`:contratos` edge-list accessor is the natural pair of
5105    /// the per-`:membros` node-list accessor (graph edges over graph
5106    /// nodes; every graph-shaped consumer reads both). Same "one
5107    /// typed dispatch on the substrate primitive, thin projections
5108    /// at each consumer" discipline. The last remaining `Vec`-carry
5109    /// axis still unlifted at the time of this lift —
5110    /// [`crate::UpgradeFromEntry::instructions`]
5111    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
5112    /// list) — inherits this accessor's discipline as future
5113    /// compounding runs migrate its consumers onto the shared slice-
5114    /// return shape. Second `&[T]`-return accessor on the top-level
5115    /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
5116    /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
5117    /// `:contratos` are the two `Vec` fields on the outer typed
5118    /// composition view — `:politicas`, `:placement`, `:entrada` are
5119    /// scalar/option-shaped and already route through their per-slot
5120    /// accessor families). Named `contratos()` to match the storage
5121    /// field's name verbatim and the tatara-lisp author-surface term
5122    /// (`:contratos`) the field's own docstring already carries; the
5123    /// accessor's identity maps onto the canonical MESH-COMPOSITION
5124    /// §III.1 vocabulary the slot's docstring already reaches for.
5125    /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
5126    /// every downstream consumer of the contract list treats it as a
5127    /// read-only sequence — the slice-view is the narrowest borrow
5128    /// that supports every present + roadmapped consumer
5129    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
5130    /// backing `Vec`'s grow/push/reserve surface that no consumer of
5131    /// the typed view reaches for (the storage-side `Vec` remains
5132    /// reachable through the `pub contratos` field for the mutation-
5133    /// carrying serde round-trip and per-test fixture-mutation paths).
5134    #[must_use]
5135    pub fn contratos(&self) -> &[WitContract] {
5136        self.contratos.as_slice()
5137    }
5138
5139    /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
5140    /// per-Aplicacao mesh-policy composite-reference accessor every
5141    /// per-Aplicacao policy-block reader keys off — returns the author-
5142    /// declared `:politicas` composite verbatim as a `&MeshPolicy`
5143    /// reference over the same backing storage the raw `&self.politicas`
5144    /// field access borrows from.
5145    ///
5146    /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
5147    /// mesh-policy composite — the load-bearing container of every
5148    /// mesh-level operational-policy axis every downstream mesh-artifact
5149    /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
5150    /// mesh-policy overlay is the single typed surface a
5151    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
5152    /// from). Every per-`:politicas` axis threads through a lifted
5153    /// per-slot accessor on the [`MeshPolicy`] type: the
5154    /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
5155    /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
5156    /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
5157    /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
5158    /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
5159    /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
5160    /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
5161    /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
5162    /// accessor. Every downstream consumer that reaches for a policy
5163    /// axis first passes through this outer accessor onto the composite
5164    /// and then dispatches onto the per-axis accessor — the two-level
5165    /// dispatch means every per-`:politicas` reader now routes through
5166    /// a typed dispatch on the substrate primitive at both altitudes.
5167    ///
5168    /// Prior to this lift the `.politicas` `MeshPolicy` composite was
5169    /// accessed inline at four production sites — the
5170    /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
5171    /// &self.politicas;` traversal seed (which drives every per-axis
5172    /// zero-floor + upper-cap + canonical-form bracket dispatch through
5173    /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
5174    /// `p.rate_limit()` on the axis-level lifted accessors), the
5175    /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
5176    /// emitter's `spec.politicas.mtls_required()` field-then-accessor
5177    /// chain (which drives every per-`(:de, :para)` CNP
5178    /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
5179    /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
5180    /// timeout + retry overlay emitter's paired
5181    /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
5182    /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
5183    /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
5184    /// open-coded outer-field accesses that expressed no compile-time
5185    /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
5186    /// future extension of the `:politicas` outer axis to a richer
5187    /// author surface (a per-cluster policy overlay the operator pins
5188    /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
5189    /// §V federation roadmap acknowledges, a per-tenant policy-alias
5190    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
5191    /// resolves per-CR at admission time, a per-Aplicacao dynamic
5192    /// policy-composite derivation the future adaptive-placement engine
5193    /// computes from a per-cluster load-topology reader, a promotion of
5194    /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
5195    /// partition once virtual-actor-style dynamic-mesh-policy
5196    /// composition comes into typed scope) would have had to be threaded
5197    /// through all four open-coded copies in lockstep or one consumer
5198    /// would silently disagree with the peers on which mesh-policy
5199    /// composite a given Aplicacao resolves to — the validator's
5200    /// per-axis bracket-dispatch seed reading the raw slot while the
5201    /// peer CNP mTLS-overlay emitter read an operator-resolved slot
5202    /// would silently split the build-time policy-shape gate from the
5203    /// runtime CNP-emission gate, a four-consumer split at the
5204    /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
5205    /// the source `caixa.lisp` with no field naming the policy-drift
5206    /// root cause. Lifting the resolution rule to a typed method on the
5207    /// substrate primitive means every downstream consumer of the
5208    /// Aplicacao's per-`:politicas` mesh-policy composite surface
5209    /// reaches for exactly one typed dispatch — the resolver's accept-
5210    /// set migrates as a unit on any future axis addition.
5211    ///
5212    /// First `&Composite`-return accessor on the top-level M3 mesh-slot
5213    /// `AplicacaoSpec` type itself — sibling to the seed slice-return
5214    /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
5215    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
5216    /// close the two `Vec`-carry axes on the outer typed composition
5217    /// view; the outer `:politicas` composite-reference axis is the
5218    /// natural pair to the paired outer `Vec`-carry accessors on the
5219    /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
5220    /// emitter reads all four axes as one unit (graph nodes + graph
5221    /// edges + mesh policy + placement pool). Peer to the same
5222    /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
5223    /// slot: every M2 `SupervisorSpec`-scoped composite reader
5224    /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
5225    /// `restart_window`, `children`) already routes through the M2
5226    /// `SupervisorSpec` accessor family — this lift extends the same
5227    /// "one typed dispatch on the substrate primitive at the outer
5228    /// composition altitude" discipline to the M3 mesh-slot
5229    /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
5230    /// remaining peer outer-composite axes still unlifted at the time
5231    /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
5232    /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
5233    /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
5234    /// inherit this accessor's discipline as future compounding runs
5235    /// migrate their consumers onto the shared reference-return shape.
5236    /// Named `politicas()` to match the storage field's name verbatim
5237    /// and the tatara-lisp author-surface term (`:politicas`) the
5238    /// field's own docstring already carries; the accessor's identity
5239    /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
5240    /// slot's docstring already reaches for. Returns `&MeshPolicy`
5241    /// (not the owning composite by copy or clone) because every
5242    /// downstream consumer of the mesh-policy composite treats it as a
5243    /// read-only per-axis dispatch source — the reference-view is the
5244    /// narrowest borrow that supports every present + roadmapped
5245    /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
5246    /// emptiness probe) without cloning the composite through every
5247    /// consumer's fast path.
5248    #[must_use]
5249    pub fn politicas(&self) -> &MeshPolicy {
5250        &self.politicas
5251    }
5252
5253    /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
5254    /// per-Aplicacao distribution-composite composite-reference accessor
5255    /// every per-Aplicacao placement-block reader keys off — returns the
5256    /// author-declared `:placement` composite verbatim as a `&Placement`
5257    /// reference over the same backing storage the raw `&self.placement`
5258    /// field access borrows from.
5259    ///
5260    /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
5261    /// distribution composite — the load-bearing container of every
5262    /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
5263    /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
5264    /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
5265    /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
5266    /// hosting-pool identity, §V for the `M3-Adaptive`-compression
5267    /// `:affinity` hint). Every per-`:placement` axis threads through a
5268    /// lifted per-slot accessor on the [`Placement`] type: the
5269    /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
5270    /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
5271    /// per-cluster distribution-target slice-return accessor, the
5272    /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
5273    /// optional-scalar accessor, and the [`Placement::shard_key`]
5274    /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
5275    /// downstream consumer that reaches for a placement axis first passes
5276    /// through this outer accessor onto the composite and then dispatches
5277    /// onto the per-axis accessor — the two-level dispatch means every
5278    /// per-`:placement` reader now routes through a typed dispatch on the
5279    /// substrate primitive at both altitudes.
5280    ///
5281    /// Prior to this lift the `.placement` `Placement` composite was
5282    /// accessed inline at three production sites — the
5283    /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
5284    /// seed (six `self.placement.<axis>()` field-then-inner-accessor
5285    /// chains: the pre-flight `.clusters().is_empty()` refusal probe
5286    /// paired with the `.estrategia()` diagnostic-carry copy, the per-
5287    /// cluster `.clusters()` validate-loop traversal head, the per-
5288    /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
5289    /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
5290    /// paired with the shape-gate cascade's `.shard_key()` /
5291    /// `.estrategia()` diagnostic-carry pair), the
5292    /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
5293    /// per-entry placement-block emitter's outer
5294    /// `serde_yaml::to_value(&spec.placement)` composite-serialization
5295    /// seed (which fans onto every per-cluster `programs[]` entry as a
5296    /// self-describing distribution overlay the aggregator filters by),
5297    /// and the `feira app graph` per-Aplicacao print line's paired
5298    /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
5299    /// then-inner-accessor chains (which drive the human-readable
5300    /// distribution summary of the typed Aplicacao view) — three open-
5301    /// coded outer-field accesses that expressed no compile-time link
5302    /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
5303    /// extension of the `:placement` outer axis to a richer author surface
5304    /// (a per-cluster placement overlay the operator pins through a
5305    /// future `:placement-overrides` slot the MESH-COMPOSITION §V
5306    /// federation roadmap acknowledges, a per-tenant placement-alias
5307    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
5308    /// resolves per-CR at admission time, a per-Aplicacao dynamic
5309    /// placement-composite derivation the future M5 adaptive-placement
5310    /// engine computes from a per-cluster load-topology reader, a
5311    /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
5312    /// partition once Orleans-style virtual-actor dynamic-placement comes
5313    /// into typed scope) would have had to be threaded through all three
5314    /// open-coded copies in lockstep or one consumer would silently
5315    /// disagree with the peers on which placement composite a given
5316    /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
5317    /// seed reading the raw slot while the peer
5318    /// `programs_for_aplicacao` emitter read an operator-resolved slot
5319    /// would silently split the build-time distribution-shape gate from
5320    /// the runtime programs.yaml distribution-annotation gate, a three-
5321    /// consumer split at the validator, the programs.yaml emitter, and
5322    /// the `feira app graph` printer far from the source `caixa.lisp`
5323    /// with no field naming the placement-drift root cause. Lifting the
5324    /// resolution rule to a typed method on the substrate primitive
5325    /// means every downstream consumer of the Aplicacao's per-
5326    /// `:placement` distribution composite surface reaches for exactly
5327    /// one typed dispatch — the resolver's accept-set migrates as a unit
5328    /// on any future axis addition.
5329    ///
5330    /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
5331    /// `AplicacaoSpec` type itself — sibling to the seed
5332    /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
5333    /// composite-reference accessor on the peer per-`:politicas` outer-
5334    /// composite axis, and to the paired slice-return accessors
5335    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
5336    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
5337    /// the two `Vec`-carry axes on the outer typed composition view; the
5338    /// outer `:placement` composite-reference axis is the natural pair
5339    /// to the peer `:politicas` composite-reference axis on the two
5340    /// operationally-symmetric M3 mesh slots (`:politicas` carries the
5341    /// how-to-run policy overlay, `:placement` carries the where-to-run
5342    /// distribution composite — every whole-Aplicacao mesh-artifact
5343    /// emitter reads both as one unit). Same "one typed dispatch on the
5344    /// substrate primitive, thin projections at each consumer"
5345    /// discipline the peer per-`:politicas` composite-reference axis
5346    /// already routes through. The one remaining outer-composite axis
5347    /// still unlifted at the time of this lift —
5348    /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
5349    /// external-gateway composite) — inherits this accessor's discipline
5350    /// as the next compounding run migrates its consumers onto the shared
5351    /// reference-return shape, closing the outer-composite altitude on
5352    /// every M3 mesh-slot axis. Named `placement()` to match the storage
5353    /// field's name verbatim and the tatara-lisp author-surface term
5354    /// (`:placement`) the field's own docstring already carries; the
5355    /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
5356    /// vocabulary the slot's docstring already reaches for. Returns
5357    /// `&Placement` (not the owning composite by copy or clone) because
5358    /// every downstream consumer of the placement composite treats it as
5359    /// a read-only per-axis dispatch source — the reference-view is the
5360    /// narrowest borrow that supports every present + roadmapped consumer
5361    /// (per-axis accessor dispatch, serde composite-serialization) without
5362    /// cloning the composite through every consumer's fast path.
5363    #[must_use]
5364    pub fn placement(&self) -> &Placement {
5365        &self.placement
5366    }
5367
5368    /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
5369    /// per-Aplicacao external-gateway composite optional-composite-
5370    /// reference accessor every per-Aplicacao gateway-block reader
5371    /// keys off — returns the author-declared `:entrada` composite
5372    /// verbatim as an `Option<&Entrada>` reference over the same
5373    /// backing storage the raw `self.entrada.as_ref()` field access
5374    /// borrows from, with `None` naming the internal-only mesh shape
5375    /// (the author-omitted `:entrada` slot the K8s Gateway API v1
5376    /// gateway_routes emitter treats as "emit nothing" and the peer
5377    /// `feira app graph` printer treats as "internal-only mesh").
5378    ///
5379    /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
5380    /// external-gateway composite — the load-bearing container of
5381    /// every does-this-Aplicacao-expose-a-public-endpoint axis every
5382    /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
5383    /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
5384    /// hostname axis, §III.4 for the `:para` destination-Servico
5385    /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
5386    /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
5387    /// axis threads through a lifted per-slot accessor on the
5388    /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
5389    /// Gateway-API `Listener.hostname` scalar accessor, the paired
5390    /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
5391    /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
5392    /// backendRefs destination-Servico scalar accessor, the
5393    /// [`Entrada::resolved_paths`] path-fallback resolver, and the
5394    /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
5395    /// scalar accessor. Every downstream consumer that reaches for
5396    /// an entrada axis first passes through this outer accessor onto
5397    /// the composite and then dispatches onto the per-axis accessor
5398    /// — the two-level dispatch means every per-`:entrada` reader
5399    /// now routes through a typed dispatch on the substrate primitive
5400    /// at both altitudes.
5401    ///
5402    /// Prior to this lift the `.entrada` `Option<Entrada>` composite
5403    /// was accessed inline at four production sites — the
5404    /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
5405    /// gate's `if let Some(e) = &self.entrada { … }` traversal head
5406    /// (which drives every per-axis refusal on the composite: the
5407    /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
5408    /// `EntradaMemberMissing` membership lookup against the
5409    /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
5410    /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
5411    /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
5412    /// per-path shape gate on each entry of `e.paths`), the
5413    /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
5414    /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
5415    /// composite-projection seed (which drives the destination-
5416    /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
5417    /// backendRefs port emitter fans on), the
5418    /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
5419    /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
5420    /// early-return seed (which drives the "no `:entrada` ⇒ no
5421    /// external artifacts" partition on the whole-Aplicacao Gateway-
5422    /// API emitter's fan-out), and the `feira app graph` per-
5423    /// Aplicacao print line's `if let Some(e) = &spec.entrada`
5424    /// external-gateway summary emitter (which drives the human-
5425    /// readable `entrada: host → para (paths=…, port=…)` /
5426    /// `entrada: (internal-only mesh)` partition on the typed
5427    /// Aplicacao view) — four open-coded outer-field accesses that
5428    /// expressed no compile-time link back to the typed slot at the
5429    /// [`AplicacaoSpec`] altitude. A future extension of the
5430    /// `:entrada` outer axis to a richer author surface (a
5431    /// multi-`:entrada` list the M4 CR materializer resolves per-CR
5432    /// at admission time so an Aplicacao can expose a public-web +
5433    /// admin-web pair, a per-cluster `:entrada-overrides` slot the
5434    /// MESH-COMPOSITION §V federation roadmap acknowledges so an
5435    /// operator can pin a per-cluster hostname override without
5436    /// re-authoring the `caixa.lisp`, a promotion of the plain
5437    /// `Option<Entrada>` to a richer `{single, multi}` partition once
5438    /// the multi-`:entrada` roadmap lands) would have had to be
5439    /// threaded through all four open-coded copies in lockstep or one
5440    /// consumer would silently disagree with the peers on which
5441    /// entrada composite a given Aplicacao resolves to — the
5442    /// validator's per-axis bracket-dispatch seed reading the raw
5443    /// slot while the peer `gateway_routes` emitter read an
5444    /// operator-resolved slot would silently split the build-time
5445    /// gateway-shape gate from the runtime Gateway + HTTPRoute
5446    /// emission gate, a four-consumer split at the validator, the
5447    /// `port_for_destination` L4-port resolver, the `gateway_routes`
5448    /// emitter, and the `feira app graph` printer far from the
5449    /// source `caixa.lisp` with no field naming the entrada-drift
5450    /// root cause. Lifting the resolution rule to a typed method on
5451    /// the substrate primitive means every downstream consumer of
5452    /// the Aplicacao's per-`:entrada` external-gateway composite
5453    /// surface reaches for exactly one typed dispatch — the
5454    /// resolver's accept-set migrates as a unit on any future axis
5455    /// addition.
5456    ///
5457    /// Third and final `&Composite`-return accessor on the top-level
5458    /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
5459    /// unlifted outer-composite axis on the outer typed composition
5460    /// view, sibling to the seed [`AplicacaoSpec::politicas`]
5461    /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
5462    /// accessor on the per-`:politicas` outer-composite axis and to
5463    /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
5464    /// distribution-composite composite-reference accessor on the
5465    /// per-`:placement` outer-composite axis; extends the outer-
5466    /// composite reference-return discipline the two peers already
5467    /// route through onto the last unlifted per-`AplicacaoSpec`
5468    /// outer-composite axis. The `:entrada` outer-composite axis is
5469    /// the natural pair to the two peer outer-composite axes on the
5470    /// three operationally-symmetric M3 mesh-slot outer composites
5471    /// (`:politicas` carries the how-to-run policy overlay,
5472    /// `:placement` carries the where-to-run distribution composite,
5473    /// `:entrada` carries the who-can-reach-it external-gateway
5474    /// composite — every whole-Aplicacao mesh-artifact emitter reads
5475    /// all three as one unit). Same "one typed dispatch on the
5476    /// substrate primitive, thin projections at each consumer"
5477    /// discipline the peer outer-composite axes already route through.
5478    /// Named `entrada()` to match the storage field's name verbatim
5479    /// and the tatara-lisp author-surface term (`:entrada`) the
5480    /// field's own docstring already carries; the accessor's
5481    /// identity maps onto the canonical MESH-COMPOSITION §III.4
5482    /// vocabulary the slot's docstring already reaches for. Returns
5483    /// `Option<&Entrada>` (not the owning composite by copy or
5484    /// clone) because every downstream consumer of the entrada
5485    /// composite treats it as a read-only per-axis dispatch source
5486    /// — the reference-view is the narrowest borrow that supports
5487    /// every present + roadmapped consumer (per-axis accessor
5488    /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
5489    /// port-fallback projection, early-return partition on the
5490    /// `None` arm) without cloning the composite through every
5491    /// consumer's fast path. The `Option` half of the return-type
5492    /// preserves the load-bearing "author-omitted `:entrada` ⇒
5493    /// internal-only mesh" partition (not a default composite the
5494    /// downstream must reject on emptiness) — the accessor projects
5495    /// the raw `Option<Entrada>` slot's presence bit through the
5496    /// reference-return unchanged.
5497    #[must_use]
5498    pub fn entrada(&self) -> Option<&Entrada> {
5499        self.entrada.as_ref()
5500    }
5501
5502    /// Validate the typed shape:
5503    ///   - `:membros` is non-empty; every entry has a non-empty `:caixa`
5504    ///     and a non-empty `:versao`; no two entries share the same
5505    ///     `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
5506    ///     not a multiset)
5507    ///   - every `:contratos` :de + :para must be in `:membros`
5508    ///   - no `:contratos` edge is a self-edge (`:de == :para`) — a
5509    ///     contract is an inter-Servico edge, so a Servico contracting
5510    ///     with itself is a build error under every WIT shape
5511    ///     (MESH-COMPOSITION §III.1)
5512    ///   - no two `:contratos` entries agree on
5513    ///     `(de, para, wit, endpoint, subject, slot)` — the typed-graph
5514    ///     edges are a set, not a multiset (peer of the `:membros` /
5515    ///     `:placement :clusters` / `:entrada :paths` duplicate gates)
5516    ///   - `:entrada :para` must be in `:membros`
5517    ///   - `:placement Sharded` must declare `:shard-key` (non-empty);
5518    ///     `:placement Replicated`/`SingleNode` must NOT declare
5519    ///     `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
5520    ///     consumes it (MESH-COMPOSITION §II.4), and the typed partition
5521    ///     between strategy and shard-key is symmetric: every validated
5522    ///     `Placement` has `shard_key.is_some()` iff `estrategia ==
5523    ///     Sharded`
5524    ///   - every `:placement` strategy must declare ≥1 `:clusters` entry —
5525    ///     `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
5526    ///     the shard pool (MESH-COMPOSITION §III.1)
5527    ///   - every `:clusters` entry is non-empty and unique
5528    ///   - `:placement :affinity`, when set, is non-empty
5529    ///   - the synchronous-`:contratos` subgraph is acyclic
5530    ///     (MESH-COMPOSITION §III.3)
5531    ///   - every declared `:politicas` value is operationally meaningful
5532    ///     (zero timeout, zero retries, zero breaker thresholds, zero rate
5533    ///     limit are all build errors — MESH-COMPOSITION §V CSE invariants;
5534    ///     omit the field instead to express "no policy on this axis")
5535    pub fn validate(&self) -> Result<(), AplicacaoError> {
5536        self.validate_membros()?;
5537        let names: std::collections::HashSet<&str> =
5538            self.membros().iter().map(Membro::nome).collect();
5539
5540        // Identity key for the typed-edge duplicate gate below: every
5541        // field that distinguishes one contract from another. Two
5542        // entries that agree on all six are *the same edge declared
5543        // twice*, the typed-graph analogue of duplicate `:membros` /
5544        // `:placement :clusters` / `:entrada :paths` entries (which
5545        // are already build errors at this layer). Rejecting it at the
5546        // validate gate closes a renderer-side footgun: caixa-mesh's
5547        // `cilium_network_policies` keys each emitted policy by
5548        // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
5549        // (de, para) and identical payload would land as two K8s
5550        // objects with colliding `metadata.name`, rejected at apply
5551        // time far from the source caixa.lisp.
5552        let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
5553            std::collections::HashSet::new();
5554        for c in self.contratos() {
5555            // Per-axis value-shape gate on every `:contratos` name
5556            // reference, before any graph-membership lookup. Empty +
5557            // DNS-1123-malformed `:de`/`:para` values silently fell
5558            // through to `ContratoMemberMissing` at the lookup arm
5559            // because every `:membros :caixa` is shape-validated
5560            // (3f9d7a0), so the `names` set structurally cannot contain
5561            // an empty / malformed string and the membership-lookup
5562            // diagnostic always misframed the root cause as
5563            // "this caixa is not in `:membros`". The shape gate runs
5564            // ahead of the lookup so structurally-impossible-to-match
5565            // inputs route through the narrower self-locating
5566            // diagnostic, preserving the legitimate "well-shaped
5567            // phantom reference" arm. `:de` runs before `:para` per
5568            // the canonical edge-direction order the existing
5569            // membership lookup, self-edge check, target dispatch,
5570            // and diagnostic strings already use.
5571            // Route the per-`:contratos` per-arm DNS-1123 shape-gate arg
5572            // + the paired [`AplicacaoError::ContratoMemberMissing`]
5573            // diagnostic's `caixa:` carrier through the lifted
5574            // [`WitContract::source`] / [`WitContract::destination`]
5575            // scalar accessors rather than the raw `&c.de` / `&c.para`
5576            // `&String`-borrow arg site + the raw `c.de.clone()` /
5577            // `c.para.clone()` field-access `String`-carry sites — the
5578            // last unlifted per-`:contratos` raw-field-access sites in
5579            // the M3 mesh-slot validator's per-edge per-arm shape-gate
5580            // arg + phantom-name diagnostic wrap-envelope emit surface.
5581            // `c.source()` is byte-identical to `&c.de` (pinned by the
5582            // sibling `wit_contract_source_returns_de_byte_equal_across_permutations`
5583            // + `wit_contract_source_borrows_from_de_storage` accessor
5584            // tests) and `c.destination()` is byte-identical to `&c.para`
5585            // (pinned by the sibling
5586            // `wit_contract_destination_returns_para_byte_equal_across_permutations`
5587            // + `wit_contract_destination_borrows_from_para_storage`
5588            // accessor tests) — so a future rebrand of either underlying
5589            // storage flows through the accessor's one body without a
5590            // coordinated per-consumer rewrite across the M3 mesh
5591            // validator's per-edge shape-gate + phantom-name refusal
5592            // arms. Peer of the sibling per-`:contratos` self-loop
5593            // arm's `.source().to_string()` / `.world_ref().to_string()`
5594            // `String`-carry sites the earlier convergence lifted onto
5595            // the same accessor pair.
5596            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
5597            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
5598            if !names.contains(c.source()) {
5599                return Err(AplicacaoError::ContratoMemberMissing {
5600                    caixa: c.source().to_string(),
5601                });
5602            }
5603            if !names.contains(c.destination()) {
5604                return Err(AplicacaoError::ContratoMemberMissing {
5605                    caixa: c.destination().to_string(),
5606                });
5607            }
5608            // A `:contratos` entry is an *inter*-Servico contract
5609            // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
5610            // typed edge between two distinct graph nodes. An edge whose
5611            // `:de` equals its `:para` is a Servico contracting with
5612            // itself — a degenerate edge under every WIT shape. The
5613            // synchronous shapes were caught only incidentally, and with
5614            // a misleading diagnostic: `detect_sync_cycles` reported
5615            // `cart → cart` as a `ContratoCycle` whose path is
5616            // `["cart", "cart"]` — framing a self-edge as a multi-node
5617            // deadlock. The pub-sub shape slipped through entirely
5618            // (`detect_sync_cycles` excludes `WitTarget::PubSub`, so a
5619            // `nats:pub-sub` edge from a member to itself silently
5620            // validated, then rendered a `CiliumNetworkPolicy` whose
5621            // endpointSelector and fromEndpoints both name the same
5622            // program — a self-allow rule that is a no-op, since
5623            // intra-pod traffic never traverses the mesh). A self-edge's
5624            // runtime meaning is an in-process call, which doesn't go
5625            // through the mesh at all, so no `:contratos` edge can carry
5626            // it. Firing the gate before the `:wit`/`target()` shape
5627            // checks means the structural "this edge can't exist" error
5628            // precedes the narrower payload-shape diagnostics, and shape-
5629            // agnostically covers all four `WitTarget` arms (HTTP / Store
5630            // / Capability / PubSub) at one point — closing the pub-sub
5631            // hole and replacing the misleading cycle diagnostic in one
5632            // gate. Peer of the duplicate-`:contratos` / duplicate-
5633            // `:membros` set gates: both reject a structurally
5634            // ill-formed graph at the typed surface, before the renderer
5635            // emits a K8s object that fails or no-ops far from the source
5636            // caixa.lisp.
5637            // Route the per-`:contratos` structural self-edge probe
5638            // through the lifted [`WitContract::is_self_loop`] typed
5639            // predicate rather than the raw `c.de == c.para` field-
5640            // equality check — the one production consumer of the per-
5641            // `:contratos` caller-equals-callee endpoint-equality axis
5642            // now keys off exactly one typed dispatch on the substrate
5643            // primitive, so any future rebrand of the axis (an M4-typed-
5644            // caller enum whose identity comparison rule the predicate
5645            // could route through, a per-cluster caller/callee-alias
5646            // table the M4 CR materializer resolves per-CR before the
5647            // equality probe) migrates as a single caixa-core edit
5648            // rather than a coordinated rewrite of the gate + every
5649            // downstream self-edge consumer. Peer of the sibling
5650            // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
5651            // [`WitContract::is_store`] shape-predicate routing on the
5652            // `:wit` world-ref axis, extended onto the per-edge
5653            // endpoint-equality axis.
5654            //
5655            // Route the paired [`AplicacaoError::ContratoSelfLoop`]
5656            // diagnostic's `caixa:` / `wit:` carriers through the
5657            // lifted [`WitContract::source`] / [`WitContract::world_ref`]
5658            // scalar accessors rather than the raw `c.de.clone()` /
5659            // `c.wit.clone()` field-access `String`-carry sites — the
5660            // last unlifted per-`:contratos` raw-field-access
5661            // `.clone()` sites in the M3 mesh-slot validator's self-
5662            // edge refusal arm. `.source().to_string()` is byte-
5663            // identical to `.de.clone()` (pinned by the sibling
5664            // `source_returns_de_byte_equal_across_permutations` accessor
5665            // test), and `.world_ref().to_string()` is byte-identical
5666            // to `.wit.clone()` (pinned by the sibling
5667            // `world_ref_returns_wit_byte_equal_across_permutations`
5668            // accessor test) — so a future rebrand of either underlying
5669            // storage flows through the accessor's one body without a
5670            // coordinated per-consumer rewrite across the M3 mesh
5671            // validator.
5672            if c.is_self_loop() {
5673                return Err(AplicacaoError::ContratoSelfLoop {
5674                    caixa: c.source().to_string(),
5675                    wit: c.world_ref().to_string(),
5676                });
5677            }
5678            if c.world_ref().is_empty() {
5679                let (de, para) = c.edge_pair();
5680                return Err(AplicacaoError::EmptyWit { de, para });
5681            }
5682            // Shape ↔ target consistency — surfaces "HTTP wit without
5683            // :endpoint", "NATS wit with :endpoint set", etc. as named
5684            // build errors instead of silent renderer drops. Threaded
5685            // through the duplicate-edge diagnostic below (via
5686            // [`WitTarget::label`]) so the "which typed target arm did
5687            // the duplicate carry" question is answered by the typed
5688            // enum's variant discriminator, not by re-probing the raw
5689            // `Option<String>` payload fields.
5690            let target_view = c.target()?;
5691            // Contract identity: (de, para, wit, endpoint, subject, slot).
5692            // Two contracts that match on all six are the same typed edge
5693            // declared twice — author error, not a legitimate variant of
5694            // "same caller-callee pair, different payload" (e.g.
5695            // cart→catalog at /products vs /search), which keeps distinct
5696            // identity keys via the differing endpoint payloads.
5697            let key = (
5698                c.source(),
5699                c.destination(),
5700                c.world_ref(),
5701                // Route the HTTP-arm payload-carrier scalar through the
5702                // lifted [`WitContract::endpoint`] accessor rather than
5703                // the raw `c.endpoint.as_deref()` field access — the two
5704                // production consumers of the per-`:contratos :endpoint`
5705                // HTTP-shaped payload-carrier scalar (the peer
5706                // [`WitContract::target`] Http-arm payload extraction,
5707                // this [`ContratoIdentity`] dedup-key HTTP arm) now key
5708                // off exactly one typed dispatch on the substrate
5709                // primitive, closing the second of six unlifted
5710                // per-`:contratos` `Option<String>`-carry sites and
5711                // pinning the peer per-`:contratos` scalar-accessor
5712                // discipline ([`WitContract::source`] /
5713                // [`WitContract::destination`] / [`WitContract::world_ref`])
5714                // onto the first per-`:contratos` payload-carrier arm.
5715                c.endpoint(),
5716                // Route the pub-sub-arm payload-carrier scalar through
5717                // the lifted [`WitContract::subject`] accessor rather
5718                // than the raw `c.subject.as_deref()` field access —
5719                // the two production consumers of the per-`:contratos
5720                // :subject` pub-sub-shaped payload-carrier scalar (the
5721                // peer [`WitContract::target`] PubSub-arm payload
5722                // extraction, this [`ContratoIdentity`] dedup-key
5723                // pub-sub arm) now key off exactly one typed dispatch
5724                // on the substrate primitive, closing the third of six
5725                // unlifted per-`:contratos` `Option<String>`-carry
5726                // sites and extending the peer per-`:contratos`
5727                // HTTP-arm [`WitContract::endpoint`] (7020470) lift
5728                // onto the pub-sub arm. Leaves the [`WitContract::slot`]
5729                // key/value-store arm as the last unlifted per-
5730                // `:contratos` `Option<String>` axis.
5731                c.subject(),
5732                // Route the store-arm payload-carrier scalar through
5733                // the lifted [`WitContract::slot`] accessor rather
5734                // than the raw `c.slot.as_deref()` field access — the
5735                // two production consumers of the per-`:contratos
5736                // :slot` key/value-store-shaped payload-carrier scalar
5737                // (the peer [`WitContract::target`] Store-arm payload
5738                // extraction, this [`ContratoIdentity`] dedup-key
5739                // store arm) now key off exactly one typed dispatch
5740                // on the substrate primitive, closing the last of six
5741                // unlifted per-`:contratos` `Option<String>`-carry
5742                // sites and completing the peer per-`:contratos`
5743                // HTTP-arm [`WitContract::endpoint`] (7020470) /
5744                // pub-sub-arm [`WitContract::subject`] (90de675) lift
5745                // family onto the store arm.
5746                c.slot(),
5747            );
5748            crate::render::insert_first_seen(&mut seen_contracts, key, || {
5749                // Route the per-`:contratos` duplicate-gate diagnostic's
5750                // `(de, para, wit)` triple through the lifted
5751                // [`WitContract::edge_triple`] typed accessor rather
5752                // than pairing `edge_pair()` for the `(de, para)` prefix
5753                // with a raw `c.wit.clone()` for the `wit:` tail — the
5754                // paired-with-raw-field-access shape was the last
5755                // per-`:contratos` diagnostic constructor bypassing the
5756                // substrate-primitive composite projection, sibling to
5757                // the eight [`AplicacaoError::Contrato*`] triple-
5758                // carrying constructors [`WitContract::target`]'s edge
5759                // closure feeds through the same accessor.
5760                let (de, para, wit) = c.edge_triple();
5761                AplicacaoError::ContratoDuplicate {
5762                    de,
5763                    para,
5764                    wit,
5765                    target: target_view.label(),
5766                }
5767            })?;
5768        }
5769
5770        // Cycles in the synchronous-edge subgraph are build errors
5771        // (MESH-COMPOSITION §III.3). Pub-sub edges are excluded — they
5772        // are "acyclic by construction" because the publisher fires
5773        // and forgets, so no caller blocks on a downstream that loops
5774        // back to it.
5775        self.detect_sync_cycles()?;
5776
5777        if let Some(e) = self.entrada() {
5778            // Route the per-`:entrada` composite-reference read
5779            // through the lifted [`AplicacaoSpec::entrada`] accessor
5780            // rather than the raw `&self.entrada` field access — the
5781            // shape-and-membership gate's traversal head is now the
5782            // canonical read-side surface every per-Aplicacao entrada
5783            // consumer routes through, closing the fourth of four
5784            // open-coded outer-field accesses on the per-`:entrada`
5785            // outer-composite axis.
5786            //
5787            // Shape gate on `:entrada :para` runs ahead of the
5788            // membership lookup. Every `:membros :caixa` past
5789            // `validate_membro_caixa` is a valid DNS-1123 label
5790            // (3f9d7a0), so the `names` set structurally cannot
5791            // contain an empty / malformed string and the membership-
5792            // lookup diagnostic always misframed the root cause as
5793            // "this caixa is not in `:membros`". The shape gate
5794            // routes structurally-impossible-to-match inputs through
5795            // the narrower self-locating diagnostic, preserving the
5796            // legitimate "well-shaped phantom reference" arm — the
5797            // same trajectory the peer `:membros :caixa` (3f9d7a0),
5798            // `:placement :clusters` (6c8c00b), and `:contratos :de`
5799            // / `:para` (8d5af6b) axes already follow. This closes
5800            // the fourth and last Aplicacao-level Servico-name
5801            // reference axis on the canonical DNS-1123 floor.
5802            // Route the per-`:entrada :para` byte-string reads through
5803            // the lifted [`Entrada::destination`] accessor rather than
5804            // the raw `e.para` field access — the three
5805            // per-`AplicacaoSpec::validate` `:entrada :para` consumers
5806            // (shape-gate `validate_entrada_para` arg, membership
5807            // lookup, `EntradaMemberMissing` diagnostic carry) now key
5808            // off exactly one typed dispatch on the substrate
5809            // primitive, closing the last unlifted per-`:entrada :para`
5810            // raw-field-access axis on the M3 mesh-slot validator.
5811            // The `.destination().to_string()` at the diagnostic site
5812            // is byte-identical to `.para.clone()` — pinned by the
5813            // sibling `destination_returns_entrada_para_byte_equal` +
5814            // `destination_borrows_from_entrada_para_storage` accessor
5815            // tests — so a future rebrand of the underlying `:para`
5816            // storage (a lift from `String` to a typed
5817            // `ServicoName(String)` newtype, a per-Aplicacao interning
5818            // arena the M4 CR materializer authors, a
5819            // `smol_str::SmolStr` inline-buffer swap) flows through
5820            // the accessor's one body without a coordinated
5821            // per-consumer rewrite across the M3 mesh validator.
5822            validate_entrada_para(e.destination())?;
5823            if !names.contains(e.destination()) {
5824                return Err(AplicacaoError::EntradaMemberMissing {
5825                    para: e.destination().to_string(),
5826                });
5827            }
5828            // Route the per-`:entrada :host` byte-string reads through
5829            // the lifted [`Entrada::hostname`] accessor rather than
5830            // the raw `e.host` field access — the emptiness gate and
5831            // the shape-gate `validate_entrada_host` arg now key off
5832            // exactly one typed dispatch on the substrate primitive,
5833            // closing the last unlifted per-`:entrada :host` raw-
5834            // field-access axis on the M3 mesh-slot validator. Peer
5835            // of the sibling per-`:entrada :para` convergence above
5836            // and pinned by the existing
5837            // `hostname_returns_entrada_host_byte_equal` +
5838            // `hostnames_returns_singleton_of_hostname_accessor`
5839            // accessor tests, so any future
5840            // Gateway-API-shaped host renormalization (a wildcard-
5841            // label lift, a trailing-`.` FQDN substitution, an IDNA
5842            // Punycode round-trip the SNI fan-out overlay authors)
5843            // flows through the accessor's one body without a
5844            // coordinated per-consumer rewrite across the M3 mesh
5845            // validator.
5846            if e.hostname().is_empty() {
5847                return Err(AplicacaoError::EmptyEntradaHost);
5848            }
5849            // The `:host` lands verbatim as a K8s Gateway API v1
5850            // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
5851            // both apiserver-validated against the same restrictive
5852            // pattern: lowercase RFC 1123 DNS subdomain, optional
5853            // single leading wildcard label (`*.`), max length 253,
5854            // per-label max length 63, no IP literals, no scheme,
5855            // no port. Until this gate landed `validate()` only
5856            // refused the empty string (`EmptyEntradaHost`); a
5857            // structurally invalid hostname (`"https://example.com"`,
5858            // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
5859            // `"_underscored.example.com"`, `"FOO.example.com"`,
5860            // `"checkout.quero.cloud."`) silently passed validate
5861            // and the apiserver `field is invalid` error surfaced at
5862            // `kubectl apply` time, far from the source caixa.lisp.
5863            // Lifting the gate to caixa-build time mirrors the
5864            // `:entrada :paths` value-shape trajectory (eb3456d) and
5865            // closes the last unstructured `:entrada` axis.
5866            validate_entrada_host(e.hostname())?;
5867            // Structural-floor gate on `:entrada :port`: every
5868            // validated `Entrada::port` past this gate lies in
5869            // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
5870            // type-inferred ceiling closes the top edge, so no companion
5871            // upper-cap arm is needed here — unlike the peer capped-
5872            // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
5873            // `require_positive_bounded_u32` bracket covers both edges).
5874            // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
5875            // accept-set-floor const rather than the prior inline
5876            // `if e.port == 0` byte-check so a future rebrand of the
5877            // accept-set floor (a hypothetical unprivileged-only
5878            // migration lifting the floor to `1024`, a per-cluster
5879            // scoping the operator pins through a future
5880            // `:placement :port-floor` slot as the M4 typed-slot
5881            // trajectory adds it, the future
5882            // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5883            // per-Aplicacao gateway resolver reaching for the same
5884            // floor) is a one-line edit on the canonical
5885            // [`SERVICO_PORT_MIN`] declaration, not a coordinated
5886            // rewrite across the emit site + the pin test + every
5887            // future per-target renderer the substrate adds.
5888            if e.port() < SERVICO_PORT_MIN {
5889                return Err(AplicacaoError::EntradaPortZero);
5890            }
5891            // Each `:entrada :paths` entry becomes a K8s Gateway API
5892            // HTTPRoute `matches[].path.value`. The Gateway API rejects
5893            // values that don't start with `/` for `type: PathPrefix`,
5894            // and an empty value is meaningless. Surface those as build
5895            // errors (MESH-COMPOSITION §III.3) rather than apply-time
5896            // failures. Empty `:paths` itself is fine — caixa-mesh
5897            // falls back to a single `/` catch-all.
5898            let mut seen = std::collections::HashSet::new();
5899            // Route the per-entry value-shape gate's traversal head
5900            // through the lifted [`Entrada::paths`] slice accessor
5901            // rather than the raw `&e.paths` field access — the
5902            // per-Aplicacao `:entrada :paths` validate loop now keys
5903            // off the canonical raw-slot surface every downstream
5904            // per-`:entrada` path-list consumer (the sibling
5905            // [`Entrada::resolved_paths`] fallback-applying resolver
5906            // internal reads, `feira app graph`'s per-Aplicacao entrada
5907            // summary line's `{:?}` Debug print) routes through, so any
5908            // future rebrand on the typed slot's raw-slot reader lands
5909            // at exactly one place. Same convergence discipline as the
5910            // sibling [`Placement::clusters`] (a6e18d7) reader-site
5911            // convergences on the peer M3 mesh-slot `Vec<String>`-carry
5912            // axis.
5913            for p in e.paths() {
5914                if p.is_empty() {
5915                    return Err(AplicacaoError::EntradaPathEmpty);
5916                }
5917                if !p.starts_with('/') {
5918                    return Err(AplicacaoError::EntradaPathNotAbsolute { path: p.clone() });
5919                }
5920                // Per-entry value-shape gate: the path lands verbatim
5921                // as a K8s Gateway API HTTPRoute `matches[].path.value`
5922                // (caixa-mesh/src/lib.rs:498), apiserver-validated
5923                // against `maxLength: 1024` + the Gateway API webhook's
5924                // path-grammar rules (no `//`, no `/./`, no `/../`, no
5925                // query/fragment separators, no whitespace, no control
5926                // characters, no non-ASCII bytes). Until this gate
5927                // landed `validate` only refused the empty string and
5928                // missing-leading-slash (eb3456d); a structurally
5929                // invalid path (`"/api?q=1"`, `"/api#frag"`,
5930                // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
5931                // 1025-byte URL-shaped slug) silently passed validate
5932                // and the failure surfaced at `kubectl apply` time as
5933                // a Gateway API webhook rejection, far from the source
5934                // caixa.lisp, with no field naming the offending
5935                // `:paths` entry. Lifting the gate to caixa-build time
5936                // mirrors the `:entrada :host` value-shape trajectory
5937                // (c7d05ec) on the sibling axis — every author surface
5938                // that emits a Gateway API field now matches the
5939                // apiserver's accepted set at validate time.
5940                validate_entrada_path(p)?;
5941                crate::render::insert_first_seen(&mut seen, p.as_str(), || {
5942                    AplicacaoError::EntradaPathDuplicate { path: p.clone() }
5943                })?;
5944            }
5945        }
5946
5947        self.validate_placement()?;
5948
5949        self.validate_politicas()?;
5950
5951        Ok(())
5952    }
5953
5954    /// Reject `:membros` values that are operationally meaningless. The
5955    /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
5956    /// every entry names a Servico that participates in the Aplicacao,
5957    /// and the rendered programs.yaml fan-out emits one entry per
5958    /// `:membros`. Three authoring footguns are closed here:
5959    ///
5960    ///   - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
5961    ///     a `programs:` entry whose `name:` is the empty string, which
5962    ///     downstream `lareira-fleet-programs` rejects at template time
5963    ///     with a non-localized error;
5964    ///   - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
5965    ///     an empty semver constraint, so the failure surfaces far from
5966    ///     the source caixa.lisp;
5967    ///   - duplicate `:caixa` names — two entries with the same name
5968    ///     produce duplicate programs.yaml entries (one silently
5969    ///     overwrites the other in the cluster's HelmRelease values), and
5970    ///     contract membership lookups against `:contratos` collapse the
5971    ///     two onto one node, masking authoring mistakes.
5972    ///
5973    /// Same value-shape discipline as `:placement :clusters` (where empty
5974    /// + duplicate cluster names are rejected) and `:entrada :paths`
5975    /// (where empty + duplicate path entries are rejected). Lifting these
5976    /// invariants to the typed surface mirrors the MESH-COMPOSITION
5977    /// §III.3 promise that the `:membros` set — the load-bearing identity
5978    /// of the application graph — is well-formed by construction.
5979    fn validate_membros(&self) -> Result<(), AplicacaoError> {
5980        if self.membros().is_empty() {
5981            return Err(AplicacaoError::NoMembros);
5982        }
5983        let mut seen = std::collections::HashSet::new();
5984        for m in self.membros() {
5985            // Route the `MembroCaixaEmpty` refusal-arm's per-member
5986            // empty-`:caixa` shape-gate through the typed
5987            // [`Membro::nome`] accessor rather than the raw `.caixa`
5988            // field access — the last un-lifted `.caixa` production-
5989            // code read site on the per-`:membros` member-caixa `:nome`
5990            // axis, sibling to the six caixa-core validator read sites
5991            // (member-set collector, per-member value-shape gate,
5992            // duplicate dedup key, cycle-detector adjacency-map seed,
5993            // self-loop gate) the 4a32abf lift already routed through
5994            // the accessor and the peer 54bf2f3 caixa-mesh emit-side
5995            // per-`programs[]` entry-`name:` `String`-carry converge.
5996            // Prior to this converge the `MembroCaixaEmpty` refusal
5997            // arm was the solitary consumer bypassing the typed
5998            // dispatch — the same-loop iteration's very next call
5999            // `validate_membro_caixa(m.nome())` already routed through
6000            // the accessor, so an author landing an empty-`:caixa`
6001            // entry hit the accessor on the shape-gate line but
6002            // bypassed it on the emptiness line one line above. A
6003            // future extension of the `:membros :caixa` axis to a
6004            // richer author surface (a per-cluster alias table pinned
6005            // through a future `:placement`-scoped slot, a namespace-
6006            // qualified rewrite the M4 CR materializer applies per-CR,
6007            // a per-member overlay from the future `:membros
6008            // :nome-suffix` slot MESH-COMPOSITION §III.2 acknowledges)
6009            // that lands on the accessor would silently disagree
6010            // between the emptiness gate and every peer consumer —
6011            // an author-declared `:caixa "checkout"` value the
6012            // accessor rewrote to `""` under a future alias arm would
6013            // pass the raw `.is_empty()` gate here while the peer
6014            // `validate_membro_caixa(m.nome())` call one line below
6015            // (and every downstream emit-side consumer routing through
6016            // the accessor) tripped on the empty-value shape far from
6017            // this diagnostic. Pinned by the drift-detection test
6018            // [`validate_membros_empty_gate_routes_through_nome_accessor`]
6019            // below.
6020            if m.nome().is_empty() {
6021                return Err(AplicacaoError::MembroCaixaEmpty);
6022            }
6023            // Every emitted cluster artifact's `metadata.name` derives
6024            // from a `:membros :caixa` value verbatim — the rendered
6025            // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
6026            // the [`crate::LABEL_PROGRAM`] label value on every CNP
6027            // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
6028            // 272), the composed `CiliumNetworkPolicy` `metadata.name`
6029            // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
6030            // `metadata.name` when the member is the `:entrada :para`
6031            // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
6032            // schema enforces the DNS-1123 label rule on admission;
6033            // a structurally invalid member name (`"Cart"`, `"my_cart"`,
6034            // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
6035            // mistaken-identity slug) silently passes the prior empty-/
6036            // duplicate-only gate and the failure surfaces at `kubectl
6037            // apply` time as a `metadata.name: Invalid value` rejection,
6038            // far from the source caixa.lisp, with no field naming the
6039            // offending `:membros` entry. Lifting the gate to caixa-build
6040            // time mirrors the `:entrada :host` value-shape trajectory
6041            // (c7d05ec) on the peer axis — every author surface that
6042            // emits a K8s name now matches the apiserver's accepted set
6043            // at validate time.
6044            validate_membro_caixa(m.nome())?;
6045            // The author surface for `:versao` is the same Cargo-shaped
6046            // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
6047            // `"*"`) every `:deps` entry carries — and the lacre pipeline
6048            // resolves both axes through the same
6049            // [`crate::version::parse_requirement`] entry-point. The
6050            // shared [`crate::render::require_valid_versao_requirement`]
6051            // helper brackets the empty-first + parse cascade both peer
6052            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
6053            // [`crate::SupervisorSpec::validate`] on `:children :versao`)
6054            // route through, so drift between the three axes' accepted
6055            // requirement sets is structurally impossible and the parse-
6056            // side no-op the empty-first arm closes (semver's empty
6057            // parse yields an implicit `*`) lives in exactly one
6058            // predicate.
6059            crate::render::require_valid_versao_requirement(
6060                m.versao_requirement(),
6061                || AplicacaoError::MembroVersaoEmpty {
6062                    caixa: m.nome().to_string(),
6063                },
6064                |reason| AplicacaoError::MembroVersaoInvalid {
6065                    caixa: m.nome().to_string(),
6066                    versao: m.versao_requirement().to_string(),
6067                    reason,
6068                },
6069            )?;
6070            crate::render::insert_first_seen(&mut seen, m.nome(), || {
6071                AplicacaoError::MembroDuplicate {
6072                    caixa: m.nome().to_string(),
6073                }
6074            })?;
6075        }
6076        Ok(())
6077    }
6078
6079    /// Reject `:placement` values that are operationally meaningless or
6080    /// internally contradictory. Each strategy variant has the same
6081    /// invariants on `:clusters` (non-empty list, non-empty unique
6082    /// entries) — the §III.1 author surface is uniform on this axis,
6083    /// even though the *meaning* of the list differs by strategy
6084    /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
6085    /// shard pool).
6086    ///
6087    /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
6088    /// are the same authoring footgun closed for `:politicas` zero
6089    /// values and `:entrada` empty paths: the field is *declared* but
6090    /// carries no meaning, so downstream renderers either skip it
6091    /// silently (cluster-fanout drops the empty entry, no diagnostic)
6092    /// or apply it literally and fail at admission time. Lifting both
6093    /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
6094    /// violation is a build error" promise.
6095    ///
6096    /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
6097    /// is required exactly when `:estrategia Sharded` (hash-keyed
6098    /// distribution, Akka cluster-sharding convention, §II.4) and
6099    /// refused on `:estrategia Replicated`/`SingleNode` (where no
6100    /// hash-keyed routing axis consumes it). The partition closes the
6101    /// "I think I configured sharding" footgun where an author writes
6102    /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
6103    /// the typed slot's value silently vanishes at the renderer layer
6104    /// — every validated `Placement` past this call satisfies
6105    /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
6106    fn validate_placement(&self) -> Result<(), AplicacaoError> {
6107        // Every strategy needs at least one named cluster: `Replicated`
6108        // and `SingleNode` use the list as hosting/takeover candidates
6109        // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
6110        // §II.1), while `Sharded` uses it as the shard pool
6111        // (Akka cluster-sharding convention — §II.4). An empty list is
6112        // meaningless under any of the three.
6113        //
6114        // Route the paired pre-flight `.is_empty()` refusal probe and
6115        // the per-cluster validate loop's traversal head through the
6116        // lifted [`Placement::clusters`] slice-return accessor rather
6117        // than the raw `self.placement.clusters` field access — the
6118        // two production consumers of the per-`:placement` cluster-
6119        // pool `Vec`-carry now key off exactly one typed dispatch on
6120        // the substrate primitive, so any future rebrand on the axis
6121        // (a per-tenant cluster-pool overlay the operator pins through
6122        // a future `:placement :clusters-overrides` slot, a per-
6123        // Aplicacao dynamic cluster-pool derivation the future M5
6124        // adaptive-placement engine computes from `:affinity` weights)
6125        // migrates as a single caixa-core edit rather than a
6126        // coordinated rewrite of the paired arms — sibling of the
6127        // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
6128        // arm migration on the per-`:supervisor` static-child-list
6129        // `Vec`-carry axis.
6130        //
6131        // Route the per-`:placement` outer-composite reference read
6132        // through the lifted [`AplicacaoSpec::placement`] outer accessor
6133        // rather than the raw `&self.placement` field access — the
6134        // per-axis bracket-dispatch fan-out below (`p.clusters()`,
6135        // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
6136        // axis-level lifted accessor family) now routes through the
6137        // substrate-primitive typed dispatch at the outer composition
6138        // altitude, the same shape the peer caixa-mesh
6139        // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
6140        // and the sibling `feira app graph` per-Aplicacao print line
6141        // now key off after this accessor lift.
6142        let p = self.placement();
6143        if p.clusters().is_empty() {
6144            return Err(AplicacaoError::PlacementWithoutClusters {
6145                estrategia: p.estrategia(),
6146            });
6147        }
6148        let mut seen = std::collections::HashSet::new();
6149        for c in p.clusters() {
6150            // Per-entry value-shape gate: the cluster name lands in
6151            // every K8s context / `lareira-fleet-programs` aggregator
6152            // filter / future M4 CR materializer's per-cluster axis
6153            // a validated `:clusters` entry passes through, each
6154            // enforcing the DNS-1123 label rule on admission. Same
6155            // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
6156            // on the peer name axis — both axes' validated values
6157            // are guaranteed-accepted by the apiserver without
6158            // re-validation at any downstream renderer or admission
6159            // layer.
6160            validate_placement_cluster(c)?;
6161            crate::render::insert_first_seen(&mut seen, c.as_str(), || {
6162                AplicacaoError::PlacementClusterDuplicate { cluster: c.clone() }
6163            })?;
6164        }
6165        // Route the per-`:placement :affinity` per-hint value-shape
6166        // gate through the typed [`Placement::affinity`] accessor rather
6167        // than the raw `&self.placement.affinity` field access — the
6168        // sole open-coded field-access site on the per-`:placement`
6169        // M3-Adaptive-compression-hint axis the accessor lift now owns.
6170        // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
6171        // the accessor's `Option<&str>` return type;
6172        // [`validate_placement_affinity`]'s `&str` parameter accepts
6173        // the narrower borrow without a re-allocation, so the routing
6174        // change is byte-for-byte in the pass arm and remains
6175        // byte-for-byte in every failure diagnostic
6176        // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
6177        // String` field is populated inside
6178        // [`validate_placement_affinity`] via the peer `.to_string()`
6179        // path on the same borrowed slice). Peer of the sibling
6180        // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
6181        // routing through [`Placement::shard_key`] at the caixa-core
6182        // site above — extends the "read `:placement` optional-scalars
6183        // through the typed accessor" discipline to the second
6184        // `Option<String>`-shape slot on the M3 mesh-slot family.
6185        //
6186        // Per-hint value-shape gate: the `:affinity` value lands
6187        // verbatim in the M3 Adaptive compression overlay
6188        // (caixa-mesh's `placement.affinity` emission) and every
6189        // future M4 placement-engine routing axis keying off the
6190        // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
6191        // selector — each enforces the DNS-1123 label rule on
6192        // admission. Same typed-shape trajectory as `:placement
6193        // :clusters` (6c8c00b) on the sibling slot and the four
6194        // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
6195        // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
6196        // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
6197        // on the Aplicacao surface to land on the canonical
6198        // [`crate::render::is_dns_1123_label`] floor.
6199        if let Some(a) = p.affinity() {
6200            validate_placement_affinity(a)?;
6201        }
6202        match p.estrategia() {
6203            // Route the `Sharded`-arm shape-gate cascade through the
6204            // typed [`Placement::shard_key`] accessor rather than the
6205            // raw `&self.placement.shard_key` field access — one of the
6206            // two open-coded field-access sites on the per-`:placement`
6207            // Akka-cluster-sharding-key axis the accessor lift now
6208            // owns. The `Some(k)`-bound `k` narrows from `&String` to
6209            // `&str` under the accessor's `Option<&str>` return type;
6210            // `str::is_empty` and [`validate_placement_shard_key`]'s
6211            // `&str` parameter both accept the narrower borrow without
6212            // a re-allocation.
6213            PlacementStrategy::Sharded => match p.shard_key() {
6214                None => return Err(AplicacaoError::ShardedWithoutKey),
6215                Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
6216                // Per-axis value-shape gate on the Akka-cluster-sharding
6217                // `:shard-key` extractor expression. The shape gate runs
6218                // after the more self-locating `ShardedKeyEmpty` arm so
6219                // a `:shard-key ""` surfaces the narrower empty
6220                // diagnostic first; every non-empty `:shard-key` past
6221                // this call is guaranteed to be a printable-ASCII
6222                // single-token reference the future M4 Akka-style
6223                // cluster-sharding reconciler can hash without
6224                // re-validating at the runtime layer. Mirrors the
6225                // payload-axis shape gates on the peer `:contratos`
6226                // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
6227                // 63e18a0 / c4213a4) — each lifts the runtime parser's
6228                // intersection-floor to a caixa-build-time gate.
6229                Some(k) => validate_placement_shard_key(k)?,
6230            },
6231            // `:shard-key` is the Akka-cluster-sharding axis
6232            // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
6233            // across the cluster pool. `Replicated` (active-active across
6234            // every named cluster) and `SingleNode` (Erlang/OTP
6235            // distributed-app takeover/failover, §II.1) have no hash-keyed
6236            // routing axis to consume the slot; downstream renderers
6237            // (caixa-mesh's `placement.shardKey` overlay at
6238            // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
6239            // sharding reconciler) ignore `:shard-key` outside the
6240            // `Sharded` arm by construction. Until this gate landed an
6241            // author who wrote `:placement (:estrategia Replicated
6242            // :shard-key "tenantId")` (an off-by-one strategy typo, a
6243            // copy-paste from a Sharded sibling caixa, the "I think I
6244            // configured sharding" footgun) silently passed validate and
6245            // the typed slot's value vanished at the renderer layer with
6246            // no diagnostic — the canonical "declared-but-inert" footgun
6247            // the empty-:affinity / empty-shard-key / zero-:politicas /
6248            // empty-:contratos-target gates already close on every other
6249            // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
6250            // Lifting the rejection to a build-time gate closes the
6251            // Sharded ↔ non-Sharded partition over the typed
6252            // `:placement` slot: every validated `Placement` past this
6253            // call has `shard_key.is_some()` iff `estrategia ==
6254            // Sharded`, structurally — the future Akka reconciler can
6255            // reach for `placement.shard_key` knowing it's `Some` exactly
6256            // when the strategy consumes it, without re-deriving the
6257            // partition from inline strategy probes.
6258            PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
6259                // Route the non-`Sharded`-arm declared-but-inert refusal
6260                // through the typed [`Placement::shard_key`] accessor —
6261                // the second of the two open-coded field-access sites the
6262                // accessor lift now owns. The `Some(k)`-bound `k` narrows
6263                // from `&String` to `&str`; the `AplicacaoError::
6264                // ShardKeyOnNonSharded { shard_key: String }` diagnostic
6265                // materializes the owned `String` via `k.to_string()`
6266                // (peer to the sibling per-Membro `String`-carry sites
6267                // 4127bb6 routed through `m.nome().to_string()` /
6268                // `m.versao_requirement().to_string()`), so the whole
6269                // `Sharded` ↔ non-`Sharded` partition on the
6270                // `:shard-key` axis now flows through the same typed
6271                // dispatch as the sibling `Sharded`-arm shape gate.
6272                if let Some(k) = p.shard_key() {
6273                    return Err(AplicacaoError::ShardKeyOnNonSharded {
6274                        estrategia: p.estrategia(),
6275                        shard_key: k.to_string(),
6276                    });
6277                }
6278            }
6279        }
6280        Ok(())
6281    }
6282
6283    /// Reject `:politicas` values that are operationally meaningless.
6284    /// Each axis is optional — omitting it expresses "no policy on this
6285    /// axis". Carrying a *zero* value for a declared axis is the bug
6286    /// this function rejects: zero is either
6287    ///
6288    ///   - re-interpreted as "infinite" by downstream proxies (Envoy's
6289    ///     `RouteAction.timeout = 0s` disables the timeout entirely),
6290    ///     directly contradicting MESH-COMPOSITION §V CSE invariant
6291    ///     "every Aplicacao declares :politicas :timeout (no infinite
6292    ///     blocking)", or
6293    ///   - a renderer footgun (a 0-failure circuit breaker trips on the
6294    ///     first call; a 0-rate rate-limit denies every request).
6295    ///
6296    /// Lifting these "0 means the opposite of what you think" idioms to
6297    /// the typed Aplicacao surface as build errors mirrors the §III.3
6298    /// promise that contract drift, capability leaks, and cycles are all
6299    /// build errors — not runtime surprises.
6300    fn validate_politicas(&self) -> Result<(), AplicacaoError> {
6301        // Route the per-`:politicas` composite-reference read through
6302        // the lifted [`AplicacaoSpec::politicas`] outer accessor rather
6303        // than the raw `&self.politicas` field access — the per-axis
6304        // bracket-dispatch fan-out below (`p.timeout()`, `p.retries()`,
6305        // `p.circuit_breaker()`, `p.rate_limit()`) now routes through
6306        // the substrate-primitive typed dispatch at the outer
6307        // composition altitude AND at every per-axis altitude, matching
6308        // the peer caixa-mesh CNP mTLS-overlay + HTTPRoute
6309        // timeout/retry-overlay emitters that already key off the same
6310        // per-axis accessor family. The four-axis fan-out is now
6311        // uniformly `p.<axis>()` — the last two raw `p.timeout` /
6312        // `p.retries` field-access sites (co-resident with the peer
6313        // `p.circuit_breaker()` / `p.rate_limit()` accessor sites that
6314        // b0e741a / 21a6c3b already lifted) now route through
6315        // [`MeshPolicy::timeout`] / [`MeshPolicy::retries`], closing
6316        // the per-`:politicas` bracket-dispatch fan-out's raw-field-
6317        // access axis on the M3 mesh-slot family.
6318        let p = self.politicas();
6319        if let Some(t) = p.timeout() {
6320            // Zero-floor + integer-millisecond canonical-form +
6321            // upper-cap bracket on the typed `:timeout` axis. See
6322            // [`crate::render::require_positive_canonical_bounded_duration`]
6323            // for the full three-arm ordering discipline (zero-floor
6324            // strictly precedes the canonical-form arm so
6325            // `Duration::ZERO` surfaces the self-locating
6326            // `PolicyTimeoutZero` diagnostic naming the omit-axis
6327            // remediation; canonical-form strictly precedes the cap
6328            // arm so a sub-millisecond above-cap `Duration` surfaces
6329            // the more fundamental round-trip-shape diagnostic first)
6330            // and the four peer typed-`Duration` sites that now share
6331            // this canonical bracket. Every validated value lies in
6332            // `1ms..=POLICY_TIMEOUT_MAX` (1ms..=1h), integer-millisecond
6333            // granularity — the same top-and-bottom-edge discipline
6334            // [`POLICY_RETRIES_MAX`] and
6335            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] apply on the sibling
6336            // capped-`u32` `:politicas` axes.
6337            crate::render::require_positive_canonical_bounded_duration(
6338                t,
6339                POLICY_TIMEOUT_MAX,
6340                || AplicacaoError::PolicyTimeoutZero,
6341                |timeout| AplicacaoError::PolicyTimeoutNotCanonical { timeout },
6342                |timeout| AplicacaoError::PolicyTimeoutExceedsCap { timeout },
6343            )?;
6344        }
6345        if let Some(r) = p.retries() {
6346            // Zero-floor + upper-cap bracket on the typed `:retries`
6347            // axis. See [`crate::render::require_positive_bounded_u32`]
6348            // for the ordering discipline (zero-floor arm strictly
6349            // precedes cap arm so `Some(0)` surfaces the self-locating
6350            // `PolicyRetriesZero` diagnostic with its omit-axis
6351            // remediation directly named, not the misleading
6352            // `0 > POLICY_RETRIES_MAX == false` cap-arm miss). Until
6353            // this bracket landed the top edge ran all the way to
6354            // `u32::MAX` and a struct-literal `MeshPolicy { retries:
6355            // Some(100_000), .. }` (or the equivalent author-surface
6356            // `(:retries 100000)` / `(:retries 4294967295)` typo
6357            // landing in the slot) silently passed validate. The
6358            // runtime substrate consuming the value (Envoy's
6359            // `retry_policy.num_retries`, the future
6360            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
6361            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
6362            // policy into a thundering-herd amplification vector —
6363            // the caller's one request fans out to `retries`
6364            // server-side calls per edge per traversal, multiplying
6365            // load by `(retries+1)^depth` across the
6366            // synchronous-`:contratos` subgraph at the precise moment
6367            // the substrate is already failing (transient failure is
6368            // the trigger), exactly the failure mode AWS App Mesh's
6369            // explicit `maxRetries ≤ 10` schema cap exists to prevent.
6370            // The bracket set is `1..=POLICY_RETRIES_MAX`. Peer with
6371            // the sibling capped-`u32` `:politicas` axes
6372            // (`max_failures`, `rate_limit.rate`) and the peer capped-
6373            // `u32` axes in `:supervisor :max-restarts` +
6374            // `:limits :cpu`; all five now route through the same
6375            // canonical bracket helper.
6376            crate::render::require_positive_bounded_u32(
6377                r,
6378                POLICY_RETRIES_MAX,
6379                || AplicacaoError::PolicyRetriesZero,
6380                |retries| AplicacaoError::PolicyRetriesExceedsCap { retries },
6381            )?;
6382        }
6383        if let Some(cb) = p.circuit_breaker() {
6384            // Zero-floor + upper-cap bracket on the typed
6385            // `:max-failures` axis. See
6386            // [`crate::render::require_positive_bounded_u32`] for the
6387            // ordering discipline (zero-floor arm strictly precedes
6388            // cap arm so `max_failures == 0` surfaces the
6389            // self-locating `PolicyBreakerZeroFailures` diagnostic
6390            // with its omit-axis remediation directly named, not the
6391            // misleading `0 > POLICY_BREAKER_MAX_FAILURES_MAX ==
6392            // false` cap-arm miss). Until this bracket landed the top
6393            // edge ran all the way to `u32::MAX` and a struct-literal
6394            // `CircuitBreaker { max_failures: 100_000, .. }` (or the
6395            // equivalent author-surface `(:max-failures 100000)` /
6396            // `(:max-failures 4294967295)` typo landing in the slot)
6397            // silently passed validate. The runtime substrate
6398            // consuming the value (Envoy's
6399            // `outlier_detection.consecutive_5xx`, the future
6400            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
6401            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
6402            // breaker policy into a no-op — the trip threshold is
6403            // structurally so high that no realistic
6404            // failures-per-`:window` traffic shape can reach it, the
6405            // breaker never trips, and every typed-slot consumer
6406            // emits an Envoy / Cilium L7 overlay carrying a
6407            // protection that is structurally never enforced. The
6408            // bracket set is `1..=POLICY_BREAKER_MAX_FAILURES_MAX`;
6409            // peer with `retries` and `rate_limit.rate` on the same
6410            // helper.
6411            crate::render::require_positive_bounded_u32(
6412                cb.max_failures(),
6413                POLICY_BREAKER_MAX_FAILURES_MAX,
6414                || AplicacaoError::PolicyBreakerZeroFailures,
6415                |max_failures| AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
6416            )?;
6417            // Zero-floor + integer-millisecond canonical-form +
6418            // upper-cap bracket on the typed `:window` axis. See
6419            // [`crate::render::require_positive_canonical_bounded_duration`]
6420            // for the full three-arm ordering discipline (peer to the
6421            // `:timeout` site immediately above); every validated
6422            // value lies in `1ms..=POLICY_BREAKER_WINDOW_MAX`
6423            // (1ms..=1h), integer-millisecond granularity — the same
6424            // top-and-bottom-edge discipline
6425            // [`POLICY_TIMEOUT_MAX`] applies on the sibling
6426            // duration-typed `:politicas :timeout` axis.
6427            crate::render::require_positive_canonical_bounded_duration(
6428                cb.window(),
6429                POLICY_BREAKER_WINDOW_MAX,
6430                || AplicacaoError::PolicyBreakerZeroWindow,
6431                |window| AplicacaoError::PolicyBreakerWindowNotCanonical { window },
6432                |window| AplicacaoError::PolicyBreakerWindowExceedsCap { window },
6433            )?;
6434        }
6435        if let Some(rl) = p.rate_limit() {
6436            // Zero-floor + upper-cap bracket on the typed
6437            // `:rate-limit` rate axis. See
6438            // [`crate::render::require_positive_bounded_u32`] for the
6439            // ordering discipline (zero-floor arm strictly precedes
6440            // cap arm so `rl.rate == 0` surfaces the self-locating
6441            // `PolicyRateLimitZero` diagnostic with its omit-axis
6442            // remediation directly named, not the misleading
6443            // `0 > POLICY_RATE_LIMIT_MAX == false` cap-arm miss).
6444            // Until this bracket landed the top edge ran all the way
6445            // to `u32::MAX` and a struct-literal
6446            // `RateLimit { rate: u32::MAX, .. }` (or the equivalent
6447            // author-surface `(:rate-limit "4294967295/s")` /
6448            // `(:rate-limit "100000000/m")` typo landing in the slot)
6449            // silently passed validate. The runtime substrate
6450            // consuming the value (Envoy's
6451            // `local_rate_limit.token_bucket.max_tokens`, the future
6452            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
6453            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
6454            // rate-limit policy into a no-op limiter: the bucket
6455            // capacity is structurally so high that no realistic
6456            // per-edge traffic shape can drain it, the limiter never
6457            // trips, and every typed-slot consumer emits a "rate
6458            // declared" L7 overlay carrying enforcement that is
6459            // structurally never reached — the canonical
6460            // declared-but-inert footgun the sibling
6461            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap arm closes on
6462            // the peer no-op-breaker shape. The bracket set is
6463            // `1..=POLICY_RATE_LIMIT_MAX`; peer with `retries` and
6464            // `max_failures` on the same helper. The rate bracket
6465            // strictly precedes the window-canonical gate so a
6466            // structurally absurd rate magnitude surfaces the more
6467            // fundamental amplification-shape diagnostic before the
6468            // narrower codec-round-trip-shape diagnostic on `:window`.
6469            crate::render::require_positive_bounded_u32(
6470                rl.rate(),
6471                POLICY_RATE_LIMIT_MAX,
6472                || AplicacaoError::PolicyRateLimitZero,
6473                |rate| AplicacaoError::PolicyRateLimitExceedsCap { rate },
6474            )?;
6475            // The `:rate-limit` author surface is the canonical
6476            // `"<n>/<s|m|h>"` form, and the [`rate_limit_codec`] parser
6477            // accepts exactly the three-unit set (1s/60s/3600s) the
6478            // [`rate_limit_codec::render`] formatter emits the canonical
6479            // unit suffix for. A `RateLimit` whose `:window` is anything
6480            // else (zero, 30s, 45s, 120s, 86400s, …) is constructible
6481            // programmatically (struct literals in Rust + the typed
6482            // `Duration` field) but renders to a `<n>/<k>s` fragment
6483            // (the codec's fall-through) the parser then rejects on
6484            // round-trip — silently breaking the THEORY.md §V.2.7
6485            // render-determinism contract for any consumer that
6486            // serializes-then-deserializes the typed slot. Lifting the
6487            // canonical-window invariant to a build-time gate at
6488            // `validate_politicas` makes the codec's round-trip property
6489            // a structural property of the validated typed value:
6490            // every `RateLimit` past `AplicacaoSpec::validate` has a
6491            // window the codec round-trips losslessly, so the next
6492            // typed-slot wiring (the future `CiliumClusterwideEnvoyConfig`
6493            // emitter for `:politicas :rate-limit`, MESH-COMPOSITION
6494            // §III.2 #3) reaches for `rate_limit.window` knowing the
6495            // value is in the codec's accepted set without re-validating
6496            // at the renderer layer. Same trajectory as c4213a4 (typed
6497            // WitContract endpoint/subject/slot value-shape gates) and
6498            // the b0c8389 :behavior + :upgrade-from script-path lifts:
6499            // the typed slot's valid set matches its codec's accepted
6500            // set, structurally.
6501            if !is_canonical_rate_limit_window(rl.window()) {
6502                return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical {
6503                    window: rl.window(),
6504                });
6505            }
6506        }
6507        Ok(())
6508    }
6509
6510    /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
6511    /// A synchronous edge is any contract whose typed [`WitTarget`] is
6512    /// `Http`, `Store`, or `Capability` — the caller blocks on the
6513    /// callee, so a cycle would deadlock at runtime. Pub-sub edges
6514    /// (`WitTarget::PubSub`) are skipped: an event publisher does not
6515    /// block on its subscribers, so they can never close a sync loop.
6516    ///
6517    /// Iterative DFS with three-coloring; the reported cycle is the
6518    /// path of caixa names traversed from the back-edge target around
6519    /// to itself, in declaration order. Adjacency lists and DFS roots
6520    /// are visited in `BTreeMap` key order so the diagnostic is
6521    /// deterministic across runs.
6522    fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
6523        use std::collections::{BTreeMap, BTreeSet};
6524
6525        #[derive(Clone, Copy, PartialEq, Eq)]
6526        enum Mark {
6527            White,
6528            Gray,
6529            Black,
6530        }
6531
6532        let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
6533        for m in self.membros() {
6534            adj.entry(m.nome()).or_default();
6535        }
6536        for c in self.contratos() {
6537            // target() was already called by validate(); re-running here
6538            // keeps detect_sync_cycles self-contained for callers that
6539            // reuse it (M4 per-edge policy resolver) without revalidating.
6540            //
6541            // The pub-sub-arm check routes through the lifted
6542            // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
6543            // arm-discriminator predicate rather than a raw `matches!(…,
6544            // WitTarget::PubSub { .. })` on the variant so a future
6545            // rebrand on the axis (an M4 per-edge WIT registry split of
6546            // [`WitTarget::PubSub`] into shape-specific peers, a
6547            // per-consumer rename that the accept-set already carries)
6548            // reaches this call site through the derive rather than a
6549            // scattered per-arm `matches!` rewrite — same
6550            // `IsVariant`-derived-arm-discriminator discipline the
6551            // peer closed-set typed enums ([`crate::CaixaKind`] via
6552            // f5bba80, [`PlacementStrategy`] via 766ec63,
6553            // [`crate::supervisor::RestartStrategy`] +
6554            // [`crate::supervisor::RestartPolicy`],
6555            // [`crate::upgrade::UpgradeInstruction`] via 915a934)
6556            // already route through on the substrate's other typed-enum
6557            // arm-discriminator axes.
6558            if c.target()?.is_pubsub() {
6559                continue;
6560            }
6561            adj.entry(c.source()).or_default().insert(c.destination());
6562        }
6563
6564        let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
6565        let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
6566
6567        // Stable DFS root order — BTreeMap iteration is sorted by key.
6568        let roots: Vec<&str> = adj.keys().copied().collect();
6569
6570        // Frame: (node, sorted-neighbours snapshot, next-edge index).
6571        for root in roots {
6572            if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
6573                continue;
6574            }
6575            let root_neighbors: Vec<&str> = adj
6576                .get(root)
6577                .map(|s| s.iter().copied().collect())
6578                .unwrap_or_default();
6579            let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
6580            color.insert(root, Mark::Gray);
6581
6582            loop {
6583                // Read+advance the top frame in one borrow scope so we
6584                // can later mutate the stack (push/pop) without holding
6585                // a borrow across.
6586                let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
6587                    let node = top.0;
6588                    if top.2 >= top.1.len() {
6589                        (node, None)
6590                    } else {
6591                        let nxt = top.1[top.2];
6592                        top.2 += 1;
6593                        (node, Some(nxt))
6594                    }
6595                });
6596                let Some((node, nxt_opt)) = step else { break };
6597                let Some(nxt) = nxt_opt else {
6598                    color.insert(node, Mark::Black);
6599                    stack.pop();
6600                    continue;
6601                };
6602                let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
6603                match nxt_color {
6604                    Mark::Gray => {
6605                        // Reconstruct the cycle from `node` back through
6606                        // the parent chain to `nxt`, then close.
6607                        let mut cycle = Vec::new();
6608                        let mut cur = node;
6609                        cycle.push(cur.to_string());
6610                        while cur != nxt {
6611                            match parent.get(cur).copied() {
6612                                Some(p) => {
6613                                    cur = p;
6614                                    cycle.push(cur.to_string());
6615                                }
6616                                None => break,
6617                            }
6618                        }
6619                        cycle.reverse();
6620                        cycle.push(nxt.to_string());
6621                        return Err(AplicacaoError::ContratoCycle { cycle });
6622                    }
6623                    Mark::White => {
6624                        parent.insert(nxt, node);
6625                        color.insert(nxt, Mark::Gray);
6626                        let nxt_neighbors: Vec<&str> = adj
6627                            .get(nxt)
6628                            .map(|s| s.iter().copied().collect())
6629                            .unwrap_or_default();
6630                        stack.push((nxt, nxt_neighbors, 0));
6631                    }
6632                    Mark::Black => {}
6633                }
6634            }
6635        }
6636        Ok(())
6637    }
6638
6639    /// Substrate-canonical destination-facing TCP port every emitted
6640    /// per-Aplicacao artifact must key `destination`-shaped port axes
6641    /// off. Returns the typed `:entrada :port` scalar when this
6642    /// Aplicacao's `:entrada` block names `destination` under its
6643    /// `:para` axis (the destination Servico *is* the ingress apex, so
6644    /// the substrate honors the author-declared listener port
6645    /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
6646    /// fallback otherwise (every non-apex destination — the internal
6647    /// mesh Servicos `:contratos` reach across, the future per-edge
6648    /// policy resolver's per-destination probe targets, the
6649    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
6650    /// L4 port resolver — reads the same substrate-canonical port floor
6651    /// by construction).
6652    ///
6653    /// Prior to this lift the "if :entrada matches this destination use
6654    /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
6655    /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
6656    /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
6657    /// prior to this lift), with no typed method on the substrate primitive
6658    /// that named the rule. A future per-destination port axis addition
6659    /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
6660    /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
6661    /// per-Servico listener ports land, a per-cluster override the operator
6662    /// pins through a future `:placement :default-port` slot — would have
6663    /// to be threaded through every renderer's inline cascade in lockstep
6664    /// or one consumer would silently disagree on which port a given
6665    /// destination Servico's ingress lands at. Lifting the rule to a
6666    /// typed method on the substrate primitive means the M4 CR
6667    /// materializer, the future per-edge policy resolver, and every
6668    /// downstream test-fixture navigator reach for exactly one typed
6669    /// dispatch — the resolver's accept-set moves as a unit on any
6670    /// future axis addition.
6671    ///
6672    /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
6673    /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
6674    /// the typed primitive, thin projections at each consumer"
6675    /// discipline lifts on the sibling `:contratos` payload / `:politicas
6676    /// :rate-limit` unit-suffix axes; extends the discipline onto the
6677    /// destination-facing port-resolution axis every per-Aplicacao
6678    /// L4-fallback renderer consumes.
6679    #[must_use]
6680    pub fn port_for_destination(&self, destination: &str) -> u16 {
6681        // Route the per-`:entrada` composite-reference read through
6682        // the lifted [`AplicacaoSpec::entrada`] accessor rather than
6683        // the raw `self.entrada.as_ref()` field access — the
6684        // per-destination L4-port fallback resolver's composite-
6685        // projection seed is now the canonical read-side surface
6686        // every per-Aplicacao entrada consumer routes through, peer
6687        // of the sibling `validate` per-`:entrada` shape-and-
6688        // membership gate migration on the same outer-composite
6689        // axis.
6690        // Route the per-`:entrada` apex-destination membership probe
6691        // through the lifted [`Entrada::destination`] accessor rather
6692        // than the raw `e.para == destination` field access — the last
6693        // un-lifted `.para` production-code read site on the per-
6694        // `:entrada` `:para` axis, sibling to the four caixa-core
6695        // consumer sites the peer 15ddd8c converge already routed
6696        // through the accessor (the three
6697        // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
6698        // membership gate sites: the `validate_entrada_para` DNS-1123
6699        // shape gate, the per-`:membros` membership lookup, and the
6700        // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
6701        // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
6702        // `entrada.para`-projection converge at
6703        // caixa-core/src/render.rs (the `gateway_api_http_route_name`
6704        // route-name projection site). Prior to this converge the
6705        // `port_for_destination` resolver was the solitary consumer
6706        // bypassing the typed dispatch on the `.para` axis — the two
6707        // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
6708        // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
6709        // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
6710        // reach through the same accessor family compose with this
6711        // resolver at the emit boundary via the apex-identity
6712        // invariant `spec.port_for_destination(entrada.destination())
6713        // == entrada.port` the sibling
6714        // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
6715        // pin pins across four permutations. A future extension of the
6716        // `:entrada :para` axis to a richer author surface (a per-
6717        // cluster alias overlay the operator pins through a future
6718        // `:placement`-scoped slot, a namespace-qualified rewrite the
6719        // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
6720        // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
6721        // §III.2 acknowledges) that lands on the accessor would silently
6722        // disagree between this resolver and the two `caixa-mesh` emit
6723        // sites — an author-declared `:para "cart"` value the accessor
6724        // rewrote to `"cart-v2"` under a future canary arm would leave
6725        // the resolver's membership arm falling through to
6726        // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
6727        // `.para`) while the peer emit-site consumers landed on the
6728        // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
6729        // silently disagreed on which destination port a given typed
6730        // `:entrada` resolves to at cluster-apply time. Pinned by the
6731        // drift-detection test
6732        // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
6733        // below.
6734        self.entrada()
6735            .filter(|e| e.destination() == destination)
6736            .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
6737    }
6738}
6739
6740/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
6741/// entry may name the Aplicacao's own `:nome`.
6742///
6743/// An Aplicacao that lists itself as a member is a degenerate self-edge in
6744/// the typed graph — the application graph is a DAG rooted at the Aplicacao
6745/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
6746/// Servicos that compose the app; an Aplicacao is never its own constituent),
6747/// and the lacre pipeline's closure-resolution would otherwise be handed a
6748/// node that is its own parent: a one-node cycle it either rejects far from
6749/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
6750/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
6751/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
6752/// label + lacre closure root), a member whose `:caixa` equals the
6753/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
6754/// peer.
6755///
6756/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
6757/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
6758/// gate `validate_upgrade_from_against_versao` and the supervision-tree
6759/// self-parent gate `crate::supervisor::validate_no_self_supervision`
6760/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
6761/// not a tree/mesh edge" discipline, here on the second typed-graph axis
6762/// (the Aplicacao :membros set; the supervision-tree :children list was the
6763/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
6764/// every validated Supervisor's children are distinct from its `:nome`,
6765/// every validated Aplicacao's membros are distinct from its `:nome`. The
6766/// transitive consequence is that `:entrada :para` and `:contratos`
6767/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
6768/// name the Aplicacao itself, without re-deriving the partition.
6769pub fn validate_no_self_membership(
6770    membros: &[Membro],
6771    parent_nome: &str,
6772) -> Result<(), AplicacaoError> {
6773    for m in membros {
6774        if m.nome() == parent_nome {
6775            return Err(AplicacaoError::MembroIsSelfAplicacao {
6776                caixa: parent_nome.to_string(),
6777            });
6778        }
6779    }
6780    Ok(())
6781}
6782
6783#[derive(Debug, Error, PartialEq, Eq)]
6784pub enum AplicacaoError {
6785    #[error("Aplicacao must declare at least one :membros entry")]
6786    NoMembros,
6787    #[error(
6788        ":membros entry has empty :caixa (every member must name a Servico; \
6789         omit the entry instead of carrying an empty name)"
6790    )]
6791    MembroCaixaEmpty,
6792    #[error(
6793        ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
6794         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
6795         name / label value the member name lands in; use a lowercase \
6796         alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
6797    )]
6798    MembroCaixaInvalid { caixa: String, reason: String },
6799    #[error(
6800        ":membros entry {caixa:?} has empty :versao (every member must pin a \
6801         semver constraint that resolves through the lacre pipeline)"
6802    )]
6803    MembroVersaoEmpty { caixa: String },
6804    #[error(
6805        ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
6806         requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
6807         `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
6808         carries; the lacre pipeline resolves both through the same parser)"
6809    )]
6810    MembroVersaoInvalid {
6811        caixa: String,
6812        versao: String,
6813        reason: String,
6814    },
6815    #[error(
6816        ":membros entry {caixa:?} appears more than once (the graph node set \
6817         is a set, not a multiset; duplicate members produce duplicate \
6818         programs.yaml entries and ambiguous :contratos membership lookups)"
6819    )]
6820    MembroDuplicate { caixa: String },
6821    #[error(
6822        "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
6823         never its own constituent Servico (the application graph is a DAG rooted \
6824         at the Aplicacao; :membros names the *other* caixas that compose the \
6825         app, not the app itself). Since every :nome is a globally-unique \
6826         substrate identity, a member naming the Aplicacao's own :nome is a \
6827         one-node lacre-closure recursion, not a coincidentally-named peer; \
6828         drop the self-referential :membros entry or rename it to the actual \
6829         constituent caixa."
6830    )]
6831    MembroIsSelfAplicacao { caixa: String },
6832    #[error(
6833        "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
6834         caixa declared in :membros; omit the contract or fill the {slot} field with a \
6835         member name)"
6836    )]
6837    ContratoCaixaEmpty { slot: &'static str },
6838    #[error(
6839        "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
6840         :contratos {slot} value names a member of :membros, which is itself a \
6841         DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
6842         object the member name lands in — Service, Pod, identity-based Cilium \
6843         selector; use a lowercase alphanumeric + hyphen identifier like \
6844         `\"checkout\"` or `\"cart-v2\"`)"
6845    )]
6846    ContratoCaixaInvalid {
6847        slot: &'static str,
6848        caixa: String,
6849        reason: String,
6850    },
6851    #[error("contrato references caixa {caixa:?} not declared in :membros")]
6852    ContratoMemberMissing { caixa: String },
6853    #[error(
6854        "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
6855         entry is an inter-Servico contract whose :de and :para must name distinct \
6856         :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
6857         the contract, or point :para at the member it actually calls)"
6858    )]
6859    ContratoSelfLoop { caixa: String, wit: String },
6860    #[error("contrato {de:?} → {para:?} has empty :wit")]
6861    EmptyWit { de: String, para: String },
6862    #[error(
6863        "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
6864         {reason} (the substrate dispatches `:wit` values on the canonical \
6865         lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
6866         `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
6867         demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
6868         kebab-case identifier per segment)"
6869    )]
6870    ContratoWitInvalid {
6871        de: String,
6872        para: String,
6873        wit: String,
6874        reason: String,
6875    },
6876    #[error(
6877        ":entrada :para is empty (every :entrada must route to a caixa declared in \
6878         :membros; fill the :para field with a member name)"
6879    )]
6880    EntradaParaEmpty,
6881    #[error(
6882        ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
6883         :entrada :para value names a member of :membros, which is itself a DNS-1123 \
6884         label per the K8s apiserver's `metadata.name` rule on every object the \
6885         member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
6886         Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
6887         `\"checkout\"` or `\"cart-v2\"`)"
6888    )]
6889    EntradaParaInvalid { para: String, reason: String },
6890    #[error(":entrada routes to caixa {para:?} not declared in :membros")]
6891    EntradaMemberMissing { para: String },
6892    #[error(":entrada must declare a non-empty :host")]
6893    EmptyEntradaHost,
6894    #[error(
6895        ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
6896         (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
6897         `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
6898         like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
6899    )]
6900    EntradaHostInvalid { host: String, reason: String },
6901    #[error(":entrada :port must be in 1..=65535, got 0")]
6902    EntradaPortZero,
6903    #[error(":entrada :paths entry is empty (use the empty list to match all)")]
6904    EntradaPathEmpty,
6905    #[error(
6906        ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
6907    )]
6908    EntradaPathNotAbsolute { path: String },
6909    #[error(
6910        ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
6911         value: {reason} (the K8s apiserver enforces the same shape on \
6912         `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
6913         single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
6914         requires percent-encoding `%XX` for non-ASCII and whitespace)"
6915    )]
6916    EntradaPathInvalid { path: String, reason: String },
6917    #[error(":entrada :paths entry {path:?} appears more than once")]
6918    EntradaPathDuplicate { path: String },
6919    #[error(
6920        ":placement {estrategia} requires at least one :clusters entry \
6921         (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
6922    )]
6923    PlacementWithoutClusters { estrategia: PlacementStrategy },
6924    #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
6925    PlacementClusterEmpty,
6926    #[error(
6927        ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
6928         (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
6929         in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
6930         future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
6931         — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
6932         identifier like `\"rio\"` or `\"mar-east\"`)"
6933    )]
6934    PlacementClusterInvalid { cluster: String, reason: String },
6935    #[error(":placement :clusters entry {cluster:?} appears more than once")]
6936    PlacementClusterDuplicate { cluster: String },
6937    #[error(
6938        ":placement :affinity must be non-empty when set (omit :affinity to express \
6939         `no placement hint`)"
6940    )]
6941    PlacementAffinityEmpty,
6942    #[error(
6943        ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
6944         (placement hints land verbatim in the M3 Adaptive compression overlay's \
6945         `placement.affinity` field and in every future M4 placement-engine routing \
6946         axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
6947         selector — both enforce the DNS-1123 label rule on admission; use a \
6948         lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
6949         `\"low-latency\"`, or `\"anti-affinity\"`)"
6950    )]
6951    PlacementAffinityInvalid { affinity: String, reason: String },
6952    #[error(":placement Sharded requires :shard-key")]
6953    ShardedWithoutKey,
6954    #[error(
6955        ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
6956         hashes every entity onto the same shard, defeating sharding entirely)"
6957    )]
6958    ShardedKeyEmpty,
6959    #[error(
6960        ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
6961         entity-id extractor expression: {reason} (the future M4 Akka-style \
6962         cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
6963         as a single-token property reference and hashes the extracted entity ID \
6964         to compute shard placement; use a printable-ASCII extractor expression \
6965         like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
6966         `\"${{tenant}}\"`)"
6967    )]
6968    ShardKeyInvalid { shard_key: String, reason: String },
6969    #[error(
6970        ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
6971         Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
6972         convention); :estrategia Replicated runs every cluster active-active and \
6973         :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
6974         distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
6975         to :estrategia Sharded if hash-keyed routing is the intent"
6976    )]
6977    ShardKeyOnNonSharded {
6978        estrategia: PlacementStrategy,
6979        shard_key: String,
6980    },
6981    #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
6982    ContratoMissingTarget {
6983        de: String,
6984        para: String,
6985        wit: String,
6986        expected: &'static str,
6987    },
6988    #[error(
6989        "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
6990         expected `:{expected}` only"
6991    )]
6992    ContratoWrongTarget {
6993        de: String,
6994        para: String,
6995        wit: String,
6996        expected: &'static str,
6997    },
6998    #[error(
6999        "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
7000         like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
7001         that matches no traffic and silently drops every request)"
7002    )]
7003    ContratoEndpointEmpty { de: String, para: String },
7004    #[error(
7005        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
7006         (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
7007         :entrada :paths)"
7008    )]
7009    ContratoEndpointNotAbsolute {
7010        de: String,
7011        para: String,
7012        endpoint: String,
7013    },
7014    #[error(
7015        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
7016         Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
7017         emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
7018         caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
7019         shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
7020         like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
7021         and whitespace)"
7022    )]
7023    ContratoEndpointInvalid {
7024        de: String,
7025        para: String,
7026        endpoint: String,
7027        reason: String,
7028    },
7029    #[error(
7030        "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
7031         subject is a no-op subscribe; omit :subject only if the WIT world is not \
7032         pub-sub-shaped)"
7033    )]
7034    ContratoSubjectEmpty { de: String, para: String },
7035    #[error(
7036        "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
7037         NATS subject: {reason} (the NATS server's subject parser enforces the \
7038         same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
7039         single-token and `>` multi-token wildcards — at publish/subscribe time; \
7040         use a token-by-token form like `\"checkout.events.charge.failed\"` or \
7041         `\"orders.*.completed\"` — a malformed subject silently drops every \
7042         message at runtime far from the source caixa.lisp)"
7043    )]
7044    ContratoSubjectInvalid {
7045        de: String,
7046        para: String,
7047        subject: String,
7048        reason: String,
7049    },
7050    #[error(
7051        "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
7052         addresses the bucket root, defeating the per-key isolation the slot exists \
7053         for; omit :slot only if the WIT world is not store-shaped)"
7054    )]
7055    ContratoSlotEmpty { de: String, para: String },
7056    #[error(
7057        "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
7058         WASI keyvalue store slot template: {reason} (the substrate enforces \
7059         the printable-ASCII intersection-floor every kv backend admits — \
7060         use a single-token path / template expression like `\"checkout/$orderId\"`, \
7061         `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
7062         percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
7063         slot either gets rejected on write by strict backends or silently \
7064         corrupts the next read on permissive ones, far from the source caixa.lisp)"
7065    )]
7066    ContratoSlotInvalid {
7067        de: String,
7068        para: String,
7069        slot: String,
7070        reason: String,
7071    },
7072    #[error(
7073        "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
7074         or an event-sourced indirection (MESH-COMPOSITION §III.3)",
7075        cycle.join(" → ")
7076    )]
7077    ContratoCycle { cycle: Vec<String> },
7078    #[error(
7079        ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
7080         than once (the typed graph edges are a set, not a multiset; duplicate \
7081         contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
7082         values that K8s admission rejects far from the source caixa.lisp)"
7083    )]
7084    ContratoDuplicate {
7085        de: String,
7086        para: String,
7087        wit: String,
7088        target: String,
7089    },
7090    #[error(
7091        ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
7092         contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
7093         express `no per-call deadline on this axis`"
7094    )]
7095    PolicyTimeoutZero,
7096    #[error(
7097        ":politicas :retries must be > 0 when set; omit :retries to express \
7098         `no retries on transient failure`"
7099    )]
7100    PolicyRetriesZero,
7101    #[error(
7102        ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
7103         (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
7104         retry policy into a thundering-herd amplification vector on transient \
7105         failure (one caller request fans out to `(retries+1)^depth` server-side \
7106         calls across the synchronous-:contratos subgraph), exactly the failure \
7107         mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
7108         Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
7109         or omit :retries to disable retries entirely"
7110    )]
7111    PolicyRetriesExceedsCap { retries: u32 },
7112    #[error(
7113        ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
7114         breaker trips on the first call); omit :circuit-breaker to disable it"
7115    )]
7116    PolicyBreakerZeroFailures,
7117    #[error(
7118        ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
7119         mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
7120         above this cap turns the typed breaker policy into a no-op: the trip \
7121         threshold is structurally so high that no realistic failures-per-:window \
7122         traffic shape can reach it, so the breaker never trips and every typed-slot \
7123         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
7124         Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
7125         structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
7126         Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
7127         omit :circuit-breaker to disable the breaker entirely"
7128    )]
7129    PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
7130    #[error(
7131        ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
7132         tracks no failures); omit :circuit-breaker to disable it"
7133    )]
7134    PolicyBreakerZeroWindow,
7135    #[error(
7136        ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
7137         request); omit :rate-limit to disable rate limiting"
7138    )]
7139    PolicyRateLimitZero,
7140    #[error(
7141        ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
7142         (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
7143         rate-limit policy into a no-op limiter: the token-bucket capacity is \
7144         structurally so high that no realistic per-edge traffic shape can drain it, \
7145         so the limiter never trips and every typed-slot consumer (the future \
7146         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
7147         local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
7148         that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
7149         Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
7150         Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
7151         Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
7152         to disable rate limiting entirely"
7153    )]
7154    PolicyRateLimitExceedsCap { rate: u32 },
7155    #[error(
7156        ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
7157         the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
7158         rate-limit codec round-trips losslessly; got {window:?} which renders to a \
7159         non-round-trippable form (omit :rate-limit to disable, or pick one of the \
7160         three canonical windows)"
7161    )]
7162    PolicyRateLimitWindowNotCanonical { window: Duration },
7163    #[error(
7164        ":politicas :timeout must be an integer number of milliseconds — the canonical \
7165         authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
7166         duration codec round-trips losslessly; got {timeout:?} which carries a \
7167         sub-millisecond residue that either truncates to a different `Duration` on \
7168         re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
7169         to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
7170         zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
7171         (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
7172    )]
7173    PolicyTimeoutNotCanonical { timeout: Duration },
7174    #[error(
7175        ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
7176         (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
7177         per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
7178         overlays carry a deadline so long no realistic synchronous-:contratos \
7179         traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
7180         CSE invariant degenerates to enforcement only at the per-Servico \
7181         `:limits :wall-clock` layer — far above the per-edge granularity the typed \
7182         `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
7183         (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
7184         ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
7185         maxes out at the same `3600s` ceiling) or omit :timeout to express \
7186         `no per-call deadline on this axis` (the synchronous-call deadline then \
7187         relies entirely on the per-Servico `:limits :wall-clock` axis)"
7188    )]
7189    PolicyTimeoutExceedsCap { timeout: Duration },
7190    #[error(
7191        ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
7192         the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
7193         the shared duration codec round-trips losslessly; got {window:?} which carries a \
7194         sub-millisecond residue that either truncates to a different `Duration` on \
7195         re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
7196         Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
7197    )]
7198    PolicyBreakerWindowNotCanonical { window: Duration },
7199    #[error(
7200        ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
7201         (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
7202         rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
7203         is structurally so long that transient failures are never forgotten, the breaker \
7204         trips once and stays tripped for the lifetime of the component, and every typed-slot \
7205         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
7206         outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
7207         Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
7208         default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
7209         the breaker entirely"
7210    )]
7211    PolicyBreakerWindowExceedsCap { window: Duration },
7212}
7213
7214#[cfg(test)]
7215mod tests {
7216    use super::*;
7217
7218    fn membro(name: &str, ver: &str) -> Membro {
7219        Membro {
7220            caixa: name.into(),
7221            versao: ver.into(),
7222        }
7223    }
7224
7225    fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
7226        WitContract {
7227            de: de.into(),
7228            para: para.into(),
7229            wit: "wasi:http/proxy".into(),
7230            endpoint: Some(ep.into()),
7231            subject: None,
7232            slot: None,
7233        }
7234    }
7235
7236    fn three_member_spec() -> AplicacaoSpec {
7237        AplicacaoSpec {
7238            membros: vec![
7239                membro("catalog", "^0.1"),
7240                membro("cart", "^0.1"),
7241                membro("payment", "^0.2"),
7242            ],
7243            contratos: vec![
7244                contract_http("cart", "catalog", "/products/:id"),
7245                contract_http("cart", "payment", "/charge"),
7246            ],
7247            politicas: MeshPolicy {
7248                timeout: Some(Duration::from_secs(30)),
7249                retries: Some(3),
7250                mtls_required: Some(true),
7251                ..Default::default()
7252            },
7253            placement: Placement {
7254                estrategia: PlacementStrategy::Replicated,
7255                clusters: vec!["rio".into(), "mar".into()],
7256                affinity: Some("data-locality".into()),
7257                shard_key: None,
7258            },
7259            entrada: Some(Entrada {
7260                host: "checkout.quero.cloud".into(),
7261                para: "cart".into(),
7262                paths: vec!["/api/cart".into(), "/api/products".into()],
7263                port: 8080,
7264            }),
7265        }
7266    }
7267
7268    #[test]
7269    fn happy_path_validates() {
7270        three_member_spec().validate().unwrap();
7271    }
7272
7273    #[test]
7274    fn rejects_empty_membros() {
7275        let mut s = three_member_spec();
7276        s.membros = vec![];
7277        assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
7278    }
7279
7280    #[test]
7281    fn rejects_empty_membro_caixa() {
7282        // A `:caixa ""` entry has no name to render into programs.yaml
7283        // and no caixa.lisp to resolve at lacre time.
7284        let mut s = three_member_spec();
7285        s.membros[1].caixa = String::new();
7286        assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
7287    }
7288
7289    #[test]
7290    fn rejects_empty_membro_versao() {
7291        // A `:versao ""` entry can't pin a semver constraint, so the
7292        // lacre pipeline fails far from the source.
7293        let mut s = three_member_spec();
7294        s.membros[2].versao = String::new();
7295        let err = s.validate().unwrap_err();
7296        assert!(
7297            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
7298            "got {err:?}"
7299        );
7300    }
7301
7302    #[test]
7303    fn rejects_duplicate_membro_caixa() {
7304        // Two `:membros` entries with the same `:caixa` collapse to one
7305        // node in the membership HashSet, which masks `:contratos`
7306        // membership errors and produces duplicate programs.yaml entries.
7307        let mut s = three_member_spec();
7308        s.membros.push(membro("cart", "^0.2"));
7309        let err = s.validate().unwrap_err();
7310        assert!(
7311            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
7312            "got {err:?}"
7313        );
7314    }
7315
7316    #[test]
7317    fn rejects_invalid_membro_versao_requirement() {
7318        // The fail-before-pass-after pin: a non-empty but malformed
7319        // semver requirement (`"^bad-version"`) silently passed
7320        // `validate()` on every pre-gate codebase because the prior
7321        // shape only refused the empty string. The parse failure
7322        // surfaced far downstream at lacre-resolve time with a
7323        // `semver::Error` that didn't name which `:membros` entry
7324        // carried the typo. The new gate moves the check to caixa-build
7325        // time at the source caixa.lisp.
7326        let mut s = three_member_spec();
7327        s.membros[2].versao = "^bad-version".into();
7328        let err = s.validate().unwrap_err();
7329        assert!(
7330            matches!(
7331                err,
7332                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
7333                    if caixa == "payment" && versao == "^bad-version"
7334            ),
7335            "got {err:?}"
7336        );
7337    }
7338
7339    #[test]
7340    fn rejects_membro_versao_with_double_caret_typo() {
7341        // `"^^0.1"` is the canonical doubled-caret typo — looks like a
7342        // Cargo-shaped requirement on first glance but fails the parser
7343        // because semver doesn't accept stacked operators. Pin this
7344        // adjacent-shape footgun explicitly so a future relaxation that
7345        // accepts "looks-canonical-but-isn't" forms surfaces here.
7346        let mut s = three_member_spec();
7347        s.membros[0].versao = "^^0.1".into();
7348        let err = s.validate().unwrap_err();
7349        assert!(
7350            matches!(
7351                err,
7352                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
7353                    if caixa == "catalog" && versao == "^^0.1"
7354            ),
7355            "got {err:?}"
7356        );
7357    }
7358
7359    #[test]
7360    fn rejects_membro_versao_with_v_prefixed_tag() {
7361        // `"v0.1"` is the canonical "git-tag-shape leaking into the
7362        // semver requirement slot" typo — an author copies the
7363        // publish-side git-tag string verbatim into `:versao`, but
7364        // Cargo's semver parser rejects the leading `v` (only digits +
7365        // canonical operators are valid in the major-version
7366        // position). The gate's diagnostic names which member entry
7367        // carried the v-prefix so the fix is one edit, not a grep
7368        // through every member's `:versao`. (Note: bare `x`-glob
7369        // shorthands like `^0.1.x` are *accepted* by the semver crate
7370        // as an `*` wildcard on the patch axis — they're a Cargo-side
7371        // valid shape, not a typo, so the gate intentionally lets them
7372        // through.)
7373        let mut s = three_member_spec();
7374        s.membros[1].versao = "v0.1".into();
7375        let err = s.validate().unwrap_err();
7376        assert!(
7377            matches!(
7378                err,
7379                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
7380                    if caixa == "cart" && versao == "v0.1"
7381            ),
7382            "got {err:?}"
7383        );
7384    }
7385
7386    #[test]
7387    fn accepts_canonical_membro_versao_forms() {
7388        // The four Cargo-shaped requirement forms `:deps :versao`
7389        // already accepts via `crate::parse_requirement` must pass the
7390        // membros gate without re-validating at the resolver layer.
7391        // Pin every leg so a future tightening of the canonical set
7392        // surfaces here as a test failure.
7393        for form in [
7394            "^0.1",      // caret — minor-range pin (the most common shape)
7395            "~0.1.2",    // tilde — patch-range pin
7396            "0.1.0",     // exact — single-version pin
7397            "*",         // wildcard — explicitly any-version (semver::VersionReq::STAR)
7398            ">=0.1, <2", // multi-range — comma-separated comparators
7399        ] {
7400            let mut s = three_member_spec();
7401            for m in &mut s.membros {
7402                m.versao = form.into();
7403            }
7404            s.validate()
7405                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
7406        }
7407    }
7408
7409    #[test]
7410    fn membro_versao_empty_takes_precedence_over_invalid() {
7411        // Order pin: the existing `MembroVersaoEmpty` diagnostic
7412        // (which doesn't try to parse) fires before the new
7413        // `MembroVersaoInvalid` parse-side diagnostic, so an empty
7414        // `:versao` keeps its narrower error message — `parse_requirement`
7415        // would also reject `""`, but the empty-string arm is the more
7416        // self-locating diagnostic for the author.
7417        let mut s = three_member_spec();
7418        s.membros[1].versao = String::new();
7419        let err = s.validate().unwrap_err();
7420        assert!(
7421            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
7422            "got {err:?}"
7423        );
7424    }
7425
7426    #[test]
7427    fn membro_versao_invalid_fires_before_duplicate_check() {
7428        // Order pin: a malformed requirement on a non-duplicate entry
7429        // surfaces *its own* diagnostic (which names the offending
7430        // `:versao` string), even when a later entry would otherwise
7431        // collapse onto an earlier name. The per-entry shape gate runs
7432        // inline before the duplicate-key insert, parallel to
7433        // `membros_validation_runs_before_contratos_membership_check`
7434        // and `duplicate_contrato_gate_runs_after_target_shape_check`.
7435        let mut s = three_member_spec();
7436        s.membros[0].versao = "^bad".into();
7437        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
7438        let err = s.validate().unwrap_err();
7439        assert!(
7440            matches!(
7441                err,
7442                AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
7443            ),
7444            "got {err:?}"
7445        );
7446    }
7447
7448    #[test]
7449    fn membro_versao_invalid_diagnostic_carries_offending_versao() {
7450        // The diagnostic-shape pin: the error names the offending
7451        // `:versao` value verbatim so the author can grep their
7452        // caixa.lisp without re-running the build, and carries a
7453        // non-empty `reason` from `semver::VersionReq::parse` so the
7454        // parser's own wording flows through to the diagnostic.
7455        let mut s = three_member_spec();
7456        s.membros[2].versao = "not-a-req".into();
7457        let err = s.validate().unwrap_err();
7458        let AplicacaoError::MembroVersaoInvalid {
7459            caixa,
7460            versao,
7461            reason,
7462        } = err
7463        else {
7464            panic!("expected MembroVersaoInvalid, got other variant");
7465        };
7466        assert_eq!(caixa, "payment");
7467        assert_eq!(versao, "not-a-req");
7468        assert!(
7469            !reason.is_empty(),
7470            "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
7471        );
7472    }
7473
7474    #[test]
7475    fn membro_versao_invalid_runs_before_contratos_check() {
7476        // A malformed `:versao` on any member must surface its own
7477        // diagnostic (which names *which* member to fix) before any
7478        // `:contratos` membership lookup raises `ContratoMemberMissing`.
7479        // The `:contratos` gate runs after `validate_membros`, so this
7480        // is structurally guaranteed — pin it explicitly so a future
7481        // refactor that reorders the gates surfaces here.
7482        let mut s = three_member_spec();
7483        s.membros[1].versao = "^^0.1".into();
7484        // Add a contrato whose `:para` doesn't exist — would normally
7485        // raise ContratoMemberMissing at the membership lookup, but
7486        // the membros gate must fire first.
7487        s.contratos
7488            .push(contract_http("cart", "phantom", "/never-reached"));
7489        let err = s.validate().unwrap_err();
7490        assert!(
7491            matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
7492            "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
7493        );
7494    }
7495
7496    #[test]
7497    fn membros_validation_runs_before_contratos_membership_check() {
7498        // If `:membros` carries a duplicate, the membership-collapse
7499        // would silently accept a `:contratos :para "phantom"` so long
7500        // as some entry hashes to "phantom". Pinning order: the
7501        // duplicate-membros error fires first, regardless of whether
7502        // contratos reference real members.
7503        let mut s = three_member_spec();
7504        s.membros = vec![
7505            membro("cart", "^0.1"),
7506            membro("cart", "^0.2"),
7507            membro("catalog", "^0.1"),
7508            membro("payment", "^0.1"),
7509        ];
7510        let err = s.validate().unwrap_err();
7511        assert!(
7512            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
7513            "got {err:?}"
7514        );
7515    }
7516
7517    #[test]
7518    fn distinct_membros_validate() {
7519        // Pin the happy-path: every `:membros` entry has a non-empty
7520        // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
7521        // The fixture already satisfies this; this test makes the
7522        // invariant explicit so a future refactor of the fixture can't
7523        // silently break the guarantee.
7524        three_member_spec().validate().unwrap();
7525    }
7526
7527    // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
7528
7529    #[test]
7530    fn rejects_membro_caixa_with_uppercase() {
7531        // The canonical "I copied the Servico's display name verbatim"
7532        // typo — caixa names are lowercase per K8s DNS-1123 label rule,
7533        // but author tools often round-trip a TitleCase or CamelCase
7534        // identifier from an ADR or a sketch. Pin the diagnostic names
7535        // the offending name and suggests the lower-cased fix in one
7536        // edit, mirroring the `rejects_entrada_host_with_uppercase`
7537        // gate's shape (c7d05ec).
7538        let mut s = three_member_spec();
7539        s.membros[1].caixa = "Cart".into();
7540        let err = s.validate().unwrap_err();
7541        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
7542            panic!("expected MembroCaixaInvalid, got other variant");
7543        };
7544        assert_eq!(caixa, "Cart");
7545        assert!(
7546            reason.contains("uppercase"),
7547            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
7548        );
7549        assert!(
7550            reason.contains("\"cart\""),
7551            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
7552        );
7553    }
7554
7555    #[test]
7556    fn rejects_membro_caixa_with_underscore() {
7557        // The canonical "I'm thinking of a Python module / Postgres
7558        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
7559        // label schema. K8s rejects `metadata.name: my_cart` at admission
7560        // time with an opaque `field is invalid` (no source-citing
7561        // diagnostic). The gate moves it to caixa-build time.
7562        let mut s = three_member_spec();
7563        s.membros[0].caixa = "my_cart".into();
7564        let err = s.validate().unwrap_err();
7565        assert!(
7566            matches!(
7567                err,
7568                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
7569                    if caixa == "my_cart" && reason.contains('_')
7570            ),
7571            "got {err:?}"
7572        );
7573    }
7574
7575    #[test]
7576    fn rejects_membro_caixa_with_dot() {
7577        // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
7578        // subdomain — even though K8s `metadata.name` itself accepts
7579        // dots (DNS-1123 subdomain rule), this string also lands as a
7580        // K8s Service name (DNS-1035 label — no dots) and as a label
7581        // value on identity-based Cilium selectors. The strictest floor
7582        // among the use sites wins. The "I want to namespace my member
7583        // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
7584        let mut s = three_member_spec();
7585        s.membros[2].caixa = "team.cart".into();
7586        let err = s.validate().unwrap_err();
7587        assert!(
7588            matches!(
7589                err,
7590                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
7591                    if caixa == "team.cart" && reason.contains('.')
7592            ),
7593            "got {err:?}"
7594        );
7595    }
7596
7597    #[test]
7598    fn rejects_membro_caixa_with_leading_hyphen() {
7599        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
7600        // with an alphanumeric. The K8s apiserver rejects `-cart`
7601        // outright; the renderer would emit a `metadata.name: "-cart"`
7602        // that fails admission far from the source caixa.lisp.
7603        let mut s = three_member_spec();
7604        s.membros[0].caixa = "-cart".into();
7605        let err = s.validate().unwrap_err();
7606        assert!(
7607            matches!(
7608                err,
7609                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
7610                    if caixa == "-cart" && reason.contains("start and end")
7611            ),
7612            "got {err:?}"
7613        );
7614    }
7615
7616    #[test]
7617    fn rejects_membro_caixa_with_trailing_hyphen() {
7618        // The symmetric arm of the boundary rule. Pin separately so
7619        // both ends of the label are covered against a future relaxation
7620        // that only checks one boundary.
7621        let mut s = three_member_spec();
7622        s.membros[1].caixa = "cart-".into();
7623        let err = s.validate().unwrap_err();
7624        assert!(
7625            matches!(
7626                err,
7627                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
7628                    if caixa == "cart-"
7629            ),
7630            "got {err:?}"
7631        );
7632    }
7633
7634    #[test]
7635    fn rejects_membro_caixa_with_unicode() {
7636        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
7637        // (`xn--…`) by the author before it reaches K8s. The byte-by-
7638        // byte ASCII validity check rejects multi-byte UTF-8 sequences
7639        // by the first byte that fails the `[a-z0-9-]` predicate.
7640        let mut s = three_member_spec();
7641        s.membros[2].caixa = "café".into();
7642        let err = s.validate().unwrap_err();
7643        assert!(
7644            matches!(
7645                err,
7646                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
7647                    if caixa == "café"
7648            ),
7649            "got {err:?}"
7650        );
7651    }
7652
7653    #[test]
7654    fn rejects_membro_caixa_with_whitespace() {
7655        // Whitespace is the canonical "I pasted from a sketch / doc"
7656        // footgun. The apiserver rejects every `metadata.name` value
7657        // carrying whitespace; pin the gate fires at the right boundary.
7658        let mut s = three_member_spec();
7659        s.membros[0].caixa = "my cart".into();
7660        let err = s.validate().unwrap_err();
7661        assert!(
7662            matches!(
7663                err,
7664                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
7665                    if caixa == "my cart"
7666            ),
7667            "got {err:?}"
7668        );
7669    }
7670
7671    #[test]
7672    fn rejects_membro_caixa_too_long() {
7673        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
7674        // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
7675        // exactly. The gate's reason names both the cap and the actual
7676        // length so the author can shorten in one edit.
7677        let mut s = three_member_spec();
7678        let too_long = "a".repeat(64);
7679        s.membros[1].caixa = too_long.clone();
7680        let err = s.validate().unwrap_err();
7681        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
7682            panic!("expected MembroCaixaInvalid");
7683        };
7684        assert_eq!(caixa, too_long);
7685        assert!(
7686            reason.contains("63") && reason.contains("64"),
7687            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
7688        );
7689    }
7690
7691    #[test]
7692    fn membro_caixa_max_length_validates() {
7693        // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
7694        // so a future tightening (e.g. dropping to 62) surfaces here as
7695        // a regression, mirroring `entrada_host_max_length_validates`
7696        // (c7d05ec).
7697        let mut s = three_member_spec();
7698        s.membros[2].caixa = "a".repeat(63);
7699        s.entrada.as_mut().unwrap().para = "a".repeat(63);
7700        // remove contratos referencing the renamed member; they'd
7701        // raise ContratoMemberMissing otherwise
7702        s.contratos
7703            .retain(|c| c.de != "payment" && c.para != "payment");
7704        s.validate().unwrap();
7705    }
7706
7707    #[test]
7708    fn accepts_canonical_membro_caixa_forms() {
7709        // The DNS-1123 label shapes a caixa author is realistically
7710        // going to write: single-word lowercase, hyphen-joined, ending
7711        // in a digit-suffixed version (`cart-v2`), starting with a
7712        // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
7713        // DNS-1035 which requires a letter at position 0), single-
7714        // character (`a` — boundary). Pin every leg so a future
7715        // tightening that bans (e.g.) digit-start identifiers surfaces
7716        // here.
7717        for form in [
7718            "checkout",
7719            "cart",
7720            "cart-v2",
7721            "a",
7722            "c0",
7723            "3rd-party-shim",
7724            "x-1-2-3-4",
7725        ] {
7726            let mut s = three_member_spec();
7727            // Renaming a member also requires updating downstream refs;
7728            // drop everything else and rebuild a minimal spec around
7729            // just the one renamed member.
7730            s.membros = vec![membro(form, "^0.1")];
7731            s.contratos = vec![];
7732            s.entrada = None;
7733            s.validate()
7734                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
7735        }
7736    }
7737
7738    #[test]
7739    fn membro_caixa_empty_takes_precedence_over_invalid() {
7740        // Order pin: the existing `MembroCaixaEmpty` diagnostic
7741        // (which doesn't try to parse) fires before the new
7742        // `MembroCaixaInvalid` parse-side diagnostic, so an empty
7743        // `:caixa` keeps its narrower error message — the new gate
7744        // would also reject `""`, but the empty-string arm is the more
7745        // self-locating diagnostic for the author. Mirrors the
7746        // `entrada_host_empty_takes_precedence_over_invalid` pin
7747        // (c7d05ec).
7748        let mut s = three_member_spec();
7749        s.membros[1].caixa = String::new();
7750        let err = s.validate().unwrap_err();
7751        assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
7752    }
7753
7754    #[test]
7755    fn membro_caixa_invalid_fires_before_versao_check() {
7756        // Order pin: an invalid-shape `:caixa` surfaces *its own*
7757        // diagnostic (which names the offending caixa name), even when
7758        // the same entry's `:versao` is also empty/invalid. The shape
7759        // gate runs first because the diagnostic is more self-locating —
7760        // an empty/invalid `:versao` on an invalid-shape caixa name is
7761        // a downstream-fix-after-the-caixa-rename concern.
7762        let mut s = three_member_spec();
7763        s.membros[1].caixa = "Cart".into();
7764        s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
7765        let err = s.validate().unwrap_err();
7766        assert!(
7767            matches!(
7768                err,
7769                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
7770            ),
7771            "got {err:?}"
7772        );
7773    }
7774
7775    #[test]
7776    fn membro_caixa_invalid_fires_before_duplicate_check() {
7777        // Order pin: a malformed-shape `:caixa` on an earlier entry
7778        // surfaces *its own* diagnostic, even when a later entry would
7779        // otherwise collapse onto a duplicate name. The per-entry shape
7780        // gate runs inline before the duplicate-key insert, parallel
7781        // to `membro_versao_invalid_fires_before_duplicate_check`.
7782        let mut s = three_member_spec();
7783        s.membros[0].caixa = "Catalog".into();
7784        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
7785        let err = s.validate().unwrap_err();
7786        assert!(
7787            matches!(
7788                err,
7789                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
7790            ),
7791            "got {err:?}"
7792        );
7793    }
7794
7795    #[test]
7796    fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
7797        // The diagnostic-shape pin: the error names the offending
7798        // `:caixa` value verbatim so the author can grep their
7799        // caixa.lisp without re-running the build, and carries a
7800        // non-empty `reason` naming the specific violation. Same
7801        // shape every typed-shape gate enshrines (c7d05ec's
7802        // `entrada_host_diagnostic_carries_offending_host`,
7803        // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
7804        let mut s = three_member_spec();
7805        s.membros[2].caixa = "BAD_NAME".into();
7806        let err = s.validate().unwrap_err();
7807        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
7808            panic!("expected MembroCaixaInvalid");
7809        };
7810        assert_eq!(caixa, "BAD_NAME");
7811        assert!(
7812            !reason.is_empty(),
7813            "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
7814        );
7815    }
7816
7817    #[test]
7818    fn rejects_contrato_with_unknown_de() {
7819        let mut s = three_member_spec();
7820        s.contratos.push(contract_http("phantom", "catalog", "/x"));
7821        let err = s.validate().unwrap_err();
7822        assert!(
7823            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
7824        );
7825    }
7826
7827    #[test]
7828    fn rejects_contrato_with_unknown_para() {
7829        let mut s = three_member_spec();
7830        s.contratos.push(contract_http("cart", "phantom", "/x"));
7831        let err = s.validate().unwrap_err();
7832        assert!(
7833            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
7834        );
7835    }
7836
7837    #[test]
7838    fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
7839        // The read-path pin: the phantom-`:de` refusal arm's
7840        // `ContratoMemberMissing.caixa` carrier must be observed through
7841        // the lifted [`WitContract::source`] accessor, not the raw
7842        // `.de.clone()` field-access `String`-carry. Peer of the sibling
7843        // per-`:contratos` self-loop arm's `.source().to_string()` /
7844        // `.world_ref().to_string()` `String`-carry sites the earlier
7845        // convergence lifted onto the same accessor pair. A future
7846        // silent detour that reintroduced the raw `.de.clone()` at the
7847        // wrap envelope while the shape-gate and membership lookup
7848        // routed through the accessor would surface here as a byte-equal
7849        // miss between the fired diagnostic's `caixa:` field and the
7850        // offending edge's `.source()` — pinning the accessor as the
7851        // sole read path across the phantom-name refusal arm's arg +
7852        // wrap-envelope emit surface.
7853        let mut s = three_member_spec();
7854        let phantom = contract_http("phantom", "catalog", "/x");
7855        s.contratos.push(phantom.clone());
7856        let err = s.validate().unwrap_err();
7857        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
7858            panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
7859        };
7860        assert_eq!(
7861            caixa,
7862            phantom.source(),
7863            "ContratoMemberMissing.caixa on the phantom-:de arm must \
7864             byte-equal WitContract::source — the wrap envelope must \
7865             route through the lifted accessor rather than the raw \
7866             .de.clone() field-access String-carry"
7867        );
7868    }
7869
7870    #[test]
7871    fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
7872        // The symmetric read-path pin on the `:para` phantom-name
7873        // refusal arm — same shape as the sibling `:de` pin above but
7874        // on the callee-Servico axis. Pins the wrap envelope's
7875        // `caixa:` field is observed through the lifted
7876        // [`WitContract::destination`] accessor, not the raw
7877        // `.para.clone()` field-access `String`-carry.
7878        let mut s = three_member_spec();
7879        let phantom = contract_http("cart", "phantom", "/x");
7880        s.contratos.push(phantom.clone());
7881        let err = s.validate().unwrap_err();
7882        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
7883            panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
7884        };
7885        assert_eq!(
7886            caixa,
7887            phantom.destination(),
7888            "ContratoMemberMissing.caixa on the phantom-:para arm must \
7889             byte-equal WitContract::destination — the wrap envelope \
7890             must route through the lifted accessor rather than the raw \
7891             .para.clone() field-access String-carry"
7892        );
7893    }
7894
7895    #[test]
7896    fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
7897        // The read-path pin on the `:de` DNS-1123-malformed shape-gate
7898        // refusal arm — the `validate_contrato_caixa` arg must be
7899        // observed through the lifted [`WitContract::source`] accessor,
7900        // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
7901        // value routes through the shared
7902        // [`crate::render::require_valid_dns_1123_label`] floor with the
7903        // accessor-projected value; the fired
7904        // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
7905        // the offending edge's `.source()`, pinning that the arg + the
7906        // downstream `caixa: caixa.to_string()` wrap route through the
7907        // same accessor's read path.
7908        let mut s = three_member_spec();
7909        let malformed = contract_http("BAD_NAME", "catalog", "/x");
7910        s.contratos.push(malformed.clone());
7911        let err = s.validate().unwrap_err();
7912        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
7913            panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
7914        };
7915        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
7916        assert_eq!(
7917            caixa,
7918            malformed.source(),
7919            "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
7920             byte-equal WitContract::source — the shape-gate arg + wrap \
7921             envelope must route through the lifted accessor rather \
7922             than the raw &c.de &String-borrow"
7923        );
7924    }
7925
7926    #[test]
7927    fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
7928        // Symmetric arm to the sibling `:de` malformed-shape pin above,
7929        // on the `:para` axis. Pins the shape-gate arg + wrap envelope
7930        // route through the lifted [`WitContract::destination`]
7931        // accessor. `:para` runs after the `:de` shape gate in the
7932        // canonical edge-direction order, so the `:de` value must be
7933        // well-shaped for the `:para` gate to fire — the `cart` :de is
7934        // canonical.
7935        let mut s = three_member_spec();
7936        let malformed = contract_http("cart", "BAD_NAME", "/x");
7937        s.contratos.push(malformed.clone());
7938        let err = s.validate().unwrap_err();
7939        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
7940            panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
7941        };
7942        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
7943        assert_eq!(
7944            caixa,
7945            malformed.destination(),
7946            "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
7947             byte-equal WitContract::destination — the shape-gate arg + \
7948             wrap envelope must route through the lifted accessor \
7949             rather than the raw &c.para &String-borrow"
7950        );
7951    }
7952
7953    // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
7954
7955    #[test]
7956    fn rejects_contrato_de_empty() {
7957        // `:de ""` previously fell through to `ContratoMemberMissing`
7958        // (with `caixa: ""`) because the validated `:membros :caixa`
7959        // set never contains the empty string. The narrower
7960        // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
7961        // the offending slot.
7962        let mut s = three_member_spec();
7963        s.contratos.push(contract_http("", "catalog", "/x"));
7964        let err = s.validate().unwrap_err();
7965        assert_eq!(
7966            err,
7967            AplicacaoError::ContratoCaixaEmpty {
7968                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
7969            },
7970            "got {err:?}"
7971        );
7972    }
7973
7974    #[test]
7975    fn rejects_contrato_para_empty() {
7976        // Symmetric arm to `:de ""` — `:para ""` previously fell
7977        // through to `ContratoMemberMissing { caixa: "" }`.
7978        let mut s = three_member_spec();
7979        s.contratos.push(contract_http("cart", "", "/x"));
7980        let err = s.validate().unwrap_err();
7981        assert_eq!(
7982            err,
7983            AplicacaoError::ContratoCaixaEmpty {
7984                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
7985            },
7986            "got {err:?}"
7987        );
7988    }
7989
7990    #[test]
7991    fn rejects_contrato_de_with_uppercase() {
7992        // The canonical "I copied the Servico's TitleCase display
7993        // name from an ADR" typo. Until this gate landed `:de "Cart"`
7994        // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
7995        // as "this caixa isn't in `:membros`" when the root cause is
7996        // "this `:de` value's shape can never legitimately match a
7997        // validated member (DNS-1123 labels are lowercase)". The
7998        // narrower diagnostic names the offending slot, the value
7999        // verbatim, and the parser-shaped reason.
8000        let mut s = three_member_spec();
8001        s.contratos.push(contract_http("Cart", "catalog", "/x"));
8002        let err = s.validate().unwrap_err();
8003        let AplicacaoError::ContratoCaixaInvalid {
8004            slot,
8005            caixa,
8006            reason,
8007        } = err
8008        else {
8009            panic!("expected ContratoCaixaInvalid, got other variant");
8010        };
8011        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
8012        assert_eq!(caixa, "Cart");
8013        assert!(
8014            reason.contains("uppercase"),
8015            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
8016        );
8017    }
8018
8019    #[test]
8020    fn rejects_contrato_para_with_underscore() {
8021        // The canonical "I'm thinking of a Python module" leak —
8022        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
8023        // Pin the `:para` axis surfaces the same diagnostic shape as
8024        // the `:de` axis on the underscore violation.
8025        let mut s = three_member_spec();
8026        s.contratos.push(contract_http("cart", "my_catalog", "/x"));
8027        let err = s.validate().unwrap_err();
8028        assert!(
8029            matches!(
8030                err,
8031                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
8032                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
8033            ),
8034            "got {err:?}"
8035        );
8036    }
8037
8038    #[test]
8039    fn rejects_contrato_de_with_dot() {
8040        // A `:contratos :de` value is a single DNS-1123 *label*, not
8041        // a subdomain — mirroring the `:membros :caixa` floor. The
8042        // strictest floor among the use sites wins.
8043        let mut s = three_member_spec();
8044        s.contratos
8045            .push(contract_http("team.cart", "catalog", "/x"));
8046        let err = s.validate().unwrap_err();
8047        assert!(
8048            matches!(
8049                err,
8050                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
8051                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
8052            ),
8053            "got {err:?}"
8054        );
8055    }
8056
8057    #[test]
8058    fn rejects_contrato_para_with_unicode() {
8059        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
8060        // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
8061        // validity check rejects multi-byte UTF-8 by the first
8062        // non-`[a-z0-9-]` byte.
8063        let mut s = three_member_spec();
8064        s.contratos.push(contract_http("cart", "café", "/x"));
8065        let err = s.validate().unwrap_err();
8066        assert!(
8067            matches!(
8068                err,
8069                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
8070                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
8071            ),
8072            "got {err:?}"
8073        );
8074    }
8075
8076    #[test]
8077    fn rejects_contrato_de_with_leading_hyphen() {
8078        // DNS-1123 boundary rule: labels must start and end with an
8079        // alphanumeric. K8s rejects `-cart` outright; the narrower
8080        // shape diagnostic now names the violation at caixa-build
8081        // time rather than the misframed membership-lookup arm.
8082        let mut s = three_member_spec();
8083        s.contratos.push(contract_http("-cart", "catalog", "/x"));
8084        let err = s.validate().unwrap_err();
8085        assert!(
8086            matches!(
8087                err,
8088                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
8089                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
8090            ),
8091            "got {err:?}"
8092        );
8093    }
8094
8095    #[test]
8096    fn contrato_de_empty_takes_precedence_over_invalid() {
8097        // Order pin: the `ContratoCaixaEmpty` arm fires before the
8098        // `ContratoCaixaInvalid` parse-side arm — same empty-first
8099        // cascade `validate_membro_caixa` / `validate_placement_cluster`
8100        // / `validate_entrada_host` already establish on their peer
8101        // name axes. The empty string is a structurally distinct
8102        // authoring footgun (the author left the field blank, vs.
8103        // typed a malformed value), so it gets its own diagnostic.
8104        let mut s = three_member_spec();
8105        s.contratos.push(contract_http("", "catalog", "/x"));
8106        let err = s.validate().unwrap_err();
8107        assert_eq!(
8108            err,
8109            AplicacaoError::ContratoCaixaEmpty {
8110                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
8111            }
8112        );
8113    }
8114
8115    #[test]
8116    fn contrato_de_shape_fires_before_para_shape() {
8117        // Per-axis order pin: within one `:contratos` entry, the `:de`
8118        // shape gate fires before the `:para` shape gate — same
8119        // edge-direction order the existing `ContratoMemberMissing` /
8120        // `ContratoSelfLoop` / target-dispatch checks use, so the
8121        // diagnostic for a contract with both `:de` and `:para`
8122        // malformed is stable. Authors fixing the surfaced `:de`
8123        // first will see `:para`'s diagnostic on re-run.
8124        let mut s = three_member_spec();
8125        s.contratos.push(contract_http("Cart", "Catalog", "/x"));
8126        let err = s.validate().unwrap_err();
8127        assert!(
8128            matches!(
8129                err,
8130                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
8131                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
8132            ),
8133            "got {err:?}"
8134        );
8135    }
8136
8137    #[test]
8138    fn contrato_shape_fires_before_membership_lookup() {
8139        // The load-bearing pin: an invalid-shape `:de` surfaces its
8140        // *own* diagnostic, not the misframed `ContratoMemberMissing`.
8141        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
8142        // an invalid-shape `:de` could never legitimately match any
8143        // member — the prior `ContratoMemberMissing` diagnostic was
8144        // a structural impossibility framed as a graph-membership
8145        // failure. The shape gate now routes every such input through
8146        // the narrower self-locating diagnostic.
8147        let mut s = three_member_spec();
8148        s.contratos.push(contract_http("Cart", "catalog", "/x"));
8149        let err = s.validate().unwrap_err();
8150        assert!(
8151            matches!(
8152                err,
8153                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
8154            ),
8155            "got {err:?}"
8156        );
8157        // And the symmetric case: an invalid-shape `:para` surfaces
8158        // its own diagnostic too, even when `:de` is well-shaped.
8159        let mut s = three_member_spec();
8160        s.contratos.push(contract_http("cart", "Catalog", "/x"));
8161        let err = s.validate().unwrap_err();
8162        assert!(
8163            matches!(
8164                err,
8165                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
8166            ),
8167            "got {err:?}"
8168        );
8169    }
8170
8171    #[test]
8172    fn contrato_shape_fires_before_self_edge_check() {
8173        // A `:de "Cart" :para "Cart"` entry is two distinct authoring
8174        // bugs: the shape violation (uppercase) and the self-edge
8175        // violation. The narrower per-axis shape diagnostic surfaces
8176        // first because fixing the shape may reveal that the author
8177        // also meant to point `:para` at a different member — the
8178        // self-edge framing is only useful once both endpoints have
8179        // valid shape.
8180        let mut s = three_member_spec();
8181        s.contratos.push(contract_http("Cart", "Cart", "/x"));
8182        let err = s.validate().unwrap_err();
8183        assert!(
8184            matches!(
8185                err,
8186                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
8187                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
8188            ),
8189            "got {err:?}"
8190        );
8191    }
8192
8193    #[test]
8194    fn contrato_well_shaped_phantom_still_raises_member_missing() {
8195        // Strict-improvement pin: a well-shaped `:de` that simply
8196        // isn't in `:membros` (a phantom reference — author meant
8197        // to add the member but didn't, or renamed and missed an
8198        // update) still surfaces `ContratoMemberMissing`, unchanged.
8199        // The shape gate only intercepts inputs that could never
8200        // legitimately match a validated member; legitimately-shaped
8201        // phantom references remain on the graph-membership axis.
8202        let mut s = three_member_spec();
8203        s.contratos
8204            .push(contract_http("phantom-shim", "catalog", "/x"));
8205        let err = s.validate().unwrap_err();
8206        assert!(
8207            matches!(
8208                err,
8209                AplicacaoError::ContratoMemberMissing { ref caixa }
8210                    if caixa == "phantom-shim"
8211            ),
8212            "got {err:?}"
8213        );
8214    }
8215
8216    #[test]
8217    fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
8218        // The diagnostic-shape pin: the error names the offending
8219        // slot (`:de` or `:para`) verbatim and the offending value
8220        // verbatim plus a non-empty parser-shaped reason, so the
8221        // author can grep their caixa.lisp for `:de "<name>"` /
8222        // `:para "<name>"` and fix it in one edit. Same diagnostic
8223        // shape as `MembroCaixaInvalid` (3f9d7a0) and
8224        // `PlacementClusterInvalid` (6c8c00b).
8225        let mut s = three_member_spec();
8226        s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
8227        let err = s.validate().unwrap_err();
8228        let AplicacaoError::ContratoCaixaInvalid {
8229            slot,
8230            caixa,
8231            reason,
8232        } = err
8233        else {
8234            panic!("expected ContratoCaixaInvalid, got {err:?}");
8235        };
8236        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
8237        assert_eq!(caixa, "BAD_NAME");
8238        assert!(
8239            !reason.is_empty(),
8240            "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
8241        );
8242    }
8243
8244    #[test]
8245    fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
8246        // Scalar-value pin: the two author-facing kebab-case labels the
8247        // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
8248        // admits on the `:contratos` per-entry endpoint-shape axis,
8249        // one arm per typed sub-slot. Mirrors the peer scalar-value
8250        // pin the sibling top-level M2 / M3 / Supervisor
8251        // author-facing-label consts carry
8252        // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
8253        // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
8254        // slot itself), so every altitude of the typed-slot algebra
8255        // shares the same "one canonical byte-string per arm"
8256        // discipline. A future rebrand (`:de` → `:from` matching the
8257        // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
8258        // sibling, `:para` → `:to` matching the same, or
8259        // `:de`/`:para` → `:source`/`:target` matching the WIT
8260        // world's `import`/`export` half-vocabulary) lands as an
8261        // edit to exactly one const, and every consumer that reaches
8262        // for the label picks it up at build time rather than at
8263        // runtime as a downstream `ContratoCaixaEmpty` /
8264        // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
8265        // diagnostic mismatch far from the rename's commit.
8266        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
8267        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
8268    }
8269
8270    #[test]
8271    fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
8272        // Production-through-const pin: the two per-axis labels the
8273        // per-`:contratos` entry endpoint-shape gate at
8274        // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
8275        // argument to [`validate_contrato_caixa`] route through the
8276        // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
8277        // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
8278        // future rebrand that reaches the const but not the gate (or
8279        // vice versa) surfaces here at build time rather than at
8280        // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
8281        // `slot: <stale-kebab-case>` diagnostic far from the rename's
8282        // commit. Mirror of the peer
8283        // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
8284        // pin (882f498) on the sibling M3 top-level slot axis.
8285        let mut s = three_member_spec();
8286        s.contratos.push(contract_http("", "catalog", "/x"));
8287        assert_eq!(
8288            s.validate().unwrap_err(),
8289            AplicacaoError::ContratoCaixaEmpty {
8290                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
8291            }
8292        );
8293        let mut s = three_member_spec();
8294        s.contratos.push(contract_http("cart", "", "/x"));
8295        assert_eq!(
8296            s.validate().unwrap_err(),
8297            AplicacaoError::ContratoCaixaEmpty {
8298                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
8299            }
8300        );
8301    }
8302
8303    #[test]
8304    fn accepts_canonical_contrato_caixa_forms() {
8305        // The DNS-1123 label shapes a caixa author is realistically
8306        // going to write on a `:contratos :de` / `:para`. Pin every
8307        // leg so a future tightening that bans (e.g.) digit-start
8308        // identifiers surfaces here, mirroring
8309        // `accepts_canonical_membro_caixa_forms` on the peer name
8310        // axis.
8311        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
8312            let mut s = three_member_spec();
8313            s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
8314            s.contratos = vec![contract_http("checkout", form, "/x")];
8315            s.entrada = None;
8316            s.validate().unwrap_or_else(|e| {
8317                panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
8318            });
8319
8320            let mut s = three_member_spec();
8321            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
8322            s.contratos = vec![contract_http(form, "catalog", "/x")];
8323            s.entrada = None;
8324            s.validate().unwrap_or_else(|e| {
8325                panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
8326            });
8327        }
8328    }
8329
8330    #[test]
8331    fn rejects_empty_wit() {
8332        let mut s = three_member_spec();
8333        s.contratos.push(WitContract {
8334            de: "cart".into(),
8335            para: "catalog".into(),
8336            wit: "".into(),
8337            endpoint: None,
8338            subject: None,
8339            slot: None,
8340        });
8341        let err = s.validate().unwrap_err();
8342        assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
8343    }
8344
8345    #[test]
8346    fn rejects_entrada_to_unknown_member() {
8347        let mut s = three_member_spec();
8348        s.entrada.as_mut().unwrap().para = "phantom".into();
8349        assert!(matches!(
8350            s.validate().unwrap_err(),
8351            AplicacaoError::EntradaMemberMissing { .. }
8352        ));
8353    }
8354
8355    // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
8356
8357    #[test]
8358    fn rejects_entrada_para_empty() {
8359        // `:para ""` previously fell through to
8360        // `EntradaMemberMissing { para: "" }` because the validated
8361        // `:membros :caixa` set never contains the empty string. The
8362        // narrower `EntradaParaEmpty` diagnostic now names the
8363        // offending slot directly — same empty-first cascade
8364        // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
8365        // `ContratoCaixaEmpty` establish on the peer name axes.
8366        let mut s = three_member_spec();
8367        s.entrada.as_mut().unwrap().para = String::new();
8368        let err = s.validate().unwrap_err();
8369        assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
8370    }
8371
8372    #[test]
8373    fn rejects_entrada_para_with_uppercase() {
8374        // The canonical "I copied the Servico's TitleCase display
8375        // name from an ADR" typo. Until this gate landed `:para "Cart"`
8376        // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
8377        // as "this caixa isn't in `:membros`" when the root cause is
8378        // "this `:para` value's shape can never legitimately match a
8379        // validated member (DNS-1123 labels are lowercase)". The
8380        // narrower diagnostic names the value verbatim plus the
8381        // parser-shaped reason.
8382        let mut s = three_member_spec();
8383        s.entrada.as_mut().unwrap().para = "Cart".into();
8384        let err = s.validate().unwrap_err();
8385        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
8386            panic!("expected EntradaParaInvalid, got other variant");
8387        };
8388        assert_eq!(para, "Cart");
8389        assert!(
8390            reason.contains("uppercase"),
8391            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
8392        );
8393    }
8394
8395    #[test]
8396    fn rejects_entrada_para_with_underscore() {
8397        // The canonical "I'm thinking of a Python module" leak —
8398        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
8399        let mut s = three_member_spec();
8400        s.entrada.as_mut().unwrap().para = "my_cart".into();
8401        let err = s.validate().unwrap_err();
8402        assert!(
8403            matches!(
8404                err,
8405                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8406                    if para == "my_cart" && reason.contains('_')
8407            ),
8408            "got {err:?}"
8409        );
8410    }
8411
8412    #[test]
8413    fn rejects_entrada_para_with_dot() {
8414        // An `:entrada :para` value is a single DNS-1123 *label*, not
8415        // a subdomain — mirroring the `:membros :caixa` floor. The
8416        // strictest floor among the use sites wins.
8417        let mut s = three_member_spec();
8418        s.entrada.as_mut().unwrap().para = "team.cart".into();
8419        let err = s.validate().unwrap_err();
8420        assert!(
8421            matches!(
8422                err,
8423                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8424                    if para == "team.cart" && reason.contains('.')
8425            ),
8426            "got {err:?}"
8427        );
8428    }
8429
8430    #[test]
8431    fn rejects_entrada_para_with_unicode() {
8432        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
8433        // (`xn--…`) before it reaches K8s.
8434        let mut s = three_member_spec();
8435        s.entrada.as_mut().unwrap().para = "café".into();
8436        let err = s.validate().unwrap_err();
8437        assert!(
8438            matches!(
8439                err,
8440                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
8441            ),
8442            "got {err:?}"
8443        );
8444    }
8445
8446    #[test]
8447    fn rejects_entrada_para_with_leading_hyphen() {
8448        // DNS-1123 boundary rule: labels must start and end with an
8449        // alphanumeric. K8s rejects `-cart` outright.
8450        let mut s = three_member_spec();
8451        s.entrada.as_mut().unwrap().para = "-cart".into();
8452        let err = s.validate().unwrap_err();
8453        assert!(
8454            matches!(
8455                err,
8456                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8457                    if para == "-cart" && reason.contains("start and end")
8458            ),
8459            "got {err:?}"
8460        );
8461    }
8462
8463    #[test]
8464    fn rejects_entrada_para_with_trailing_hyphen() {
8465        // Symmetric boundary arm.
8466        let mut s = three_member_spec();
8467        s.entrada.as_mut().unwrap().para = "cart-".into();
8468        let err = s.validate().unwrap_err();
8469        assert!(
8470            matches!(
8471                err,
8472                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8473                    if para == "cart-" && reason.contains("start and end")
8474            ),
8475            "got {err:?}"
8476        );
8477    }
8478
8479    #[test]
8480    fn rejects_entrada_para_too_long() {
8481        // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
8482        // bytes per label. K8s rejects longer names at admission on
8483        // every `metadata.name` axis.
8484        let mut s = three_member_spec();
8485        s.entrada.as_mut().unwrap().para = "a".repeat(64);
8486        let err = s.validate().unwrap_err();
8487        assert!(
8488            matches!(
8489                err,
8490                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8491                    if para.len() == 64 && reason.contains("max length")
8492            ),
8493            "got {err:?}"
8494        );
8495    }
8496
8497    #[test]
8498    fn entrada_para_empty_takes_precedence_over_invalid() {
8499        // Order pin: the `EntradaParaEmpty` arm fires before the
8500        // `EntradaParaInvalid` parse-side arm — same empty-first
8501        // cascade `validate_membro_caixa` / `validate_placement_cluster`
8502        // / `validate_contrato_caixa` already establish.
8503        let mut s = three_member_spec();
8504        s.entrada.as_mut().unwrap().para = String::new();
8505        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
8506    }
8507
8508    #[test]
8509    fn entrada_para_shape_fires_before_membership_lookup() {
8510        // The load-bearing pin: an invalid-shape `:para` surfaces its
8511        // *own* diagnostic, not the misframed `EntradaMemberMissing`.
8512        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
8513        // an invalid-shape `:para` could never legitimately match any
8514        // member — the prior `EntradaMemberMissing` diagnostic framed
8515        // a structural impossibility as a graph-membership failure.
8516        let mut s = three_member_spec();
8517        s.entrada.as_mut().unwrap().para = "Cart".into();
8518        let err = s.validate().unwrap_err();
8519        assert!(
8520            matches!(
8521                err,
8522                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
8523            ),
8524            "got {err:?}"
8525        );
8526    }
8527
8528    #[test]
8529    fn entrada_para_shape_fires_before_host_gate() {
8530        // Per-`:entrada` order pin: the `:para` shape gate fires
8531        // before the `:host` gate, mirroring the existing
8532        // `entrada_host_member_missing_takes_precedence_over_host_invalid`
8533        // ordering where the member-lookup arm preceded the host gate.
8534        // The shape gate slots ahead of that, so a malformed `:para`
8535        // surfaces its own diagnostic even when `:host` is also wrong.
8536        let mut s = three_member_spec();
8537        let e = s.entrada.as_mut().unwrap();
8538        e.para = "Cart".into();
8539        e.host = "BAD HOST".into();
8540        let err = s.validate().unwrap_err();
8541        assert!(
8542            matches!(
8543                err,
8544                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
8545            ),
8546            "got {err:?}"
8547        );
8548    }
8549
8550    #[test]
8551    fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
8552        // Strict-improvement pin: a well-shaped `:para` that simply
8553        // isn't in `:membros` (a phantom reference — author meant to
8554        // add the member but didn't, or renamed and missed an
8555        // update) still surfaces `EntradaMemberMissing`, unchanged.
8556        // The shape gate only intercepts inputs that could never
8557        // legitimately match a validated member.
8558        let mut s = three_member_spec();
8559        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
8560        let err = s.validate().unwrap_err();
8561        assert!(
8562            matches!(
8563                err,
8564                AplicacaoError::EntradaMemberMissing { ref para }
8565                    if para == "phantom-shim"
8566            ),
8567            "got {err:?}"
8568        );
8569    }
8570
8571    #[test]
8572    fn entrada_para_invalid_diagnostic_carries_offending_para() {
8573        // The diagnostic-shape pin: the error names the offending
8574        // `:para` value verbatim plus a non-empty parser-shaped
8575        // reason, so the author can grep their caixa.lisp for
8576        // `:para "<name>"` and fix it in one edit. Same diagnostic
8577        // shape as `MembroCaixaInvalid` (3f9d7a0),
8578        // `PlacementClusterInvalid` (6c8c00b), and
8579        // `ContratoCaixaInvalid` (8d5af6b).
8580        let mut s = three_member_spec();
8581        s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
8582        let err = s.validate().unwrap_err();
8583        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
8584            panic!("expected EntradaParaInvalid, got {err:?}");
8585        };
8586        assert_eq!(para, "BAD_NAME");
8587        assert!(
8588            !reason.is_empty(),
8589            "EntradaParaInvalid `reason` must carry a parser-shaped wording"
8590        );
8591    }
8592
8593    #[test]
8594    fn accepts_canonical_entrada_para_forms() {
8595        // Positive-control sweep covering the DNS-1123 label shapes a
8596        // caixa author is realistically going to write on `:entrada
8597        // :para`. Pin every leg so a future tightening that bans
8598        // (e.g.) digit-start identifiers surfaces here, mirroring
8599        // `accepts_canonical_membro_caixa_forms` and
8600        // `accepts_canonical_contrato_caixa_forms` on the peer name
8601        // axes.
8602        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
8603            let mut s = three_member_spec();
8604            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
8605            s.contratos = vec![contract_http(form, "catalog", "/x")];
8606            s.entrada = Some(Entrada {
8607                host: "checkout.quero.cloud".into(),
8608                para: form.into(),
8609                paths: vec!["/api".into()],
8610                port: 8080,
8611            });
8612            s.validate().unwrap_or_else(|e| {
8613                panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
8614            });
8615        }
8616    }
8617
8618    #[test]
8619    fn rejects_replicated_without_clusters() {
8620        let mut s = three_member_spec();
8621        s.placement.clusters = vec![];
8622        assert!(matches!(
8623            s.validate().unwrap_err(),
8624            AplicacaoError::PlacementWithoutClusters { .. }
8625        ));
8626    }
8627
8628    #[test]
8629    fn rejects_sharded_without_key() {
8630        let mut s = three_member_spec();
8631        s.placement.estrategia = PlacementStrategy::Sharded;
8632        s.placement.shard_key = None;
8633        s.placement.clusters = vec!["rio".into()];
8634        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
8635    }
8636
8637    #[test]
8638    fn sharded_with_key_validates() {
8639        let mut s = three_member_spec();
8640        s.placement.estrategia = PlacementStrategy::Sharded;
8641        s.placement.shard_key = Some("$tenantId".into());
8642        s.validate().unwrap();
8643    }
8644
8645    #[test]
8646    fn round_trip_via_json_preserves_shape() {
8647        let s = three_member_spec();
8648        let json = serde_json::to_string(&s.membros).unwrap();
8649        let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
8650        assert_eq!(back, s.membros);
8651
8652        let json = serde_json::to_string(&s.contratos).unwrap();
8653        let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
8654        assert_eq!(back, s.contratos);
8655
8656        let json = serde_json::to_string(&s.placement).unwrap();
8657        let back: Placement = serde_json::from_str(&json).unwrap();
8658        assert_eq!(back, s.placement);
8659
8660        let json = serde_json::to_string(&s.entrada).unwrap();
8661        let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
8662        assert_eq!(back, s.entrada);
8663    }
8664
8665    #[test]
8666    fn rate_limit_round_trip_seconds() {
8667        let policy = MeshPolicy {
8668            rate_limit: Some(RateLimit {
8669                rate: 100,
8670                window: Duration::from_secs(1),
8671            }),
8672            ..Default::default()
8673        };
8674        let json = serde_json::to_string(&policy).unwrap();
8675        assert!(json.contains("\"100/s\""));
8676        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
8677        assert_eq!(back.rate_limit.unwrap().rate, 100);
8678        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
8679    }
8680
8681    #[test]
8682    fn rate_limit_round_trip_minutes() {
8683        let policy = MeshPolicy {
8684            rate_limit: Some(RateLimit {
8685                rate: 5000,
8686                window: Duration::from_secs(60),
8687            }),
8688            ..Default::default()
8689        };
8690        let json = serde_json::to_string(&policy).unwrap();
8691        assert!(json.contains("\"5000/m\""));
8692    }
8693
8694    #[test]
8695    fn circuit_breaker_round_trip() {
8696        let policy = MeshPolicy {
8697            circuit_breaker: Some(CircuitBreaker {
8698                max_failures: 5,
8699                window: Duration::from_secs(60),
8700            }),
8701            ..Default::default()
8702        };
8703        let json = serde_json::to_string(&policy).unwrap();
8704        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
8705        assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
8706        assert_eq!(
8707            back.circuit_breaker.unwrap().window,
8708            Duration::from_secs(60)
8709        );
8710    }
8711
8712    #[test]
8713    fn rejects_http_contrato_without_endpoint() {
8714        let mut s = three_member_spec();
8715        s.contratos.push(WitContract {
8716            de: "cart".into(),
8717            para: "catalog".into(),
8718            wit: "wasi:http/proxy".into(),
8719            endpoint: None,
8720            subject: None,
8721            slot: None,
8722        });
8723        let err = s.validate().unwrap_err();
8724        assert!(matches!(
8725            err,
8726            AplicacaoError::ContratoMissingTarget {
8727                expected: WitTarget::HTTP_FIELD_NAME,
8728                ..
8729            }
8730        ));
8731    }
8732
8733    #[test]
8734    fn rejects_http_contrato_with_subject() {
8735        let mut s = three_member_spec();
8736        s.contratos.push(WitContract {
8737            de: "cart".into(),
8738            para: "catalog".into(),
8739            wit: "wasi:http/proxy".into(),
8740            endpoint: Some("/x".into()),
8741            subject: Some("not.allowed.here".into()),
8742            slot: None,
8743        });
8744        let err = s.validate().unwrap_err();
8745        assert!(matches!(
8746            err,
8747            AplicacaoError::ContratoWrongTarget {
8748                expected: WitTarget::HTTP_FIELD_NAME,
8749                ..
8750            }
8751        ));
8752    }
8753
8754    #[test]
8755    fn rejects_pubsub_contrato_without_subject() {
8756        let mut s = three_member_spec();
8757        s.contratos.push(WitContract {
8758            de: "cart".into(),
8759            para: "catalog".into(),
8760            wit: "nats:pub-sub".into(),
8761            endpoint: None,
8762            subject: None,
8763            slot: None,
8764        });
8765        let err = s.validate().unwrap_err();
8766        assert!(matches!(
8767            err,
8768            AplicacaoError::ContratoMissingTarget {
8769                expected: WitTarget::PUBSUB_FIELD_NAME,
8770                ..
8771            }
8772        ));
8773    }
8774
8775    #[test]
8776    fn rejects_pubsub_contrato_with_endpoint() {
8777        let mut s = three_member_spec();
8778        s.contratos.push(WitContract {
8779            de: "cart".into(),
8780            para: "catalog".into(),
8781            wit: "kafka:topic".into(),
8782            endpoint: Some("/wrong".into()),
8783            subject: Some("topic.x".into()),
8784            slot: None,
8785        });
8786        let err = s.validate().unwrap_err();
8787        assert!(matches!(
8788            err,
8789            AplicacaoError::ContratoWrongTarget {
8790                expected: WitTarget::PUBSUB_FIELD_NAME,
8791                ..
8792            }
8793        ));
8794    }
8795
8796    #[test]
8797    fn rejects_store_contrato_without_slot() {
8798        let mut s = three_member_spec();
8799        s.contratos.push(WitContract {
8800            de: "cart".into(),
8801            para: "catalog".into(),
8802            wit: "wasi:keyvalue/store".into(),
8803            endpoint: None,
8804            subject: None,
8805            slot: None,
8806        });
8807        let err = s.validate().unwrap_err();
8808        assert!(matches!(
8809            err,
8810            AplicacaoError::ContratoMissingTarget {
8811                expected: WitTarget::STORE_FIELD_NAME,
8812                ..
8813            }
8814        ));
8815    }
8816
8817    // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
8818
8819    #[test]
8820    fn rejects_http_contrato_with_empty_endpoint() {
8821        // `Some("")` for an HTTP endpoint passes the presence check
8822        // (target() previously returned WitTarget::Http { endpoint: "" })
8823        // but renders as a `path: ""` Cilium L7 rule that matches no
8824        // traffic. Same value-shape footgun closed for :entrada :paths
8825        // entries (eb3456d).
8826        let mut s = three_member_spec();
8827        s.contratos.push(WitContract {
8828            de: "cart".into(),
8829            para: "catalog".into(),
8830            wit: "wasi:http/proxy".into(),
8831            endpoint: Some(String::new()),
8832            subject: None,
8833            slot: None,
8834        });
8835        let err = s.validate().unwrap_err();
8836        assert!(
8837            matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
8838                if de == "cart" && para == "catalog"),
8839            "got {err:?}"
8840        );
8841    }
8842
8843    #[test]
8844    fn rejects_http_contrato_with_relative_endpoint() {
8845        // Cilium L7 :path + Gateway API PathPrefix both require a
8846        // leading `/`. Same shape required of :entrada :paths
8847        // (eb3456d). Lifted into target() so every consumer of the
8848        // typed WitTarget view inherits the guarantee.
8849        let mut s = three_member_spec();
8850        s.contratos.push(WitContract {
8851            de: "cart".into(),
8852            para: "catalog".into(),
8853            wit: "wasi:http/proxy".into(),
8854            endpoint: Some("products/:id".into()),
8855            subject: None,
8856            slot: None,
8857        });
8858        let err = s.validate().unwrap_err();
8859        assert!(
8860            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
8861                if endpoint == "products/:id"),
8862            "got {err:?}"
8863        );
8864    }
8865
8866    #[test]
8867    fn rejects_pubsub_contrato_with_empty_subject() {
8868        // NATS / Kafka publish without a subject is a no-op subscribe;
8869        // never the author's intent. Same empty-string rejection as
8870        // :membros :caixa, :placement :clusters entries, :entrada
8871        // :paths entries — every value carried by every typed slot is
8872        // value-shape-checked at validate().
8873        let mut s = three_member_spec();
8874        s.contratos.push(WitContract {
8875            de: "cart".into(),
8876            para: "catalog".into(),
8877            wit: "nats:pub-sub".into(),
8878            endpoint: None,
8879            subject: Some(String::new()),
8880            slot: None,
8881        });
8882        let err = s.validate().unwrap_err();
8883        assert!(
8884            matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
8885                if de == "cart" && para == "catalog"),
8886            "got {err:?}"
8887        );
8888    }
8889
8890    #[test]
8891    fn rejects_store_contrato_with_empty_slot() {
8892        // An empty slot template addresses the bucket root, defeating
8893        // the per-key isolation the slot exists for — a footgun on
8894        // `wasi:keyvalue/store` whose closest analog is the empty
8895        // shard-key rejected on :placement Sharded (c7c7799).
8896        let mut s = three_member_spec();
8897        s.contratos.push(WitContract {
8898            de: "cart".into(),
8899            para: "catalog".into(),
8900            wit: "wasi:keyvalue/store".into(),
8901            endpoint: None,
8902            subject: None,
8903            slot: Some(String::new()),
8904        });
8905        let err = s.validate().unwrap_err();
8906        assert!(
8907            matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
8908                if de == "cart" && para == "catalog"),
8909            "got {err:?}"
8910        );
8911    }
8912
8913    #[test]
8914    fn http_contrato_root_endpoint_validates() {
8915        // Pin the boundary case: a single-`/` endpoint is the catch-all
8916        // form the Gateway HTTPRoute renderer falls back to when
8917        // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
8918        // must remain a valid contrato endpoint too.
8919        let mut s = three_member_spec();
8920        s.contratos.push(contract_http("cart", "catalog", "/"));
8921        s.validate().unwrap();
8922    }
8923
8924    // ── :contratos :endpoint value-shape gate ────────────────────────────
8925    //
8926    // Mirrors the `:entrada :paths` value-shape suite on the peer
8927    // HTTP-path axis. Until this gate landed `WitContract::target()`
8928    // only refused the empty string + the missing-leading-`/` form
8929    // (c4213a4); a structurally invalid endpoint passed validate and
8930    // landed verbatim as a Cilium L7 `path:` rule
8931    // (caixa-mesh/src/lib.rs:311) that either silently dropped all
8932    // traffic or was rejected at apply time by Cilium policy admission.
8933    // Every authoring footgun the K8s Gateway API webhook / Cilium
8934    // policy validator would catch on admission now becomes a caixa-
8935    // build-time `ContratoEndpointInvalid` with the offending
8936    // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
8937    // shape as `EntradaPathInvalid` on the sibling axis; same shared
8938    // predicate (`crate::render::is_gateway_api_http_path`) ensures
8939    // drift between the two axes' rule enforcement is a build error
8940    // at the predicate.
8941
8942    fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
8943        // Fresh spec per call so the would-be-duplicate edge
8944        // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
8945        // `three_member_spec`'s pre-existing
8946        // `(cart, catalog, …, /products/:id)` entry — only the
8947        // endpoint payload differs.
8948        let mut s = three_member_spec();
8949        s.contratos.push(contract_http("cart", "catalog", ep));
8950        s.validate().unwrap_err()
8951    }
8952
8953    #[test]
8954    fn rejects_http_contrato_endpoint_with_query() {
8955        // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
8956        // silently rendered as a Cilium L7 `path: "/charge?token=X"`
8957        // rule the L7 matcher would never satisfy.
8958        let err = contrato_endpoint_err("/charge?token=X");
8959        assert!(
8960            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
8961                if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
8962            "got {err:?}"
8963        );
8964    }
8965
8966    #[test]
8967    fn rejects_http_contrato_endpoint_with_fragment() {
8968        let err = contrato_endpoint_err("/charge#frag");
8969        assert!(
8970            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
8971                if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
8972            "got {err:?}"
8973        );
8974    }
8975
8976    #[test]
8977    fn rejects_http_contrato_endpoint_with_whitespace() {
8978        let err = contrato_endpoint_err("/foo bar");
8979        assert!(
8980            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
8981                if endpoint == "/foo bar" && reason.contains("whitespace")),
8982            "got {err:?}"
8983        );
8984    }
8985
8986    #[test]
8987    fn rejects_http_contrato_endpoint_with_control_char() {
8988        let err = contrato_endpoint_err("/api/\x01bar");
8989        assert!(
8990            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
8991                if endpoint == "/api/\x01bar" && reason.contains("control character")),
8992            "got {err:?}"
8993        );
8994    }
8995
8996    #[test]
8997    fn rejects_http_contrato_endpoint_with_non_ascii() {
8998        let err = contrato_endpoint_err("/api/café");
8999        assert!(
9000            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9001                if endpoint == "/api/café" && reason.contains("non-ASCII")),
9002            "got {err:?}"
9003        );
9004    }
9005
9006    #[test]
9007    fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
9008        let err = contrato_endpoint_err("/api//cart");
9009        assert!(
9010            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9011                if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
9012            "got {err:?}"
9013        );
9014    }
9015
9016    #[test]
9017    fn rejects_http_contrato_endpoint_with_dot_segment() {
9018        let err = contrato_endpoint_err("/api/./cart");
9019        assert!(
9020            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9021                if endpoint == "/api/./cart" && reason.contains("`.` segment")),
9022            "got {err:?}"
9023        );
9024    }
9025
9026    #[test]
9027    fn rejects_http_contrato_endpoint_with_parent_segment() {
9028        // Path-traversal in a contrato endpoint is the canonical
9029        // "L7 rule that the workload's HTTP server's path-resolution
9030        // logic interprets differently than the policy enforcer"
9031        // footgun. Rejected outright at validate time.
9032        let err = contrato_endpoint_err("/api/../etc");
9033        assert!(
9034            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9035                if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
9036            "got {err:?}"
9037        );
9038    }
9039
9040    #[test]
9041    fn rejects_http_contrato_endpoint_too_long() {
9042        // 1025-byte endpoint — one over the Gateway API
9043        // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
9044        // path matcher has no inherent length limit but the policy
9045        // CR itself rides through the K8s apiserver, which enforces
9046        // ConfigMap-shaped limits; sharing the Gateway API cap is the
9047        // conservative floor.
9048        let big = format!("/api/{}", "a".repeat(1020));
9049        assert_eq!(big.len(), 1025);
9050        let err = contrato_endpoint_err(&big);
9051        assert!(
9052            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9053                if endpoint == &big && reason.contains("max length of 1024")),
9054            "got {err:?}"
9055        );
9056    }
9057
9058    #[test]
9059    fn http_contrato_endpoint_max_length_validates() {
9060        // 1024-byte endpoint — exactly the cap. Boundary pin: drift
9061        // in the cap surfaces here and at
9062        // `rejects_http_contrato_endpoint_too_long` simultaneously,
9063        // mirroring `entrada_path_max_length_validates` on the peer
9064        // axis.
9065        let big = format!("/api/{}", "a".repeat(1019));
9066        assert_eq!(big.len(), 1024);
9067        let mut s = three_member_spec();
9068        s.contratos.push(contract_http("cart", "catalog", &big));
9069        s.validate().unwrap();
9070    }
9071
9072    #[test]
9073    fn http_contrato_endpoint_accepts_canonical_forms() {
9074        // Positive-set sweep: every canonical HTTP-path shape the
9075        // sibling `:entrada :paths` axis accepts (the bare-root `/`,
9076        // plain paths, hidden-file-style `.config` segments distinct
9077        // from the `.` segment, digit-bearing segments, the canonical
9078        // route-template `:param` form, trailing-slash form,
9079        // percent-encoded segments, the `/foo..bar` interior-`..`-
9080        // substring forms that are NOT `..` segments) must remain a
9081        // valid contrato endpoint too. Drift between this list and
9082        // the entrada path positive sweep surfaces at the shared
9083        // `is_gateway_api_http_path` substrate-side suite — one
9084        // source of truth. Uses a fresh `(payment, catalog)` edge so
9085        // none of the swept endpoints collide with the pre-existing
9086        // `(cart, catalog, /products/:id)` / `(cart, payment,
9087        // /charge)` entries in `three_member_spec`.
9088        for ep in [
9089            "/",
9090            "/charge",
9091            "/v1/charge",
9092            "/api/.config",
9093            "/products/:id",
9094            "/api/cart/",
9095            "/api/caf%C3%A9",
9096            "/foo..bar",
9097            "/...",
9098        ] {
9099            let mut s = three_member_spec();
9100            s.contratos.push(contract_http("payment", "catalog", ep));
9101            s.validate()
9102                .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
9103        }
9104    }
9105
9106    #[test]
9107    fn contrato_endpoint_empty_takes_precedence_over_invalid() {
9108        // Ordering pin: `ContratoEndpointEmpty` is the more self-
9109        // locating diagnostic on `""` and must lead — the value-
9110        // shape gate is only reached after the empty-check fires.
9111        // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
9112        // on the peer axis.
9113        let mut s = three_member_spec();
9114        s.contratos.push(WitContract {
9115            de: "cart".into(),
9116            para: "catalog".into(),
9117            wit: "wasi:http/proxy".into(),
9118            endpoint: Some(String::new()),
9119            subject: None,
9120            slot: None,
9121        });
9122        let err = s.validate().unwrap_err();
9123        assert!(
9124            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
9125            "got {err:?}"
9126        );
9127    }
9128
9129    #[test]
9130    fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
9131        // Ordering pin: an endpoint without a leading `/` surfaces the
9132        // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
9133        // value-shape gate is only consulted on endpoints that already
9134        // satisfy the absolute-prefix invariant. Mirrors
9135        // `entrada_path_not_absolute_takes_precedence_over_invalid`.
9136        let err = contrato_endpoint_err("bad path");
9137        assert!(
9138            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
9139                if endpoint == "bad path"),
9140            "got {err:?}"
9141        );
9142    }
9143
9144    #[test]
9145    fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
9146        // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
9147        // `:para` + a non-empty reason flow through verbatim so the
9148        // author can grep their caixa.lisp for the offending contrato
9149        // block and fix it in one edit. Same shape as
9150        // `entrada_path_diagnostic_carries_offending_path`.
9151        let err = contrato_endpoint_err("/api?q=1");
9152        match err {
9153            AplicacaoError::ContratoEndpointInvalid {
9154                de,
9155                para,
9156                endpoint,
9157                reason,
9158            } => {
9159                assert_eq!(de, "cart");
9160                assert_eq!(para, "catalog");
9161                assert_eq!(endpoint, "/api?q=1");
9162                assert!(!reason.is_empty(), "reason field must be non-empty");
9163            }
9164            other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
9165        }
9166    }
9167
9168    #[test]
9169    fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
9170        // The compounding theorem: every &str inside a WitTarget
9171        // returned by target() is non-empty (and absolute, for Http).
9172        // Renderers downstream of typed_view() can rely on this
9173        // without re-checking — the type system carries the proof.
9174        let http = contract_http("cart", "catalog", "/x");
9175        match http.target().unwrap() {
9176            WitTarget::Http { endpoint } => {
9177                assert!(!endpoint.is_empty());
9178                assert!(endpoint.starts_with('/'));
9179            }
9180            other => panic!("expected Http, got {other:?}"),
9181        }
9182        let nats = WitContract {
9183            de: "a".into(),
9184            para: "b".into(),
9185            wit: "nats:pub-sub".into(),
9186            endpoint: None,
9187            subject: Some("topic.x".into()),
9188            slot: None,
9189        };
9190        match nats.target().unwrap() {
9191            WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
9192            other => panic!("expected PubSub, got {other:?}"),
9193        }
9194        let kv = WitContract {
9195            de: "a".into(),
9196            para: "b".into(),
9197            wit: "wasi:keyvalue/store".into(),
9198            endpoint: None,
9199            subject: None,
9200            slot: Some("checkout/$orderId".into()),
9201        };
9202        match kv.target().unwrap() {
9203            WitTarget::Store { slot } => assert!(!slot.is_empty()),
9204            other => panic!("expected Store, got {other:?}"),
9205        }
9206    }
9207
9208    #[test]
9209    fn target_diagnostic_names_offending_endpoint_value() {
9210        // When the malformed endpoint string is non-trivial, the
9211        // diagnostic carries the actual value back to the author —
9212        // not a generic "endpoint malformed" error.
9213        let bad = WitContract {
9214            de: "src".into(),
9215            para: "dst".into(),
9216            wit: "wasi:http/proxy".into(),
9217            endpoint: Some("api/v1/charge".into()),
9218            subject: None,
9219            slot: None,
9220        };
9221        match bad.target().unwrap_err() {
9222            AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
9223                assert_eq!(de, "src");
9224                assert_eq!(para, "dst");
9225                assert_eq!(endpoint, "api/v1/charge");
9226            }
9227            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
9228        }
9229    }
9230
9231    #[test]
9232    fn rejects_unknown_wit_with_target_set() {
9233        let mut s = three_member_spec();
9234        s.contratos.push(WitContract {
9235            de: "cart".into(),
9236            para: "catalog".into(),
9237            wit: "custom:exchange".into(),
9238            endpoint: Some("/leaked".into()),
9239            subject: None,
9240            slot: None,
9241        });
9242        let err = s.validate().unwrap_err();
9243        assert!(matches!(
9244            err,
9245            AplicacaoError::ContratoWrongTarget {
9246                expected: WitTarget::CAPABILITY_EXPECTED,
9247                ..
9248            }
9249        ));
9250    }
9251
9252    #[test]
9253    fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
9254        // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
9255        // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
9256        // fourth arm of the same "which payload field name goes in the
9257        // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
9258        // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
9259        // consts cover on the peer HTTP / PubSub / Store arms
9260        // (`wit_target_field_name_pins_per_variant`). Until this lift
9261        // landed the byte-string sat twice — once inline in the
9262        // [`WitContract::target`] Capability-arm rejection at the
9263        // production dispatch, once in `rejects_unknown_wit_with_target_set`
9264        // pinning against the same literal — with no compile-time link
9265        // between them. Same "one canonical declaration, next to the
9266        // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
9267        // lift established for the payload-less arm's human-readable
9268        // label axis; this test is the shape peer of
9269        // `wit_target_label_pins_per_variant`'s Capability-arm assertion
9270        // pair (routes-through-const + scalar-value pin) on the
9271        // wrong-target diagnostic-scalar axis.
9272        //
9273        // Fail-before-pass-after was verified locally by mutating the
9274        // const declaration to `"capability"` — the scalar-value pin
9275        // below fires (`"capability" != "none"`) and the routes-through
9276        // assertion below still holds (production and const walk in
9277        // lockstep), which is the correct behavior: a rename on the
9278        // const drifts here first, not at a downstream consumer.
9279        assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
9280
9281        let mut s = three_member_spec();
9282        s.contratos.push(WitContract {
9283            de: "cart".into(),
9284            para: "catalog".into(),
9285            wit: "custom:exchange".into(),
9286            endpoint: Some("/leaked".into()),
9287            subject: None,
9288            slot: None,
9289        });
9290        match s.validate().unwrap_err() {
9291            AplicacaoError::ContratoWrongTarget { expected, .. } => {
9292                assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
9293            }
9294            other => panic!("expected ContratoWrongTarget, got {other:?}"),
9295        }
9296    }
9297
9298    #[test]
9299    fn unknown_wit_capability_only_validates() {
9300        let mut s = three_member_spec();
9301        s.contratos.push(WitContract {
9302            de: "cart".into(),
9303            para: "catalog".into(),
9304            // A WIT world we haven't yet shaped — accept it as a typed
9305            // capability edge so authors aren't blocked while the WIT
9306            // registry catches up. No payload field may be carried.
9307            wit: "custom:exchange".into(),
9308            endpoint: None,
9309            subject: None,
9310            slot: None,
9311        });
9312        s.validate().unwrap();
9313        let added = s.contratos.last().unwrap();
9314        assert_eq!(added.target().unwrap(), WitTarget::Capability);
9315    }
9316
9317    #[test]
9318    fn target_typed_view_round_trips_each_shape() {
9319        let http = contract_http("cart", "catalog", "/products/:id");
9320        assert_eq!(
9321            http.target().unwrap(),
9322            WitTarget::Http {
9323                endpoint: "/products/:id"
9324            }
9325        );
9326        let nats = WitContract {
9327            de: "a".into(),
9328            para: "b".into(),
9329            wit: "nats:pub-sub".into(),
9330            endpoint: None,
9331            subject: Some("topic.x".into()),
9332            slot: None,
9333        };
9334        assert_eq!(
9335            nats.target().unwrap(),
9336            WitTarget::PubSub { subject: "topic.x" }
9337        );
9338        let kv = WitContract {
9339            de: "a".into(),
9340            para: "b".into(),
9341            wit: "wasi:keyvalue/store".into(),
9342            endpoint: None,
9343            subject: None,
9344            slot: Some("checkout/$orderId".into()),
9345        };
9346        assert_eq!(
9347            kv.target().unwrap(),
9348            WitTarget::Store {
9349                slot: "checkout/$orderId"
9350            }
9351        );
9352    }
9353
9354    #[test]
9355    fn wit_contract_kind_predicates() {
9356        let http = contract_http("a", "b", "/x");
9357        assert!(http.is_http());
9358        assert!(!http.is_pubsub());
9359        assert!(!http.is_store());
9360
9361        let nats = WitContract {
9362            de: "a".into(),
9363            para: "b".into(),
9364            wit: "nats:pub-sub".into(),
9365            endpoint: None,
9366            subject: Some("topic.x".into()),
9367            slot: None,
9368        };
9369        assert!(nats.is_pubsub());
9370        assert!(!nats.is_http());
9371
9372        let kv = WitContract {
9373            de: "a".into(),
9374            para: "b".into(),
9375            wit: "wasi:keyvalue/store".into(),
9376            endpoint: None,
9377            subject: None,
9378            slot: Some("checkout/$orderId".into()),
9379        };
9380        assert!(kv.is_store());
9381        assert!(!kv.is_http());
9382    }
9383
9384    // ── :contratos :wit value-shape gate ─────────────────────────────────
9385    //
9386    // Mirrors the `:contratos :endpoint` value-shape suite on the peer
9387    // dispatch-discriminator axis. Until this gate landed
9388    // `WitContract::target()` accepted any non-empty string and
9389    // silently demoted unrecognized shapes to a capability-only L4
9390    // edge — the canonical "I thought I had L7 HTTP routing, got
9391    // L4-only" footgun. Every authoring footgun the WIT registry's
9392    // own grammar rejects (uppercase, hyphen-for-colon typo,
9393    // whitespace, empty package, doubled `@`, …) now becomes a
9394    // caixa-build-time `ContratoWitInvalid` with the offending
9395    // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
9396    // as `ContratoEndpointInvalid` on the sibling axis; same shared
9397    // predicate (`crate::render::is_wit_world_ref`) ensures drift
9398    // between any two axes' rule enforcement is a build error at the
9399    // predicate, not piecemeal across renderers.
9400
9401    fn contrato_wit_err(wit: &str) -> AplicacaoError {
9402        // Fresh spec per call so the new contract doesn't collide on
9403        // identity with `three_member_spec`'s pre-existing entries.
9404        // The new edge uses `(payment, catalog)` — a pair the fixture
9405        // doesn't already declare — with no payload field set, so the
9406        // wit-shape gate fires before any payload-shape arm.
9407        let mut s = three_member_spec();
9408        s.contratos.push(WitContract {
9409            de: "payment".into(),
9410            para: "catalog".into(),
9411            wit: wit.into(),
9412            endpoint: None,
9413            subject: None,
9414            slot: None,
9415        });
9416        s.validate().unwrap_err()
9417    }
9418
9419    #[test]
9420    fn rejects_wit_with_uppercase_namespace() {
9421        // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
9422        // didn't match the lowercase `wasi:http/` prefix is_http() keys
9423        // off, so the dispatch fell through to the capability arm and
9424        // the contract silently rendered as an L4-only Cilium edge.
9425        // The new gate surfaces the uppercase typo at validate time
9426        // with the offending `:wit` named.
9427        let err = contrato_wit_err("WASI:http/proxy");
9428        assert!(
9429            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9430                if wit == "WASI:http/proxy" && reason.contains("lowercase")),
9431            "got {err:?}"
9432        );
9433    }
9434
9435    #[test]
9436    fn rejects_wit_with_hyphen_for_colon_typo() {
9437        // The canonical "I forgot the `:` separator" typo — pre-gate
9438        // this passed as Capability silently, so the renderer emitted
9439        // an L4-only policy where the author expected L7 HTTP rules.
9440        let err = contrato_wit_err("wasi-http/proxy");
9441        assert!(
9442            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9443                if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
9444            "got {err:?}"
9445        );
9446    }
9447
9448    #[test]
9449    fn rejects_wit_with_multiple_colons() {
9450        // Doubled `:` — the namespace/package split has nowhere to
9451        // anchor, so the dispatch silently demotes to Capability.
9452        let err = contrato_wit_err("wasi:http:proxy");
9453        assert!(
9454            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9455                if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
9456            "got {err:?}"
9457        );
9458    }
9459
9460    #[test]
9461    fn rejects_wit_with_empty_package() {
9462        // `wasi:` — namespace alone with no package. Pre-gate this
9463        // failed neither the is_http nor is_pubsub nor is_store
9464        // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
9465        // a bare `wasi:`), so it silently demoted to Capability.
9466        let err = contrato_wit_err("wasi:");
9467        assert!(
9468            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9469                if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
9470            "got {err:?}"
9471        );
9472    }
9473
9474    #[test]
9475    fn rejects_wit_with_underscore() {
9476        // Underscore — WIT identifiers are kebab-case, same rule
9477        // DNS-1123 enforces on its peer axes. The diagnostic carries
9478        // the explicit "use `-` instead" remediation.
9479        let err = contrato_wit_err("wasi:http_proxy");
9480        assert!(
9481            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9482                if wit == "wasi:http_proxy" && reason.contains('_')),
9483            "got {err:?}"
9484        );
9485    }
9486
9487    #[test]
9488    fn rejects_wit_with_whitespace() {
9489        // Whitespace mid-token — the prefix check matches but the
9490        // package-and-onward parse silently demoted to Capability.
9491        let err = contrato_wit_err("wasi:http proxy");
9492        assert!(
9493            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9494                if wit == "wasi:http proxy" && reason.contains("whitespace")),
9495            "got {err:?}"
9496        );
9497    }
9498
9499    #[test]
9500    fn rejects_wit_with_non_ascii() {
9501        // Un-percent-encoded non-ASCII byte — the canonical "I copied
9502        // the package name from a doc with smart quotes / accented
9503        // characters" footgun.
9504        let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
9505        assert!(
9506            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9507                if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
9508            "got {err:?}"
9509        );
9510    }
9511
9512    #[test]
9513    fn rejects_wit_with_consecutive_hyphens() {
9514        // `pub--sub` — WIT identifiers join words with single hyphens.
9515        let err = contrato_wit_err("nats:pub--sub");
9516        assert!(
9517            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9518                if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
9519            "got {err:?}"
9520        );
9521    }
9522
9523    #[test]
9524    fn rejects_wit_with_trailing_at_no_version() {
9525        // `wasi:http/proxy@` — the version-suffix author started to
9526        // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
9527        // parser would reject this; surface it at validate time.
9528        let err = contrato_wit_err("wasi:http/proxy@");
9529        assert!(
9530            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9531                if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
9532            "got {err:?}"
9533        );
9534    }
9535
9536    #[test]
9537    fn rejects_wit_too_long() {
9538        // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
9539        // The legitimate-shape arms all pass (lowercase, single `:`,
9540        // kebab-case identifiers); only the cap arm fires. Surfaces
9541        // the paste-from-binary / accidental-multi-line-blob landing
9542        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
9543        // on the peer axis.
9544        let big = format!("wasi:{}", "a".repeat(124));
9545        assert_eq!(big.len(), 129);
9546        let err = contrato_wit_err(&big);
9547        assert!(
9548            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9549                if wit == &big && reason.contains("max length of 128")),
9550            "got {err:?}"
9551        );
9552    }
9553
9554    #[test]
9555    fn wit_max_length_validates() {
9556        // 128-byte WIT reference — exactly the cap. Boundary pin:
9557        // drift in the cap surfaces here and at `rejects_wit_too_long`
9558        // simultaneously, mirroring
9559        // `http_contrato_endpoint_max_length_validates` on the peer
9560        // axis.
9561        let big = format!("wasi:{}", "a".repeat(123));
9562        assert_eq!(big.len(), 128);
9563        let mut s = three_member_spec();
9564        s.contratos.push(WitContract {
9565            de: "payment".into(),
9566            para: "catalog".into(),
9567            wit: big,
9568            endpoint: None,
9569            subject: None,
9570            slot: None,
9571        });
9572        s.validate().unwrap();
9573    }
9574
9575    #[test]
9576    fn wit_accepts_canonical_forms_at_aplicacao_layer() {
9577        // Positive-set sweep through the AplicacaoSpec::validate
9578        // surface (rather than the substrate-side predicate directly)
9579        // — pins every shape the existing test fixtures + the
9580        // checkout-aplicacao example carry, so the gate's accept-set
9581        // matches the substrate's emit-set. Drift between this list
9582        // and `render::tests::wit_world_ref_accepts_canonical_forms`
9583        // surfaces at the substrate layer's positive sweep — one
9584        // source of truth for the rule.
9585        for wit in [
9586            "wasi:http/proxy",
9587            "wasi:keyvalue/store",
9588            "nats:pub-sub",
9589            "kafka:topic",
9590            "custom:exchange",
9591            "pleme:cap/audit",
9592            "wasi:http/proxy@0.2.0",
9593        ] {
9594            // Payload field paired to the dispatched WIT shape so the
9595            // shape-↔-target arm doesn't fire instead of the wit-shape
9596            // arm we're exercising. Routes off the same
9597            // `wit_shape_is_http` / `wit_shape_is_pubsub` /
9598            // `wit_shape_is_store` free functions the production
9599            // `WitContract::is_http` / `is_pubsub` / `is_store`
9600            // methods delegate to (both consult the lifted
9601            // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
9602            // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
9603            // future prefix addition to the routing accept-set
9604            // reaches this test's payload-dispatch arm by
9605            // construction — no per-test-site drift can hide a
9606            // shape-→-target-slot mismatch that would silently
9607            // demote a canonical `:wit` value to the
9608            // `(None, None, None)` capability-only arm and let the
9609            // `AplicacaoSpec::validate` positive sweep pass on a
9610            // shape it should exercise as HTTP / pub-sub / store.
9611            let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
9612                (Some("/x".into()), None, None)
9613            } else if wit_shape_is_pubsub(wit) {
9614                (None, Some("topic.x".into()), None)
9615            } else if wit_shape_is_store(wit) {
9616                (None, None, Some("bucket/$key".into()))
9617            } else {
9618                (None, None, None)
9619            };
9620            let mut s = three_member_spec();
9621            s.contratos.push(WitContract {
9622                de: "payment".into(),
9623                para: "catalog".into(),
9624                wit: wit.into(),
9625                endpoint,
9626                subject,
9627                slot,
9628            });
9629            s.validate()
9630                .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
9631        }
9632    }
9633
9634    #[test]
9635    fn wit_shape_predicates_accept_canonical_prefix_set() {
9636        // Positive-set sweep pinning every prefix in
9637        // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
9638        // WIT_STORE_SHAPE_PREFIXES against the three free-function
9639        // dispatch predicates. The six prefixes are the load-bearing
9640        // routing keys the substrate's WIT-shape dispatch consults
9641        // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
9642        // key/value-store-slot admission); any drift between the
9643        // free-function accept-set and this list surfaces here
9644        // rather than at apply time as a silent
9645        // shape-→-capability-only demotion.
9646        assert!(wit_shape_is_http("wasi:http/proxy"));
9647        assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
9648        assert!(wit_shape_is_http("http:incoming"));
9649
9650        assert!(wit_shape_is_pubsub("nats:pub-sub"));
9651        assert!(wit_shape_is_pubsub("kafka:topic"));
9652
9653        assert!(wit_shape_is_store("wasi:keyvalue/store"));
9654        assert!(wit_shape_is_store("kv:cache/session"));
9655    }
9656
9657    #[test]
9658    fn wit_shape_predicates_reject_uncanonical_forms() {
9659        // Negative-set pin: the six canonical prefixes are
9660        // lowercase-only (mirrors the `is_wit_world_ref` substrate
9661        // predicate's lowercase invariant — see its docstring on the
9662        // "I thought I had L7 HTTP routing, got L4-only" footgun).
9663        // The empty string, an uppercase-prefixed form, a hyphen-
9664        // instead-of-colon typo, and a bare kebab identifier all miss
9665        // every shape arm — reachable-by-construction only via the
9666        // `is_wit_world_ref` gate that admission-checks the `:wit`
9667        // value first, but pinned here so any future
9668        // free-function change (e.g. a case-insensitive
9669        // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
9670        // this unit level.
9671        for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
9672            assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
9673            assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
9674            assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
9675        }
9676    }
9677
9678    #[test]
9679    fn wit_shape_predicates_partition_canonical_set() {
9680        // Every canonical prefix routes to exactly one shape arm —
9681        // the three prefix sets are pairwise disjoint. Pins the
9682        // routing property [`WitContract::target`] relies on: an
9683        // `is_http()` return of `true` guarantees `is_pubsub()` and
9684        // `is_store()` return `false`, so the shape-→-target-slot
9685        // dispatch (endpoint vs subject vs slot) is unambiguous.
9686        // Drift (e.g. a future `"kv:"` moved into the HTTP set
9687        // without removal from the store set) would silently route
9688        // one prefix to two arms and the first-matching-arm order
9689        // becomes load-bearing — this pin surfaces it as a build
9690        // error instead.
9691        for prefix in WIT_HTTP_SHAPE_PREFIXES {
9692            let sample = format!("{prefix}x");
9693            assert!(wit_shape_is_http(&sample));
9694            assert!(!wit_shape_is_pubsub(&sample));
9695            assert!(!wit_shape_is_store(&sample));
9696        }
9697        for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
9698            let sample = format!("{prefix}x");
9699            assert!(!wit_shape_is_http(&sample));
9700            assert!(wit_shape_is_pubsub(&sample));
9701            assert!(!wit_shape_is_store(&sample));
9702        }
9703        for prefix in WIT_STORE_SHAPE_PREFIXES {
9704            let sample = format!("{prefix}x");
9705            assert!(!wit_shape_is_http(&sample));
9706            assert!(!wit_shape_is_pubsub(&sample));
9707            assert!(wit_shape_is_store(&sample));
9708        }
9709    }
9710
9711    #[test]
9712    fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
9713        // Positive pin: [`wit_shape_matches`] is exactly the
9714        // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
9715        // parameterized on the accept-set. Two-prefix accept-set,
9716        // one-prefix accept-set, and empty accept-set (which must
9717        // reject everything, including the empty string — an empty
9718        // `any()` fold returns `false`) all pinned so a future
9719        // reimplementation that swaps `starts_with` for `contains`,
9720        // `==`, or a case-folded comparator surfaces at unit-test
9721        // time.
9722        let two = &["wasi:http/", "http:"];
9723        assert!(wit_shape_matches("wasi:http/proxy", two));
9724        assert!(wit_shape_matches("http:incoming", two));
9725        assert!(!wit_shape_matches("wasi:keyvalue/store", two));
9726
9727        let one = &["nats:"];
9728        assert!(wit_shape_matches("nats:pub-sub", one));
9729        assert!(!wit_shape_matches("kafka:topic", one));
9730
9731        // Empty accept-set matches nothing — the identity element
9732        // for the disjunctive `any()` fold across the prefix set.
9733        // Reachable via a future `wit_shape_is_<name>` const paired
9734        // to a still-empty prefix table on a nascent shape-arm draft.
9735        let empty: &[&str] = &[];
9736        assert!(!wit_shape_matches("wasi:http/proxy", empty));
9737        assert!(!wit_shape_matches("", empty));
9738
9739        // starts_with, not contains: a prefix embedded mid-string
9740        // never matches. Pins the routing invariant [`WitContract::target`]
9741        // relies on (an authored `:wit "custom:wasi:http/"` string
9742        // does not silently route through the HTTP arm just because
9743        // it happens to contain the canonical HTTP prefix).
9744        assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
9745    }
9746
9747    #[test]
9748    fn wit_shape_predicates_delegate_to_wit_shape_matches() {
9749        // Equivalence pin: each per-shape predicate is exactly
9750        // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
9751        // every canonical prefix + the empty string + one negative
9752        // sample against every peer so a future predicate that grew
9753        // its own inline `iter().any(starts_with)` (rather than
9754        // delegating through the lifted combinator) drifts loudly here
9755        // — the peer-const table's contents must agree with the
9756        // predicate's accept-set by construction.
9757        let samples = [
9758            String::new(),
9759            "wasi:http/proxy".to_string(),
9760            "http:incoming".to_string(),
9761            "nats:pub-sub".to_string(),
9762            "kafka:topic".to_string(),
9763            "wasi:keyvalue/store".to_string(),
9764            "kv:cache/session".to_string(),
9765            "custom-shape".to_string(),
9766            "WASI:HTTP/proxy".to_string(),
9767        ];
9768        for wit in &samples {
9769            assert_eq!(
9770                wit_shape_is_http(wit),
9771                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
9772                "wit_shape_is_http drifted from combinator on {wit:?}",
9773            );
9774            assert_eq!(
9775                wit_shape_is_pubsub(wit),
9776                wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
9777                "wit_shape_is_pubsub drifted from combinator on {wit:?}",
9778            );
9779            assert_eq!(
9780                wit_shape_is_store(wit),
9781                wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
9782                "wit_shape_is_store drifted from combinator on {wit:?}",
9783            );
9784        }
9785    }
9786
9787    #[test]
9788    fn wit_contract_shape_methods_delegate_to_free_functions() {
9789        // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
9790        // `is_store` are `&self` conveniences on top of the free
9791        // functions — for every canonical prefix the method's return
9792        // matches its free-function peer. Sweeps the union of the
9793        // three prefix sets so a future method that grew its own
9794        // inline prefix logic (rather than delegating) drifts loudly
9795        // here on the first prefix the free function accepts and the
9796        // method doesn't.
9797        for shape_set in [
9798            WIT_HTTP_SHAPE_PREFIXES,
9799            WIT_PUBSUB_SHAPE_PREFIXES,
9800            WIT_STORE_SHAPE_PREFIXES,
9801        ] {
9802            for prefix in shape_set {
9803                let c = WitContract {
9804                    de: "cart".into(),
9805                    para: "catalog".into(),
9806                    wit: format!("{prefix}x"),
9807                    endpoint: None,
9808                    subject: None,
9809                    slot: None,
9810                };
9811                assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
9812                assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
9813                assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
9814            }
9815        }
9816    }
9817
9818    #[test]
9819    fn empty_wit_takes_precedence_over_invalid() {
9820        // Ordering pin: `EmptyWit` is the more self-locating
9821        // diagnostic on `""` and must lead — the value-shape gate is
9822        // only reached after the empty-check fires. Mirrors
9823        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
9824        // the peer payload axis.
9825        let mut s = three_member_spec();
9826        s.contratos.push(WitContract {
9827            de: "payment".into(),
9828            para: "catalog".into(),
9829            wit: String::new(),
9830            endpoint: None,
9831            subject: None,
9832            slot: None,
9833        });
9834        let err = s.validate().unwrap_err();
9835        assert!(
9836            matches!(err, AplicacaoError::EmptyWit { .. }),
9837            "got {err:?}"
9838        );
9839    }
9840
9841    #[test]
9842    fn wit_invalid_fires_before_payload_shape_arm() {
9843        // Ordering pin: a malformed `:wit` surfaces *its own*
9844        // diagnostic (which names the offending wit verbatim) before
9845        // any payload-field check — a contrato whose wit is
9846        // structurally invalid AND carries a wrong target field
9847        // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
9848        // because the dispatch on the wit is what decides which
9849        // payload field is "right" in the first place. Without this
9850        // ordering, the author would see "wrong target field" for a
9851        // wit that hasn't even been parsed, which doesn't name the
9852        // root cause.
9853        let mut s = three_member_spec();
9854        s.contratos.push(WitContract {
9855            de: "payment".into(),
9856            para: "catalog".into(),
9857            // Hyphen-for-colon typo + endpoint set: pre-gate this
9858            // raised `ContratoWrongTarget { expected: "none" }` (the
9859            // Capability arm rejecting the endpoint), masking the
9860            // real authoring mistake (the wit isn't `wasi:http/proxy`).
9861            wit: "wasi-http/proxy".into(),
9862            endpoint: Some("/x".into()),
9863            subject: None,
9864            slot: None,
9865        });
9866        let err = s.validate().unwrap_err();
9867        assert!(
9868            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
9869                if wit == "wasi-http/proxy"),
9870            "got {err:?}"
9871        );
9872    }
9873
9874    #[test]
9875    fn wit_invalid_diagnostic_carries_offending_wit() {
9876        // Diagnostic-shape pin — the offending `:wit` + `:de` +
9877        // `:para` + a non-empty reason flow through verbatim so the
9878        // author can grep their caixa.lisp for the offending contrato
9879        // block and fix it in one edit. Same shape as
9880        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
9881        let err = contrato_wit_err("WASI:HTTP/proxy");
9882        match err {
9883            AplicacaoError::ContratoWitInvalid {
9884                de,
9885                para,
9886                wit,
9887                reason,
9888            } => {
9889                assert_eq!(de, "payment");
9890                assert_eq!(para, "catalog");
9891                assert_eq!(wit, "WASI:HTTP/proxy");
9892                assert!(!reason.is_empty(), "reason field must be non-empty");
9893            }
9894            other => panic!("expected ContratoWitInvalid, got {other:?}"),
9895        }
9896    }
9897
9898    // ── :contratos :subject value-shape gate ─────────────────────────────
9899    //
9900    // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
9901    // suites on the peer payload axes. Until this gate landed
9902    // `WitContract::target()` only refused the empty string; a
9903    // structurally invalid subject silently passed validate and the
9904    // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
9905    // Subject'` on publish / subscribe, or as a silent message drop,
9906    // far from the source caixa.lisp. Every authoring footgun the
9907    // NATS server's subject parser would catch on admission now
9908    // becomes a caixa-build-time `ContratoSubjectInvalid` with the
9909    // offending `:subject` + `:de` + `:para` named verbatim. Same
9910    // diagnostic shape as `ContratoEndpointInvalid` /
9911    // `ContratoWitInvalid` on the peer payload axes; same shared
9912    // predicate (`crate::render::is_nats_subject`) ensures drift
9913    // between any two axes' rule enforcement is a build error at the
9914    // predicate, not piecemeal across renderers.
9915
9916    fn contrato_subject_err(subject: &str) -> AplicacaoError {
9917        // Fresh spec per call so the new contract doesn't collide on
9918        // identity with `three_member_spec`'s pre-existing entries.
9919        // The new edge uses `(payment, catalog)` — a pair the fixture
9920        // doesn't already declare — with `:wit "nats:pub-sub"` and the
9921        // varying `:subject`, so the subject-shape gate fires cleanly
9922        // after the wit-shape gate (which `"nats:pub-sub"` passes).
9923        let mut s = three_member_spec();
9924        s.contratos.push(WitContract {
9925            de: "payment".into(),
9926            para: "catalog".into(),
9927            wit: "nats:pub-sub".into(),
9928            endpoint: None,
9929            subject: Some(subject.into()),
9930            slot: None,
9931        });
9932        s.validate().unwrap_err()
9933    }
9934
9935    #[test]
9936    fn rejects_pubsub_contrato_subject_with_whitespace() {
9937        // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
9938        // landed at the NATS server as a malformed subject the parser
9939        // rejects with `-ERR 'Invalid Subject'`. Now caught at the
9940        // source caixa.lisp.
9941        let err = contrato_subject_err("foo bar");
9942        assert!(
9943            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
9944                if subject == "foo bar" && reason.contains("whitespace")),
9945            "got {err:?}"
9946        );
9947    }
9948
9949    #[test]
9950    fn rejects_pubsub_contrato_subject_with_control_char() {
9951        let err = contrato_subject_err("foo\x01bar");
9952        assert!(
9953            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
9954                if subject == "foo\x01bar" && reason.contains("control character")),
9955            "got {err:?}"
9956        );
9957    }
9958
9959    #[test]
9960    fn rejects_pubsub_contrato_subject_with_non_ascii() {
9961        // Un-percent-encoded non-ASCII byte — the canonical "I copied
9962        // the subject from a doc with smart quotes / accented
9963        // characters" footgun.
9964        let err = contrato_subject_err("foo.caf\u{e9}");
9965        assert!(
9966            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
9967                if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
9968            "got {err:?}"
9969        );
9970    }
9971
9972    #[test]
9973    fn rejects_pubsub_contrato_subject_with_leading_dot() {
9974        // Empty leading token — NATS rejects.
9975        let err = contrato_subject_err(".foo");
9976        assert!(
9977            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
9978                if subject == ".foo" && reason.contains("must not start with `.`")),
9979            "got {err:?}"
9980        );
9981    }
9982
9983    #[test]
9984    fn rejects_pubsub_contrato_subject_with_trailing_dot() {
9985        // Empty trailing token — NATS rejects. The remediation
9986        // (use `>` instead) is in the reason string.
9987        let err = contrato_subject_err("foo.");
9988        assert!(
9989            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
9990                if subject == "foo." && reason.contains("must not end with `.`")),
9991            "got {err:?}"
9992        );
9993    }
9994
9995    #[test]
9996    fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
9997        // The canonical "I forgot to fill in the middle segment"
9998        // typo — `"foo..bar"`. NATS rejects empty tokens.
9999        let err = contrato_subject_err("foo..bar");
10000        assert!(
10001            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10002                if subject == "foo..bar" && reason.contains("consecutive `.`")),
10003            "got {err:?}"
10004        );
10005    }
10006
10007    #[test]
10008    fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
10009        // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
10010        // as the final segment. Pre-gate this passed as a typed edge
10011        // and surfaced at runtime as a NATS subscribe rejection.
10012        let err = contrato_subject_err("foo.>.bar");
10013        assert!(
10014            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10015                if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
10016            "got {err:?}"
10017        );
10018    }
10019
10020    #[test]
10021    fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
10022        // `foo*.bar` — NATS wildcards are standalone tokens. The
10023        // remediation is in the reason string.
10024        let err = contrato_subject_err("foo*.bar");
10025        assert!(
10026            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10027                if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
10028            "got {err:?}"
10029        );
10030    }
10031
10032    #[test]
10033    fn rejects_pubsub_contrato_subject_with_invalid_char() {
10034        // `foo,bar` — comma is not a valid NATS subject character.
10035        // Pinned separately from the wildcard arms so the invalid-
10036        // character diagnostic is in force.
10037        let err = contrato_subject_err("foo,bar");
10038        assert!(
10039            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10040                if subject == "foo,bar" && reason.contains("invalid character")),
10041            "got {err:?}"
10042        );
10043    }
10044
10045    #[test]
10046    fn rejects_pubsub_contrato_subject_too_long() {
10047        // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
10048        // The legitimate-shape arms all pass (one all-`a` token, no
10049        // `.`, no wildcards); only the cap arm fires. Surfaces the
10050        // paste-from-binary / accidental-multi-line-blob landing
10051        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
10052        // on the peer axis.
10053        let big = "a".repeat(257);
10054        assert_eq!(big.len(), 257);
10055        let err = contrato_subject_err(&big);
10056        assert!(
10057            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10058                if subject == &big && reason.contains("max length of 256")),
10059            "got {err:?}"
10060        );
10061    }
10062
10063    #[test]
10064    fn pubsub_contrato_subject_max_length_validates() {
10065        // 256-byte subject — exactly the cap. Boundary pin: drift in
10066        // the cap surfaces here and at
10067        // `rejects_pubsub_contrato_subject_too_long` simultaneously,
10068        // mirroring `http_contrato_endpoint_max_length_validates` and
10069        // `wit_max_length_validates` on the peer axes.
10070        let big = "a".repeat(256);
10071        assert_eq!(big.len(), 256);
10072        let mut s = three_member_spec();
10073        s.contratos.push(WitContract {
10074            de: "payment".into(),
10075            para: "catalog".into(),
10076            wit: "nats:pub-sub".into(),
10077            endpoint: None,
10078            subject: Some(big),
10079            slot: None,
10080        });
10081        s.validate().unwrap();
10082    }
10083
10084    #[test]
10085    fn pubsub_contrato_subject_accepts_canonical_forms() {
10086        // Positive-set sweep: every canonical NATS subject shape the
10087        // substrate-side `is_nats_subject` predicate accepts (the
10088        // multi-dot `events.order.charged`, the snake_case / kebab-
10089        // case / mixed-case tokens, the digit-bearing tokens, the
10090        // single-token wildcard `*` at every segment position, and
10091        // the trailing `>` multi-token wildcard) must remain a valid
10092        // contrato subject too. Drift between this list and the
10093        // substrate-side `nats_subject_accepts_canonical_forms` sweep
10094        // surfaces at the shared predicate — one source of truth.
10095        // Uses a fresh `(payment, catalog)` edge so none of the swept
10096        // subjects collide with the pre-existing entries in
10097        // `three_member_spec`.
10098        for subject in [
10099            "checkout.events.charge.failed",
10100            "rio.events.order.charged",
10101            "orders",
10102            "orders.123",
10103            "snake_case.token",
10104            "kebab-case.token",
10105            "MixedCase.Token",
10106            "orders.*.charged",
10107            "*.events.*",
10108            "orders.>",
10109        ] {
10110            let mut s = three_member_spec();
10111            s.contratos.push(WitContract {
10112                de: "payment".into(),
10113                para: "catalog".into(),
10114                wit: "nats:pub-sub".into(),
10115                endpoint: None,
10116                subject: Some(subject.into()),
10117                slot: None,
10118            });
10119            s.validate()
10120                .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
10121        }
10122    }
10123
10124    #[test]
10125    fn contrato_subject_empty_takes_precedence_over_invalid() {
10126        // Ordering pin: `ContratoSubjectEmpty` is the more self-
10127        // locating diagnostic on `""` and must lead — the value-shape
10128        // gate is only reached after the empty-check fires. Mirrors
10129        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
10130        // the peer payload axis.
10131        let mut s = three_member_spec();
10132        s.contratos.push(WitContract {
10133            de: "payment".into(),
10134            para: "catalog".into(),
10135            wit: "nats:pub-sub".into(),
10136            endpoint: None,
10137            subject: Some(String::new()),
10138            slot: None,
10139        });
10140        let err = s.validate().unwrap_err();
10141        assert!(
10142            matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
10143            "got {err:?}"
10144        );
10145    }
10146
10147    #[test]
10148    fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
10149        // Diagnostic-shape pin — the offending `:subject` + `:de` +
10150        // `:para` + a non-empty reason flow through verbatim so the
10151        // author can grep their caixa.lisp for the offending contrato
10152        // block and fix it in one edit. Same shape as
10153        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
10154        // and `wit_invalid_diagnostic_carries_offending_wit`.
10155        let err = contrato_subject_err("foo..bar");
10156        match err {
10157            AplicacaoError::ContratoSubjectInvalid {
10158                de,
10159                para,
10160                subject,
10161                reason,
10162            } => {
10163                assert_eq!(de, "payment");
10164                assert_eq!(para, "catalog");
10165                assert_eq!(subject, "foo..bar");
10166                assert!(!reason.is_empty(), "reason field must be non-empty");
10167            }
10168            other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
10169        }
10170    }
10171
10172    #[test]
10173    fn target_view_pubsub_subject_passes_through_to_typed_view() {
10174        // The compounding theorem on the pub-sub axis: every
10175        // `WitTarget::PubSub { subject }` returned by `target()` carries
10176        // a NATS-server-accepted subject. Renderers downstream of
10177        // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
10178        // NATS Stream/Consumer CR emitter, the future `feira app graph`
10179        // view's subject labeller) can rely on this without re-checking
10180        // — the type system carries the proof. Mirrors
10181        // `target_view_payload_is_guaranteed_nonempty_after_target_call`
10182        // on the peer axes.
10183        let nats = WitContract {
10184            de: "a".into(),
10185            para: "b".into(),
10186            wit: "nats:pub-sub".into(),
10187            endpoint: None,
10188            subject: Some("orders.events.*.charged".into()),
10189            slot: None,
10190        };
10191        match nats.target().unwrap() {
10192            WitTarget::PubSub { subject } => {
10193                assert_eq!(subject, "orders.events.*.charged");
10194            }
10195            other => panic!("expected PubSub, got {other:?}"),
10196        }
10197    }
10198
10199    // ── :contratos :slot value-shape gate ────────────────────────────────
10200    //
10201    // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
10202    // (63e18a0) value-shape suites on the peer payload axes. Until this
10203    // gate landed `WitContract::target()` only refused the empty string
10204    // for the Store arm; a structurally invalid slot (raw whitespace,
10205    // control character, non-ASCII byte, paste-from-binary multi-line
10206    // blob) silently passed validate and surfaced at runtime as a
10207    // per-backend kv write rejection or a silent next-read corruption,
10208    // far from the source caixa.lisp with no field naming which
10209    // `:contratos` edge carried the typo. Every authoring footgun the
10210    // kv backend intersection-floor would catch on write now becomes a
10211    // caixa-build-time `ContratoSlotInvalid` with the offending
10212    // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
10213    // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
10214    // peer payload axes; same shared predicate
10215    // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
10216    // any two axes' rule enforcement is a build error at the
10217    // predicate, not piecemeal across renderers. Closes the typed
10218    // payload-axis value-shape trajectory across all three legs of the
10219    // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
10220
10221    fn contrato_slot_err(slot: &str) -> AplicacaoError {
10222        // Fresh spec per call so the new contract doesn't collide on
10223        // identity with `three_member_spec`'s pre-existing entries
10224        // and doesn't close a synchronous cycle the cycle detector
10225        // would reject before the slot-shape gate fires. The new edge
10226        // uses `(payment, catalog)` — a pair the fixture doesn't
10227        // already declare in either direction (the fixture carries
10228        // `cart -> catalog` and `cart -> payment`, so `payment ->
10229        // catalog` doesn't form a cycle on the sync subgraph) — with
10230        // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
10231        // slot-shape gate fires cleanly after the wit-shape gate
10232        // (which `"wasi:keyvalue/store"` passes). Same edge pair the
10233        // peer `contrato_subject_err` helper uses (63e18a0).
10234        let mut s = three_member_spec();
10235        s.contratos.push(WitContract {
10236            de: "payment".into(),
10237            para: "catalog".into(),
10238            wit: "wasi:keyvalue/store".into(),
10239            endpoint: None,
10240            subject: None,
10241            slot: Some(slot.into()),
10242        });
10243        s.validate().unwrap_err()
10244    }
10245
10246    #[test]
10247    fn rejects_store_contrato_slot_with_whitespace() {
10248        // Fail-before-pass-after pin — pre-gate `"check out/$order"`
10249        // silently landed at the kv backend with whitespace whose
10250        // runtime behavior varies unpredictably across backends (etcd
10251        // accepts, Redis accepts then breaks on next CLI op, DynamoDB
10252        // rejects on write). Now caught at the source caixa.lisp.
10253        let err = contrato_slot_err("check out/$order");
10254        assert!(
10255            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10256                if slot == "check out/$order" && reason.contains("whitespace")),
10257            "got {err:?}"
10258        );
10259    }
10260
10261    #[test]
10262    fn rejects_store_contrato_slot_with_tab() {
10263        // Tab byte arm-pinned separately from the space arm so a
10264        // future relaxation that admits one but not the other surfaces
10265        // here.
10266        let err = contrato_slot_err("check\tout");
10267        assert!(
10268            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10269                if slot == "check\tout" && reason.contains("whitespace")),
10270            "got {err:?}"
10271        );
10272    }
10273
10274    #[test]
10275    fn rejects_store_contrato_slot_with_control_char() {
10276        // SOH (0x01) — distinct from the whitespace arm. Redis admits
10277        // and corrupts on RESP protocol framing; DynamoDB rejects on
10278        // write.
10279        let err = contrato_slot_err("checkout/\x01order");
10280        assert!(
10281            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10282                if slot == "checkout/\x01order" && reason.contains("control character")),
10283            "got {err:?}"
10284        );
10285    }
10286
10287    #[test]
10288    fn rejects_store_contrato_slot_with_newline() {
10289        // Embedded newline — the canonical "the paste-from-binary slug
10290        // spans multiple lines" footgun. Distinct from the whitespace
10291        // arm because `\n` is a control character (0x0A).
10292        let err = contrato_slot_err("checkout\norder");
10293        assert!(
10294            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10295                if slot == "checkout\norder" && reason.contains("control character")),
10296            "got {err:?}"
10297        );
10298    }
10299
10300    #[test]
10301    fn rejects_store_contrato_slot_with_non_ascii() {
10302        // Un-percent-encoded non-ASCII byte — the canonical "I copied
10303        // the slot from a doc with accented characters" footgun. Each
10304        // kv backend re-encodes non-ASCII differently (etcd preserves
10305        // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
10306        // rejects), so the typed slot's value set is the intersection-
10307        // floor every backend admits identically (printable ASCII).
10308        let err = contrato_slot_err("ch\u{e9}ckout/$order");
10309        assert!(
10310            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10311                if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
10312            "got {err:?}"
10313        );
10314    }
10315
10316    #[test]
10317    fn rejects_store_contrato_slot_too_long() {
10318        // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
10319        // legitimate-shape arms all pass (a single all-`a` token, no
10320        // separators); only the cap arm fires. Surfaces the paste-
10321        // from-binary / accidental-multi-line-blob landing footgun.
10322        // Mirrors `rejects_pubsub_contrato_subject_too_long` and
10323        // `rejects_http_contrato_endpoint_too_long` on the peer
10324        // payload axes.
10325        let big = "a".repeat(513);
10326        assert_eq!(big.len(), 513);
10327        let err = contrato_slot_err(&big);
10328        assert!(
10329            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10330                if slot == &big && reason.contains("max length of 512")),
10331            "got {err:?}"
10332        );
10333    }
10334
10335    #[test]
10336    fn store_contrato_slot_max_length_validates() {
10337        // 512-byte slot — exactly the cap. Boundary pin: drift in the
10338        // cap surfaces here and at `rejects_store_contrato_slot_too_long`
10339        // simultaneously, mirroring
10340        // `pubsub_contrato_subject_max_length_validates` and
10341        // `http_contrato_endpoint_max_length_validates` on the peer
10342        // payload axes.
10343        let big = "a".repeat(512);
10344        assert_eq!(big.len(), 512);
10345        let mut s = three_member_spec();
10346        s.contratos.push(WitContract {
10347            de: "payment".into(),
10348            para: "catalog".into(),
10349            wit: "wasi:keyvalue/store".into(),
10350            endpoint: None,
10351            subject: None,
10352            slot: Some(big),
10353        });
10354        s.validate().unwrap();
10355    }
10356
10357    #[test]
10358    fn store_contrato_slot_accepts_canonical_forms() {
10359        // Positive-set sweep: every canonical kv slot template the
10360        // substrate-side `is_wasi_keyvalue_slot` predicate accepts
10361        // (single-token identifiers, path-namespaced `$`-templates,
10362        // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
10363        // snake_case / kebab-case / MixedCase tokens, digit-bearing
10364        // tokens, percent-encoded fragments) must remain valid
10365        // contrato slots too. Drift between this list and the
10366        // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
10367        // surfaces at the shared predicate — one source of truth.
10368        // Uses a fresh `(payment, catalog)` edge so none of the swept
10369        // slots collide with the pre-existing entries in
10370        // `three_member_spec`.
10371        for slot in [
10372            "checkout",
10373            "checkout/$orderId",
10374            "users:{tenant}/{id}",
10375            "session.<sid>",
10376            "session.tokens.<sid>",
10377            "snake_case_key",
10378            "kebab-case-key",
10379            "MixedCase",
10380            "shard0",
10381            "v2/key",
10382            "users/caf%C3%A9",
10383        ] {
10384            let mut s = three_member_spec();
10385            s.contratos.push(WitContract {
10386                de: "payment".into(),
10387                para: "catalog".into(),
10388                wit: "wasi:keyvalue/store".into(),
10389                endpoint: None,
10390                subject: None,
10391                slot: Some(slot.into()),
10392            });
10393            s.validate()
10394                .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
10395        }
10396    }
10397
10398    #[test]
10399    fn contrato_slot_empty_takes_precedence_over_invalid() {
10400        // Ordering pin: `ContratoSlotEmpty` is the more self-locating
10401        // diagnostic on `""` and must lead — the value-shape gate is
10402        // only reached after the empty-check fires. Mirrors
10403        // `contrato_subject_empty_takes_precedence_over_invalid` and
10404        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
10405        // the peer payload axes.
10406        let mut s = three_member_spec();
10407        s.contratos.push(WitContract {
10408            de: "payment".into(),
10409            para: "catalog".into(),
10410            wit: "wasi:keyvalue/store".into(),
10411            endpoint: None,
10412            subject: None,
10413            slot: Some(String::new()),
10414        });
10415        let err = s.validate().unwrap_err();
10416        assert!(
10417            matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
10418            "got {err:?}"
10419        );
10420    }
10421
10422    #[test]
10423    fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
10424        // Diagnostic-shape pin — the offending `:slot` + `:de` +
10425        // `:para` + a non-empty reason flow through verbatim so the
10426        // author can grep their caixa.lisp for the offending contrato
10427        // block and fix it in one edit. Same shape as
10428        // `contrato_subject_invalid_diagnostic_carries_offending_subject`
10429        // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
10430        // on the peer payload axes.
10431        let err = contrato_slot_err("check out/$order");
10432        match err {
10433            AplicacaoError::ContratoSlotInvalid {
10434                de,
10435                para,
10436                slot,
10437                reason,
10438            } => {
10439                assert_eq!(de, "payment");
10440                assert_eq!(para, "catalog");
10441                assert_eq!(slot, "check out/$order");
10442                assert!(!reason.is_empty(), "reason field must be non-empty");
10443            }
10444            other => panic!("expected ContratoSlotInvalid, got {other:?}"),
10445        }
10446    }
10447
10448    #[test]
10449    fn target_view_store_slot_passes_through_to_typed_view() {
10450        // The compounding theorem on the store axis: every
10451        // `WitTarget::Store { slot }` returned by `target()` carries a
10452        // kv-backend-accepted slot template. Renderers downstream of
10453        // `typed_view()` (the future per-Servico `:capabilities
10454        // wasi:keyvalue/store` axis emitter, the future `feira app
10455        // graph` view's slot labeller, the future kv-provider CR
10456        // materializer) can rely on this without re-checking — the
10457        // type system carries the proof. Mirrors
10458        // `target_view_pubsub_subject_passes_through_to_typed_view` on
10459        // the peer payload axis.
10460        let store = WitContract {
10461            de: "a".into(),
10462            para: "b".into(),
10463            wit: "wasi:keyvalue/store".into(),
10464            endpoint: None,
10465            subject: None,
10466            slot: Some("checkout/$orderId".into()),
10467        };
10468        match store.target().unwrap() {
10469            WitTarget::Store { slot } => {
10470                assert_eq!(slot, "checkout/$orderId");
10471            }
10472            other => panic!("expected Store, got {other:?}"),
10473        }
10474    }
10475
10476    #[test]
10477    fn rejects_self_loop_in_synchronous_contratos() {
10478        // A synchronous self-edge (`cart → cart` over HTTP) is now
10479        // rejected by the dedicated `ContratoSelfLoop` gate — a precise
10480        // "this edge is degenerate" diagnostic — rather than incidentally
10481        // by the cycle detector framing it as a `["cart", "cart"]`
10482        // multi-node deadlock.
10483        let mut s = three_member_spec();
10484        s.contratos.push(contract_http("cart", "cart", "/loop"));
10485        let err = s.validate().unwrap_err();
10486        match err {
10487            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
10488                assert_eq!(caixa, "cart");
10489                assert_eq!(wit, "wasi:http/proxy");
10490            }
10491            other => panic!("expected ContratoSelfLoop, got {other:?}"),
10492        }
10493    }
10494
10495    #[test]
10496    fn rejects_self_loop_in_pubsub_contratos() {
10497        // The cycle detector excludes pub-sub edges (acyclic by
10498        // construction), so before the explicit gate a `nats:pub-sub`
10499        // self-edge silently validated and rendered a self-allow CNP.
10500        // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
10501        let mut s = three_member_spec();
10502        s.contratos.push(WitContract {
10503            de: "payment".into(),
10504            para: "payment".into(),
10505            wit: "nats:pub-sub".into(),
10506            endpoint: None,
10507            subject: Some("rio.events.payment".into()),
10508            slot: None,
10509        });
10510        let err = s.validate().unwrap_err();
10511        match err {
10512            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
10513                assert_eq!(caixa, "payment");
10514                assert_eq!(wit, "nats:pub-sub");
10515            }
10516            other => panic!("expected ContratoSelfLoop, got {other:?}"),
10517        }
10518    }
10519
10520    #[test]
10521    fn self_loop_fires_before_payload_shape_check() {
10522        // The structural "this edge can't exist" error precedes the
10523        // narrower payload-shape diagnostics: a self-edge carrying an
10524        // otherwise-malformed endpoint still reports ContratoSelfLoop,
10525        // not ContratoEndpointInvalid.
10526        let mut s = three_member_spec();
10527        s.contratos.push(WitContract {
10528            de: "cart".into(),
10529            para: "cart".into(),
10530            wit: "wasi:http/proxy".into(),
10531            endpoint: Some("not-absolute".into()),
10532            subject: None,
10533            slot: None,
10534        });
10535        match s.validate().unwrap_err() {
10536            AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
10537            other => panic!("expected ContratoSelfLoop, got {other:?}"),
10538        }
10539    }
10540
10541    #[test]
10542    fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
10543        // A self-edge naming a non-member reports the more fundamental
10544        // ContratoMemberMissing first (the member doesn't exist), so the
10545        // self-loop gate is reached only once both endpoints resolve.
10546        let mut s = three_member_spec();
10547        s.contratos.push(contract_http("ghost", "ghost", "/loop"));
10548        match s.validate().unwrap_err() {
10549            AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
10550            other => panic!("expected ContratoMemberMissing, got {other:?}"),
10551        }
10552    }
10553
10554    #[test]
10555    fn rejects_two_node_synchronous_cycle() {
10556        let mut s = three_member_spec();
10557        // existing edges: cart → catalog, cart → payment
10558        // adding catalog → cart closes a 2-cycle on the HTTP subgraph
10559        s.contratos
10560            .push(contract_http("catalog", "cart", "/refresh"));
10561        let err = s.validate().unwrap_err();
10562        match err {
10563            AplicacaoError::ContratoCycle { cycle } => {
10564                // Cycle traversal should mention both endpoints, with
10565                // the back-edge target appearing as both first and last
10566                // element to close the loop.
10567                assert!(cycle.len() >= 3);
10568                assert_eq!(cycle.first(), cycle.last());
10569                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
10570                assert!(body.contains("cart"));
10571                assert!(body.contains("catalog"));
10572            }
10573            other => panic!("expected ContratoCycle, got {other:?}"),
10574        }
10575    }
10576
10577    #[test]
10578    fn rejects_three_node_synchronous_cycle() {
10579        let mut s = three_member_spec();
10580        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
10581        s.contratos = vec![
10582            contract_http("catalog", "cart", "/x"),
10583            contract_http("cart", "payment", "/y"),
10584            contract_http("payment", "catalog", "/z"),
10585        ];
10586        let err = s.validate().unwrap_err();
10587        match err {
10588            AplicacaoError::ContratoCycle { cycle } => {
10589                assert_eq!(cycle.first(), cycle.last());
10590                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
10591                assert_eq!(body.len(), 3);
10592                assert!(body.contains("cart"));
10593                assert!(body.contains("catalog"));
10594                assert!(body.contains("payment"));
10595            }
10596            other => panic!("expected ContratoCycle, got {other:?}"),
10597        }
10598    }
10599
10600    #[test]
10601    fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
10602        // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
10603        // "acyclic by construction" — so a cycle whose closing edge
10604        // is pub-sub should NOT raise ContratoCycle.
10605        let mut s = three_member_spec();
10606        s.contratos = vec![
10607            contract_http("catalog", "cart", "/x"),
10608            contract_http("cart", "payment", "/y"),
10609            // Closing edge is pub-sub — async; not a sync deadlock.
10610            WitContract {
10611                de: "payment".into(),
10612                para: "catalog".into(),
10613                wit: "nats:pub-sub".into(),
10614                endpoint: None,
10615                subject: Some("checkout.events.charge.completed".into()),
10616                slot: None,
10617            },
10618        ];
10619        s.validate().expect("pub-sub edge breaks the sync cycle");
10620    }
10621
10622    #[test]
10623    fn store_edge_counts_as_synchronous_for_cycle_detection() {
10624        // wasi:keyvalue/store is request/response; a cycle through one
10625        // *is* a sync deadlock, just like HTTP.
10626        let mut s = three_member_spec();
10627        s.contratos = vec![
10628            contract_http("catalog", "cart", "/x"),
10629            WitContract {
10630                de: "cart".into(),
10631                para: "catalog".into(),
10632                wit: "wasi:keyvalue/store".into(),
10633                endpoint: None,
10634                subject: None,
10635                slot: Some("session/$id".into()),
10636            },
10637        ];
10638        let err = s.validate().unwrap_err();
10639        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
10640    }
10641
10642    #[test]
10643    fn capability_edge_counts_as_synchronous_for_cycle_detection() {
10644        // Capability-only edges (unknown WIT shape, no payload) default
10645        // to synchronous — safer; authors with truly async capability
10646        // semantics can model them as pub-sub explicitly.
10647        let mut s = three_member_spec();
10648        s.contratos = vec![
10649            contract_http("catalog", "cart", "/x"),
10650            WitContract {
10651                de: "cart".into(),
10652                para: "catalog".into(),
10653                wit: "custom:exchange".into(),
10654                endpoint: None,
10655                subject: None,
10656                slot: None,
10657            },
10658        ];
10659        let err = s.validate().unwrap_err();
10660        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
10661    }
10662
10663    #[test]
10664    fn long_acyclic_chain_validates() {
10665        // A long sync chain (no back-edges) must validate even when
10666        // every node is reachable from the first.
10667        let mut s = three_member_spec();
10668        s.membros = vec![
10669            membro("a", "^0.1"),
10670            membro("b", "^0.1"),
10671            membro("c", "^0.1"),
10672            membro("d", "^0.1"),
10673            membro("e", "^0.1"),
10674        ];
10675        s.contratos = vec![
10676            contract_http("a", "b", "/1"),
10677            contract_http("b", "c", "/2"),
10678            contract_http("c", "d", "/3"),
10679            contract_http("d", "e", "/4"),
10680        ];
10681        s.entrada.as_mut().unwrap().para = "a".into();
10682        s.validate().unwrap();
10683    }
10684
10685    #[test]
10686    fn diamond_acyclic_validates() {
10687        // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
10688        let mut s = three_member_spec();
10689        s.membros = vec![
10690            membro("a", "^0.1"),
10691            membro("b", "^0.1"),
10692            membro("c", "^0.1"),
10693            membro("d", "^0.1"),
10694        ];
10695        s.contratos = vec![
10696            contract_http("a", "b", "/1"),
10697            contract_http("a", "c", "/2"),
10698            contract_http("b", "d", "/3"),
10699            contract_http("c", "d", "/4"),
10700        ];
10701        s.entrada.as_mut().unwrap().para = "a".into();
10702        s.validate().unwrap();
10703    }
10704
10705    // ── duplicate-`:contratos` build-error gate ──────────────────────────
10706
10707    #[test]
10708    fn rejects_duplicate_http_contrato() {
10709        // Fail-before-pass-after pin: the fixture's `cart → catalog`
10710        // HTTP edge appears once. Push an identical entry — same
10711        // (de, para, wit, endpoint) — and validate() must reject it.
10712        // Until this gate landed the typed surface accepted the
10713        // duplicate silently and caixa-mesh's `cilium_network_policies`
10714        // emitted two ``CiliumNetworkPolicy`` objects with identical
10715        // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
10716        // admission rejects on `kubectl apply` far from the source.
10717        let mut s = three_member_spec();
10718        s.contratos
10719            .push(contract_http("cart", "catalog", "/products/:id"));
10720        let err = s.validate().unwrap_err();
10721        assert!(
10722            matches!(
10723                err,
10724                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
10725                    if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
10726            ),
10727            "got {err:?}"
10728        );
10729    }
10730
10731    #[test]
10732    fn rejects_duplicate_pubsub_contrato() {
10733        // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
10734        // edges with identical (de, para, subject) are degenerate;
10735        // pin that the typed surface refuses both at validate time.
10736        let mut s = three_member_spec();
10737        let pubsub = WitContract {
10738            de: "payment".into(),
10739            para: "cart".into(),
10740            wit: "nats:pub-sub".into(),
10741            endpoint: None,
10742            subject: Some("checkout.events.charge.failed".into()),
10743            slot: None,
10744        };
10745        s.contratos.push(pubsub.clone());
10746        s.contratos.push(pubsub);
10747        let err = s.validate().unwrap_err();
10748        assert!(
10749            matches!(
10750                err,
10751                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
10752                    if de == "payment" && para == "cart" && wit == "nats:pub-sub"
10753            ),
10754            "got {err:?}"
10755        );
10756    }
10757
10758    #[test]
10759    fn rejects_duplicate_store_contrato() {
10760        // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
10761        // edges with identical (de, para, slot) collapse to one mesh-
10762        // policy edge; pin the build error.
10763        let mut s = three_member_spec();
10764        let store = WitContract {
10765            de: "cart".into(),
10766            para: "payment".into(),
10767            wit: "wasi:keyvalue/store".into(),
10768            endpoint: None,
10769            subject: None,
10770            slot: Some("checkout/$orderId".into()),
10771        };
10772        // Drop the conflicting HTTP `cart → payment` edge from the
10773        // fixture so the duplicate-store pair is the only one
10774        // distinguishable on this pair.
10775        s.contratos
10776            .retain(|c| !(c.de == "cart" && c.para == "payment"));
10777        s.contratos.push(store.clone());
10778        s.contratos.push(store);
10779        let err = s.validate().unwrap_err();
10780        assert!(
10781            matches!(
10782                err,
10783                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
10784                    if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
10785            ),
10786            "got {err:?}"
10787        );
10788    }
10789
10790    #[test]
10791    fn rejects_duplicate_capability_contrato() {
10792        // Same gate on the pure-capability axis (no payload selector).
10793        // Two contracts with identical (de, para, wit) and no
10794        // endpoint/subject/slot are duplicate edges; pin so a future
10795        // `target_label` change can't accidentally collapse the
10796        // capability arm into a None-shaped key that compares equal
10797        // to a populated one.
10798        let mut s = three_member_spec();
10799        let capability = WitContract {
10800            de: "cart".into(),
10801            para: "catalog".into(),
10802            wit: "pleme:cap/audit".into(),
10803            endpoint: None,
10804            subject: None,
10805            slot: None,
10806        };
10807        s.contratos.push(capability.clone());
10808        s.contratos.push(capability);
10809        let err = s.validate().unwrap_err();
10810        match err {
10811            AplicacaoError::ContratoDuplicate {
10812                de,
10813                para,
10814                wit,
10815                target,
10816            } => {
10817                assert_eq!(de, "cart");
10818                assert_eq!(para, "catalog");
10819                assert_eq!(wit, "pleme:cap/audit");
10820                assert!(
10821                    target.contains("capability"),
10822                    "capability-edge duplicate diagnostic must surface the \
10823                     no-payload shape (got target = {target:?})"
10824                );
10825            }
10826            other => panic!("expected ContratoDuplicate, got {other:?}"),
10827        }
10828    }
10829
10830    #[test]
10831    fn accepts_distinct_http_paths_between_same_pair() {
10832        // Negative pin: two HTTP contracts cart → catalog at distinct
10833        // endpoints (`/products/:id` and `/search`) are *not*
10834        // duplicates — they're distinct typed edges differing on the
10835        // payload axis. The duplicate-gate must not over-match here,
10836        // since the cart-calls-catalog-on-multiple-paths shape is the
10837        // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
10838        // example: cart calls catalog at /products/:id, payment at
10839        // /charge — same shape extends to two paths on one para).
10840        let mut s = three_member_spec();
10841        s.contratos
10842            .push(contract_http("cart", "catalog", "/search"));
10843        s.validate()
10844            .expect("distinct endpoints between same (de, para) must validate");
10845    }
10846
10847    #[test]
10848    fn accepts_same_endpoint_on_different_pairs() {
10849        // Negative pin: the same `/charge` endpoint reused on two
10850        // different (de, para) pairs is two distinct edges, not a
10851        // duplicate. Pinning this shape so the gate's identity key
10852        // includes both `de` and `para` (not just `(wit, endpoint)`).
10853        let mut s = three_member_spec();
10854        s.contratos
10855            .push(contract_http("payment", "catalog", "/charge"));
10856        s.validate()
10857            .expect("same endpoint reused on distinct (de, para) must validate");
10858    }
10859
10860    #[test]
10861    fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
10862        // Pin the diagnostic shape: the duplicate-edge error names
10863        // *which* target field carried the conflict, so the author
10864        // doesn't have to re-grep the source caixa.lisp to find it.
10865        // Same self-locating diagnostic discipline as
10866        // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
10867        let mut s = three_member_spec();
10868        s.contratos
10869            .push(contract_http("cart", "catalog", "/products/:id"));
10870        let err = s.validate().unwrap_err();
10871        let msg = format!("{err}");
10872        assert!(
10873            msg.contains("\"/products/:id\""),
10874            "duplicate-contrato diagnostic must name the offending \
10875             :endpoint payload (got: {msg:?})"
10876        );
10877        assert!(
10878            msg.contains("cart") && msg.contains("catalog"),
10879            "diagnostic must name both endpoints of the duplicate edge \
10880             (got: {msg:?})"
10881        );
10882    }
10883
10884    #[test]
10885    fn duplicate_contrato_gate_runs_after_membership_check() {
10886        // Order pin: a duplicate contract whose `:de` is *also* not in
10887        // `:membros` surfaces the membership error first — the
10888        // missing-member diagnostic is more locating than the
10889        // duplicate-edge one (the author has to fix the membership
10890        // before the duplicate is meaningful). Same ordering
10891        // discipline as `membros_validation_runs_before_contratos_membership_check`.
10892        let mut s = three_member_spec();
10893        s.contratos.push(contract_http("phantom", "catalog", "/x"));
10894        s.contratos.push(contract_http("phantom", "catalog", "/x"));
10895        let err = s.validate().unwrap_err();
10896        assert!(
10897            matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
10898            "membership-missing must fire before duplicate-edge (got {err:?})"
10899        );
10900    }
10901
10902    #[test]
10903    fn duplicate_contrato_gate_runs_after_target_shape_check() {
10904        // Order pin: a contract with a malformed target (e.g. an HTTP
10905        // wit world with an empty :endpoint) surfaces the target-shape
10906        // error first, not the duplicate one. Even when two such
10907        // malformed entries are identical, the per-contract `target()`
10908        // check fires inside the loop *before* the duplicate-key
10909        // insert, so the diagnostic remains the most-locating one.
10910        let mut s = three_member_spec();
10911        let malformed = WitContract {
10912            de: "cart".into(),
10913            para: "catalog".into(),
10914            wit: "wasi:http/proxy".into(),
10915            endpoint: Some(String::new()),
10916            subject: None,
10917            slot: None,
10918        };
10919        s.contratos.push(malformed.clone());
10920        s.contratos.push(malformed);
10921        let err = s.validate().unwrap_err();
10922        assert!(
10923            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
10924            "endpoint-empty must fire before duplicate-edge (got {err:?})"
10925        );
10926    }
10927
10928    #[test]
10929    fn wit_target_label_pins_per_variant_format() {
10930        // Label format is the single source of truth every duplicate-
10931        // `:contratos` diagnostic + every future `feira app graph`
10932        // consumer routes through. Pin the shape per variant so a
10933        // future edit to `WitTarget::label` (e.g. a JSON emitter that
10934        // strips the leading `:`, or a rename from `endpoint` →
10935        // `path`) surfaces as a red-red test rather than as a silent
10936        // downstream diagnostic drift. Together with the exhaustive
10937        // `match` on `WitTarget` inside `label()`, adding a future
10938        // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
10939        // peer, per-edge WIT registry variants) is a compile error at
10940        // the label site — not a fall-through into the `Capability`
10941        // "no payload" default the prior raw-field-probe helper
10942        // silently landed on.
10943        assert_eq!(
10944            WitTarget::Http {
10945                endpoint: "/charge",
10946            }
10947            .label(),
10948            "\
10949:endpoint \"/charge\""
10950        );
10951        assert_eq!(
10952            WitTarget::PubSub {
10953                subject: "events.checkout.paid",
10954            }
10955            .label(),
10956            "\
10957:subject \"events.checkout.paid\""
10958        );
10959        assert_eq!(
10960            WitTarget::Store {
10961                slot: "checkout/$order",
10962            }
10963            .label(),
10964            "\
10965:slot \"checkout/$order\""
10966        );
10967        assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
10968        // Capability-arm label routes through the lifted
10969        // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
10970        // declaration per arm, next to the variant" discipline the
10971        // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
10972        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
10973        // consts already carry extends to the payload-less arm; the
10974        // byte-string equality pin below plus this label-routes-
10975        // through-the-const pin make a future rebrand on either the
10976        // const declaration or the `label()` template a build error
10977        // here rather than a downstream consumer surprise.
10978        assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
10979        assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
10980    }
10981
10982    #[test]
10983    fn wit_target_display_routes_through_label_helper() {
10984        // Fail-before-pass-after pin on the fourth (and only remaining)
10985        // typed-shape-discriminator axis to converge onto the
10986        // three-path-convergence discipline the sibling M3
10987        // [`PlacementStrategy`] (0a2f653) and M2
10988        // [`crate::supervisor::RestartStrategy`] /
10989        // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
10990        // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
10991        // through [`WitTarget::label`], so every consumer reaching for
10992        // `format!("{v}")` on a typed payload target lands on the same
10993        // stable author-facing byte-string [`WitTarget::label`] returns
10994        // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
10995        // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
10996        // `:contratos` gate seeds via [`WitTarget::label`] at
10997        // aplicacao.rs:5491 already threads through.
10998        //
10999        // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
11000        // through to the `Debug` derive's structural output
11001        // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
11002        // rather than the [`WitTarget::label`] helper's stable byte-
11003        // string (`:endpoint "/charge"` — the author-facing `:contratos`
11004        // keyword form). Every future consumer that reaches for
11005        // `format!("{target}")` — the canonical shape every user-facing
11006        // pretty-print site on the sibling typed-enum axes
11007        // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
11008        // [`crate::supervisor::RestartPolicy`]) already uses — would
11009        // silently land under a different byte-string than the
11010        // [`WitTarget::label`] callers that the duplicate-`:contratos`
11011        // diagnostic already threads through, with the mismatch
11012        // surfacing as a downstream diagnostic / graph / audit line
11013        // reading one spelling while the substrate's own gate emitted
11014        // another.
11015        //
11016        // Pin the routing here so a future
11017        // `impl std::fmt::Display for WitTarget<'_>` reimplementation
11018        // that hand-rolls the per-arm formatting instead of delegating
11019        // to [`WitTarget::label`] fails at caixa-core build time.
11020        for variant in [
11021            WitTarget::Http {
11022                endpoint: "/charge",
11023            },
11024            WitTarget::PubSub {
11025                subject: "events.checkout.paid",
11026            },
11027            WitTarget::Store {
11028                slot: "checkout/$order",
11029            },
11030            WitTarget::Capability,
11031        ] {
11032            assert_eq!(
11033                variant.to_string(),
11034                variant.label(),
11035                "WitTarget::{variant:?} Display must route through \
11036                 WitTarget::label (single source of truth: the lifted \
11037                 payload_pair 4-arm dispatch the label helper already \
11038                 threads through)"
11039            );
11040        }
11041    }
11042
11043    #[test]
11044    fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
11045        // Consumer-side pin on the three-path convergence:
11046        // [`std::fmt::Display`] agrees byte-for-byte with the
11047        // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
11048        // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
11049        // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
11050        // Pre-lift the two paths were structurally independent — the
11051        // substrate-side gate reached for `target_view.label()` while a
11052        // future downstream diagnostic / graph / audit line reaching
11053        // for `format!("{target}")` would silently land on the `Debug`
11054        // derive's structural output. Pin the two paths byte-for-byte
11055        // here so any future variant addition (M4 `Rest`/`Grpc` split
11056        // of [`WitTarget::Http`], `Queue`-shaped peer of
11057        // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
11058        // match error at [`WitTarget::payload_pair`] rather than a
11059        // silent per-consumer dispatch miss.
11060        for variant in [
11061            WitTarget::Http {
11062                endpoint: "/charge",
11063            },
11064            WitTarget::PubSub {
11065                subject: "events.checkout.paid",
11066            },
11067            WitTarget::Store {
11068                slot: "checkout/$order",
11069            },
11070            WitTarget::Capability,
11071        ] {
11072            assert_eq!(
11073                format!("{variant}"),
11074                variant.label(),
11075                "WitTarget::{variant:?} Display byte-string must match \
11076                 the AplicacaoError::ContratoDuplicate `target:` carrier \
11077                 the AplicacaoSpec::validate duplicate-`:contratos` gate \
11078                 seeds via WitTarget::label — three-path convergence: \
11079                 Display + label + payload_pair all resolve to the same \
11080                 per-arm byte-string"
11081            );
11082        }
11083    }
11084
11085    #[test]
11086    fn wit_target_payload_pair_pins_per_variant() {
11087        // Pin the per-arm `(field-name, payload)` pair single-sourced
11088        // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
11089        // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
11090        // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
11091        // and [`WitTarget::field_name`] (returns the first component)
11092        // route through. Until this lift landed [`WitTarget::label`]
11093        // dispatched on the same three arms with a per-arm
11094        // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
11095        // paired [`WitTarget::HTTP_FIELD_NAME`] /
11096        // [`WitTarget::PUBSUB_FIELD_NAME`] /
11097        // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
11098        // canonical "same shape, written N times" duplication
11099        // THEORY.md §I.3.5 promotes to a build-time concern. A future
11100        // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
11101        // [`WitTarget::Http`], `Queue`-shaped peer of
11102        // [`WitTarget::Store`]) is one match-arm edit at
11103        // [`WitTarget::payload_pair`], visible here as a compile-time
11104        // exhaustiveness error on both this pin and the label-format
11105        // pin above.
11106        assert_eq!(
11107            WitTarget::Http {
11108                endpoint: "/charge"
11109            }
11110            .payload_pair(),
11111            Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
11112        );
11113        assert_eq!(
11114            WitTarget::PubSub {
11115                subject: "events.x",
11116            }
11117            .payload_pair(),
11118            Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
11119        );
11120        assert_eq!(
11121            WitTarget::Store {
11122                slot: "checkout/$order",
11123            }
11124            .payload_pair(),
11125            Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
11126        );
11127        assert_eq!(WitTarget::Capability.payload_pair(), None);
11128    }
11129
11130    #[test]
11131    fn wit_target_field_name_pins_per_variant() {
11132        // Pin the per-arm author-facing `:contratos` payload field
11133        // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
11134        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
11135        // + returned by [`WitTarget::field_name`]. Every downstream
11136        // consumer (the [`WitContract::target`] gate's `expected:`
11137        // scalar, the [`WitTarget::label`] template's keyword prefix,
11138        // the `feira app graph` verb's `endpoint=…` prefix) routes
11139        // through the same three peer consts, so a rename on the
11140        // author-surface `(defcaixa … :contratos ((:de … :para …
11141        // :wit … :endpoint …)))` field lands in exactly one place.
11142        assert_eq!(
11143            WitTarget::Http {
11144                endpoint: "/charge"
11145            }
11146            .field_name(),
11147            Some(WitTarget::HTTP_FIELD_NAME),
11148        );
11149        assert_eq!(
11150            WitTarget::PubSub {
11151                subject: "events.x",
11152            }
11153            .field_name(),
11154            Some(WitTarget::PUBSUB_FIELD_NAME),
11155        );
11156        assert_eq!(
11157            WitTarget::Store {
11158                slot: "checkout/$order",
11159            }
11160            .field_name(),
11161            Some(WitTarget::STORE_FIELD_NAME),
11162        );
11163        // Capability arm carries no payload field — the diagnostic
11164        // never reports `expected: "capability"` because the gate's
11165        // Capability arm accepts no payload at all (it fires the
11166        // "expected: none" WrongTarget error instead), so the field-
11167        // name method returns None here rather than a placeholder.
11168        assert_eq!(WitTarget::Capability.field_name(), None);
11169
11170        // Peer const scalar values pinned so a rename on either side
11171        // (author-surface field name in the `(defcaixa …)` DSL, or
11172        // the diagnostic's `expected:` scalar) can't drift without
11173        // failing here first.
11174        assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
11175        assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
11176        assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
11177    }
11178
11179    #[test]
11180    fn wit_target_field_names_are_pairwise_distinct() {
11181        // Distinctness pin: if any two of the three payload-field-name
11182        // scalars ever collapse (e.g. an accidental `endpoint` copy-
11183        // paste over the `subject` const), the [`WitContract::target`]
11184        // gate's diagnostic would point authors at the wrong field —
11185        // an "expected `:endpoint`" error on a pub-sub edge would
11186        // silently misroute the fix. Same cross-axis-distinctness
11187        // discipline as the peer M3 `:placement :estrategia` variant-
11188        // discriminator scalar-value pins (cc8f749) applied to the
11189        // payload-field-name axis.
11190        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
11191        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
11192        assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
11193    }
11194
11195    #[test]
11196    fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
11197        // 4-way distinctness pin extending the sibling
11198        // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
11199        // (which covers only the HTTP / PubSub / Store payload arms)
11200        // onto the fourth scalar the shared
11201        // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
11202        // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
11203        // (`"none"`), the payload-less Capability-arm rejection scalar.
11204        //
11205        // All four [`WitTarget::HTTP_FIELD_NAME`] /
11206        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
11207        // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
11208        // dispatch surface [`WitContract::target`] writes onto the
11209        // `ContratoWrongTarget::expected` field — the same `&'static
11210        // str` axis authors read as "this WIT world's shape admits
11211        // (only|not) `:<field>`". Pairwise-distinctness is the invariant
11212        // downstream consumers rely on: an `expected: "endpoint"`
11213        // diagnostic on a Capability-shaped edge tells the author to
11214        // add a `:endpoint "…"` slot to a WIT world that admits none,
11215        // silently misrouting the fix. Until this pin landed the three
11216        // payload-arm consts were distinctness-guarded by the sibling
11217        // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
11218        // scalar (d4f54f2) sat unguarded — a rebrand collision (the
11219        // author-facing vocabulary shift from `"none"` to `"endpoint"`
11220        // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
11221        // into per-shape peers) would have silently landed one
11222        // Capability-arm rejection on a payload-arm's `expected:` byte-
11223        // string and desynchronized the diagnostic from the author's
11224        // typed shape.
11225        //
11226        // Same 4-way pairwise-distinctness pin discipline as the peer
11227        // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
11228        // (cc8f749) applies on the sibling M3 closed-set typed-enum
11229        // scalar-value dispatch axis; extends the pin trajectory the
11230        // sibling `wit_target_field_names_are_pairwise_distinct`
11231        // 3-way pin opened to cover the last unguarded corner on the
11232        // `ContratoWrongTarget::expected` scalar-value axis.
11233        //
11234        // Fail-before-pass-after locally verified by mutating
11235        // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
11236        // — this pin fires as expected; restoring passes.
11237        let all = [
11238            WitTarget::HTTP_FIELD_NAME,
11239            WitTarget::PUBSUB_FIELD_NAME,
11240            WitTarget::STORE_FIELD_NAME,
11241            WitTarget::CAPABILITY_EXPECTED,
11242        ];
11243        for (i, a) in all.iter().enumerate() {
11244            for (j, b) in all.iter().enumerate() {
11245                if i != j {
11246                    assert_ne!(
11247                        a, b,
11248                        "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
11249                         STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
11250                         pairwise distinct — got duplicate {a:?} at indices \
11251                         {i} and {j}; all four scalars thread through the \
11252                         shared `AplicacaoError::ContratoWrongTarget::expected` \
11253                         &'static str axis, so a collapse silently misdirects \
11254                         the diagnostic on which typed shape the WIT world admits",
11255                    );
11256                }
11257            }
11258        }
11259    }
11260
11261    #[test]
11262    fn wit_target_is_variant_predicates_partition_the_arm_set() {
11263        // Fail-before-pass-after pin on the
11264        // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
11265        // each of the four variants exactly one of the generated
11266        // `is_http` / `is_pubsub` / `is_store` / `is_capability`
11267        // predicates returns `true` and the other three return
11268        // `false`. Prior to this derive the only production
11269        // arm-discriminator on [`WitTarget`] — the sync-cycle
11270        // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
11271        // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
11272        // the variant that expressed no compile-time link back to
11273        // the closed-set typed dispatch a future fifth
11274        // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
11275        // split of [`WitTarget::PubSub`] into shape-specific peers,
11276        // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
11277        // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
11278        // to thread through in lockstep or the DFS exclusion would
11279        // silently disagree with the peer diagnostic templates on
11280        // which arms carry sync-versus-async semantics. Peer of the
11281        // sibling [`crate::CaixaKind`] (f5bba80),
11282        // [`PlacementStrategy`] (766ec63),
11283        // [`crate::supervisor::RestartStrategy`],
11284        // [`crate::supervisor::RestartPolicy`], and
11285        // [`crate::upgrade::UpgradeInstruction`] (915a934)
11286        // `IsVariant` derives on the sibling closed-set typed-enum
11287        // discriminator axes — extends the same one-typed-dispatch-
11288        // per-variant discipline onto the last unlifted closed-set
11289        // typed-enum discriminator on the caixa surface (the M3
11290        // mesh-slot per-`:contratos` target-arm axis), closing the
11291        // arm-discriminator convergence trajectory across every
11292        // closed-set typed enum in caixa-core.
11293        let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
11294            (
11295                WitTarget::Http { endpoint: "/x" },
11296                [true, false, false, false],
11297            ),
11298            (
11299                WitTarget::PubSub {
11300                    subject: "events.x",
11301                },
11302                [false, true, false, false],
11303            ),
11304            (
11305                WitTarget::Store { slot: "kv/x" },
11306                [false, false, true, false],
11307            ),
11308            (WitTarget::Capability, [false, false, false, true]),
11309        ];
11310        for (variant, expected) in rows {
11311            let observed = [
11312                variant.is_http(),
11313                variant.is_pubsub(),
11314                variant.is_store(),
11315                variant.is_capability(),
11316            ];
11317            assert_eq!(
11318                observed, expected,
11319                "WitTarget::{variant:?} is_* predicates must partition \
11320                 the arm set (http, pubsub, store, capability); got {observed:?}"
11321            );
11322        }
11323    }
11324
11325    #[test]
11326    fn wit_target_is_variant_predicates_are_const_fn() {
11327        // The [`gen_platform::IsVariant`] derive emits `const fn`
11328        // predicates on the peer [`crate::CaixaKind`] +
11329        // [`crate::upgrade::UpgradeInstruction`] +
11330        // [`crate::supervisor::RestartStrategy`] +
11331        // [`crate::supervisor::RestartPolicy`] +
11332        // [`PlacementStrategy`] closed-set typed enums — pin the
11333        // same posture on [`WitTarget`] so a future accidental
11334        // downgrade to non-`const` (an added runtime helper reachable
11335        // only from a non-`const` context, a manual hand-rolled
11336        // `impl` that shadows the derive-generated method) trips at
11337        // caixa-core build time rather than surfacing as a downstream
11338        // `const`-context regression far from the derive declaration.
11339        //
11340        // Unlike the peer unit-variant enums (`CaixaKind` /
11341        // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
11342        // whose `const` constructors need no arguments, the three
11343        // payload-carrying [`WitTarget`] arms are const-constructed
11344        // through `&'static str` payloads — the same `'static`
11345        // lifetime the closed-set typed enum's four-arm partition
11346        // pin above already threads through.
11347        const HTTP: WitTarget<'static> = WitTarget::Http { endpoint: "/x" };
11348        const PUBSUB: WitTarget<'static> = WitTarget::PubSub { subject: "e" };
11349        const STORE: WitTarget<'static> = WitTarget::Store { slot: "kv/x" };
11350        const CAPABILITY: WitTarget<'static> = WitTarget::Capability;
11351        const IS_HTTP: bool = HTTP.is_http();
11352        const IS_PUBSUB: bool = PUBSUB.is_pubsub();
11353        const IS_STORE: bool = STORE.is_store();
11354        const IS_CAPABILITY: bool = CAPABILITY.is_capability();
11355        assert!(IS_HTTP);
11356        assert!(IS_PUBSUB);
11357        assert!(IS_STORE);
11358        assert!(IS_CAPABILITY);
11359    }
11360
11361    #[test]
11362    fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
11363        // Consumer-side pin on the sole production converge site:
11364        // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
11365        // edges from the synchronous-subgraph DFS via the lifted
11366        // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
11367        // predicate (rebound from the prior raw
11368        // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
11369        // variant). Byte-equivalent today (`is_pubsub` is the
11370        // derive-generated `matches!(self, Self::PubSub { .. })` by
11371        // construction, the `#[is_variant(name = "pubsub")]` override
11372        // aliasing the auto-derived `is_pub_sub` back to the sibling
11373        // [`WitContract::is_pubsub`] name); pin the behavior so a
11374        // future accidental drift (a rebind onto a peer arm
11375        // predicate, a manual hand-rolled `impl` that shadows the
11376        // derive-generated method with different semantics, a peer
11377        // arm rename that shifts which variant carries sync-versus-
11378        // async semantics) trips at caixa-core test time rather than
11379        // at some downstream operator's runtime dispatch far from the
11380        // rebind commit.
11381        //
11382        // The fixture constructs a two-Servico Aplicacao with one
11383        // pub-sub edge that would close a sync-cycle if the DFS did
11384        // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
11385        // pub-sub exclusion means the DFS sees only the `b → a` HTTP
11386        // edge, which is not a cycle. A regression in the converge
11387        // (a rebind that reads the pub-sub arm as sync) would report
11388        // `AplicacaoError::ContratoCycle`.
11389        let s = AplicacaoSpec {
11390            membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
11391            contratos: vec![
11392                // Pub-sub edge: DFS must skip via is_pubsub().
11393                WitContract {
11394                    de: "a".into(),
11395                    para: "b".into(),
11396                    wit: "nats:pub-sub".into(),
11397                    endpoint: None,
11398                    subject: Some("events.x".into()),
11399                    slot: None,
11400                },
11401                // HTTP edge: DFS must include.
11402                WitContract {
11403                    de: "b".into(),
11404                    para: "a".into(),
11405                    wit: "wasi:http/proxy".into(),
11406                    endpoint: Some("/x".into()),
11407                    subject: None,
11408                    slot: None,
11409                },
11410            ],
11411            politicas: MeshPolicy::default(),
11412            placement: Placement {
11413                estrategia: PlacementStrategy::Replicated,
11414                clusters: vec!["rio".into()],
11415                affinity: None,
11416                shard_key: None,
11417            },
11418            entrada: None,
11419        };
11420        s.validate()
11421            .expect("pub-sub edge must be excluded from sync-cycle DFS");
11422    }
11423
11424    #[test]
11425    fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
11426        // Consumer-side pin: the same three peer consts thread through
11427        // both the [`WitTarget::label`] template (leading-`:` keyword
11428        // prefix in the duplicate-`:contratos` diagnostic) and the
11429        // [`WitContract::target`] gate's [`AplicacaoError::
11430        // ContratoMissingTarget`] `expected:` scalar (the field the
11431        // author needs to add). Pin both routes at once so a future
11432        // refactor can't accidentally split them onto separate string
11433        // literals — the "one place, everywhere reaches for it"
11434        // invariant the peer const set carries.
11435        let http_label = WitTarget::Http { endpoint: "/x" }.label();
11436        assert!(
11437            http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
11438            "label must lead with :{} keyword (got {http_label:?})",
11439            WitTarget::HTTP_FIELD_NAME,
11440        );
11441
11442        let mut s = three_member_spec();
11443        s.contratos.push(WitContract {
11444            de: "cart".into(),
11445            para: "catalog".into(),
11446            wit: "kafka:topic".into(),
11447            endpoint: None,
11448            subject: None,
11449            slot: None,
11450        });
11451        match s.validate().unwrap_err() {
11452            AplicacaoError::ContratoMissingTarget { expected, .. } => {
11453                assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
11454            }
11455            other => panic!("expected ContratoMissingTarget, got {other:?}"),
11456        }
11457    }
11458
11459    #[test]
11460    fn duplicate_pubsub_diagnostic_names_offending_subject() {
11461        // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
11462        // on the pub-sub target axis: the duplicate-edge diagnostic
11463        // must name the `:subject` payload verbatim (not just the
11464        // `(de, para, wit)` triple). Prior to lifting the label onto
11465        // [`WitTarget::label`] the diagnostic derived the label from
11466        // raw [`WitContract`] `Option<String>` probes — a future
11467        // `WitTarget` variant addition (M4 per-edge WIT registry)
11468        // would silently fall through to the `Capability` "no
11469        // payload" default without a compiler warning. Pinning the
11470        // pub-sub arm's format closes the second of three
11471        // payload-carrying `WitTarget` arms this diagnostic threads
11472        // through.
11473        let mut s = three_member_spec();
11474        let pubsub = WitContract {
11475            de: "payment".into(),
11476            para: "cart".into(),
11477            wit: "nats:pub-sub".into(),
11478            endpoint: None,
11479            subject: Some("events.checkout.paid".into()),
11480            slot: None,
11481        };
11482        s.contratos.push(pubsub.clone());
11483        s.contratos.push(pubsub);
11484        let err = s.validate().unwrap_err();
11485        let msg = format!("{err}");
11486        assert!(
11487            msg.contains(":subject \"events.checkout.paid\""),
11488            "duplicate-pubsub diagnostic must name the offending \
11489             :subject payload (got: {msg:?})"
11490        );
11491    }
11492
11493    #[test]
11494    fn duplicate_store_diagnostic_names_offending_slot() {
11495        // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
11496        // key-value target axis: the diagnostic must name the `:slot`
11497        // payload verbatim. Third of three payload-carrying
11498        // `WitTarget` arms this diagnostic threads through, closing
11499        // the per-arm label pin trilogy (`Http` — 6841,
11500        // `PubSub` + `Store` — this test + peer above).
11501        let mut s = three_member_spec();
11502        let store = WitContract {
11503            de: "cart".into(),
11504            para: "payment".into(),
11505            wit: "wasi:keyvalue/store".into(),
11506            endpoint: None,
11507            subject: None,
11508            slot: Some("checkout/$orderId".into()),
11509        };
11510        s.contratos
11511            .retain(|c| !(c.de == "cart" && c.para == "payment"));
11512        s.contratos.push(store.clone());
11513        s.contratos.push(store);
11514        let err = s.validate().unwrap_err();
11515        let msg = format!("{err}");
11516        assert!(
11517            msg.contains(":slot \"checkout/$orderId\""),
11518            "duplicate-store diagnostic must name the offending :slot \
11519             payload (got: {msg:?})"
11520        );
11521    }
11522
11523    #[test]
11524    fn rejects_entrada_path_without_leading_slash() {
11525        let mut s = three_member_spec();
11526        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
11527        let err = s.validate().unwrap_err();
11528        assert!(
11529            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
11530            "got {err:?}"
11531        );
11532    }
11533
11534    #[test]
11535    fn rejects_empty_entrada_path() {
11536        let mut s = three_member_spec();
11537        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "".into()];
11538        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
11539    }
11540
11541    #[test]
11542    fn rejects_duplicate_entrada_paths() {
11543        let mut s = three_member_spec();
11544        s.entrada.as_mut().unwrap().paths = vec![
11545            "/api/cart".into(),
11546            "/api/products".into(),
11547            "/api/cart".into(),
11548        ];
11549        let err = s.validate().unwrap_err();
11550        assert!(
11551            matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
11552            "got {err:?}"
11553        );
11554    }
11555
11556    #[test]
11557    fn rejects_zero_entrada_port() {
11558        let mut s = three_member_spec();
11559        s.entrada.as_mut().unwrap().port = 0;
11560        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
11561    }
11562
11563    // ── :entrada :paths value-shape gate ─────────────────────────────
11564    //
11565    // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
11566    // sibling `:paths` axis. Every authoring footgun the K8s Gateway
11567    // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
11568    // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
11569    // time now becomes a caixa-build-time `EntradaPathInvalid` with
11570    // the offending `:paths` entry named verbatim.
11571
11572    #[test]
11573    fn rejects_entrada_path_with_query() {
11574        // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
11575        // silently passed validate and the Gateway API webhook
11576        // rejected it at apply time with no source citation.
11577        let mut s = three_member_spec();
11578        s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
11579        let err = s.validate().unwrap_err();
11580        assert!(
11581            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11582                if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
11583            "got {err:?}"
11584        );
11585    }
11586
11587    #[test]
11588    fn rejects_entrada_path_with_fragment() {
11589        let mut s = three_member_spec();
11590        s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
11591        let err = s.validate().unwrap_err();
11592        assert!(
11593            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11594                if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
11595            "got {err:?}"
11596        );
11597    }
11598
11599    #[test]
11600    fn rejects_entrada_path_with_space() {
11601        let mut s = three_member_spec();
11602        s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
11603        let err = s.validate().unwrap_err();
11604        assert!(
11605            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11606                if path == "/api/my cart" && reason.contains("whitespace")),
11607            "got {err:?}"
11608        );
11609    }
11610
11611    #[test]
11612    fn rejects_entrada_path_with_tab() {
11613        let mut s = three_member_spec();
11614        s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
11615        let err = s.validate().unwrap_err();
11616        assert!(
11617            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11618                if path == "/api/\tcart" && reason.contains("whitespace")),
11619            "got {err:?}"
11620        );
11621    }
11622
11623    #[test]
11624    fn rejects_entrada_path_with_control_char() {
11625        // 0x01 (SOH) — a non-whitespace control char surfaces the
11626        // distinct "control character" reason arm, separate from
11627        // the whitespace arm. Pinned so a future refactor that
11628        // collapses the two arms can't accidentally drop the more
11629        // self-locating diagnostic.
11630        let mut s = three_member_spec();
11631        s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
11632        let err = s.validate().unwrap_err();
11633        assert!(
11634            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11635                if path == "/api/\x01cart" && reason.contains("control character")),
11636            "got {err:?}"
11637        );
11638    }
11639
11640    #[test]
11641    fn rejects_entrada_path_with_non_ascii() {
11642        // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
11643        // unreserved-set rule rejects. The Gateway API webhook
11644        // rejects literal non-ASCII bytes; percent-encoding is the
11645        // only way to author non-ASCII in a path.
11646        let mut s = three_member_spec();
11647        s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
11648        let err = s.validate().unwrap_err();
11649        assert!(
11650            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11651                if path == "/api/café" && reason.contains("non-ASCII")),
11652            "got {err:?}"
11653        );
11654    }
11655
11656    #[test]
11657    fn rejects_entrada_path_with_consecutive_slashes() {
11658        let mut s = three_member_spec();
11659        s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
11660        let err = s.validate().unwrap_err();
11661        assert!(
11662            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11663                if path == "/api//cart" && reason.contains("consecutive `/`")),
11664            "got {err:?}"
11665        );
11666    }
11667
11668    #[test]
11669    fn rejects_entrada_path_with_dot_segment() {
11670        let mut s = three_member_spec();
11671        s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
11672        let err = s.validate().unwrap_err();
11673        assert!(
11674            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11675                if path == "/api/./cart" && reason.contains("`.` segment")),
11676            "got {err:?}"
11677        );
11678    }
11679
11680    #[test]
11681    fn rejects_entrada_path_with_trailing_dot_segment() {
11682        // The bare `/.` and the trailing `/foo/.` are both rejected
11683        // by the Gateway API webhook; pinned separately so a future
11684        // narrowing that catches only the inner form surfaces here.
11685        let mut s = three_member_spec();
11686        s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
11687        let err = s.validate().unwrap_err();
11688        assert!(
11689            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11690                if path == "/api/." && reason.contains("`.` segment")),
11691            "got {err:?}"
11692        );
11693    }
11694
11695    #[test]
11696    fn rejects_entrada_path_with_parent_segment() {
11697        let mut s = three_member_spec();
11698        s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
11699        let err = s.validate().unwrap_err();
11700        assert!(
11701            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11702                if path == "/api/../etc" && reason.contains("`..` parent-segment")),
11703            "got {err:?}"
11704        );
11705    }
11706
11707    #[test]
11708    fn rejects_entrada_path_with_trailing_parent_segment() {
11709        // Trailing `/..` — symmetric arm of the parent-segment rule,
11710        // pinned separately so a future relaxation that only checks
11711        // the inner form (`/../`) surfaces here.
11712        let mut s = three_member_spec();
11713        s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
11714        let err = s.validate().unwrap_err();
11715        assert!(
11716            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11717                if path == "/api/.." && reason.contains("`..` parent-segment")),
11718            "got {err:?}"
11719        );
11720    }
11721
11722    #[test]
11723    fn rejects_entrada_path_too_long() {
11724        // 1025-byte path — one over the Gateway API HTTPPathMatch.value
11725        // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
11726        // ASCII-alphanumeric body so only the length rule fires.
11727        let mut s = three_member_spec();
11728        let big = format!("/api/{}", "a".repeat(1020));
11729        assert_eq!(big.len(), 1025);
11730        s.entrada.as_mut().unwrap().paths = vec![big.clone()];
11731        let err = s.validate().unwrap_err();
11732        assert!(
11733            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11734                if path == &big && reason.contains("max length of 1024")),
11735            "got {err:?}"
11736        );
11737    }
11738
11739    #[test]
11740    fn entrada_path_max_length_validates() {
11741        // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
11742        // maxLength cap. Boundary pin: drift in the cap surfaces here
11743        // and at `rejects_entrada_path_too_long` simultaneously.
11744        let mut s = three_member_spec();
11745        let big = format!("/api/{}", "a".repeat(1019));
11746        assert_eq!(big.len(), 1024);
11747        s.entrada.as_mut().unwrap().paths = vec![big];
11748        s.validate().unwrap();
11749    }
11750
11751    #[test]
11752    fn entrada_accepts_canonical_paths() {
11753        // Positive-control sweep — every form the Gateway API
11754        // apiserver accepts must round-trip through validate. Covers
11755        // the root catch-all, plain paths, dot-prefixed segments
11756        // (hidden-file-style, distinct from `.` and `..` segments
11757        // which are rejected), digit-bearing segments, the canonical
11758        // route-template `:param` form (`:` is RFC 3986 reserved-set
11759        // valid in paths), trailing-slash form, percent-encoded
11760        // segments, and an interior `..` *substring* (`/foo..bar` is
11761        // not the `..` segment and is allowed).
11762        for path in [
11763            "/",
11764            "/api/cart",
11765            "/healthz",
11766            "/api/.config",
11767            "/v1/products",
11768            "/products/:id",
11769            "/api/cart/",
11770            "/api/caf%C3%A9",
11771            "/foo..bar",
11772            "/...",
11773        ] {
11774            let mut s = three_member_spec();
11775            s.entrada.as_mut().unwrap().paths = vec![path.into()];
11776            s.validate()
11777                .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
11778        }
11779    }
11780
11781    #[test]
11782    fn entrada_path_empty_takes_precedence_over_invalid() {
11783        // Ordering pin: `EntradaPathEmpty` is the more self-locating
11784        // diagnostic on `""` and must lead — `validate_entrada_path`
11785        // is only reached after the empty-check fires at the call
11786        // site. (The predicate itself defends against direct
11787        // invocation by returning the same error on `""`.)
11788        let mut s = three_member_spec();
11789        s.entrada.as_mut().unwrap().paths = vec!["".into()];
11790        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
11791    }
11792
11793    #[test]
11794    fn entrada_path_not_absolute_takes_precedence_over_invalid() {
11795        // Ordering pin: a path without a leading `/` surfaces the
11796        // narrower `EntradaPathNotAbsolute` diagnostic first; the
11797        // value-shape gate is only consulted on paths that already
11798        // satisfy the absolute-prefix invariant.
11799        let mut s = three_member_spec();
11800        // `bad path` would fire the whitespace rule under the
11801        // value-shape gate, but missing-leading-`/` is the more
11802        // self-locating diagnostic.
11803        s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
11804        let err = s.validate().unwrap_err();
11805        assert!(
11806            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
11807            "got {err:?}"
11808        );
11809    }
11810
11811    #[test]
11812    fn entrada_path_invalid_fires_before_duplicate_check() {
11813        // Ordering pin: a malformed path on the *first* entry of a
11814        // would-be duplicate pair fires the value-shape gate before
11815        // the duplicate gate, mirroring the
11816        // `placement_cluster_invalid_fires_before_duplicate_check`
11817        // (6cbb900) pattern on the peer axis.
11818        let mut s = three_member_spec();
11819        s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
11820        let err = s.validate().unwrap_err();
11821        assert!(
11822            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
11823            "got {err:?}"
11824        );
11825    }
11826
11827    #[test]
11828    fn entrada_path_diagnostic_carries_offending_path() {
11829        // Diagnostic-shape pin — the offending path + a non-empty
11830        // reason flow through verbatim so the author can grep their
11831        // caixa.lisp for `:paths` and fix it in one edit. Same shape
11832        // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
11833        let mut s = three_member_spec();
11834        s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
11835        let err = s.validate().unwrap_err();
11836        match err {
11837            AplicacaoError::EntradaPathInvalid { path, reason } => {
11838                assert_eq!(path, "/api?q=1");
11839                assert!(!reason.is_empty(), "reason field must be non-empty");
11840            }
11841            other => panic!("expected EntradaPathInvalid, got {other:?}"),
11842        }
11843    }
11844
11845    #[test]
11846    fn rejects_entrada_path_with_curly_brace_template_form() {
11847        // Per-axis pin on the shared `is_gateway_api_http_path`
11848        // reserved-byte arm: the canonical "I wrote an OpenAPI
11849        // path-template `{id}` instead of the Gateway API `:id` form"
11850        // footgun the K8s apiserver would otherwise catch at admission
11851        // time on every `HTTPRoute.spec.rules[].matches[].path.value`
11852        // landing site, far from the caixa.lisp. Surfaces as
11853        // `EntradaPathInvalid` carrying the offending path verbatim
11854        // plus the canonical `%7B`/`%7D` percent-encoding remediation
11855        // — the substrate-side `gateway_api_http_path_rejects_every_
11856        // reserved_printable_ascii_byte` predicate-level sweep pins the
11857        // full eleven-byte set; this per-axis pin confirms the
11858        // diagnostic flows through to the `EntradaPathInvalid` variant.
11859        let mut s = three_member_spec();
11860        s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
11861        let err = s.validate().unwrap_err();
11862        assert!(
11863            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11864                if path == "/api/cart/{id}"
11865                    && reason.contains("reserved character")
11866                    && reason.contains("'{'")
11867                    && reason.contains("%7B")),
11868            "got {err:?}"
11869        );
11870    }
11871
11872    #[test]
11873    fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
11874        // Per-axis peer of `rejects_entrada_path_with_curly_brace_
11875        // template_form` on the sibling `:contratos :endpoint` axis.
11876        // Same shared `is_gateway_api_http_path` reserved-byte arm
11877        // fires through `ContratoEndpointInvalid`, with the offending
11878        // endpoint + `:de` + `:para` + reason flowing through verbatim.
11879        // Pins that the lifted predicate's tightening lands on both
11880        // caller axes simultaneously — one source of truth for the
11881        // Gateway API HTTPPathMatch.value accepted set.
11882        let err = contrato_endpoint_err("/api/cart/{id}");
11883        assert!(
11884            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
11885                if endpoint == "/api/cart/{id}"
11886                    && reason.contains("reserved character")
11887                    && reason.contains("'{'")
11888                    && reason.contains("%7B")),
11889            "got {err:?}"
11890        );
11891    }
11892
11893    // ── :entrada :host value-shape gate ──────────────────────────────
11894    //
11895    // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
11896    // the sibling `:host` axis. Every authoring footgun the K8s
11897    // Gateway API v1 apiserver would catch at admission time becomes
11898    // a caixa-build-time `EntradaHostInvalid` with the offending
11899    // `:host` named verbatim. Same diagnostic shape as
11900    // `MembroVersaoInvalid` (9888b13).
11901
11902    #[test]
11903    fn rejects_entrada_host_with_scheme() {
11904        // Fail-before-pass-after pin — pre-gate codebases silently
11905        // accepted `https://…` and the apiserver rejected it at apply
11906        // time with no source citation.
11907        let mut s = three_member_spec();
11908        s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
11909        let err = s.validate().unwrap_err();
11910        assert!(
11911            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
11912                if host == "https://checkout.quero.cloud"),
11913            "got {err:?}"
11914        );
11915    }
11916
11917    #[test]
11918    fn rejects_entrada_host_with_port() {
11919        // The `:8080` port suffix is the canonical "I forgot the port
11920        // belongs in `:entrada :port`" footgun. The top-level `:` arm
11921        // (introduced after the per-label loop-only impl silently
11922        // surfaced a deep "label \"cloud:8080\" contains invalid
11923        // character ':'" leak) names the canonical fix verbatim — the
11924        // `:entrada :port` slot.
11925        let mut s = three_member_spec();
11926        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
11927        let err = s.validate().unwrap_err();
11928        assert!(
11929            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
11930                if host == "checkout.quero.cloud:8080"
11931                && reason.contains(":entrada :port")),
11932            "got {err:?}"
11933        );
11934    }
11935
11936    #[test]
11937    fn rejects_entrada_host_with_trailing_colon() {
11938        // Trailing `:` (e.g. an in-progress `:host "example.com:"`
11939        // edit) — the per-label loop would land it as a deep
11940        // "label \"com:\" must start and end with an alphanumeric"
11941        // / "contains invalid character ':'" leak. The top-level
11942        // `:` arm pre-empts with the canonical `:port` slot
11943        // diagnostic.
11944        let mut s = three_member_spec();
11945        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
11946        let err = s.validate().unwrap_err();
11947        assert!(
11948            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
11949                if host == "checkout.quero.cloud:"
11950                && reason.contains(":entrada :port")),
11951            "got {err:?}"
11952        );
11953    }
11954
11955    #[test]
11956    fn rejects_entrada_host_unbracketed_ipv6_literal() {
11957        // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
11958        // literals across the board (peer with `rejects_entrada_host_
11959        // ipv4_literal` above for the four-label-all-digit IPv4 arm).
11960        // Before this top-level `:` arm landed the per-label loop
11961        // surfaced a single-label byte-class diagnostic that named the
11962        // `:` byte but not the IP-literal prohibition. The top-level
11963        // `:` arm names both the `:port` slot and the IP-literal
11964        // prohibition verbatim, so an author whose `:host "2001:..."`
11965        // value lands here gets a self-locating fix either way.
11966        let mut s = three_member_spec();
11967        s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
11968        let err = s.validate().unwrap_err();
11969        assert!(
11970            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
11971                if host == "2001:db8::1"
11972                && reason.contains("IPv6")),
11973            "got {err:?}"
11974        );
11975    }
11976
11977    #[test]
11978    fn rejects_entrada_host_wildcard_with_port() {
11979        // Wildcard host with port suffix — the `*.` strip and the
11980        // per-label loop on `["foo", "quero", "cloud:8080"]` would
11981        // surface the deep byte-class leak. The top-level `:` arm sits
11982        // upstream of the `*.` strip, so it names the canonical `:port`
11983        // fix verbatim regardless of whether the host is wildcard-led.
11984        let mut s = three_member_spec();
11985        s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
11986        let err = s.validate().unwrap_err();
11987        assert!(
11988            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
11989                if host == "*.quero.cloud:8080"
11990                && reason.contains(":entrada :port")),
11991            "got {err:?}"
11992        );
11993    }
11994
11995    #[test]
11996    fn rejects_entrada_host_with_path() {
11997        let mut s = three_member_spec();
11998        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
11999        let err = s.validate().unwrap_err();
12000        assert!(
12001            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
12002                if host == "checkout.quero.cloud/api"),
12003            "got {err:?}"
12004        );
12005    }
12006
12007    #[test]
12008    fn rejects_entrada_host_with_uppercase() {
12009        // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
12010        // rejected, not silently lower-cased.
12011        let mut s = three_member_spec();
12012        s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
12013        let err = s.validate().unwrap_err();
12014        assert!(
12015            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12016                if reason.contains("uppercase")),
12017            "got {err:?}"
12018        );
12019    }
12020
12021    #[test]
12022    fn rejects_entrada_host_with_underscore() {
12023        // RFC 1123 allows `[a-z0-9-]` only; underscore is the
12024        // canonical "I'm thinking of HTTP cookies / SRV records" leak.
12025        let mut s = three_member_spec();
12026        s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
12027        let err = s.validate().unwrap_err();
12028        assert!(
12029            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12030                if reason.contains('_')),
12031            "got {err:?}"
12032        );
12033    }
12034
12035    #[test]
12036    fn rejects_entrada_host_ipv4_literal() {
12037        // Gateway API v1 explicitly forbids IP literals as Hostnames.
12038        let mut s = three_member_spec();
12039        s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
12040        let err = s.validate().unwrap_err();
12041        assert!(
12042            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12043                if reason.contains("IPv4")),
12044            "got {err:?}"
12045        );
12046    }
12047
12048    #[test]
12049    fn rejects_entrada_host_with_trailing_dot() {
12050        // The Gateway API regex anchors at end-of-string with no
12051        // trailing `.` allowance — the FQDN root-dot form is rejected.
12052        let mut s = three_member_spec();
12053        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
12054        let err = s.validate().unwrap_err();
12055        assert!(
12056            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
12057                if host == "checkout.quero.cloud."),
12058            "got {err:?}"
12059        );
12060    }
12061
12062    #[test]
12063    fn rejects_entrada_host_with_leading_dot() {
12064        let mut s = three_member_spec();
12065        s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
12066        let err = s.validate().unwrap_err();
12067        assert!(
12068            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12069                if reason.contains("empty label")),
12070            "got {err:?}"
12071        );
12072    }
12073
12074    #[test]
12075    fn rejects_entrada_host_with_consecutive_dots() {
12076        let mut s = three_member_spec();
12077        s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
12078        let err = s.validate().unwrap_err();
12079        assert!(
12080            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12081                if reason.contains("empty label")),
12082            "got {err:?}"
12083        );
12084    }
12085
12086    #[test]
12087    fn rejects_entrada_host_with_leading_hyphen_label() {
12088        let mut s = three_member_spec();
12089        s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
12090        let err = s.validate().unwrap_err();
12091        assert!(
12092            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12093                if reason.contains("alphanumeric")),
12094            "got {err:?}"
12095        );
12096    }
12097
12098    #[test]
12099    fn rejects_entrada_host_with_trailing_hyphen_label() {
12100        let mut s = three_member_spec();
12101        s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
12102        let err = s.validate().unwrap_err();
12103        assert!(
12104            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12105                if reason.contains("alphanumeric")),
12106            "got {err:?}"
12107        );
12108    }
12109
12110    #[test]
12111    fn rejects_entrada_host_with_inner_wildcard() {
12112        // Gateway API allows `*` only as the first label (`*.foo`);
12113        // any inner or trailing `*` is rejected.
12114        let mut s = three_member_spec();
12115        s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
12116        let err = s.validate().unwrap_err();
12117        assert!(
12118            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12119                if reason.contains("wildcard")),
12120            "got {err:?}"
12121        );
12122    }
12123
12124    #[test]
12125    fn rejects_entrada_host_bare_wildcard() {
12126        // `*.` with no domain is meaningless; Gateway API rejects it.
12127        let mut s = three_member_spec();
12128        s.entrada.as_mut().unwrap().host = "*.".into();
12129        let err = s.validate().unwrap_err();
12130        assert!(
12131            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12132                if reason.contains("wildcard")),
12133            "got {err:?}"
12134        );
12135    }
12136
12137    #[test]
12138    fn rejects_entrada_host_with_whitespace() {
12139        let mut s = three_member_spec();
12140        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
12141        let err = s.validate().unwrap_err();
12142        assert!(
12143            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12144                if reason.contains("whitespace")),
12145            "got {err:?}"
12146        );
12147    }
12148
12149    #[test]
12150    fn rejects_entrada_host_space_names_offending_byte() {
12151        // Embedded space in the `:entrada :host` axis surfaces the
12152        // byte-naming diagnostic through the lifted
12153        // `find_ascii_whitespace_byte` predicate. Peer with the
12154        // sibling `parse_rejects_leading_whitespace` pins on
12155        // `supervisor::duration_codec` (a7ae622) — same "the
12156        // diagnostic carries the offending byte's `0x{b:02x}` shape"
12157        // discipline extended from the shared duration codec to the
12158        // Gateway API v1 Hostname axis.
12159        let mut s = three_member_spec();
12160        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
12161        let err = s.validate().unwrap_err();
12162        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12163            panic!("expected EntradaHostInvalid, got {err:?}");
12164        };
12165        assert!(
12166            reason.contains("ASCII whitespace byte"),
12167            "expected byte-naming diagnostic, got {reason:?}"
12168        );
12169        assert!(
12170            reason.contains("0x20"),
12171            "expected offending space byte 0x20, got {reason:?}"
12172        );
12173    }
12174
12175    #[test]
12176    fn rejects_entrada_host_tab_names_offending_byte() {
12177        // Embedded tab byte in the `:entrada :host` axis — the
12178        // canonical paste-from-YAML-block-scalar / paste-from-
12179        // indented-doc footgun. Pins that the lifted predicate covers
12180        // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
12181        // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
12182        // not just the leading-space case the pre-lift `.bytes().any`
12183        // arm's opaque "must not contain whitespace" reason already
12184        // covered. Peer with `parse_rejects_tab_byte` on
12185        // `supervisor::duration_codec` (a7ae622).
12186        let mut s = three_member_spec();
12187        s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
12188        let err = s.validate().unwrap_err();
12189        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12190            panic!("expected EntradaHostInvalid, got {err:?}");
12191        };
12192        assert!(
12193            reason.contains("ASCII whitespace byte"),
12194            "expected byte-naming diagnostic, got {reason:?}"
12195        );
12196        assert!(
12197            reason.contains("0x09"),
12198            "expected offending tab byte 0x09, got {reason:?}"
12199        );
12200    }
12201
12202    #[test]
12203    fn rejects_entrada_host_lf_names_offending_byte() {
12204        // Embedded LF byte in the `:entrada :host` axis — the
12205        // canonical paste-from-shell-heredoc / paste-from-multiline-
12206        // doc footgun the caixa-mesh YAML emitter would silently
12207        // reinterpret at the Gateway API v1 HTTPRoute admission
12208        // layer (an embedded LF byte in a YAML plain scalar either
12209        // truncates the value at the emitter or crashes the parser
12210        // on the k8s-apiserver side). Pins the third representative
12211        // of the full ASCII-whitespace set through the shared
12212        // predicate.
12213        let mut s = three_member_spec();
12214        s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
12215        let err = s.validate().unwrap_err();
12216        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12217            panic!("expected EntradaHostInvalid, got {err:?}");
12218        };
12219        assert!(
12220            reason.contains("ASCII whitespace byte"),
12221            "expected byte-naming diagnostic, got {reason:?}"
12222        );
12223        assert!(
12224            reason.contains("0x0a"),
12225            "expected offending LF byte 0x0a, got {reason:?}"
12226        );
12227    }
12228
12229    #[test]
12230    fn rejects_entrada_host_nbsp_names_offending_codepoint() {
12231        // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
12232        // axis — the canonical paste-from-typography /
12233        // paste-from-word-processor footgun. Before the non-ASCII
12234        // Unicode `White_Space` scan lifted through the shared
12235        // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
12236        // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
12237        // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
12238        // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
12239        // with the far-from-source `label "…" must start and end
12240        // with an alphanumeric` diagnostic — burying the
12241        // paste-from-typography origin under a label-shape leak.
12242        // Peer with the sibling non-ASCII-whitespace pins at
12243        // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
12244        // — 1b75b38), `limits::parse_duration`,
12245        // `limits::parse_millicores`, and the shared duration codec
12246        // — same "the diagnostic carries the offending Unicode
12247        // codepoint's `U+XXXX` shape" discipline extended from every
12248        // typed-magnitude codec to the Gateway API v1 Hostname axis.
12249        let mut s = three_member_spec();
12250        s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
12251        let err = s.validate().unwrap_err();
12252        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12253            panic!("expected EntradaHostInvalid, got {err:?}");
12254        };
12255        assert!(
12256            reason.contains("non-ASCII Unicode whitespace character"),
12257            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
12258        );
12259        assert!(
12260            reason.contains("U+00A0"),
12261            "expected offending NBSP codepoint U+00A0, got {reason:?}"
12262        );
12263    }
12264
12265    #[test]
12266    fn rejects_entrada_host_line_separator_names_offending_codepoint() {
12267        // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
12268        // `:entrada :host` axis — the canonical paste-from-web-doc /
12269        // paste-from-published-HTML footgun. `char::is_whitespace`
12270        // returns true for `U+2028` per the Unicode `White_Space`
12271        // property, so `str::trim` at any downstream site would
12272        // silently strip it — same drift class as NBSP but on a
12273        // different codepoint region. Pins the second representative
12274        // (non-Latin-1 `char::is_whitespace` member) through the
12275        // shared predicate. Peer with
12276        // `parse_byte_size_rejects_internal_line_separator` on
12277        // `limits::parse_byte_size` (1b75b38).
12278        let mut s = three_member_spec();
12279        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
12280        let err = s.validate().unwrap_err();
12281        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12282            panic!("expected EntradaHostInvalid, got {err:?}");
12283        };
12284        assert!(
12285            reason.contains("non-ASCII Unicode whitespace character"),
12286            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
12287        );
12288        assert!(
12289            reason.contains("U+2028"),
12290            "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
12291        );
12292    }
12293
12294    #[test]
12295    fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
12296        // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
12297        // labels in the `:entrada :host` axis — the canonical
12298        // paste-from-CJK-typography footgun (CJK IMEs default to
12299        // full-width whitespace when the space bar is pressed in
12300        // Japanese / Chinese input modes). Pins the third
12301        // representative of the non-ASCII Unicode `White_Space` set
12302        // through the shared predicate: the CJK block, distinct from
12303        // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
12304        // SEPARATOR `U+2028` — covering the same axis breadth the
12305        // sibling `parse_byte_size_rejects_trailing_ideographic_space`
12306        // (1b75b38) pins on `limits::parse_byte_size`.
12307        let mut s = three_member_spec();
12308        s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
12309        let err = s.validate().unwrap_err();
12310        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12311            panic!("expected EntradaHostInvalid, got {err:?}");
12312        };
12313        assert!(
12314            reason.contains("non-ASCII Unicode whitespace character"),
12315            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
12316        );
12317        assert!(
12318            reason.contains("U+3000"),
12319            "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
12320        );
12321    }
12322
12323    #[test]
12324    fn rejects_entrada_host_too_long() {
12325        // Total length cap = 253; build a 254-byte host out of two
12326        // 63-byte labels + one 62-byte label + dots.
12327        let mut s = three_member_spec();
12328        let big = format!(
12329            "{}.{}.{}.{}",
12330            "a".repeat(63),
12331            "b".repeat(63),
12332            "c".repeat(63),
12333            "d".repeat(254 - 63 * 3 - 3)
12334        );
12335        assert_eq!(big.len(), 254);
12336        s.entrada.as_mut().unwrap().host = big;
12337        let err = s.validate().unwrap_err();
12338        assert!(
12339            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12340                if reason.contains("max length of 253")),
12341            "got {err:?}"
12342        );
12343    }
12344
12345    #[test]
12346    fn rejects_entrada_host_label_too_long() {
12347        let mut s = three_member_spec();
12348        // 64-byte label — one over the per-label cap.
12349        s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
12350        let err = s.validate().unwrap_err();
12351        assert!(
12352            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12353                if reason.contains("label max length of 63")),
12354            "got {err:?}"
12355        );
12356    }
12357
12358    #[test]
12359    fn entrada_host_diagnostic_carries_offending_host() {
12360        // Diagnostic-shape pin — the offending host + a non-empty
12361        // reason flow through verbatim so the author can grep their
12362        // caixa.lisp for `:host "<host>"` and fix it in one edit.
12363        let mut s = three_member_spec();
12364        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
12365        let err = s.validate().unwrap_err();
12366        match err {
12367            AplicacaoError::EntradaHostInvalid { host, reason } => {
12368                assert_eq!(host, "checkout.quero.cloud:8080");
12369                assert!(!reason.is_empty(), "reason field must be non-empty");
12370            }
12371            other => panic!("expected EntradaHostInvalid, got {other:?}"),
12372        }
12373    }
12374
12375    #[test]
12376    fn entrada_host_empty_takes_precedence_over_invalid() {
12377        // Ordering pin: `EmptyEntradaHost` is the more self-locating
12378        // diagnostic on `""` and must lead — `validate_entrada_host`
12379        // is only reached after the empty-check fires at the call
12380        // site. (The predicate itself defends against direct
12381        // invocation by returning the same error on `""`.)
12382        let mut s = three_member_spec();
12383        s.entrada.as_mut().unwrap().host = String::new();
12384        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
12385    }
12386
12387    #[test]
12388    fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
12389        // Ordering pin: a missing :para member is the more
12390        // self-locating diagnostic and fires before the host gate.
12391        let mut s = three_member_spec();
12392        let e = s.entrada.as_mut().unwrap();
12393        e.para = "ghost".into();
12394        e.host = "BAD HOST".into();
12395        let err = s.validate().unwrap_err();
12396        assert!(
12397            matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
12398            "got {err:?}"
12399        );
12400    }
12401
12402    #[test]
12403    fn entrada_host_invalid_fires_before_port_zero() {
12404        // Ordering pin: the host gate fires before the port gate so
12405        // a malformed host is named even when the port is also wrong.
12406        let mut s = three_member_spec();
12407        let e = s.entrada.as_mut().unwrap();
12408        e.host = "Checkout.quero.cloud".into();
12409        e.port = 0;
12410        let err = s.validate().unwrap_err();
12411        assert!(
12412            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
12413                if host == "Checkout.quero.cloud"),
12414            "got {err:?}"
12415        );
12416    }
12417
12418    #[test]
12419    fn entrada_accepts_canonical_hosts() {
12420        // Positive-control sweep — every form the Gateway API
12421        // apiserver accepts must round-trip through validate. Covers
12422        // a plain DNS subdomain, a leading wildcard, a single-label
12423        // host (cluster-internal), a max-length-edge label, a
12424        // hyphen-bearing label, and a Punycode IDN label.
12425        for host in [
12426            "checkout.quero.cloud",
12427            "*.quero.cloud",
12428            "checkout",
12429            // 63-byte label — exactly the per-label cap.
12430            "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
12431            "foo-bar.quero.cloud",
12432            // Punycode IDN — valid because the author pre-encoded.
12433            "xn--bcher-kva.example.com",
12434        ] {
12435            let mut s = three_member_spec();
12436            s.entrada.as_mut().unwrap().host = host.into();
12437            s.validate()
12438                .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
12439        }
12440    }
12441
12442    #[test]
12443    fn entrada_host_max_length_validates() {
12444        // 253-byte host is the cap exactly — must validate. Build a
12445        // 253-byte host out of three 63-byte labels + one 61-byte
12446        // label + 3 dots = 252 bytes, then pad one byte to 253.
12447        let mut s = three_member_spec();
12448        let host = format!(
12449            "{}.{}.{}.{}",
12450            "a".repeat(63),
12451            "b".repeat(63),
12452            "c".repeat(63),
12453            "d".repeat(253 - 63 * 3 - 3)
12454        );
12455        assert_eq!(host.len(), 253);
12456        s.entrada.as_mut().unwrap().host = host;
12457        s.validate().unwrap();
12458    }
12459
12460    #[test]
12461    fn entrada_host_total_length_cap_threads_lifted_render_const() {
12462        // Cross-crate-side pin: the aplicacao-side `:entrada :host`
12463        // total-length gate now reads the K8s Gateway API v1 Hostname
12464        // `maxLength: 253` cap from the lifted
12465        // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
12466        // of truth — the same constant every future Gateway-API-Hostname
12467        // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
12468        // materializer's per-host validator, the future per-`Certificate`
12469        // SAN emitter for cert-manager, the multi-`:entrada`
12470        // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
12471        // from. Before the lift, the aplicacao-side reader consumed a
12472        // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
12473        // 253-byte value as the peer render-side canonical bounds
12474        // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
12475        // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
12476        // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
12477        // module boundary — a future 253-byte drift on either side would
12478        // silently split into two axes' worth of admission-schema mismatch
12479        // without a build-time signal. Pin the cap through a fresh 254-
12480        // byte host that hits the total-length arm, then read the reason
12481        // for the exact byte count the shared constant carries: any future
12482        // regression on the lift (a private alias reintroduced, a hard-
12483        // coded literal at the arm, a mismatch between the aplicacao-side
12484        // and render-side canonicals) surfaces as this pin's diagnostic
12485        // failing to match, not as a per-cluster admission rejection far
12486        // from the caixa.lisp source line.
12487        let mut s = three_member_spec();
12488        let over_cap = format!(
12489            "{}.{}.{}.{}",
12490            "a".repeat(63),
12491            "b".repeat(63),
12492            "c".repeat(63),
12493            "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
12494        );
12495        assert_eq!(
12496            over_cap.len(),
12497            crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
12498        );
12499        s.entrada.as_mut().unwrap().host = over_cap;
12500        let err = s.validate().unwrap_err();
12501        match err {
12502            AplicacaoError::EntradaHostInvalid { reason, .. } => {
12503                let needle = format!(
12504                    "max length of {} bytes",
12505                    crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
12506                );
12507                assert!(
12508                    reason.contains(&needle),
12509                    "diagnostic must name the lifted \
12510                     GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
12511                );
12512            }
12513            other => panic!("expected EntradaHostInvalid, got {other:?}"),
12514        }
12515    }
12516
12517    #[test]
12518    fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
12519        // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
12520        // on the per-label-cap axis. Before the lift, the aplicacao-side
12521        // per-label arm consumed a private const alias
12522        // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
12523        // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
12524        // split from it at the module boundary — every `.`-separated
12525        // label in a Gateway API v1 Hostname is a DNS-1123 label under
12526        // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
12527        // so the private alias's 63 and the canonical const's 63 were
12528        // pinning the same underlying rule twice. Pin the cap through a
12529        // 64-byte label that hits the per-label arm, then read the reason
12530        // for the exact byte count the shared constant carries: any
12531        // future drift on either side (a private alias reintroduced, a
12532        // hard-coded literal at the arm, a mismatch between the two
12533        // 63-byte pins) surfaces at this pin's diagnostic rather than at
12534        // a per-cluster admission rejection whose "field is invalid"
12535        // opacity misframes the root cause.
12536        let mut s = three_member_spec();
12537        let over_cap_label = format!(
12538            "{}.quero.cloud",
12539            "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
12540        );
12541        s.entrada.as_mut().unwrap().host = over_cap_label;
12542        let err = s.validate().unwrap_err();
12543        match err {
12544            AplicacaoError::EntradaHostInvalid { reason, .. } => {
12545                let needle = format!(
12546                    "label max length of {} bytes",
12547                    crate::render::DNS_1123_LABEL_MAX_LEN,
12548                );
12549                assert!(
12550                    reason.contains(&needle),
12551                    "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
12552                     cap verbatim on the per-label arm, got: {reason:?}",
12553                );
12554            }
12555            other => panic!("expected EntradaHostInvalid, got {other:?}"),
12556        }
12557    }
12558
12559    #[test]
12560    fn entrada_with_empty_paths_validates() {
12561        // Empty `:paths` is the documented "match every path" form;
12562        // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
12563        let mut s = three_member_spec();
12564        s.entrada.as_mut().unwrap().paths = vec![];
12565        s.validate().unwrap();
12566    }
12567
12568    #[test]
12569    fn entrada_root_path_validates() {
12570        // The author-supplied bare-root `:entrada :paths` entry is the
12571        // same byte-shape the peer emit-side catch-all constant
12572        // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
12573        // the author's `:paths` list is empty — sweeping the test-side
12574        // probe literal onto the lifted const closes the two-axis pin
12575        // (author-side admit + emit-side canonical fallback) around
12576        // one `&'static str`, so a future rebrand of the catch-all
12577        // reaches both consumers by construction. Peer to
12578        // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
12579        // on the canonical-literal pin surface.
12580        let mut s = three_member_spec();
12581        s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
12582        s.validate().unwrap();
12583    }
12584
12585    #[test]
12586    fn placement_strategy_variants_round_trip() {
12587        for s in [
12588            PlacementStrategy::SingleNode,
12589            PlacementStrategy::Replicated,
12590            PlacementStrategy::Sharded,
12591        ] {
12592            let p = Placement {
12593                estrategia: s,
12594                clusters: vec!["rio".into()],
12595                affinity: None,
12596                shard_key: if s.is_sharded() {
12597                    Some("$key".into())
12598                } else {
12599                    None
12600                },
12601            };
12602            let json = serde_json::to_string(&p).unwrap();
12603            let back: Placement = serde_json::from_str(&json).unwrap();
12604            assert_eq!(back, p);
12605        }
12606    }
12607
12608    #[test]
12609    fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
12610        // The fail-before-pass-after pin: pre-lift there was no
12611        // single-source binding between the [`PlacementStrategy`]
12612        // variant name the `Serialize` derive emits and the byte-
12613        // string every downstream cluster-side dispatcher (the
12614        // `lareira-fleet-programs` aggregator's per-entry strategy
12615        // branch, the future `app-operator` reconciler, the M3
12616        // Adaptive compression pass's per-strategy weighting) probes
12617        // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
12618        // future `#[serde(rename_all = "kebab-case")]` attribute on
12619        // the enum — or a variant rename in the source — would
12620        // silently rebrand the emitted scalar under one spelling
12621        // while every downstream dispatcher still probed the other,
12622        // with the failure surfacing at the aggregator's dispatch
12623        // step or the operator's reconcile posture (workloads coming
12624        // up under the `default()` `Replicated` arm rather than the
12625        // typed slot's declared strategy) far from the source
12626        // rebrand commit and with no field naming the drift. Pinning
12627        // the two paths (the `Serialize` derive's serialized string
12628        // AND the [`PlacementStrategy::as_str`] helper) to the same
12629        // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
12630        // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
12631        // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
12632        // makes any future drift on either endpoint fail here at
12633        // caixa-core build time.
12634        for (variant, expected) in [
12635            (
12636                PlacementStrategy::SingleNode,
12637                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
12638            ),
12639            (
12640                PlacementStrategy::Replicated,
12641                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
12642            ),
12643            (
12644                PlacementStrategy::Sharded,
12645                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
12646            ),
12647        ] {
12648            let json = serde_json::to_string(&variant).unwrap();
12649            assert_eq!(
12650                json,
12651                format!("\"{expected}\""),
12652                "PlacementStrategy::{variant:?} must serialize to {expected:?}"
12653            );
12654            assert_eq!(
12655                variant.as_str(),
12656                expected,
12657                "PlacementStrategy::{variant:?}.as_str() must return the lifted \
12658                 M3_PLACEMENT_ESTRATEGIA_* constant"
12659            );
12660        }
12661    }
12662
12663    #[test]
12664    fn m3_placement_estrategia_consts_are_pairwise_distinct() {
12665        // Cross-arm drift-detection pin on the M3
12666        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
12667        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
12668        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
12669        // scalar-value pentad: a future collapse of two canonical
12670        // variant byte-strings onto the same value (an accidental
12671        // copy-paste flip of
12672        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
12673        // read `"SingleNode"`, a per-arm rebrand that lands one const
12674        // without touching its paired peer) would silently reroute
12675        // every downstream operator's per-strategy dispatch onto the
12676        // sibling arm's reconcile branch and pass every
12677        // propagation-probe test that expected only the stale arm's
12678        // value — a `Replicated`-declared Aplicacao would come up
12679        // under the `SingleNode` primary-and-standby reconcile
12680        // posture, so every-cluster active-active workload would
12681        // silently collapse onto one-cluster-runs-at-a-time takeover
12682        // semantics against its declared strategy, with no field
12683        // naming the strategy-value drift root cause. Peer of the
12684        // sibling
12685        // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
12686        // (09ffb2d) /
12687        // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
12688        // (ccdf955) /
12689        // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
12690        // (d739850) distinctness pins on the sibling OTP-shape /
12691        // caixa-kind closed-set typed-enum discriminator axes — the
12692        // fourth (and structurally the M3 mesh-primitive-defining)
12693        // closed-set typed-enum axis to converge on the same
12694        // "pairwise-distinct-by-construction" discipline.
12695        //
12696        // Fail-before-pass-after locally verified by mutating
12697        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
12698        // also read `"SingleNode"` — this pin fires as expected;
12699        // restoring passes.
12700        let all = [
12701            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
12702            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
12703            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
12704        ];
12705        for (i, a) in all.iter().enumerate() {
12706            for (j, b) in all.iter().enumerate() {
12707                if i != j {
12708                    assert_ne!(
12709                        a, b,
12710                        "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
12711                         distinct — got duplicate {a:?} at indices {i} and {j}",
12712                    );
12713                }
12714            }
12715        }
12716    }
12717
12718    #[test]
12719    fn placement_strategy_display_routes_through_as_str_helper() {
12720        // The fail-before-pass-after pin: pre-lift the sibling
12721        // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
12722        // / [`crate::supervisor::RestartPolicy`] both carried a stable
12723        // [`std::fmt::Display`] surface via their
12724        // `#[discriminant(also_display)]` gen-platform derive, but
12725        // [`PlacementStrategy`] did not — every consumer reaching for
12726        // a strategy byte-string past the wire format had to pick
12727        // between three paths ([`PlacementStrategy::as_str`], the
12728        // `Serialize` derive's serialized string, or `format!("{v:?}")`
12729        // on the `Debug` derive), any two of which a future variant
12730        // rename or `#[serde(rename_all = "kebab-case")]` attribute
12731        // would silently desynchronize. Wiring [`std::fmt::Display`]
12732        // through [`PlacementStrategy::as_str`] closes the third path:
12733        // every `format!("{v}")` call reaches the same lifted
12734        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
12735        // and the [`PlacementStrategy::as_str`] helper already route
12736        // through, so a future variant rename lands at exactly one
12737        // place. Pin the routing here so a future
12738        // `impl std::fmt::Display for PlacementStrategy` reimplementation
12739        // that hand-rolls the arms instead of delegating to
12740        // [`PlacementStrategy::as_str`] fails at caixa-core build time.
12741        for variant in [
12742            PlacementStrategy::SingleNode,
12743            PlacementStrategy::Replicated,
12744            PlacementStrategy::Sharded,
12745        ] {
12746            assert_eq!(
12747                variant.to_string(),
12748                variant.as_str(),
12749                "PlacementStrategy::{variant:?} Display must route through \
12750                 PlacementStrategy::as_str (single source of truth: the lifted \
12751                 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
12752            );
12753        }
12754    }
12755
12756    #[test]
12757    fn placement_strategy_display_matches_serialized_wire_byte_string() {
12758        // The fail-before-pass-after pin on the second half of the
12759        // three-path convergence: `Display` (user-facing text) agrees
12760        // byte-for-byte with the `Serialize` derive's wire format
12761        // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
12762        // scalar) on every variant. Pre-lift the two paths were
12763        // structurally independent — a future
12764        // `#[serde(rename_all = "kebab-case")]` attribute on the enum
12765        // would silently rebrand the emitted wire scalar
12766        // (`single-node`, `replicated`, `sharded`) while every consumer
12767        // that pretty-prints the strategy (the M3 diagnostic templates,
12768        // the future `feira app graph` per-Aplicacao strategy line,
12769        // the future M4 CR materializer's admission-webhook rejection
12770        // body) would still emit the TitleCase form the `as_str` /
12771        // `Display` route returns, with the mismatch surfacing at
12772        // consumer parse time / operator dispatch time far from the
12773        // source rebrand commit. Pin the two paths byte-for-byte here
12774        // so any future serde-attribute or variant-rename drift is a
12775        // caixa-core-build-time test failure at this call, not a
12776        // silent per-consumer dispatch miss.
12777        for variant in [
12778            PlacementStrategy::SingleNode,
12779            PlacementStrategy::Replicated,
12780            PlacementStrategy::Sharded,
12781        ] {
12782            let wire = serde_json::to_string(&variant).unwrap();
12783            // Strip the outer `"…"` the JSON string form carries — the
12784            // wire scalar the K8s / YAML apiserver consumes is the
12785            // enclosed byte-string, not the quote wrapper.
12786            let unquoted = wire
12787                .strip_prefix('"')
12788                .and_then(|s| s.strip_suffix('"'))
12789                .expect("serialized PlacementStrategy is a JSON string");
12790            assert_eq!(
12791                variant.to_string(),
12792                unquoted,
12793                "PlacementStrategy::{variant:?} Display byte-string must match the \
12794                 Serialize derive's wire byte-string (three-path convergence: \
12795                 Display + as_str + Serialize all resolve to the same \
12796                 M3_PLACEMENT_ESTRATEGIA_* const)"
12797            );
12798        }
12799    }
12800
12801    #[test]
12802    fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
12803        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
12804        // derive on [`PlacementStrategy`]: for each of the three variants
12805        // exactly one of the generated `is_single_node` / `is_replicated`
12806        // / `is_sharded` predicates returns `true` and the other two
12807        // return `false`. Prior to this derive the three per-arm
12808        // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
12809        // (the `placement_strategy_variants_round_trip` fixture, the
12810        // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
12811        // fixture, and the
12812        // `validate_placement_reads_through_lifted_estrategia_accessor`
12813        // fixture) each open-coded a per-arm PartialEq compare against
12814        // the enum variant — three sites that expressed no compile-time
12815        // link back to the closed-set typed dispatch a future fourth
12816        // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
12817        // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
12818        // would have to thread through in lockstep or one fixture would
12819        // silently disagree with the others on which arms consume the
12820        // `:shard-key` axis. Peer of the sibling
12821        // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
12822        // / [`crate::supervisor::RestartPolicy`] /
12823        // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
12824        // the sibling closed-set typed-enum discriminator axes — extends
12825        // the same one-typed-dispatch-per-variant discipline onto the
12826        // fifth (and only remaining) closed-set typed-enum discriminator
12827        // on the caixa surface, closing the axis on the M3 mesh-slot
12828        // family.
12829        let rows: [(PlacementStrategy, [bool; 3]); 3] = [
12830            (PlacementStrategy::SingleNode, [true, false, false]),
12831            (PlacementStrategy::Replicated, [false, true, false]),
12832            (PlacementStrategy::Sharded, [false, false, true]),
12833        ];
12834        for (variant, expected) in rows {
12835            let observed = [
12836                variant.is_single_node(),
12837                variant.is_replicated(),
12838                variant.is_sharded(),
12839            ];
12840            assert_eq!(
12841                observed, expected,
12842                "PlacementStrategy::{variant:?} is_* predicates must partition \
12843                 the arm set (single_node, replicated, sharded); got {observed:?}"
12844            );
12845        }
12846    }
12847
12848    #[test]
12849    fn placement_strategy_is_variant_predicates_are_const_fn() {
12850        // The [`gen_platform::IsVariant`] derive emits `const fn`
12851        // predicates on the peer [`crate::CaixaKind`] +
12852        // [`crate::upgrade::UpgradeInstruction`] +
12853        // [`crate::supervisor::RestartStrategy`] +
12854        // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
12855        // pin the same posture on [`PlacementStrategy`] so a future
12856        // accidental downgrade to non-`const` (an added runtime helper
12857        // reachable only from a non-`const` context, a manual hand-rolled
12858        // `impl` that shadows the derive-generated method) trips at
12859        // caixa-core build time rather than surfacing as a downstream
12860        // `const`-context regression far from the derive declaration.
12861        const IS_SINGLE_NODE: bool = PlacementStrategy::SingleNode.is_single_node();
12862        const IS_REPLICATED: bool = PlacementStrategy::Replicated.is_replicated();
12863        const IS_SHARDED: bool = PlacementStrategy::Sharded.is_sharded();
12864        assert!(IS_SINGLE_NODE);
12865        assert!(IS_REPLICATED);
12866        assert!(IS_SHARDED);
12867    }
12868
12869    #[test]
12870    fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
12871        // Pin the M3 diagnostic template routes through the typed
12872        // [`PlacementStrategy`] Display byte-string (rebound from the
12873        // prior `{estrategia:?}` `Debug` route). Pre-lift the two
12874        // routes emitted identical bytes (the `Debug` derive on a
12875        // unit variant emits the variant name verbatim, exactly what
12876        // `as_str` returns), but the two paths were structurally
12877        // independent — a future `#[serde(rename_all = "…")]`
12878        // attribute or variant rename would coordinate the wire /
12879        // `Display` / `as_str` triple through the lifted const but
12880        // leave the `Debug` route on the compiler-derived variant name,
12881        // silently desynchronizing the diagnostic byte-string from the
12882        // wire byte-string. Rebinding the template onto `Display`
12883        // ties the diagnostic to the same lifted
12884        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
12885        // emits — drift becomes structurally impossible. Pin the
12886        // byte-string here so a future edit that reverts the template
12887        // to `{estrategia:?}` is caught at caixa-core test time, not
12888        // at consumer dispatch time.
12889        for (variant, expected_scalar) in [
12890            (
12891                PlacementStrategy::SingleNode,
12892                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
12893            ),
12894            (
12895                PlacementStrategy::Replicated,
12896                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
12897            ),
12898            (
12899                PlacementStrategy::Sharded,
12900                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
12901            ),
12902        ] {
12903            let err = AplicacaoError::PlacementWithoutClusters {
12904                estrategia: variant,
12905            };
12906            let msg = err.to_string();
12907            assert!(
12908                msg.starts_with(&format!(":placement {expected_scalar} requires")),
12909                "PlacementWithoutClusters diagnostic for {variant:?} must open \
12910                 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
12911            );
12912        }
12913    }
12914
12915    #[test]
12916    fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
12917        // Peer of
12918        // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
12919        // on the second M3 diagnostic that carries the typed
12920        // [`PlacementStrategy`] in its `#[error(…)]` template. Both
12921        // diagnostics now route the strategy scalar through the same
12922        // [`std::fmt::Display`] surface, tying the diagnostic
12923        // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
12924        // const set the wire format also emits. The two non-Sharded
12925        // arms are exercised here (the diagnostic exists to flag a
12926        // `:shard-key` slot the current strategy will never consume);
12927        // the peer `Sharded` arm never reaches this diagnostic (the
12928        // `Sharded` strategy consumes `:shard-key` — the
12929        // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
12930        // slot instead).
12931        for (variant, expected_scalar) in [
12932            (
12933                PlacementStrategy::SingleNode,
12934                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
12935            ),
12936            (
12937                PlacementStrategy::Replicated,
12938                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
12939            ),
12940        ] {
12941            let err = AplicacaoError::ShardKeyOnNonSharded {
12942                estrategia: variant,
12943                shard_key: "$tenantId".into(),
12944            };
12945            let msg = err.to_string();
12946            assert!(
12947                msg.starts_with(&format!(":placement {expected_scalar} carries")),
12948                "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
12949                 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
12950            );
12951        }
12952    }
12953
12954    #[test]
12955    fn rejects_zero_policy_timeout() {
12956        let mut s = three_member_spec();
12957        s.politicas.timeout = Some(Duration::ZERO);
12958        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
12959    }
12960
12961    #[test]
12962    fn rejects_zero_policy_retries() {
12963        let mut s = three_member_spec();
12964        s.politicas.retries = Some(0);
12965        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
12966    }
12967
12968    #[test]
12969    fn rejects_policy_retries_above_cap() {
12970        // The fail-before-pass-after pin: `Some(11)` is structurally
12971        // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
12972        // passed validate on every pre-gate codebase because the
12973        // typed slot's only check was the zero-floor arm. The
12974        // thundering-herd amplification vector only surfaced at the
12975        // runtime substrate (Envoy / Cilium L7 retry overlay)
12976        // far from the source caixa.lisp with no field naming the
12977        // offending policy.
12978        let mut s = three_member_spec();
12979        s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
12980        assert_eq!(
12981            s.validate().unwrap_err(),
12982            AplicacaoError::PolicyRetriesExceedsCap {
12983                retries: POLICY_RETRIES_MAX + 1
12984            }
12985        );
12986    }
12987
12988    #[test]
12989    fn rejects_policy_retries_far_above_cap() {
12990        // The `u32::MAX` worst case — the four-billion-retry policy
12991        // a typo (`(:retries 4294967295)`) or struct-literal
12992        // copy-paste lands in the slot. Pin the cap arm's coverage
12993        // explicitly across the full `u32` overflow so a future
12994        // relaxation that drops the upper bound surfaces here.
12995        let mut s = three_member_spec();
12996        s.politicas.retries = Some(u32::MAX);
12997        assert_eq!(
12998            s.validate().unwrap_err(),
12999            AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
13000        );
13001    }
13002
13003    #[test]
13004    fn accepts_policy_retries_at_cap() {
13005        // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
13006        // must validate. The cap is inclusive on the top edge,
13007        // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
13008        // discipline on the sibling [`crate::LimitsSpec::memory`]
13009        // axis. Pin the boundary explicitly so a future off-by-one
13010        // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
13011        // surfaces here as a test failure rather than a silent
13012        // contract narrowing.
13013        let mut s = three_member_spec();
13014        s.politicas.retries = Some(POLICY_RETRIES_MAX);
13015        s.validate()
13016            .expect("retries == POLICY_RETRIES_MAX must validate");
13017    }
13018
13019    #[test]
13020    fn accepts_policy_retries_typical_values() {
13021        // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
13022        // every value in the validated set must pass. The
13023        // Envoy / Istio production-playbook recommendation band
13024        // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
13025        // (`maxRetries ≤ 10`) both lie within this set.
13026        for r in 1..=POLICY_RETRIES_MAX {
13027            let mut s = three_member_spec();
13028            s.politicas.retries = Some(r);
13029            s.validate()
13030                .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
13031        }
13032    }
13033
13034    #[test]
13035    fn policy_retries_zero_takes_precedence_over_cap() {
13036        // The cross-arm ordering pin: `Some(0)` is structurally
13037        // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
13038        // (cap), but the zero-floor diagnostic is the more
13039        // self-locating one (it directly names the omit-axis
13040        // remediation), so the validate gate must fire on zero
13041        // first. Pin the order so a future refactor that reorders
13042        // the arms surfaces here as a test failure rather than a
13043        // silent diagnostic regression. Same shape every other
13044        // zero-then-shape ordering on this surface uses
13045        // ([`AplicacaoError::PolicyTimeoutZero`] then
13046        // [`AplicacaoError::PolicyTimeoutNotCanonical`];
13047        // [`AplicacaoError::PolicyBreakerZeroWindow`] then
13048        // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
13049        let mut s = three_member_spec();
13050        s.politicas.retries = Some(0);
13051        assert_eq!(
13052            s.validate().unwrap_err(),
13053            AplicacaoError::PolicyRetriesZero,
13054            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
13055        );
13056    }
13057
13058    #[test]
13059    fn policy_retries_cap_diagnostic_carries_offending_value() {
13060        // The diagnostic-shape pin: the offending `u32` is carried
13061        // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
13062        // variant so the surfaced error message names the value the
13063        // author wrote (`":politicas :retries (47) exceeds the
13064        // mesh-policy ceiling …"`), not just the cap. Same
13065        // self-locating diagnostic shape every other typed-cap arm
13066        // on this surface carries
13067        // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
13068        // offending byte count verbatim).
13069        let mut s = three_member_spec();
13070        s.politicas.retries = Some(47);
13071        let err = s.validate().unwrap_err();
13072        assert!(
13073            matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
13074            "got {err:?}"
13075        );
13076        let msg = err.to_string();
13077        assert!(
13078            msg.contains("47"),
13079            ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
13080        );
13081    }
13082
13083    #[test]
13084    fn policy_retries_cap_is_aws_app_mesh_aligned() {
13085        // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
13086        // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
13087        // schema cap — the only upstream mesh-policy schema that
13088        // documents an explicit hard cap. Pinning the literal value
13089        // here surfaces a future drift (a relaxation to 20, a
13090        // tightening to 5) as a deliberate test edit, not a silent
13091        // contract narrowing.
13092        assert_eq!(POLICY_RETRIES_MAX, 10);
13093    }
13094
13095    #[test]
13096    fn rejects_circuit_breaker_zero_max_failures() {
13097        let mut s = three_member_spec();
13098        s.politicas.circuit_breaker = Some(CircuitBreaker {
13099            max_failures: 0,
13100            window: Duration::from_secs(60),
13101        });
13102        assert_eq!(
13103            s.validate().unwrap_err(),
13104            AplicacaoError::PolicyBreakerZeroFailures
13105        );
13106    }
13107
13108    #[test]
13109    fn rejects_circuit_breaker_max_failures_above_cap() {
13110        // The fail-before-pass-after pin: `1001` is structurally one
13111        // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
13112        // silently passed validate on every pre-gate codebase
13113        // because the typed slot's only check was the zero-floor
13114        // arm. The breaker-no-op vector only surfaced at the runtime
13115        // substrate (Envoy / Cilium L7 outlier-detection overlay)
13116        // far from the source caixa.lisp with no field naming the
13117        // offending policy.
13118        let mut s = three_member_spec();
13119        s.politicas.circuit_breaker = Some(CircuitBreaker {
13120            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
13121            window: Duration::from_secs(60),
13122        });
13123        assert_eq!(
13124            s.validate().unwrap_err(),
13125            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
13126                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
13127            }
13128        );
13129    }
13130
13131    #[test]
13132    fn rejects_circuit_breaker_max_failures_far_above_cap() {
13133        // The `u32::MAX` worst case — the four-billion-failure
13134        // threshold a typo (`(:max-failures 4294967295)`) or a
13135        // struct-literal copy-paste lands in the slot. Pin the cap
13136        // arm's coverage explicitly across the full `u32` overflow
13137        // so a future relaxation that drops the upper bound surfaces
13138        // here.
13139        let mut s = three_member_spec();
13140        s.politicas.circuit_breaker = Some(CircuitBreaker {
13141            max_failures: u32::MAX,
13142            window: Duration::from_secs(60),
13143        });
13144        assert_eq!(
13145            s.validate().unwrap_err(),
13146            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
13147                max_failures: u32::MAX,
13148            }
13149        );
13150    }
13151
13152    #[test]
13153    fn accepts_circuit_breaker_max_failures_at_cap() {
13154        // The boundary value — exactly
13155        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
13156        // cap is inclusive on the top edge, matching the
13157        // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
13158        // discipline on the sibling capped axes. Pin the boundary
13159        // explicitly so a future off-by-one tightening
13160        // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
13161        // surfaces here as a test failure rather than a silent
13162        // contract narrowing.
13163        let mut s = three_member_spec();
13164        s.politicas.circuit_breaker = Some(CircuitBreaker {
13165            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
13166            window: Duration::from_secs(60),
13167        });
13168        s.validate()
13169            .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
13170    }
13171
13172    #[test]
13173    fn accepts_circuit_breaker_max_failures_typical_values() {
13174        // The documented production-playbook band positive-control
13175        // sweep — every value Hystrix / Istio / Envoy / Polly /
13176        // Resilience4j recommend (5..=50) must pass, plus a sweep
13177        // through the hyperscale band (100, 500, 1000) the cap
13178        // accepts. Pin the inclusive validated set explicitly so a
13179        // future tightening of the ceiling surfaces here.
13180        for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
13181            let mut s = three_member_spec();
13182            s.politicas.circuit_breaker = Some(CircuitBreaker {
13183                max_failures: n,
13184                window: Duration::from_secs(60),
13185            });
13186            s.validate()
13187                .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
13188        }
13189    }
13190
13191    #[test]
13192    fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
13193        // The cross-arm ordering pin: `0` is structurally outside
13194        // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
13195        // (cap), but the zero-floor diagnostic is the more
13196        // self-locating one (it directly names the omit-axis
13197        // remediation), so the validate gate must fire on zero
13198        // first. Same shape every other zero-then-shape ordering on
13199        // this surface uses
13200        // ([`AplicacaoError::PolicyRetriesZero`] then
13201        // [`AplicacaoError::PolicyRetriesExceedsCap`];
13202        // [`AplicacaoError::PolicyTimeoutZero`] then
13203        // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
13204        let mut s = three_member_spec();
13205        s.politicas.circuit_breaker = Some(CircuitBreaker {
13206            max_failures: 0,
13207            window: Duration::from_secs(60),
13208        });
13209        assert_eq!(
13210            s.validate().unwrap_err(),
13211            AplicacaoError::PolicyBreakerZeroFailures,
13212            "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
13213        );
13214    }
13215
13216    #[test]
13217    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
13218        // The cross-arm ordering pin between the cap and the
13219        // sibling `:window` gates (zero-window, canonical-window).
13220        // A breaker carrying both an over-cap `max_failures` AND a
13221        // structurally invalid window (zero, sub-ms) must surface
13222        // the cap diagnostic first — the cap arm is wired
13223        // immediately after the zero-failure arm and strictly
13224        // before the window arms, so the offending value the
13225        // diagnostic names matches the order the author would
13226        // discover the gates by reading top-to-bottom through
13227        // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
13228        // future refactor that reorders the arms surfaces here as a
13229        // test failure rather than a silent diagnostic regression.
13230        let mut s = three_member_spec();
13231        s.politicas.circuit_breaker = Some(CircuitBreaker {
13232            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
13233            window: Duration::ZERO,
13234        });
13235        assert_eq!(
13236            s.validate().unwrap_err(),
13237            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
13238                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
13239            },
13240            "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
13241        );
13242    }
13243
13244    #[test]
13245    fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
13246        // The diagnostic-shape pin: the offending `u32` is carried
13247        // verbatim into the
13248        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
13249        // variant so the surfaced error message names the value the
13250        // author wrote (`":politicas :circuit-breaker :max-failures
13251        // (50000) exceeds the mesh-policy ceiling …"`), not just
13252        // the cap. Same self-locating diagnostic shape every other
13253        // typed-cap arm on this surface carries
13254        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
13255        // offending retry count verbatim,
13256        // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
13257        // offending byte count verbatim).
13258        let mut s = three_member_spec();
13259        s.politicas.circuit_breaker = Some(CircuitBreaker {
13260            max_failures: 50_000,
13261            window: Duration::from_secs(60),
13262        });
13263        let err = s.validate().unwrap_err();
13264        assert!(
13265            matches!(
13266                err,
13267                AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
13268                    max_failures: 50_000
13269                }
13270            ),
13271            "got {err:?}"
13272        );
13273        let msg = err.to_string();
13274        assert!(
13275            msg.contains("50000"),
13276            ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
13277        );
13278    }
13279
13280    #[test]
13281    fn policy_breaker_max_failures_cap_pins_canonical_value() {
13282        // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
13283        // value at 1000 — an order of magnitude above every
13284        // documented production-playbook recommendation band
13285        // (Hystrix `requestVolumeThreshold` default 20, Istio
13286        // `outlierDetection.consecutive5xxErrors` default 5, Envoy
13287        // `outlier_detection.consecutive_5xx` default 5, Polly /
13288        // Resilience4j typical 5..=50) and below the
13289        // clearly-pathological "effectively no protection" floor
13290        // (10_000, 100_000, u32::MAX). Pinning the literal value
13291        // here surfaces a future drift (a relaxation to 10_000, a
13292        // tightening to 100) as a deliberate test edit, not a
13293        // silent contract narrowing.
13294        assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
13295    }
13296
13297    #[test]
13298    fn rejects_circuit_breaker_zero_window() {
13299        let mut s = three_member_spec();
13300        s.politicas.circuit_breaker = Some(CircuitBreaker {
13301            max_failures: 5,
13302            window: Duration::ZERO,
13303        });
13304        assert_eq!(
13305            s.validate().unwrap_err(),
13306            AplicacaoError::PolicyBreakerZeroWindow
13307        );
13308    }
13309
13310    #[test]
13311    fn rejects_zero_rate_limit() {
13312        let mut s = three_member_spec();
13313        s.politicas.rate_limit = Some(RateLimit {
13314            rate: 0,
13315            window: Duration::from_secs(1),
13316        });
13317        assert_eq!(
13318            s.validate().unwrap_err(),
13319            AplicacaoError::PolicyRateLimitZero
13320        );
13321    }
13322
13323    #[test]
13324    fn rejects_rate_limit_zero_window() {
13325        // `RateLimit { rate: 100, window: Duration::ZERO }` is
13326        // constructible programmatically (the typed `Duration` field
13327        // imposes no nonzero invariant) but renders through
13328        // `rate_limit_codec::render` as `"100/0s"` — a fragment the
13329        // codec's `parse` rejects as `unknown rate-limit window unit
13330        // "0s"`. Until this validate-time gate landed the typed slot
13331        // accepted the value silently and the round-trip break only
13332        // surfaced at deserialize time (potentially in a downstream
13333        // consumer that never re-validates). Pin the rejection at
13334        // `AplicacaoSpec::validate` so the typed slot's valid set
13335        // matches the codec's round-trippable set structurally.
13336        let mut s = three_member_spec();
13337        s.politicas.rate_limit = Some(RateLimit {
13338            rate: 100,
13339            window: Duration::ZERO,
13340        });
13341        assert_eq!(
13342            s.validate().unwrap_err(),
13343            AplicacaoError::PolicyRateLimitWindowNotCanonical {
13344                window: Duration::ZERO
13345            }
13346        );
13347    }
13348
13349    #[test]
13350    fn rejects_rate_limit_arbitrary_seconds_window() {
13351        // 45 seconds is a valid `Duration` but not one of the three
13352        // canonical rate-limit windows the codec round-trips
13353        // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
13354        // refuses on round-trip — same round-trip-break shape the
13355        // zero-window arm above pins, with a non-zero magnitude to
13356        // guard against a future "reject only zero" half-measure.
13357        let mut s = three_member_spec();
13358        let window = Duration::from_secs(45);
13359        s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
13360        assert_eq!(
13361            s.validate().unwrap_err(),
13362            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
13363        );
13364    }
13365
13366    #[test]
13367    fn rejects_rate_limit_two_minute_window() {
13368        // 120 seconds = 2 minutes is a "looks-canonical" but
13369        // not-canonical window: it's a clean integer multiple of the
13370        // minute unit, but the codec only round-trips the
13371        // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
13372        // A `Duration::from_secs(120)` window renders as `"100/120s"`
13373        // which the parser rejects. Pinning this case rules out a
13374        // future "accept any clean multiple of s/m/h" relaxation
13375        // that would silently break the codec contract.
13376        let mut s = three_member_spec();
13377        let window = Duration::from_secs(120);
13378        s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
13379        assert_eq!(
13380            s.validate().unwrap_err(),
13381            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
13382        );
13383    }
13384
13385    #[test]
13386    fn rejects_rate_limit_subsecond_window() {
13387        // A sub-second window (e.g. 500ms) is a valid `Duration` but
13388        // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
13389        // Pin the rejection so a future relaxation can't silently
13390        // admit fractional-second windows that the codec can't
13391        // round-trip.
13392        let mut s = three_member_spec();
13393        let window = Duration::from_millis(500);
13394        s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
13395        assert_eq!(
13396            s.validate().unwrap_err(),
13397            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
13398        );
13399    }
13400
13401    #[test]
13402    fn rejects_policy_rate_limit_above_cap() {
13403        // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
13404        // is structurally one past the cap and silently passed
13405        // validate on every pre-gate codebase because the typed slot's
13406        // only `rate` check was the zero-floor arm. The no-op-limiter
13407        // shape only surfaced at the runtime substrate (Envoy's
13408        // `local_rate_limit.token_bucket.max_tokens`, the future
13409        // Cilium L7 rate-limit overlay) far from the source caixa.lisp
13410        // with no field naming the offending policy.
13411        let mut s = three_member_spec();
13412        s.politicas.rate_limit = Some(RateLimit {
13413            rate: POLICY_RATE_LIMIT_MAX + 1,
13414            window: Duration::from_secs(1),
13415        });
13416        assert_eq!(
13417            s.validate().unwrap_err(),
13418            AplicacaoError::PolicyRateLimitExceedsCap {
13419                rate: POLICY_RATE_LIMIT_MAX + 1
13420            }
13421        );
13422    }
13423
13424    #[test]
13425    fn rejects_policy_rate_limit_far_above_cap() {
13426        // The `u32::MAX` worst case — the four-billion-token rate-limit
13427        // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
13428        // copy-paste lands in the slot. Pin the cap arm's coverage
13429        // explicitly across the full `u32` overflow so a future
13430        // relaxation that drops the upper bound surfaces here. Peer to
13431        // `rejects_policy_retries_far_above_cap` on the sibling
13432        // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
13433        // on the sibling `:max-failures` axis.
13434        let mut s = three_member_spec();
13435        s.politicas.rate_limit = Some(RateLimit {
13436            rate: u32::MAX,
13437            window: Duration::from_secs(1),
13438        });
13439        assert_eq!(
13440            s.validate().unwrap_err(),
13441            AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
13442        );
13443    }
13444
13445    #[test]
13446    fn accepts_policy_rate_limit_at_cap() {
13447        // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
13448        // must validate. The cap is inclusive on the top edge, matching
13449        // every other typed upper bound in this crate
13450        // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
13451        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
13452        // across all three canonical windows so a future off-by-one
13453        // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
13454        // window-conditional cap surfaces here as a test failure rather
13455        // than a silent contract narrowing.
13456        for secs in [1u64, 60, 3600] {
13457            let mut s = three_member_spec();
13458            s.politicas.rate_limit = Some(RateLimit {
13459                rate: POLICY_RATE_LIMIT_MAX,
13460                window: Duration::from_secs(secs),
13461            });
13462            s.validate().unwrap_or_else(|e| {
13463                panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
13464            });
13465        }
13466    }
13467
13468    #[test]
13469    fn accepts_policy_rate_limit_typical_values() {
13470        // The documented production-playbook recommendation band —
13471        // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
13472        // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
13473        // Enterprise ~1M per-hour. Every value in the validated set
13474        // must pass; pin the band explicitly so a future tightening
13475        // surfaces here.
13476        for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
13477            for secs in [1u64, 60, 3600] {
13478                let mut s = three_member_spec();
13479                s.politicas.rate_limit = Some(RateLimit {
13480                    rate,
13481                    window: Duration::from_secs(secs),
13482                });
13483                s.validate().unwrap_or_else(|e| {
13484                    panic!("rate={rate} window={secs}s must validate; got {e:?}")
13485                });
13486            }
13487        }
13488    }
13489
13490    #[test]
13491    fn policy_rate_limit_zero_takes_precedence_over_cap() {
13492        // The cross-arm ordering pin: `rate == 0` is structurally
13493        // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
13494        // (cap), but the zero-floor diagnostic is the more
13495        // self-locating one (it directly names the omit-axis
13496        // remediation). Pin the order so a future refactor that
13497        // reorders the arms surfaces here as a test failure rather
13498        // than a silent diagnostic regression. Same shape every other
13499        // zero-then-cap ordering on this surface uses
13500        // ([`AplicacaoError::PolicyRetriesZero`] then
13501        // [`AplicacaoError::PolicyRetriesExceedsCap`];
13502        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
13503        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
13504        let mut s = three_member_spec();
13505        s.politicas.rate_limit = Some(RateLimit {
13506            rate: 0,
13507            window: Duration::from_secs(1),
13508        });
13509        assert_eq!(
13510            s.validate().unwrap_err(),
13511            AplicacaoError::PolicyRateLimitZero,
13512            "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
13513        );
13514    }
13515
13516    #[test]
13517    fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
13518        // Two-axis-bad pin: rate above cap *and* window non-canonical.
13519        // The validate gate must fire on the rate cap first — the
13520        // amplification-shape (no-op limiter) diagnostic is the more
13521        // fundamental one; the window-canonical diagnostic is the
13522        // narrower codec-round-trip shape. Pin the ordering so a future
13523        // refactor that reorders the rate-then-window check arms
13524        // surfaces here as a test failure rather than a silent
13525        // diagnostic regression.
13526        let mut s = three_member_spec();
13527        s.politicas.rate_limit = Some(RateLimit {
13528            rate: POLICY_RATE_LIMIT_MAX + 1,
13529            window: Duration::from_secs(45),
13530        });
13531        assert_eq!(
13532            s.validate().unwrap_err(),
13533            AplicacaoError::PolicyRateLimitExceedsCap {
13534                rate: POLICY_RATE_LIMIT_MAX + 1
13535            },
13536            "above-cap rate must surface the cap diagnostic, not the window diagnostic"
13537        );
13538    }
13539
13540    #[test]
13541    fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
13542        // The diagnostic-shape pin: the offending `u32` is carried
13543        // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
13544        // variant so the surfaced error message names the value the
13545        // author wrote (`":politicas :rate-limit rate (5000000) exceeds
13546        // the mesh-policy ceiling …"`), not just the cap. Same
13547        // self-locating diagnostic shape every other typed-cap arm on
13548        // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
13549        // carries the offending retries count verbatim,
13550        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
13551        // the offending failure count verbatim).
13552        let mut s = three_member_spec();
13553        s.politicas.rate_limit = Some(RateLimit {
13554            rate: 5_000_000,
13555            window: Duration::from_secs(1),
13556        });
13557        let err = s.validate().unwrap_err();
13558        assert!(
13559            matches!(
13560                err,
13561                AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
13562            ),
13563            "got {err:?}"
13564        );
13565        let msg = err.to_string();
13566        assert!(
13567            msg.contains("5000000"),
13568            ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
13569        );
13570    }
13571
13572    #[test]
13573    fn policy_rate_limit_cap_pins_canonical_value() {
13574        // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
13575        // 1_000_000 — two-to-three orders of magnitude above every
13576        // documented production-playbook recommendation band (Envoy /
13577        // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
13578        // Gateway 10_000..=100_000 per-minute) and below the
13579        // clearly-pathological "paste-from-binary blob" floor
13580        // (100_000_000, u32::MAX). Pinning the literal value here
13581        // surfaces a future drift (a relaxation to 10_000_000, a
13582        // tightening to 100_000) as a deliberate test edit, not a
13583        // silent contract narrowing.
13584        assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
13585    }
13586
13587    #[test]
13588    fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
13589        // Both axes are invalid here: rate == 0 *and* window is
13590        // non-canonical. The validate gate must fire on rate first
13591        // (matching the existing `rejects_zero_rate_limit` ordering),
13592        // so the existing diagnostic continues to lead with the
13593        // simpler "zero rate" framing. Pinning the order of checks
13594        // so a future refactor that reorders the arms surfaces here
13595        // as a test failure rather than a silent diagnostic
13596        // regression.
13597        let mut s = three_member_spec();
13598        s.politicas.rate_limit = Some(RateLimit {
13599            rate: 0,
13600            window: Duration::from_secs(45),
13601        });
13602        assert_eq!(
13603            s.validate().unwrap_err(),
13604            AplicacaoError::PolicyRateLimitZero
13605        );
13606    }
13607
13608    #[test]
13609    fn rate_limit_canonical_windows_validate() {
13610        // The three canonical windows the codec round-trips
13611        // losslessly — 1s / 60s / 3600s — must all pass `validate()`
13612        // unchanged. Pin the full canonical set as a positive case
13613        // (the existing `rate_limit_round_trip_seconds` /
13614        // `rate_limit_round_trip_minutes` tests pin the
13615        // serialize-then-deserialize property at the codec layer; this
13616        // test pins the validate-side complement so a future tightening
13617        // of the canonical set — e.g. dropping `:hour` — surfaces here
13618        // as a test failure rather than a silent contract narrowing).
13619        for secs in [1u64, 60, 3600] {
13620            let mut s = three_member_spec();
13621            s.politicas.rate_limit = Some(RateLimit {
13622                rate: 100,
13623                window: Duration::from_secs(secs),
13624            });
13625            s.validate().expect("canonical window must validate");
13626        }
13627    }
13628
13629    #[test]
13630    fn rate_limit_validated_value_round_trips_through_codec() {
13631        // The structural property the validate gate enforces:
13632        // every `RateLimit` past `AplicacaoSpec::validate` round-trips
13633        // losslessly through the `rate_limit_codec` (serialize → string
13634        // → deserialize → equal value). Pin this end-to-end so a future
13635        // change to either side (the validate gate's accepted window
13636        // set, the codec's parse/render unit set) that breaks the
13637        // alignment surfaces here. The previous-state shape (typed
13638        // slot accepts arbitrary `Duration`, codec only round-trips
13639        // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
13640        // window — the validate gate now forecloses that.
13641        for secs in [1u64, 60, 3600] {
13642            let mut s = three_member_spec();
13643            s.politicas.rate_limit = Some(RateLimit {
13644                rate: 250,
13645                window: Duration::from_secs(secs),
13646            });
13647            s.validate().unwrap();
13648            let json = serde_json::to_string(&s.politicas).unwrap();
13649            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
13650            assert_eq!(
13651                back.rate_limit, s.politicas.rate_limit,
13652                "every validated :rate-limit must round-trip losslessly through the codec"
13653            );
13654        }
13655    }
13656
13657    #[test]
13658    fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
13659        // The hour-window canonical form (`"<n>/h"`) was missing from
13660        // the prior `rate_limit_round_trip_seconds` / `_minutes` test
13661        // pair. Now that the validate gate pins 3600s as part of the
13662        // canonical set, pin its serialize-side render shape too so
13663        // the third leg of the s/m/h tripod is explicitly tested.
13664        let policy = MeshPolicy {
13665            rate_limit: Some(RateLimit {
13666                rate: 10000,
13667                window: Duration::from_secs(3600),
13668            }),
13669            ..Default::default()
13670        };
13671        let json = serde_json::to_string(&policy).unwrap();
13672        assert!(
13673            json.contains("\"10000/h\""),
13674            "hour-window canonical form must render with `h` suffix (got: {json})"
13675        );
13676        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
13677        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
13678    }
13679
13680    #[test]
13681    fn is_canonical_rate_limit_window_predicate_tracks_codec() {
13682        // Pin the predicate's accepted set against the codec's
13683        // accepted set explicitly. A future addition to the codec
13684        // (e.g. accepting `:day`/`:week` as authoring units) must be
13685        // accompanied by a parallel addition here, and a regression
13686        // that drops one of the three canonical units from either
13687        // side surfaces as a test failure. The predicate is the
13688        // single source of truth for the canonical-window set; this
13689        // test enshrines that the codec's parse arms and the
13690        // predicate's accept arms agree exactly.
13691        assert!(super::is_canonical_rate_limit_window(Duration::from_secs(
13692            1
13693        )));
13694        assert!(super::is_canonical_rate_limit_window(Duration::from_secs(
13695            60
13696        )));
13697        assert!(super::is_canonical_rate_limit_window(Duration::from_secs(
13698            3600
13699        )));
13700        // Non-canonical windows the predicate rejects.
13701        assert!(!super::is_canonical_rate_limit_window(Duration::ZERO));
13702        assert!(!super::is_canonical_rate_limit_window(Duration::from_secs(
13703            2
13704        )));
13705        assert!(!super::is_canonical_rate_limit_window(Duration::from_secs(
13706            30
13707        )));
13708        assert!(!super::is_canonical_rate_limit_window(Duration::from_secs(
13709            120
13710        )));
13711        assert!(!super::is_canonical_rate_limit_window(Duration::from_secs(
13712            86400
13713        )));
13714        // Sub-second windows: even `Duration::from_millis(1000)` is
13715        // exactly 1s and accepted; `Duration::from_millis(500)` is
13716        // sub-second and rejected.
13717        assert!(super::is_canonical_rate_limit_window(
13718            Duration::from_millis(1000)
13719        ));
13720        assert!(!super::is_canonical_rate_limit_window(
13721            Duration::from_millis(500)
13722        ));
13723        assert!(!super::is_canonical_rate_limit_window(
13724            Duration::from_millis(1500)
13725        ));
13726    }
13727
13728    #[test]
13729    fn rate_limit_unit_table_projections_are_mutual_inverses() {
13730        // Bidirection pin against the lifted [`RATE_LIMIT_UNIT_TABLE`]
13731        // (the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}`
13732        // bijection every consumer of the rate-limit unit surface
13733        // reads from). Until this table landed the three (str,
13734        // Duration) pairs sat scattered across four peer sites —
13735        // `rate_limit_codec::parse`'s `match unit` arm, `render`'s
13736        // `if secs == 1 { "s" } else if …` cascade, and
13737        // `is_canonical_rate_limit_window`'s `secs == 1 || 60 ||
13738        // 3600` disjunction — each carrying its own hand-written copy
13739        // with no compile-time link between them. A future
13740        // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
13741        // sub-second window) would have to be threaded through all
13742        // three sites in lockstep or a drift would silently split
13743        // the accepted-window set. Lifting the pairs onto one const
13744        // + two projection helpers collapses the surface: this pin
13745        // enshrines that both projections agree on every table row
13746        // and neither leaks a spurious entry the other doesn't
13747        // recognize.
13748        for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
13749            let window = super::rate_limit_window_from_unit(unit)
13750                .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
13751            assert_eq!(
13752                window,
13753                Duration::from_secs(secs),
13754                "unit {unit:?} must resolve to {secs}s"
13755            );
13756            assert_eq!(
13757                super::rate_limit_window_unit(window),
13758                Some(unit),
13759                "Duration({secs}s) must render as {unit:?}"
13760            );
13761        }
13762        // Non-table units yield None on the `unit → Duration`
13763        // projection — a future `"d"` addition to the table would
13764        // flip this arm; today it pins the current three-row table's
13765        // rejection semantics.
13766        assert!(super::rate_limit_window_from_unit("d").is_none());
13767        assert!(super::rate_limit_window_from_unit("ms").is_none());
13768        assert!(super::rate_limit_window_from_unit("").is_none());
13769        // Non-table Durations yield None on the `Duration → unit`
13770        // projection — pins that the two projections agree on the
13771        // "not in the table" semantic too, so a drift where the
13772        // parse-side accepts a value the render-side can't emit is
13773        // a build error at the two-arm pair, not a silent codec
13774        // round-trip break.
13775        assert!(super::rate_limit_window_unit(Duration::from_secs(2)).is_none());
13776        assert!(super::rate_limit_window_unit(Duration::from_secs(86_400)).is_none());
13777        assert!(super::rate_limit_window_unit(Duration::from_millis(1500)).is_none());
13778    }
13779
13780    #[test]
13781    fn rejects_policy_timeout_sub_millisecond() {
13782        // A purely sub-millisecond `Duration` (`from_micros(500)` =
13783        // 500_000 ns) is not the zero `Duration` — the `is_zero()`
13784        // arm passes — but `as_millis() == 0`, so the shared codec's
13785        // `render` arm returns the literal `"0s"`, which the
13786        // codec's `parse` arm then deserializes as `Duration::ZERO`
13787        // and the `PolicyTimeoutZero` zero-floor gate would reject
13788        // on re-validate. Pin the rejection at the typed slot's
13789        // canonical-floor gate so the round-trip break surfaces at
13790        // validate time, naming the offending `Duration`, rather
13791        // than at the next serialize → deserialize round-trip far
13792        // from the source `caixa.lisp`.
13793        let mut s = three_member_spec();
13794        let timeout = Duration::from_micros(500);
13795        s.politicas.timeout = Some(timeout);
13796        assert_eq!(
13797            s.validate().unwrap_err(),
13798            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
13799        );
13800    }
13801
13802    #[test]
13803    fn rejects_policy_timeout_non_integer_millisecond() {
13804        // A `Duration` with non-integer-millisecond residue
13805        // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
13806        // through the shared codec's `render` arm as `"1ms"` (the
13807        // `as_millis()` floor truncates), which the codec's `parse`
13808        // arm then deserializes as `Duration::from_millis(1)` =
13809        // 1_000_000 ns — silently *different* from the original.
13810        // Pin the rejection so this round-trip break surfaces at
13811        // validate time, where the offending `Duration` is named,
13812        // rather than as a silent value-laundered round-trip on the
13813        // next codec round-trip.
13814        let mut s = three_member_spec();
13815        let timeout = Duration::from_micros(1500);
13816        s.politicas.timeout = Some(timeout);
13817        assert_eq!(
13818            s.validate().unwrap_err(),
13819            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
13820        );
13821    }
13822
13823    #[test]
13824    fn accepts_policy_timeout_integer_millisecond_forms() {
13825        // The codec's accepted set — integer multiples of 1ms — is
13826        // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
13827        // `1h` all pass the canonical gate. Pin the canonical-forms
13828        // sweep so a future tightening of the codec's grammar (e.g.
13829        // dropping `:ms`) surfaces here as a test failure rather
13830        // than a silent contract narrowing on the typed slot.
13831        for timeout in [
13832            Duration::from_millis(1),
13833            Duration::from_millis(500),
13834            Duration::from_millis(1500),
13835            Duration::from_secs(30),
13836            Duration::from_secs(120),
13837            Duration::from_secs(3600),
13838        ] {
13839            let mut s = three_member_spec();
13840            s.politicas.timeout = Some(timeout);
13841            s.validate()
13842                .expect("integer-millisecond :timeout must validate");
13843        }
13844    }
13845
13846    #[test]
13847    fn policy_timeout_zero_takes_precedence_over_canonical() {
13848        // `Duration::ZERO` carries `subsec_nanos() == 0` and would
13849        // pass the canonical-millisecond gate; the more self-locating
13850        // `PolicyTimeoutZero` arm (which names the omit-axis
13851        // remediation directly) must fire first. Pin the ordering so
13852        // a future refactor that reorders the arms surfaces here as a
13853        // test failure rather than a silent diagnostic regression.
13854        let mut s = three_member_spec();
13855        s.politicas.timeout = Some(Duration::ZERO);
13856        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
13857    }
13858
13859    #[test]
13860    fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
13861        // The diagnostic envelope carries the offending `Duration`
13862        // verbatim so the author can grep their `caixa.lisp` for
13863        // `:timeout "<value>"` and fix it in one edit. Same
13864        // diagnostic shape every other typed-slot canonical-form
13865        // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
13866        // peer `:rate-limit :window` axis.
13867        let mut s = three_member_spec();
13868        let timeout = Duration::from_nanos(1_000_001);
13869        s.politicas.timeout = Some(timeout);
13870        match s.validate().unwrap_err() {
13871            AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
13872                assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
13873            }
13874            other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
13875        }
13876    }
13877
13878    #[test]
13879    fn rejects_policy_timeout_above_cap() {
13880        // The fail-before-pass-after pin: 3601s = 1h + 1s is
13881        // structurally one canonical-tick past the
13882        // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
13883        // integer-millisecond magnitude the canonical-form arm above
13884        // accepts cleanly, that the codec round-trips losslessly as
13885        // `"3601s"`, and that silently passed validate on every
13886        // pre-gate codebase because the typed slot's only checks were
13887        // the zero-floor and canonical-form arms. The mesh-level
13888        // deadline degenerates only at the runtime substrate (Envoy
13889        // / Cilium L7 timeout overlay) far from the source
13890        // `caixa.lisp` with no field naming the offending policy.
13891        let mut s = three_member_spec();
13892        let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
13893        s.politicas.timeout = Some(timeout);
13894        assert_eq!(
13895            s.validate().unwrap_err(),
13896            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
13897        );
13898    }
13899
13900    #[test]
13901    fn rejects_policy_timeout_one_millisecond_above_cap() {
13902        // Boundary case: exactly 1ms past the cap (the granularity
13903        // the canonical-form gate enforces). Catches a future
13904        // "strictly less than" half-measure and pins the diagnostic
13905        // to name the offending `Duration` verbatim. Peer of
13906        // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
13907        // boundary pin on the sibling `:limits :memory` top edge.
13908        let mut s = three_member_spec();
13909        let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
13910        s.politicas.timeout = Some(timeout);
13911        assert_eq!(
13912            s.validate().unwrap_err(),
13913            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
13914        );
13915    }
13916
13917    #[test]
13918    fn rejects_policy_timeout_far_above_cap() {
13919        // The "obvious authoring footgun" case: a `(:timeout "24h")`
13920        // or `(:timeout "86400s")` — values the canonical-form arm
13921        // accepts as integer-millisecond magnitudes, the codec
13922        // round-trips losslessly through serde, but the mesh-level
13923        // policy cannot honor (a 24-hour synchronous-`:contratos`
13924        // deadline is operationally indistinguishable from
13925        // omit-the-axis). Until this gate landed validate accepted
13926        // it. Pin both common above-cap values (24h, 7d) so a future
13927        // relaxation that drops the upper bound surfaces here.
13928        for timeout in [
13929            Duration::from_secs(86_400),    // 24h
13930            Duration::from_secs(604_800),   // 7d
13931            Duration::from_secs(1_000_000), // ~11.5 days
13932        ] {
13933            let mut s = three_member_spec();
13934            s.politicas.timeout = Some(timeout);
13935            assert_eq!(
13936                s.validate().unwrap_err(),
13937                AplicacaoError::PolicyTimeoutExceedsCap { timeout }
13938            );
13939        }
13940    }
13941
13942    #[test]
13943    fn accepts_policy_timeout_at_cap() {
13944        // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
13945        // must validate. The cap is inclusive on the top edge,
13946        // matching the [`POLICY_RETRIES_MAX`] /
13947        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
13948        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
13949        // sibling capped axes. Pin the boundary explicitly so a
13950        // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
13951        // instead of `>`) surfaces here as a test failure rather
13952        // than a silent contract narrowing.
13953        let mut s = three_member_spec();
13954        s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
13955        s.validate()
13956            .expect("timeout == POLICY_TIMEOUT_MAX must validate");
13957    }
13958
13959    #[test]
13960    fn accepts_policy_timeout_typical_values() {
13961        // The documented production-playbook band positive-control
13962        // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
13963        // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
13964        // plus a sweep through the long-running-workflow band
13965        // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
13966        // validated set explicitly so a future tightening of the
13967        // ceiling surfaces here as a deliberate test edit, not a
13968        // silent contract narrowing.
13969        for timeout in [
13970            Duration::from_millis(1),
13971            Duration::from_millis(500),
13972            Duration::from_secs(1),
13973            Duration::from_secs(10),
13974            Duration::from_secs(15), // Envoy default
13975            Duration::from_secs(30),
13976            Duration::from_secs(60), // AWS App Mesh typical
13977            Duration::from_secs(300),
13978            Duration::from_secs(900),
13979            Duration::from_secs(1800),
13980            Duration::from_secs(3600), // exactly 1h, the cap
13981        ] {
13982            let mut s = three_member_spec();
13983            s.politicas.timeout = Some(timeout);
13984            s.validate()
13985                .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
13986        }
13987    }
13988
13989    #[test]
13990    fn policy_timeout_zero_takes_precedence_over_cap() {
13991        // The cross-arm ordering pin: `Duration::ZERO` is
13992        // structurally outside both `>= 1ms` (zero-floor) and
13993        // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
13994        // diagnostic is the more self-locating one (it directly
13995        // names the omit-axis remediation), so the validate gate
13996        // must fire on zero first. Same shape every other
13997        // zero-then-shape ordering on this surface uses
13998        // ([`AplicacaoError::PolicyRetriesZero`] then
13999        // [`AplicacaoError::PolicyRetriesExceedsCap`];
14000        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
14001        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
14002        let mut s = three_member_spec();
14003        s.politicas.timeout = Some(Duration::ZERO);
14004        assert_eq!(
14005            s.validate().unwrap_err(),
14006            AplicacaoError::PolicyTimeoutZero,
14007            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
14008        );
14009    }
14010
14011    #[test]
14012    fn policy_timeout_canonical_takes_precedence_over_cap() {
14013        // The cross-arm ordering pin: a `Duration` that is *both*
14014        // sub-millisecond (non-canonical-form) and structurally
14015        // above the cap surfaces the canonical-form diagnostic
14016        // first, because the round-trip-shape break is the more
14017        // fundamental issue (the value can't even round-trip
14018        // through the codec, so the cap diagnostic naming
14019        // `1ms..=1h` would be misleading — there's no integer-ms
14020        // form of the offending value). Pin the order so a future
14021        // refactor that reorders the arms surfaces here as a test
14022        // failure rather than a silent diagnostic regression.
14023        let mut s = three_member_spec();
14024        // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
14025        // *and* total magnitude above the 1h cap.
14026        let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
14027        s.politicas.timeout = Some(timeout);
14028        assert_eq!(
14029            s.validate().unwrap_err(),
14030            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
14031            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
14032        );
14033    }
14034
14035    #[test]
14036    fn policy_timeout_cap_diagnostic_carries_offending_value() {
14037        // The diagnostic-shape pin: the offending `Duration` is
14038        // carried verbatim into the
14039        // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
14040        // surfaced error message names the value the author wrote
14041        // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
14042        // exceeds the mesh-policy ceiling …"`), not just the cap.
14043        // Same self-locating diagnostic shape every other typed-cap
14044        // arm on this surface carries
14045        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
14046        // offending retry count verbatim).
14047        let mut s = three_member_spec();
14048        let timeout = Duration::from_secs(7200); // 2h
14049        s.politicas.timeout = Some(timeout);
14050        let err = s.validate().unwrap_err();
14051        assert!(
14052            matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
14053            "got {err:?}"
14054        );
14055        let msg = err.to_string();
14056        assert!(
14057            msg.contains("7200"),
14058            ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
14059        );
14060    }
14061
14062    #[test]
14063    fn policy_timeout_cap_pins_canonical_value() {
14064        // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
14065        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
14066        // the shared duration codec emits as a clean canonical
14067        // string (`"<n>h"`). Pinning the literal value here surfaces
14068        // a future drift (a relaxation to 24h, a tightening to 5m)
14069        // as a deliberate test edit, not a silent contract
14070        // narrowing. Same shape every other typed-cap value pin on
14071        // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
14072        assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
14073        assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
14074    }
14075
14076    #[test]
14077    fn policy_timeout_cap_value_round_trips_through_codec() {
14078        // The codec round-trip property the cap arm preserves: the
14079        // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
14080        // the shared duration codec — every value at the cap renders
14081        // to a clean canonical string (`"1h"`) and parses back to
14082        // the same `Duration`. Pin this so a future drift between
14083        // the cap constant and the codec's largest emitted unit
14084        // surfaces here. Same shape every other typed boundary pin
14085        // on this surface uses
14086        // (`wasm32_memory_cap_matches_parsed_4_gib`).
14087        let policy = MeshPolicy {
14088            timeout: Some(POLICY_TIMEOUT_MAX),
14089            ..Default::default()
14090        };
14091        let json = serde_json::to_string(&policy).unwrap();
14092        // The codec emits `"1h"` for the canonical 1-hour magnitude.
14093        assert!(
14094            json.contains("\"1h\""),
14095            "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
14096        );
14097        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
14098        assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
14099    }
14100
14101    #[test]
14102    fn rejects_circuit_breaker_window_sub_millisecond() {
14103        // Peer of the `:timeout` sub-millisecond arm on the second
14104        // typed-`Duration` `:politicas` axis: a purely sub-ms
14105        // `Duration` (`from_micros(500)`) renders through the shared
14106        // codec as `"0s"`, which the codec parses back to
14107        // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
14108        // zero-floor gate then rejects on re-validate.
14109        let mut s = three_member_spec();
14110        let window = Duration::from_micros(500);
14111        s.politicas.circuit_breaker = Some(CircuitBreaker {
14112            max_failures: 5,
14113            window,
14114        });
14115        assert_eq!(
14116            s.validate().unwrap_err(),
14117            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
14118        );
14119    }
14120
14121    #[test]
14122    fn rejects_circuit_breaker_window_non_integer_millisecond() {
14123        // Peer of the `:timeout` non-integer-ms arm: a `Duration`
14124        // with non-integer-millisecond residue renders through the
14125        // shared codec as the truncated `"<n>ms"` form, parsing back
14126        // to a *different* `Duration` on the next round-trip.
14127        let mut s = three_member_spec();
14128        let window = Duration::from_micros(1500);
14129        s.politicas.circuit_breaker = Some(CircuitBreaker {
14130            max_failures: 5,
14131            window,
14132        });
14133        assert_eq!(
14134            s.validate().unwrap_err(),
14135            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
14136        );
14137    }
14138
14139    #[test]
14140    fn accepts_circuit_breaker_window_integer_millisecond_forms() {
14141        // The canonical-forms sweep on the breaker axis: every
14142        // integer-ms multiple the codec round-trips losslessly
14143        // passes the canonical gate.
14144        for window in [
14145            Duration::from_millis(1),
14146            Duration::from_millis(500),
14147            Duration::from_millis(1500),
14148            Duration::from_secs(30),
14149            Duration::from_secs(60),
14150            Duration::from_secs(3600),
14151        ] {
14152            let mut s = three_member_spec();
14153            s.politicas.circuit_breaker = Some(CircuitBreaker {
14154                max_failures: 5,
14155                window,
14156            });
14157            s.validate()
14158                .expect("integer-millisecond :circuit-breaker :window must validate");
14159        }
14160    }
14161
14162    #[test]
14163    fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
14164        // `Duration::ZERO` would pass the canonical-ms gate (the
14165        // sub-ns residue is zero) but must surface the narrower
14166        // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
14167        // remediation.
14168        let mut s = three_member_spec();
14169        s.politicas.circuit_breaker = Some(CircuitBreaker {
14170            max_failures: 5,
14171            window: Duration::ZERO,
14172        });
14173        assert_eq!(
14174            s.validate().unwrap_err(),
14175            AplicacaoError::PolicyBreakerZeroWindow
14176        );
14177    }
14178
14179    #[test]
14180    fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
14181        // Both axes invalid: max_failures == 0 *and* window is
14182        // sub-ms. The validate gate must fire on max_failures first
14183        // (matching the existing ordering pin
14184        // `rejects_circuit_breaker_zero_max_failures` enshrines), so
14185        // the existing diagnostic continues to lead with the simpler
14186        // "zero threshold" framing.
14187        let mut s = three_member_spec();
14188        s.politicas.circuit_breaker = Some(CircuitBreaker {
14189            max_failures: 0,
14190            window: Duration::from_micros(500),
14191        });
14192        assert_eq!(
14193            s.validate().unwrap_err(),
14194            AplicacaoError::PolicyBreakerZeroFailures
14195        );
14196    }
14197
14198    #[test]
14199    fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
14200        let mut s = three_member_spec();
14201        let window = Duration::from_nanos(60_000_000_001);
14202        s.politicas.circuit_breaker = Some(CircuitBreaker {
14203            max_failures: 5,
14204            window,
14205        });
14206        match s.validate().unwrap_err() {
14207            AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
14208                assert_eq!(w, window, "diagnostic must carry the offending Duration");
14209            }
14210            other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
14211        }
14212    }
14213
14214    #[test]
14215    fn rejects_circuit_breaker_window_above_cap() {
14216        // The fail-before-pass-after pin: 3601s = 1h + 1s is
14217        // structurally one canonical-tick past the
14218        // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
14219        // integer-millisecond magnitude the canonical-form arm above
14220        // accepts cleanly, that the codec round-trips losslessly as
14221        // `"3601s"`, and that silently passed validate on every
14222        // pre-gate codebase because the typed slot's only checks were
14223        // the zero-floor and canonical-form arms. The
14224        // rolling-window-to-lifetime-counter degeneration surfaces
14225        // only at the runtime substrate (Envoy's outlier_detection
14226        // interval, the future CiliumClusterwideEnvoyConfig overlay)
14227        // far from the source `caixa.lisp` with no field naming the
14228        // offending policy.
14229        let mut s = three_member_spec();
14230        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
14231        s.politicas.circuit_breaker = Some(CircuitBreaker {
14232            max_failures: 5,
14233            window,
14234        });
14235        assert_eq!(
14236            s.validate().unwrap_err(),
14237            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
14238        );
14239    }
14240
14241    #[test]
14242    fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
14243        // Boundary case: exactly 1ms past the cap (the granularity the
14244        // canonical-form gate enforces). Catches a future "strictly
14245        // less than" half-measure and pins the diagnostic to name the
14246        // offending `Duration` verbatim. Peer of
14247        // `rejects_policy_timeout_one_millisecond_above_cap` on the
14248        // sibling duration-typed `:politicas :timeout` top edge.
14249        let mut s = three_member_spec();
14250        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
14251        s.politicas.circuit_breaker = Some(CircuitBreaker {
14252            max_failures: 5,
14253            window,
14254        });
14255        assert_eq!(
14256            s.validate().unwrap_err(),
14257            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
14258        );
14259    }
14260
14261    #[test]
14262    fn rejects_circuit_breaker_window_far_above_cap() {
14263        // The "obvious authoring footgun" case: a `(:window "24h")` or
14264        // `(:window "86400s")` — values the canonical-form arm
14265        // accepts as integer-millisecond magnitudes, the codec
14266        // round-trips losslessly through serde, but the
14267        // rolling-window breaker contract cannot honor (a 24-hour
14268        // rolling failure window is operationally a lifetime counter).
14269        // Until this gate landed validate accepted it. Pin both common
14270        // above-cap values (24h, 7d) so a future relaxation that
14271        // drops the upper bound surfaces here.
14272        for window in [
14273            Duration::from_secs(86_400),    // 24h
14274            Duration::from_secs(604_800),   // 7d
14275            Duration::from_secs(1_000_000), // ~11.5 days
14276        ] {
14277            let mut s = three_member_spec();
14278            s.politicas.circuit_breaker = Some(CircuitBreaker {
14279                max_failures: 5,
14280                window,
14281            });
14282            assert_eq!(
14283                s.validate().unwrap_err(),
14284                AplicacaoError::PolicyBreakerWindowExceedsCap { window }
14285            );
14286        }
14287    }
14288
14289    #[test]
14290    fn accepts_circuit_breaker_window_at_cap() {
14291        // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
14292        // (1h) — must validate. The cap is inclusive on the top edge,
14293        // matching the [`POLICY_TIMEOUT_MAX`] /
14294        // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
14295        // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
14296        // sibling capped axes. Pin the boundary explicitly so a
14297        // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
14298        // instead of `>`) surfaces here as a test failure rather than
14299        // a silent contract narrowing.
14300        let mut s = three_member_spec();
14301        s.politicas.circuit_breaker = Some(CircuitBreaker {
14302            max_failures: 5,
14303            window: POLICY_BREAKER_WINDOW_MAX,
14304        });
14305        s.validate()
14306            .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
14307    }
14308
14309    #[test]
14310    fn accepts_circuit_breaker_window_typical_values() {
14311        // The documented production-playbook band positive-control
14312        // sweep — every value Hystrix / resilience4j / Istio / Envoy
14313        // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
14314        // through the long-tail failure-detection band (15m, 30m, 1h)
14315        // the cap accepts. Pin the inclusive validated set explicitly
14316        // so a future tightening of the ceiling surfaces here as a
14317        // deliberate test edit, not a silent contract narrowing.
14318        for window in [
14319            Duration::from_millis(1),
14320            Duration::from_millis(500),
14321            Duration::from_secs(1),
14322            Duration::from_secs(10), // Hystrix / Istio / Envoy default
14323            Duration::from_secs(30),
14324            Duration::from_secs(60),  // resilience4j typical
14325            Duration::from_secs(300), // AWS App Mesh typical
14326            Duration::from_secs(900),
14327            Duration::from_secs(1800),
14328            Duration::from_secs(3600), // exactly 1h, the cap
14329        ] {
14330            let mut s = three_member_spec();
14331            s.politicas.circuit_breaker = Some(CircuitBreaker {
14332                max_failures: 5,
14333                window,
14334            });
14335            s.validate()
14336                .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
14337        }
14338    }
14339
14340    #[test]
14341    fn circuit_breaker_zero_window_takes_precedence_over_cap() {
14342        // The cross-arm ordering pin: `Duration::ZERO` is structurally
14343        // outside both `>= 1ms` (zero-floor) and
14344        // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
14345        // diagnostic is the more self-locating one (it directly names
14346        // the omit-axis remediation), so the validate gate must fire
14347        // on zero first. Same shape every other zero-then-cap
14348        // ordering on this surface uses
14349        // ([`AplicacaoError::PolicyTimeoutZero`] then
14350        // [`AplicacaoError::PolicyTimeoutExceedsCap`];
14351        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
14352        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
14353        let mut s = three_member_spec();
14354        s.politicas.circuit_breaker = Some(CircuitBreaker {
14355            max_failures: 5,
14356            window: Duration::ZERO,
14357        });
14358        assert_eq!(
14359            s.validate().unwrap_err(),
14360            AplicacaoError::PolicyBreakerZeroWindow,
14361            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
14362        );
14363    }
14364
14365    #[test]
14366    fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
14367        // The cross-arm ordering pin: a `Duration` that is *both*
14368        // sub-millisecond (non-canonical-form) and structurally above
14369        // the cap surfaces the canonical-form diagnostic first,
14370        // because the round-trip-shape break is the more fundamental
14371        // issue (the value can't even round-trip through the codec, so
14372        // the cap diagnostic naming `1ms..=1h` would be misleading —
14373        // there's no integer-ms form of the offending value). Pin the
14374        // order so a future refactor that reorders the arms surfaces
14375        // here as a test failure rather than a silent diagnostic
14376        // regression. Peer of
14377        // `policy_timeout_canonical_takes_precedence_over_cap` on the
14378        // sibling duration-typed `:politicas :timeout` axis.
14379        let mut s = three_member_spec();
14380        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
14381        s.politicas.circuit_breaker = Some(CircuitBreaker {
14382            max_failures: 5,
14383            window,
14384        });
14385        assert_eq!(
14386            s.validate().unwrap_err(),
14387            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
14388            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
14389        );
14390    }
14391
14392    #[test]
14393    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
14394        // The cross-arm ordering pin between the two breaker axes: a
14395        // `CircuitBreaker` whose *both* `max_failures` is above its
14396        // cap *and* `window` is above its cap surfaces the
14397        // max-failures cap diagnostic first, because the validate
14398        // gate visits the failures arm before the window arm. Pin the
14399        // order so a future refactor that reorders the breaker arms
14400        // surfaces here.
14401        let mut s = three_member_spec();
14402        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
14403        s.politicas.circuit_breaker = Some(CircuitBreaker {
14404            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
14405            window,
14406        });
14407        assert_eq!(
14408            s.validate().unwrap_err(),
14409            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
14410                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
14411            },
14412            "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
14413        );
14414    }
14415
14416    #[test]
14417    fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
14418        // The diagnostic-shape pin: the offending `Duration` is
14419        // carried verbatim into the
14420        // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
14421        // the surfaced error message names the value the author wrote
14422        // (`":politicas :circuit-breaker :window (Duration { secs:
14423        // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
14424        // just the cap. Same self-locating diagnostic shape every
14425        // other typed-cap arm on this surface carries
14426        // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
14427        // offending `Duration` verbatim).
14428        let mut s = three_member_spec();
14429        let window = Duration::from_secs(7200); // 2h
14430        s.politicas.circuit_breaker = Some(CircuitBreaker {
14431            max_failures: 5,
14432            window,
14433        });
14434        let err = s.validate().unwrap_err();
14435        assert!(
14436            matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
14437            "got {err:?}"
14438        );
14439        let msg = err.to_string();
14440        assert!(
14441            msg.contains("7200"),
14442            ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
14443        );
14444    }
14445
14446    #[test]
14447    fn circuit_breaker_window_cap_pins_canonical_value() {
14448        // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
14449        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
14450        // shared duration codec emits as a clean canonical string
14451        // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
14452        // the sibling duration-typed `:politicas :timeout` axis (the
14453        // two duration-typed `:politicas` axes share a uniform top
14454        // edge). Pinning the literal value here surfaces a future
14455        // drift (a relaxation to 24h, a tightening to 5m) as a
14456        // deliberate test edit, not a silent contract narrowing. Same
14457        // shape every other typed-cap value pin on this surface uses
14458        // (`policy_timeout_cap_pins_canonical_value`).
14459        assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
14460        assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
14461        assert_eq!(
14462            POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
14463            "the two duration-typed `:politicas` caps share the same top edge"
14464        );
14465    }
14466
14467    #[test]
14468    fn circuit_breaker_window_cap_value_round_trips_through_codec() {
14469        // The codec round-trip property the cap arm preserves: the
14470        // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
14471        // through the shared duration codec — every value at the cap
14472        // renders to a clean canonical string (`"1h"`) and parses back
14473        // to the same `Duration`. Pin this so a future drift between
14474        // the cap constant and the codec's largest emitted unit
14475        // surfaces here. Same shape every other typed boundary pin on
14476        // this surface uses
14477        // (`policy_timeout_cap_value_round_trips_through_codec`).
14478        let policy = MeshPolicy {
14479            circuit_breaker: Some(CircuitBreaker {
14480                max_failures: 5,
14481                window: POLICY_BREAKER_WINDOW_MAX,
14482            }),
14483            ..Default::default()
14484        };
14485        let json = serde_json::to_string(&policy).unwrap();
14486        // The codec emits `"1h"` for the canonical 1-hour magnitude.
14487        assert!(
14488            json.contains("\"1h\""),
14489            "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
14490        );
14491        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
14492        assert_eq!(
14493            back.circuit_breaker.unwrap().window,
14494            POLICY_BREAKER_WINDOW_MAX
14495        );
14496    }
14497
14498    #[test]
14499    fn is_integer_millisecond_duration_predicate_tracks_codec() {
14500        // Pin the predicate's accepted set against the codec's
14501        // accepted set explicitly. The codec parses
14502        // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
14503        // accepted value is an integer-millisecond multiple — so the
14504        // predicate must accept exactly that set. Same shape every
14505        // other predicate-on-the-typed-slot helper carries
14506        // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
14507        // Read directly from the codec-owned predicate — the crate's
14508        // single source of truth every typed-`Duration` axis now routes
14509        // through via
14510        // [`crate::render::require_positive_canonical_bounded_duration`].
14511        use super::supervisor::duration_codec::is_integer_millisecond_duration;
14512        assert!(is_integer_millisecond_duration(Duration::ZERO));
14513        assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
14514        assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
14515        assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
14516        assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
14517        assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
14518        // Non-integer-millisecond residue: rejected.
14519        assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
14520        assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
14521        assert!(!is_integer_millisecond_duration(Duration::from_micros(
14522            1500
14523        )));
14524        assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
14525        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
14526            999_999
14527        )));
14528        // The 1-ns-past-1ms boundary: rejected (no longer a clean
14529        // integer-millisecond multiple).
14530        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
14531            1_000_001
14532        )));
14533    }
14534
14535    #[test]
14536    fn policy_timeout_validated_value_round_trips_through_codec() {
14537        // The structural property the canonical-ms gate enforces:
14538        // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
14539        // round-trips losslessly through the shared `duration_codec`
14540        // (serialize → string → deserialize → equal value). Pin this
14541        // end-to-end so a future change to either side (the validate
14542        // gate's accepted granularity, the codec's parse/render unit
14543        // set) that breaks the alignment surfaces here. The
14544        // previous-state shape (typed slot accepts arbitrary
14545        // `Duration`, codec only round-trips integer-ms) would fail
14546        // this test for any `Duration::from_micros(1500)` timeout —
14547        // the validate gate now forecloses that.
14548        for timeout in [
14549            Duration::from_millis(1),
14550            Duration::from_millis(1500),
14551            Duration::from_secs(30),
14552            Duration::from_secs(3600),
14553        ] {
14554            let mut s = three_member_spec();
14555            s.politicas.timeout = Some(timeout);
14556            s.validate().unwrap();
14557            let json = serde_json::to_string(&s.politicas).unwrap();
14558            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
14559            assert_eq!(
14560                back.timeout, s.politicas.timeout,
14561                "every validated :timeout must round-trip losslessly through the codec"
14562            );
14563        }
14564    }
14565
14566    #[test]
14567    fn circuit_breaker_window_validated_value_round_trips_through_codec() {
14568        // Peer of the `:timeout` round-trip property on the breaker
14569        // axis.
14570        for window in [
14571            Duration::from_millis(1),
14572            Duration::from_millis(1500),
14573            Duration::from_secs(30),
14574            Duration::from_secs(3600),
14575        ] {
14576            let mut s = three_member_spec();
14577            s.politicas.circuit_breaker = Some(CircuitBreaker {
14578                max_failures: 5,
14579                window,
14580            });
14581            s.validate().unwrap();
14582            let json = serde_json::to_string(&s.politicas).unwrap();
14583            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
14584            assert_eq!(
14585                back.circuit_breaker.unwrap().window,
14586                window,
14587                "every validated :circuit-breaker :window must round-trip losslessly"
14588            );
14589        }
14590    }
14591
14592    #[test]
14593    fn empty_politicas_validates() {
14594        // Omitting every policy axis is fine — defaults express "no
14595        // policy on this axis", not "policy = 0". The fixture's typical
14596        // values continue to validate; this test pins that
14597        // MeshPolicy::default() is a clean pass through validate().
14598        let mut s = three_member_spec();
14599        s.politicas = MeshPolicy::default();
14600        s.validate().unwrap();
14601    }
14602
14603    #[test]
14604    fn typical_politicas_validates_with_every_axis_set() {
14605        // The full §III.1 example block (timeout + retries + breaker +
14606        // mtls + rate-limit) — every axis nonzero — must remain a
14607        // clean pass.
14608        let mut s = three_member_spec();
14609        s.politicas = MeshPolicy {
14610            timeout: Some(Duration::from_secs(30)),
14611            retries: Some(3),
14612            circuit_breaker: Some(CircuitBreaker {
14613                max_failures: 5,
14614                window: Duration::from_secs(60),
14615            }),
14616            mtls_required: Some(true),
14617            rate_limit: Some(RateLimit {
14618                rate: 100,
14619                window: Duration::from_secs(1),
14620            }),
14621        };
14622        s.validate().unwrap();
14623    }
14624
14625    #[test]
14626    fn rejects_empty_cluster_name() {
14627        let mut s = three_member_spec();
14628        s.placement.clusters = vec!["rio".into(), "".into()];
14629        assert_eq!(
14630            s.validate().unwrap_err(),
14631            AplicacaoError::PlacementClusterEmpty
14632        );
14633    }
14634
14635    #[test]
14636    fn rejects_duplicate_cluster_names() {
14637        let mut s = three_member_spec();
14638        s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
14639        let err = s.validate().unwrap_err();
14640        assert!(
14641            matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
14642            "got {err:?}"
14643        );
14644    }
14645
14646    #[test]
14647    fn rejects_placement_cluster_with_uppercase() {
14648        // The canonical "I copied the cluster's display name verbatim"
14649        // typo — K8s context names are lowercase per DNS-1123 label
14650        // rule, but org docs often round-trip a TitleCase identifier
14651        // (`Rio`, `Mar-East`) from an ADR. Mirrors the
14652        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
14653        // on the peer name axis.
14654        let mut s = three_member_spec();
14655        s.placement.clusters = vec!["Rio".into(), "mar".into()];
14656        let err = s.validate().unwrap_err();
14657        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
14658            panic!("expected PlacementClusterInvalid, got other variant");
14659        };
14660        assert_eq!(cluster, "Rio");
14661        assert!(
14662            reason.contains("uppercase"),
14663            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
14664        );
14665        assert!(
14666            reason.contains("\"rio\""),
14667            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
14668        );
14669    }
14670
14671    #[test]
14672    fn rejects_placement_cluster_with_underscore() {
14673        // The canonical "I'm thinking of an env var / hostname slug"
14674        // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
14675        // schema. K8s context filtering on `my_cluster` silently misses
14676        // the cluster the author intended; the gate moves it to caixa-
14677        // build time. Same shape as `rejects_membro_caixa_with_underscore`
14678        // (3f9d7a0).
14679        let mut s = three_member_spec();
14680        s.placement.clusters = vec!["my_cluster".into()];
14681        let err = s.validate().unwrap_err();
14682        assert!(
14683            matches!(
14684                err,
14685                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
14686                    if cluster == "my_cluster" && reason.contains('_')
14687            ),
14688            "got {err:?}"
14689        );
14690    }
14691
14692    #[test]
14693    fn rejects_placement_cluster_with_dot() {
14694        // A `:placement :clusters` entry is a single DNS-1123 *label*,
14695        // not a subdomain — even though K8s context names sometimes
14696        // carry a dotted form via kubeconfig conventions, the strictest
14697        // floor among the use sites (DNS-1035 cluster.x-k8s.io
14698        // `metadata.name`, Cilium identity label values) wins. The "I
14699        // want to namespace my cluster names with `.`" intent is
14700        // expressed via `-` (`mar-east`).
14701        let mut s = three_member_spec();
14702        s.placement.clusters = vec!["team.rio".into()];
14703        let err = s.validate().unwrap_err();
14704        assert!(
14705            matches!(
14706                err,
14707                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
14708                    if cluster == "team.rio" && reason.contains('.')
14709            ),
14710            "got {err:?}"
14711        );
14712    }
14713
14714    #[test]
14715    fn rejects_placement_cluster_with_leading_hyphen() {
14716        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
14717        // with an alphanumeric. The K8s apiserver rejects `-rio`
14718        // outright; the rendered fan-out would emit a `metadata.name:
14719        // "-rio"` that fails admission far from the source caixa.lisp.
14720        let mut s = three_member_spec();
14721        s.placement.clusters = vec!["-rio".into()];
14722        let err = s.validate().unwrap_err();
14723        assert!(
14724            matches!(
14725                err,
14726                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
14727                    if cluster == "-rio" && reason.contains("start and end")
14728            ),
14729            "got {err:?}"
14730        );
14731    }
14732
14733    #[test]
14734    fn rejects_placement_cluster_with_trailing_hyphen() {
14735        // The symmetric arm of the boundary rule. Pin separately so
14736        // both ends are covered against a future relaxation that only
14737        // checks one boundary (parallel to
14738        // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
14739        let mut s = three_member_spec();
14740        s.placement.clusters = vec!["rio-".into()];
14741        let err = s.validate().unwrap_err();
14742        assert!(
14743            matches!(
14744                err,
14745                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
14746                    if cluster == "rio-"
14747            ),
14748            "got {err:?}"
14749        );
14750    }
14751
14752    #[test]
14753    fn rejects_placement_cluster_with_unicode() {
14754        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
14755        // before it reaches K8s. The byte-by-byte ASCII validity check
14756        // rejects multi-byte UTF-8 sequences by the first byte that
14757        // fails `[a-z0-9-]`.
14758        let mut s = three_member_spec();
14759        s.placement.clusters = vec!["rió".into()];
14760        let err = s.validate().unwrap_err();
14761        assert!(
14762            matches!(
14763                err,
14764                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
14765                    if cluster == "rió"
14766            ),
14767            "got {err:?}"
14768        );
14769    }
14770
14771    #[test]
14772    fn rejects_placement_cluster_with_whitespace() {
14773        // Whitespace is the canonical "I pasted from a sketch / doc"
14774        // footgun. The apiserver rejects every cluster `metadata.name`
14775        // value carrying whitespace.
14776        let mut s = three_member_spec();
14777        s.placement.clusters = vec!["rio cluster".into()];
14778        let err = s.validate().unwrap_err();
14779        assert!(
14780            matches!(
14781                err,
14782                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
14783                    if cluster == "rio cluster"
14784            ),
14785            "got {err:?}"
14786        );
14787    }
14788
14789    #[test]
14790    fn rejects_placement_cluster_too_long() {
14791        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
14792        // pin. The diagnostic names both the cap (63) and the actual
14793        // length so the author can shorten in one edit. Mirrors
14794        // `rejects_membro_caixa_too_long` (3f9d7a0).
14795        let mut s = three_member_spec();
14796        let too_long = "a".repeat(64);
14797        s.placement.clusters = vec![too_long.clone()];
14798        let err = s.validate().unwrap_err();
14799        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
14800            panic!("expected PlacementClusterInvalid");
14801        };
14802        assert_eq!(cluster, too_long);
14803        assert!(
14804            reason.contains("63") && reason.contains("64"),
14805            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
14806        );
14807    }
14808
14809    #[test]
14810    fn placement_cluster_max_length_validates() {
14811        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
14812        // future tightening (e.g. dropping to 62) surfaces here as a
14813        // regression, mirroring `membro_caixa_max_length_validates`
14814        // (3f9d7a0).
14815        let mut s = three_member_spec();
14816        s.placement.clusters = vec!["a".repeat(63)];
14817        s.validate().unwrap();
14818    }
14819
14820    #[test]
14821    fn accepts_canonical_placement_cluster_forms() {
14822        // The DNS-1123 label shapes a caixa author is realistically
14823        // going to write for cluster names: single-word lowercase
14824        // (`rio`), regional hyphen-joined (`mar-east`), single
14825        // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
14826        // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
14827        // Pin every leg so a future tightening that bans (e.g.) digit-
14828        // start identifiers surfaces here.
14829        for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
14830            let mut s = three_member_spec();
14831            s.placement.clusters = vec![form.into()];
14832            s.validate().unwrap_or_else(|e| {
14833                panic!("canonical cluster form {form:?} must validate, got {e:?}")
14834            });
14835        }
14836    }
14837
14838    #[test]
14839    fn placement_cluster_empty_takes_precedence_over_invalid() {
14840        // Order pin: the existing `PlacementClusterEmpty` diagnostic
14841        // (which doesn't try to parse) fires before the new
14842        // `PlacementClusterInvalid` parse-side diagnostic, so an empty
14843        // `:clusters` entry keeps its narrower error message — the new
14844        // gate would also reject `""`, but the empty-string arm is the
14845        // more self-locating diagnostic. Mirrors the
14846        // `membro_caixa_empty_takes_precedence_over_invalid` pin
14847        // (3f9d7a0).
14848        let mut s = three_member_spec();
14849        s.placement.clusters = vec!["rio".into(), "".into()];
14850        let err = s.validate().unwrap_err();
14851        assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
14852    }
14853
14854    #[test]
14855    fn placement_cluster_invalid_fires_before_duplicate_check() {
14856        // Order pin: a malformed-shape `:clusters` entry surfaces *its
14857        // own* diagnostic, even when a later entry would otherwise
14858        // collapse onto a duplicate name. The per-entry shape gate runs
14859        // inline before the duplicate-key insert, parallel to
14860        // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
14861        let mut s = three_member_spec();
14862        s.placement.clusters = vec!["Rio".into(), "rio".into()];
14863        let err = s.validate().unwrap_err();
14864        assert!(
14865            matches!(
14866                err,
14867                AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
14868            ),
14869            "got {err:?}"
14870        );
14871    }
14872
14873    #[test]
14874    fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
14875        // The diagnostic-shape pin: the error names the offending
14876        // `:clusters` value verbatim so the author can grep their
14877        // caixa.lisp without re-running the build, and carries a
14878        // non-empty `reason` naming the specific violation. Same shape
14879        // every typed-shape gate enshrines
14880        // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
14881        // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
14882        let mut s = three_member_spec();
14883        s.placement.clusters = vec!["BAD_CLUSTER".into()];
14884        let err = s.validate().unwrap_err();
14885        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
14886            panic!("expected PlacementClusterInvalid");
14887        };
14888        assert_eq!(cluster, "BAD_CLUSTER");
14889        assert!(
14890            !reason.is_empty(),
14891            "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
14892        );
14893    }
14894
14895    #[test]
14896    fn rejects_sharded_with_empty_clusters() {
14897        // §III.1: Sharded uses :clusters as the shard pool. An empty
14898        // pool means "shard across no clusters" — meaningless, same as
14899        // Replicated with no hosts.
14900        let mut s = three_member_spec();
14901        s.placement.estrategia = PlacementStrategy::Sharded;
14902        s.placement.shard_key = Some("$tenantId".into());
14903        s.placement.clusters = vec![];
14904        assert!(matches!(
14905            s.validate().unwrap_err(),
14906            AplicacaoError::PlacementWithoutClusters {
14907                estrategia: PlacementStrategy::Sharded
14908            }
14909        ));
14910    }
14911
14912    #[test]
14913    fn rejects_sharded_with_empty_shard_key() {
14914        let mut s = three_member_spec();
14915        s.placement.estrategia = PlacementStrategy::Sharded;
14916        s.placement.shard_key = Some("".into());
14917        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
14918    }
14919
14920    #[test]
14921    fn rejects_shard_key_under_replicated_strategy() {
14922        // The fail-before-pass-after pin: a `:placement (:estrategia
14923        // Replicated :shard-key "tenantId")` manifest carries the
14924        // hash-keyed-distribution slot on a strategy that never consumes
14925        // it. Before the gate the typed slot's value silently vanished
14926        // at the renderer layer (caixa-mesh emits `placement.shardKey`
14927        // verbatim regardless of strategy; the Akka-style cluster-
14928        // sharding reconciler keys off `estrategia == Sharded` and
14929        // ignores the slot otherwise), with no diagnostic. Lifting the
14930        // rejection to a build-time gate makes the
14931        // `shard_key.is_some() == matches!(estrategia, Sharded)`
14932        // partition a structural property of every validated
14933        // [`Placement`].
14934        let mut s = three_member_spec();
14935        // The fixture already uses Replicated; just add a shard-key.
14936        s.placement.shard_key = Some("$tenantId".into());
14937        let err = s.validate().unwrap_err();
14938        let AplicacaoError::ShardKeyOnNonSharded {
14939            estrategia,
14940            shard_key,
14941        } = err
14942        else {
14943            panic!("expected ShardKeyOnNonSharded, got {err:?}");
14944        };
14945        assert_eq!(estrategia, PlacementStrategy::Replicated);
14946        assert_eq!(shard_key, "$tenantId");
14947    }
14948
14949    #[test]
14950    fn rejects_shard_key_under_singlenode_strategy() {
14951        // Peer of the Replicated case above on the SingleNode arm: OTP
14952        // distributed-app takeover (one cluster runs at a time) has no
14953        // hash-keyed routing axis to consume `:shard-key` either, so
14954        // the rejection fires on both non-Sharded arms uniformly.
14955        let mut s = three_member_spec();
14956        s.placement.estrategia = PlacementStrategy::SingleNode;
14957        s.placement.shard_key = Some("$tenantId".into());
14958        let err = s.validate().unwrap_err();
14959        let AplicacaoError::ShardKeyOnNonSharded {
14960            estrategia,
14961            shard_key,
14962        } = err
14963        else {
14964            panic!("expected ShardKeyOnNonSharded, got {err:?}");
14965        };
14966        assert_eq!(estrategia, PlacementStrategy::SingleNode);
14967        assert_eq!(shard_key, "$tenantId");
14968    }
14969
14970    #[test]
14971    fn rejects_empty_shard_key_under_replicated_strategy() {
14972        // The `Some("")` case under non-Sharded is rejected by
14973        // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
14974        // fires before the empty-value gate), not
14975        // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
14976        // the `Sharded` arm). Pin the partition so a future reorder of
14977        // the validate_placement match arms doesn't silently swap which
14978        // diagnostic the author sees — both are author errors, but
14979        // ShardKeyOnNonSharded names which strategy is the actual fix
14980        // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
14981        // only says "pick a non-empty key".
14982        let mut s = three_member_spec();
14983        s.placement.shard_key = Some(String::new());
14984        let err = s.validate().unwrap_err();
14985        assert!(
14986            matches!(
14987                err,
14988                AplicacaoError::ShardKeyOnNonSharded {
14989                    estrategia: PlacementStrategy::Replicated,
14990                    ref shard_key,
14991                } if shard_key.is_empty()
14992            ),
14993            "got {err:?}"
14994        );
14995    }
14996
14997    #[test]
14998    fn replicated_without_shard_key_validates() {
14999        // The complement of the rejection: `:placement :estrategia
15000        // Replicated` with `:shard-key None` is the canonical happy
15001        // path on every existing fixture. Pin the no-shard-key case so
15002        // the new gate doesn't accidentally fire on `None`.
15003        let mut s = three_member_spec();
15004        assert!(matches!(
15005            s.placement.estrategia,
15006            PlacementStrategy::Replicated
15007        ));
15008        s.placement.shard_key = None;
15009        s.validate().unwrap();
15010    }
15011
15012    #[test]
15013    fn singlenode_without_shard_key_validates() {
15014        // Peer of the Replicated no-shard-key case on the SingleNode
15015        // arm — both non-Sharded strategies must validate cleanly when
15016        // the slot is omitted.
15017        let mut s = three_member_spec();
15018        s.placement.estrategia = PlacementStrategy::SingleNode;
15019        s.placement.shard_key = None;
15020        s.validate().unwrap();
15021    }
15022
15023    fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
15024        // Fixture builder for the `:placement :shard-key` shape gate
15025        // tests: a three-member Aplicacao on the `Sharded` strategy
15026        // with the supplied `:shard-key` slot. Co-locates the
15027        // arm-construction so every test below carries one line of
15028        // setup (the offending `:shard-key` value) and the assertion.
15029        let mut s = three_member_spec();
15030        s.placement.estrategia = PlacementStrategy::Sharded;
15031        s.placement.shard_key = Some(key.into());
15032        s
15033    }
15034
15035    #[test]
15036    fn rejects_shard_key_with_embedded_space() {
15037        // The canonical paste-from-aligned-doc footgun:
15038        // `:shard-key "$tenant Id"` — the Akka-style entity-id
15039        // extractor reads the slot as a single-token reference, and an
15040        // embedded space breaks the token boundary at the runtime
15041        // hash-extractor pass with no diagnostic naming the offending
15042        // entry.
15043        let s = sharded_spec_with_key("$tenant Id");
15044        let err = s.validate().unwrap_err();
15045        assert!(
15046            matches!(
15047                err,
15048                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
15049                    if shard_key == "$tenant Id" && reason.contains("space")
15050            ),
15051            "got {err:?}"
15052        );
15053    }
15054
15055    #[test]
15056    fn rejects_shard_key_with_leading_space() {
15057        // Leading-space arm of the embedded-whitespace footgun — the
15058        // paste-from-aligned-doc / paste-from-CSV-cell variant where
15059        // the leading column-padding leaked into the slot.
15060        let s = sharded_spec_with_key(" $tenantId");
15061        let err = s.validate().unwrap_err();
15062        assert!(
15063            matches!(
15064                err,
15065                AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
15066                    if shard_key == " $tenantId"
15067            ),
15068            "got {err:?}"
15069        );
15070    }
15071
15072    #[test]
15073    fn rejects_shard_key_with_trailing_newline() {
15074        // The canonical paste-from-shell-heredoc footgun — every
15075        // `<<EOF` heredoc terminator paste leaves a trailing newline
15076        // the YAML emitter then folds away inconsistently across
15077        // emitter implementations.
15078        let s = sharded_spec_with_key("$tenantId\n");
15079        let err = s.validate().unwrap_err();
15080        assert!(
15081            matches!(
15082                err,
15083                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
15084                    if shard_key == "$tenantId\n" && reason.contains("0x0a")
15085            ),
15086            "got {err:?}"
15087        );
15088    }
15089
15090    #[test]
15091    fn rejects_shard_key_with_embedded_tab() {
15092        // The paste-from-aligned-doc tab-stop variant — tabs land
15093        // alongside spaces in copy-paste from formatted columns.
15094        let s = sharded_spec_with_key("$tenant\tId");
15095        let err = s.validate().unwrap_err();
15096        assert!(
15097            matches!(
15098                err,
15099                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
15100                    if shard_key == "$tenant\tId" && reason.contains("tab")
15101            ),
15102            "got {err:?}"
15103        );
15104    }
15105
15106    #[test]
15107    fn rejects_shard_key_with_control_character() {
15108        // The paste-from-binary / paste-from-screen-cleared-terminal
15109        // footgun — an embedded `\x01` (SOH) byte that some YAML
15110        // emitters silently strip and others escape as ``,
15111        // breaking round-trip across emitter implementations.
15112        let s = sharded_spec_with_key("$tenant\u{0001}Id");
15113        let err = s.validate().unwrap_err();
15114        assert!(
15115            matches!(
15116                err,
15117                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
15118                    if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
15119            ),
15120            "got {err:?}"
15121        );
15122    }
15123
15124    #[test]
15125    fn rejects_shard_key_with_non_ascii() {
15126        // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
15127        // footgun — non-ASCII bytes normalize differently between the
15128        // caixa-mesh-side YAML emitter and the in-cluster reconciler's
15129        // YAML parser, the same entity ID can silently map to two
15130        // distinct shards on a re-render.
15131        let s = sharded_spec_with_key("$tenàntId");
15132        let err = s.validate().unwrap_err();
15133        assert!(
15134            matches!(
15135                err,
15136                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
15137                    if shard_key == "$tenàntId" && reason.contains("non-ASCII")
15138            ),
15139            "got {err:?}"
15140        );
15141    }
15142
15143    #[test]
15144    fn rejects_shard_key_too_long() {
15145        // Length cap pin: 64 bytes — one byte over the
15146        // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
15147        // here is a paste-from-doc multi-line blob landing in
15148        // `:shard-key` instead of a single-token extractor expression.
15149        let too_long = "a".repeat(64);
15150        let s = sharded_spec_with_key(&too_long);
15151        let err = s.validate().unwrap_err();
15152        let AplicacaoError::ShardKeyInvalid {
15153            ref shard_key,
15154            ref reason,
15155        } = err
15156        else {
15157            panic!("expected ShardKeyInvalid, got {err:?}");
15158        };
15159        assert_eq!(shard_key, &too_long);
15160        assert!(
15161            reason.contains("63") && reason.contains("64"),
15162            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
15163        );
15164    }
15165
15166    #[test]
15167    fn shard_key_max_length_validates() {
15168        // Boundary pin: 63 bytes exactly — the
15169        // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
15170        // dropping to 62) surfaces here as a regression, mirroring
15171        // `placement_cluster_max_length_validates` /
15172        // `placement_affinity_max_length_validates` on the peer
15173        // identifier-shaped slots.
15174        let s = sharded_spec_with_key(&"a".repeat(63));
15175        s.validate().unwrap();
15176    }
15177
15178    #[test]
15179    fn accepts_canonical_shard_key_forms() {
15180        // The Akka-style entity-id extractor shapes a caixa author is
15181        // realistically going to write — pin every leg so a future
15182        // tightening that bans (e.g.) the `${...}` interpolation
15183        // variant or the `metadata.<field>` JSONPath form surfaces
15184        // here as a regression. The canonical forms span:
15185        //
15186        //   - bare property name (`tenantId`, `customerId`)
15187        //   - Akka `ExtractEntityId` placeholder (`$tenantId`)
15188        //   - JSONPath-style nested reference (`metadata.tenantId`,
15189        //     `$.user.id`)
15190        //   - interpolation-style template (`${tenant}`)
15191        //   - snake_case property name (`customer_id`)
15192        //   - kebab-case property name (`customer-id` — accepted
15193        //     because the slot is a printable-ASCII single-token
15194        //     reference, not a DNS-1123 label like
15195        //     `:placement :affinity` / `:clusters`)
15196        //   - single character (`a`, `$` — boundary)
15197        for form in [
15198            "tenantId",
15199            "customerId",
15200            "$tenantId",
15201            "metadata.tenantId",
15202            "$.user.id",
15203            "${tenant}",
15204            "customer_id",
15205            "customer-id",
15206            "a",
15207            "$",
15208        ] {
15209            let s = sharded_spec_with_key(form);
15210            s.validate().unwrap_or_else(|e| {
15211                panic!("canonical shard-key form {form:?} must validate, got {e:?}")
15212            });
15213        }
15214    }
15215
15216    #[test]
15217    fn shard_key_empty_takes_precedence_over_invalid() {
15218        // Order pin: the existing `ShardedKeyEmpty` diagnostic
15219        // (reserved for the `Sharded` `Some("")` arm) fires before the
15220        // new `ShardKeyInvalid` parse-side diagnostic, so an empty
15221        // `:shard-key` keeps its narrower error message — the new gate
15222        // would also reject `""` defensively, but the empty-string arm
15223        // is the more self-locating diagnostic. Mirrors the
15224        // `placement_cluster_empty_takes_precedence_over_invalid` pin
15225        // on the peer identifier-shaped slot.
15226        let s = sharded_spec_with_key("");
15227        let err = s.validate().unwrap_err();
15228        assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
15229    }
15230
15231    #[test]
15232    fn shard_key_invalid_diagnostic_carries_offending_value() {
15233        // The diagnostic-shape pin: the error names the offending
15234        // `:shard-key` value verbatim so the author can grep their
15235        // caixa.lisp without re-running the build, and carries a
15236        // parser-shaped `reason:` naming the specific violation —
15237        // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
15238        // on the peer identifier-shaped slot.
15239        let s = sharded_spec_with_key("$tenant Id");
15240        let err = s.validate().unwrap_err();
15241        let AplicacaoError::ShardKeyInvalid {
15242            ref shard_key,
15243            ref reason,
15244        } = err
15245        else {
15246            panic!("expected ShardKeyInvalid, got {err:?}");
15247        };
15248        assert_eq!(shard_key, "$tenant Id");
15249        assert!(
15250            !reason.is_empty(),
15251            "reason must name the specific violation, got empty string"
15252        );
15253    }
15254
15255    #[test]
15256    fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
15257        // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
15258        // `:shard-key` carried on non-Sharded strategies) fires before
15259        // the shape gate, so a malformed `:shard-key` carried on (e.g.)
15260        // a `Replicated` strategy surfaces the more self-locating
15261        // strategy-mismatch diagnostic (naming the actual fix — drop
15262        // the slot, or switch to Sharded) rather than the shape
15263        // diagnostic. The strategy-mismatch arm is the more actionable
15264        // diagnostic: a malformed shard-key on Replicated is "you
15265        // shouldn't have a :shard-key here at all", not "your
15266        // :shard-key value is malformed".
15267        let mut s = three_member_spec();
15268        // Replicated is the default fixture strategy.
15269        s.placement.shard_key = Some("$tenant Id".into());
15270        let err = s.validate().unwrap_err();
15271        assert!(
15272            matches!(
15273                err,
15274                AplicacaoError::ShardKeyOnNonSharded {
15275                    estrategia: PlacementStrategy::Replicated,
15276                    ..
15277                }
15278            ),
15279            "got {err:?}"
15280        );
15281    }
15282
15283    #[test]
15284    fn rejects_empty_affinity_hint() {
15285        let mut s = three_member_spec();
15286        s.placement.affinity = Some("".into());
15287        assert_eq!(
15288            s.validate().unwrap_err(),
15289            AplicacaoError::PlacementAffinityEmpty
15290        );
15291    }
15292
15293    #[test]
15294    fn placement_without_affinity_validates() {
15295        // Omitting :affinity is fine — the placement engine falls back
15296        // to the default heuristic. Pin the no-hint case so the
15297        // affinity-empty rejection doesn't accidentally fire on `None`.
15298        let mut s = three_member_spec();
15299        s.placement.affinity = None;
15300        s.validate().unwrap();
15301    }
15302
15303    #[test]
15304    fn rejects_placement_affinity_with_uppercase() {
15305        // The canonical "I copied the ADR's display name verbatim" typo
15306        // — placement hints land verbatim in K8s label-selector
15307        // territory, where the apiserver enforces the DNS-1123 label
15308        // rule (lowercase-only) on every identity-keyed admission axis.
15309        // Mirrors `rejects_placement_cluster_with_uppercase` on the
15310        // sibling slot.
15311        let mut s = three_member_spec();
15312        s.placement.affinity = Some("DataLocality".into());
15313        let err = s.validate().unwrap_err();
15314        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
15315            panic!("expected PlacementAffinityInvalid, got other variant");
15316        };
15317        assert_eq!(affinity, "DataLocality");
15318        assert!(
15319            reason.contains("uppercase"),
15320            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
15321        );
15322        assert!(
15323            reason.contains("\"datalocality\""),
15324            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
15325        );
15326    }
15327
15328    #[test]
15329    fn rejects_placement_affinity_with_underscore() {
15330        // The canonical "I'm thinking of an env var / Python identifier"
15331        // leak — `_` is forbidden by every DNS-1123 label schema. Same
15332        // shape as `rejects_placement_cluster_with_underscore` on the
15333        // sibling slot.
15334        let mut s = three_member_spec();
15335        s.placement.affinity = Some("data_locality".into());
15336        let err = s.validate().unwrap_err();
15337        assert!(
15338            matches!(
15339                err,
15340                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
15341                    if affinity == "data_locality" && reason.contains('_')
15342            ),
15343            "got {err:?}"
15344        );
15345    }
15346
15347    #[test]
15348    fn rejects_placement_affinity_with_dot() {
15349        // A `:placement :affinity` value is a single DNS-1123 *label*
15350        // (it lands as a K8s label value selector key), not a subdomain.
15351        // The "I want to namespace my hint with `.`" intent is expressed
15352        // via `-` (`data-locality-east`).
15353        let mut s = three_member_spec();
15354        s.placement.affinity = Some("data.locality".into());
15355        let err = s.validate().unwrap_err();
15356        assert!(
15357            matches!(
15358                err,
15359                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
15360                    if affinity == "data.locality" && reason.contains('.')
15361            ),
15362            "got {err:?}"
15363        );
15364    }
15365
15366    #[test]
15367    fn rejects_placement_affinity_with_unicode() {
15368        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
15369        // before it reaches K8s. The byte-by-byte ASCII validity check
15370        // rejects multi-byte UTF-8 sequences by the first byte that
15371        // fails `[a-z0-9-]`.
15372        let mut s = three_member_spec();
15373        s.placement.affinity = Some("data-localité".into());
15374        let err = s.validate().unwrap_err();
15375        assert!(
15376            matches!(
15377                err,
15378                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
15379                    if affinity == "data-localité"
15380            ),
15381            "got {err:?}"
15382        );
15383    }
15384
15385    #[test]
15386    fn rejects_placement_affinity_with_leading_hyphen() {
15387        // DNS-1123 boundary rule: labels must start with an
15388        // alphanumeric. Pin separately from the trailing-hyphen arm so
15389        // a future relaxation that only checks one boundary surfaces
15390        // here as a regression (parallel to
15391        // `rejects_placement_cluster_with_leading_hyphen`).
15392        let mut s = three_member_spec();
15393        s.placement.affinity = Some("-data-locality".into());
15394        let err = s.validate().unwrap_err();
15395        assert!(
15396            matches!(
15397                err,
15398                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
15399                    if affinity == "-data-locality" && reason.contains("start and end")
15400            ),
15401            "got {err:?}"
15402        );
15403    }
15404
15405    #[test]
15406    fn rejects_placement_affinity_with_trailing_hyphen() {
15407        // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
15408        // ends are covered against a future relaxation.
15409        let mut s = three_member_spec();
15410        s.placement.affinity = Some("data-locality-".into());
15411        let err = s.validate().unwrap_err();
15412        assert!(
15413            matches!(
15414                err,
15415                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
15416                    if affinity == "data-locality-"
15417            ),
15418            "got {err:?}"
15419        );
15420    }
15421
15422    #[test]
15423    fn rejects_placement_affinity_with_whitespace() {
15424        // Whitespace is the canonical "I pasted from a sketch / doc"
15425        // footgun. The apiserver rejects every label-selector value
15426        // carrying whitespace.
15427        let mut s = three_member_spec();
15428        s.placement.affinity = Some("data locality".into());
15429        let err = s.validate().unwrap_err();
15430        assert!(
15431            matches!(
15432                err,
15433                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
15434                    if affinity == "data locality"
15435            ),
15436            "got {err:?}"
15437        );
15438    }
15439
15440    #[test]
15441    fn rejects_placement_affinity_too_long() {
15442        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
15443        // pin. The diagnostic names both the cap (63) and the actual
15444        // length so the author can shorten in one edit. Mirrors
15445        // `rejects_placement_cluster_too_long`.
15446        let mut s = three_member_spec();
15447        let too_long = "a".repeat(64);
15448        s.placement.affinity = Some(too_long.clone());
15449        let err = s.validate().unwrap_err();
15450        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
15451            panic!("expected PlacementAffinityInvalid");
15452        };
15453        assert_eq!(affinity, too_long);
15454        assert!(
15455            reason.contains("63") && reason.contains("64"),
15456            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
15457        );
15458    }
15459
15460    #[test]
15461    fn placement_affinity_max_length_validates() {
15462        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
15463        // future tightening (e.g. dropping to 62) surfaces here as a
15464        // regression, mirroring `placement_cluster_max_length_validates`.
15465        let mut s = three_member_spec();
15466        s.placement.affinity = Some("a".repeat(63));
15467        s.validate().unwrap();
15468    }
15469
15470    #[test]
15471    fn accepts_canonical_placement_affinity_forms() {
15472        // The DNS-1123 label shapes a caixa author is realistically
15473        // going to write for placement hints: the M3 canonical examples
15474        // (`data-locality`, `low-latency`, `anti-affinity`), the
15475        // single-token form (`affinity`), the single-character boundary
15476        // (`a`), the digit-start (DNS-1123 allows this, unlike
15477        // DNS-1035), and a regional-suffixed form. Pin every leg so a
15478        // future tightening that bans (e.g.) digit-start identifiers
15479        // surfaces here.
15480        for form in [
15481            "data-locality",
15482            "low-latency",
15483            "anti-affinity",
15484            "affinity",
15485            "a",
15486            "3-tier",
15487            "locality-east",
15488        ] {
15489            let mut s = three_member_spec();
15490            s.placement.affinity = Some(form.into());
15491            s.validate().unwrap_or_else(|e| {
15492                panic!("canonical affinity form {form:?} must validate, got {e:?}")
15493            });
15494        }
15495    }
15496
15497    #[test]
15498    fn placement_affinity_empty_takes_precedence_over_invalid() {
15499        // Order pin: the existing `PlacementAffinityEmpty` diagnostic
15500        // (which doesn't try to parse) fires before the new
15501        // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
15502        // `:affinity` keeps its narrower error message — the new gate
15503        // would also reject `""`, but the empty-string arm is the more
15504        // self-locating diagnostic. Mirrors the
15505        // `placement_cluster_empty_takes_precedence_over_invalid` pin.
15506        let mut s = three_member_spec();
15507        s.placement.affinity = Some(String::new());
15508        let err = s.validate().unwrap_err();
15509        assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
15510    }
15511
15512    #[test]
15513    fn placement_affinity_invalid_diagnostic_carries_offending_value() {
15514        // The diagnostic shape pin: every rejection carries the offending
15515        // `affinity:` verbatim plus a parser-shaped `reason:` so the
15516        // author can grep their caixa.lisp for `:affinity "<hint>"` and
15517        // fix it in one edit. Mirrors the
15518        // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
15519        // pin on the sibling slot.
15520        let mut s = three_member_spec();
15521        s.placement.affinity = Some("Data_Locality".into());
15522        let err = s.validate().unwrap_err();
15523        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
15524            panic!("expected PlacementAffinityInvalid");
15525        };
15526        assert_eq!(affinity, "Data_Locality");
15527        assert!(
15528            !reason.is_empty(),
15529            "diagnostic reason must not be empty (got: {reason:?})"
15530        );
15531    }
15532
15533    #[test]
15534    fn singlenode_with_takeover_candidates_validates() {
15535        // OTP distributed-application convention (MESH-COMPOSITION
15536        // §II.1): SingleNode runs on one cluster at a time but the
15537        // :clusters list enumerates the takeover candidates. Multiple
15538        // entries are not a contradiction — they are the failover pool.
15539        let mut s = three_member_spec();
15540        s.placement.estrategia = PlacementStrategy::SingleNode;
15541        s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
15542        s.validate().unwrap();
15543    }
15544
15545    // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
15546
15547    #[test]
15548    fn mesh_policy_default_is_empty() {
15549        // The Default impl carries None on every axis — the typed
15550        // analog of an unset `:politicas (())` slot. Renderers that
15551        // overlay the policy onto a cluster artifact key off this
15552        // predicate to skip the slot entirely; pinning so a future
15553        // axis added to MeshPolicy can't silently break the contract
15554        // (a new field whose Default is non-None would flip is_empty
15555        // to false on every existing caixa, surfacing here).
15556        assert!(MeshPolicy::default().is_empty());
15557    }
15558
15559    #[test]
15560    fn mesh_policy_with_only_timeout_is_not_empty() {
15561        let p = MeshPolicy {
15562            timeout: Some(Duration::from_secs(30)),
15563            ..Default::default()
15564        };
15565        assert!(!p.is_empty());
15566    }
15567
15568    #[test]
15569    fn mesh_policy_with_only_retries_is_not_empty() {
15570        let p = MeshPolicy {
15571            retries: Some(3),
15572            ..Default::default()
15573        };
15574        assert!(!p.is_empty());
15575    }
15576
15577    #[test]
15578    fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
15579        let p = MeshPolicy {
15580            circuit_breaker: Some(CircuitBreaker {
15581                max_failures: 5,
15582                window: Duration::from_secs(60),
15583            }),
15584            ..Default::default()
15585        };
15586        assert!(!p.is_empty());
15587    }
15588
15589    #[test]
15590    fn mesh_policy_with_only_mtls_required_is_not_empty() {
15591        // Even `mtls_required: Some(false)` (an explicit opt-out) is
15592        // not empty — the author *named* the axis, the renderer needs
15593        // to honor that vs. fall back to the cluster default.
15594        let p = MeshPolicy {
15595            mtls_required: Some(false),
15596            ..Default::default()
15597        };
15598        assert!(!p.is_empty());
15599    }
15600
15601    #[test]
15602    fn mesh_policy_with_only_rate_limit_is_not_empty() {
15603        let p = MeshPolicy {
15604            rate_limit: Some(RateLimit {
15605                rate: 100,
15606                window: Duration::from_secs(1),
15607            }),
15608            ..Default::default()
15609        };
15610        assert!(!p.is_empty());
15611    }
15612
15613    #[test]
15614    fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
15615        // The three-member happy-path fixture sets timeout + retries +
15616        // mtls_required — every populated axis must read non-empty.
15617        // Pin the round-trip so the M3.x per-:politicas emitter (the
15618        // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
15619        // on is_empty() to decide whether to emit at all without
15620        // re-deriving the contract from inline field probes.
15621        assert!(!three_member_spec().politicas.is_empty());
15622    }
15623
15624    // ── shared duration codec: cross-slot integer-magnitude gate ──
15625    //
15626    // The integer-magnitude discipline applied to
15627    // `supervisor::duration_codec::parse` lifts onto every typed slot
15628    // that routes through the shared codec — `MeshPolicy::timeout`
15629    // (`:politicas :timeout`) and `CircuitBreaker::window`
15630    // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
15631    // These cross-slot tests pin that the gate fires at the serde
15632    // layer for both typed slots, not just for the supervisor side.
15633
15634    #[test]
15635    fn policy_timeout_serde_rejects_fractional_seconds() {
15636        // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
15637        // so the shared codec's integer-magnitude gate applies on
15638        // deserialize. `"1.5s"` previously parsed to 1500ms and round-
15639        // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
15640        // deserialize with the canonical-form diagnostic naming the
15641        // offending `"1.5"` and the remediation `"1500ms"`.
15642        let payload = r#"{"timeout":"1.5s"}"#;
15643        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
15644        let msg = err.to_string();
15645        assert!(
15646            msg.contains("not a non-negative integer"),
15647            "expected integer-magnitude diagnostic in {msg:?}"
15648        );
15649        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
15650        assert!(
15651            msg.contains("\"1500ms\""),
15652            "missing canonical-form remediation in {msg:?}"
15653        );
15654    }
15655
15656    #[test]
15657    fn policy_timeout_serde_rejects_leading_plus_sign() {
15658        // Pin the leading-`+` arm cross-slot — the prior f64 parser
15659        // accepted `"+30s"` silently and round-tripped to `"30s"`.
15660        let payload = r#"{"timeout":"+30s"}"#;
15661        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
15662        let msg = err.to_string();
15663        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
15664    }
15665
15666    #[test]
15667    fn circuit_breaker_window_serde_rejects_fractional_minutes() {
15668        // `CircuitBreaker::window` uses `with =
15669        // "supervisor::duration_codec_required"` (the required-Duration
15670        // variant that delegates to the same shared parser). `"0.5m"`
15671        // parsed to 30s and round-tripped to `"30s"` on next emit —
15672        // DRIFT closed.
15673        let payload = format!(
15674            r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
15675            max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
15676            window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
15677        );
15678        let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
15679        let msg = err.to_string();
15680        assert!(
15681            msg.contains("not a non-negative integer"),
15682            "expected integer-magnitude diagnostic in {msg:?}"
15683        );
15684        assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
15685        assert!(
15686            msg.contains("\"30s\""),
15687            "missing canonical-form remediation in {msg:?}"
15688        );
15689    }
15690
15691    #[test]
15692    fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
15693        // Pin the happy-path on the cross-slot side: every canonical
15694        // author shape `render` ever emits parses cleanly through the
15695        // shared codec on the `CircuitBreaker` slot. The
15696        // codec's accepted set (post-gate) is exactly its emitted set
15697        // for the integer-magnitude class.
15698        for window_lit in ["30s", "500ms", "2m", "1h"] {
15699            let payload = format!(
15700                r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
15701                max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
15702                window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
15703            );
15704            let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
15705                panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
15706            });
15707            assert_eq!(cb.max_failures, 5);
15708        }
15709    }
15710
15711    // ── rate_limit_codec: integer-magnitude gate ──
15712    //
15713    // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
15714    // / 737a676 / d53c922 trajectory landed on every typed-duration /
15715    // typed-byte-size codec in caixa-core lifts onto the fifth typed
15716    // codec — `rate_limit_codec` — through the digit-only magnitude
15717    // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
15718    // These tests pin the gate at the serde layer for `:politicas
15719    // :rate-limit` (the only typed slot the codec backs), and at the
15720    // codec-internal `parse` layer for the canonical positive cases.
15721
15722    #[test]
15723    fn rate_limit_serde_rejects_fractional_rate() {
15724        // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
15725        // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
15726        // wording, which didn't name the canonical-form remediation or
15727        // the round-trip drift the next emit would produce. Now refused
15728        // at deserialize with the canonical-form diagnostic naming the
15729        // offending `"1.5"` magnitude and the round-trip drift wording.
15730        let payload = r#"{"rateLimit":"1.5/s"}"#;
15731        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
15732        let msg = err.to_string();
15733        assert!(
15734            msg.contains("not a non-negative integer"),
15735            "expected integer-magnitude diagnostic in {msg:?}"
15736        );
15737        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
15738        assert!(
15739            msg.contains("THEORY.md"),
15740            "missing render-determinism contract citation in {msg:?}"
15741        );
15742    }
15743
15744    #[test]
15745    fn rate_limit_serde_rejects_leading_plus_sign() {
15746        // `u32::from_str("+100")` returns `Ok(100)` (Rust's
15747        // permissive-`+` parse), so `"+100/s"` silently parsed to
15748        // `RateLimit { 100, 1s }` and round-tripped through `render` to
15749        // `"100/s"` — a *different* canonical string on the next emit,
15750        // breaking the THEORY.md Part V render-determinism contract
15751        // exactly the way the peer duration codecs' `"+30s"` case did.
15752        // This is the load-bearing class the digit-only gate closes
15753        // beyond what `u32::from_str`'s strictness covers on its own.
15754        let payload = r#"{"rateLimit":"+100/s"}"#;
15755        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
15756        let msg = err.to_string();
15757        assert!(
15758            msg.contains("not a non-negative integer"),
15759            "expected integer-magnitude diagnostic in {msg:?}"
15760        );
15761        assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
15762    }
15763
15764    #[test]
15765    fn rate_limit_serde_rejects_leading_minus_sign() {
15766        // The signed-negative arm: `"-1/s"` lands on the
15767        // non-canonical-but-numeric branch via the `i64` fallback (the
15768        // `f64` parse also succeeds), surfacing the canonical-form
15769        // diagnostic. Replaces the prior value-laundered "not a u32"
15770        // wording with the unified diagnostic across signs.
15771        let payload = r#"{"rateLimit":"-1/s"}"#;
15772        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
15773        let msg = err.to_string();
15774        assert!(
15775            msg.contains("not a non-negative integer"),
15776            "expected integer-magnitude diagnostic in {msg:?}"
15777        );
15778        assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
15779    }
15780
15781    #[test]
15782    fn rate_limit_serde_rejects_decimal_shaped_integer() {
15783        // `"100.0/s"` is integer-valued numerically but not in the
15784        // codec's accepted set — `render` emits `"100/s"`, so the
15785        // round-trip would drift. Lifted to the canonical-form
15786        // diagnostic peer with the duration codec's `"1.0s"` case
15787        // (1c55a2a).
15788        let payload = r#"{"rateLimit":"100.0/s"}"#;
15789        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
15790        let msg = err.to_string();
15791        assert!(
15792            msg.contains("not a non-negative integer"),
15793            "expected integer-magnitude diagnostic in {msg:?}"
15794        );
15795        assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
15796    }
15797
15798    #[test]
15799    fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
15800        // Non-numeric, non-digit-only input lands on the existing
15801        // narrower `"not a u32"` arm (preserved for diagnostic-shape
15802        // stability on the parser-shape footgun case). Pin this so a
15803        // future relaxation of the numeric-fallback predicate doesn't
15804        // silently collapse garbage onto the canonical-form arm — same
15805        // partition the peer duration codecs draw between
15806        // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
15807        let payload = r#"{"rateLimit":"abc/s"}"#;
15808        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
15809        let msg = err.to_string();
15810        assert!(
15811            msg.contains("not a u32"),
15812            "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
15813        );
15814        assert!(
15815            !msg.contains("not a non-negative integer"),
15816            "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
15817        );
15818    }
15819
15820    #[test]
15821    fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
15822        // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
15823        // u32's range. The digit-only gate passes; `u32::from_str`
15824        // fails on overflow. Surface that with the overflow-shaped
15825        // diagnostic naming the offending magnitude verbatim, peer
15826        // with `supervisor::duration_codec`'s overflow arm. Pinning
15827        // the wording so a future refactor doesn't silently collapse
15828        // overflow onto the canonical-form arm.
15829        let payload = r#"{"rateLimit":"4294967296/s"}"#;
15830        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
15831        let msg = err.to_string();
15832        assert!(
15833            msg.contains("overflows u32"),
15834            "expected overflow diagnostic in {msg:?}"
15835        );
15836        assert!(
15837            msg.contains("\"4294967296\""),
15838            "missing offending magnitude in {msg:?}"
15839        );
15840    }
15841
15842    #[test]
15843    fn rate_limit_serde_rejects_leading_zero_magnitude() {
15844        // `"0100/s"` is digit-only, so the existing
15845        // non-digit-only / sign / fractional arm doesn't catch it —
15846        // `u32::from_str("0100")` returns `Ok(100)`, so before this
15847        // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
15848        // round-tripped through `render` to `"100/s"` — a *different*
15849        // canonical string on the next emit, breaking the THEORY.md
15850        // Part V render-determinism contract exactly the way the
15851        // peer `"+100/s"` case did before the leading-`+` arm landed.
15852        // This is the load-bearing class the leading-zero gate closes
15853        // beyond what the existing digit-only / sign / fractional
15854        // gates cover, and the peer arm to the leading-`+` test
15855        // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
15856        // canonical-form-drift axis.
15857        let payload = r#"{"rateLimit":"0100/s"}"#;
15858        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
15859        let msg = err.to_string();
15860        assert!(
15861            msg.contains("non-canonical leading zero"),
15862            "expected leading-zero diagnostic in {msg:?}"
15863        );
15864        assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
15865        assert!(
15866            msg.contains("THEORY.md"),
15867            "missing render-determinism contract citation in {msg:?}"
15868        );
15869    }
15870
15871    #[test]
15872    fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
15873        // `"00/s"` is the degenerate leading-zero case — every byte
15874        // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
15875        // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
15876        // a *different* canonical string, same render-determinism
15877        // violation. The single-byte `"0/s"` itself is in the
15878        // accepted set (round-trips losslessly through `render`,
15879        // refused downstream by `PolicyRateLimitZero`); the
15880        // multi-byte `"00/s"` is not. Pins the boundary between the
15881        // accepted single-`0` and the rejected leading-zero class.
15882        let payload = r#"{"rateLimit":"00/s"}"#;
15883        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
15884        let msg = err.to_string();
15885        assert!(
15886            msg.contains("non-canonical leading zero"),
15887            "expected leading-zero diagnostic in {msg:?}"
15888        );
15889        assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
15890    }
15891
15892    #[test]
15893    fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
15894        // Cross-window pin — the gate is window-agnostic; the
15895        // leading-zero class is a property of the magnitude, not the
15896        // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
15897        // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
15898        // single-window coverage extended across the three canonical
15899        // windows the codec accepts.
15900        let payload = r#"{"rateLimit":"007/h"}"#;
15901        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
15902        let msg = err.to_string();
15903        assert!(
15904            msg.contains("non-canonical leading zero"),
15905            "expected leading-zero diagnostic in {msg:?}"
15906        );
15907        assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
15908    }
15909
15910    #[test]
15911    fn rate_limit_serde_rejects_leading_whitespace() {
15912        // `" 100/s"` — the canonical paste-from-aligned-doc /
15913        // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
15914        // the top-level `s.trim()` silently ate the leading space and
15915        // parsed the value to `RateLimit { 100, 1s }`, which then
15916        // round-tripped through `render` to `"100/s"` (a *different*
15917        // canonical string on the next emit) — the exact
15918        // canonical-form-drift class the leading-`+` / leading-zero
15919        // arms already close, extended to the whitespace byte class.
15920        let payload = r#"{"rateLimit":" 100/s"}"#;
15921        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
15922        let msg = err.to_string();
15923        assert!(
15924            msg.contains("contains whitespace byte"),
15925            "expected whitespace diagnostic in {msg:?}"
15926        );
15927        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
15928        assert!(
15929            msg.contains("THEORY.md"),
15930            "missing render-determinism contract citation in {msg:?}"
15931        );
15932    }
15933
15934    #[test]
15935    fn rate_limit_serde_rejects_trailing_whitespace() {
15936        // `"100/s "` — the canonical shell-history / trailing-space
15937        // paste footgun. Before this gate the top-level `s.trim()`
15938        // silently ate the trailing space and parsed to
15939        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
15940        // next emit — same canonical-form drift as the leading-space
15941        // sibling, closed on the same whitespace-byte arm.
15942        let payload = r#"{"rateLimit":"100/s "}"#;
15943        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
15944        let msg = err.to_string();
15945        assert!(
15946            msg.contains("contains whitespace byte"),
15947            "expected whitespace diagnostic in {msg:?}"
15948        );
15949        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
15950    }
15951
15952    #[test]
15953    fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
15954        // `"100 / s"` — the canonical typographically-spaced author
15955        // shape (the same idiom every prose reference to a rate limit
15956        // renders as, mistakenly retained when the value is pasted
15957        // into a codec-shaped slot). Before this gate the per-part
15958        // `rate_str.trim()` / `unit.trim()` calls silently ate both
15959        // spaces on either side of `/` and parsed to
15960        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
15961        // codec's *internal* whitespace-tolerance vector, orthogonal
15962        // to the leading / trailing surface but the same canonical-
15963        // form-drift class. Pins the arm as strictly stronger than the
15964        // pre-existing top-level `s.trim()` behavior: it fires on
15965        // whitespace anywhere in the value, not just at the string
15966        // boundary.
15967        let payload = r#"{"rateLimit":"100 / s"}"#;
15968        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
15969        let msg = err.to_string();
15970        assert!(
15971            msg.contains("contains whitespace byte"),
15972            "expected whitespace diagnostic in {msg:?}"
15973        );
15974        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
15975    }
15976
15977    #[test]
15978    fn rate_limit_serde_rejects_tab_byte() {
15979        // `"\t100/s"` — the canonical paste-from-indented-doc /
15980        // paste-from-YAML-block-scalar footgun where a tab byte leads
15981        // the magnitude. Pins that the gate covers tab (`0x09`) as
15982        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
15983        // members and both would be silently swallowed by `s.trim()`
15984        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
15985        // space alone to the full ASCII-whitespace set (space `0x20`,
15986        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
15987        // the tab arm as a representative of the non-space members.
15988        let payload = r#"{"rateLimit":"\t100/s"}"#;
15989        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
15990        let msg = err.to_string();
15991        assert!(
15992            msg.contains("contains whitespace byte"),
15993            "expected whitespace diagnostic in {msg:?}"
15994        );
15995        assert!(
15996            msg.contains("0x09"),
15997            "missing offending tab byte in {msg:?}"
15998        );
15999    }
16000
16001    // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
16002    //
16003    // Successor to the ASCII-whitespace arm (1ad7755) on
16004    // `rate_limit_codec` — closes the strictly-complementary class the
16005    // byte-scan cannot see, through the lifted
16006    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
16007
16008    #[test]
16009    fn rate_limit_serde_rejects_leading_nbsp() {
16010        // NBSP prefix — paste-from-typography footgun. Byte-scan
16011        // misses, `str::trim` silently strips it, value drifts to
16012        // `"100/s"` on next serialize.
16013        let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
16014        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16015        let msg = err.to_string();
16016        assert!(
16017            msg.contains("non-ASCII Unicode whitespace character"),
16018            "expected non-ASCII whitespace diagnostic in {msg:?}"
16019        );
16020        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
16021    }
16022
16023    #[test]
16024    fn rate_limit_serde_rejects_internal_em_space() {
16025        // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
16026        // paste-from-typography footgun on the `<integer>/<unit>`
16027        // shape.
16028        let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
16029        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16030        let msg = err.to_string();
16031        assert!(
16032            msg.contains("non-ASCII Unicode whitespace character"),
16033            "expected non-ASCII whitespace diagnostic in {msg:?}"
16034        );
16035        assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
16036    }
16037
16038    #[test]
16039    fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
16040        // Positive-control pin: every ASCII-only canonical form the
16041        // renderer emits stays accepted through the new arm.
16042        for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
16043            let payload = format!(r#"{{"rateLimit":{lit}}}"#);
16044            let p: MeshPolicy = serde_json::from_str(&payload)
16045                .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
16046            assert!(p.rate_limit.is_some());
16047        }
16048    }
16049
16050    #[test]
16051    fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
16052        // The boundary case — `"0/s"` is the canonical form
16053        // `render(RateLimit { 0, 1s })` emits, so the codec accepts
16054        // it at the parse layer; the downstream
16055        // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
16056        // `rate == 0` at the typed-validate layer above. Pins the
16057        // partition: the leading-zero gate at the codec layer does
16058        // not poach the rate-zero semantic-validation arm at the
16059        // typed-validate layer above (a future stricter codec must
16060        // not reject `"0/s"` here, or it'd collapse the diagnostic
16061        // partitioning that lets `PolicyRateLimitZero` name the
16062        // offending typed slot).
16063        let payload = r#"{"rateLimit":"0/s"}"#;
16064        let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
16065            panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
16066        });
16067        let rl = policy.rate_limit.expect("rate_limit must be Some");
16068        assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
16069        assert_eq!(
16070            rl.window,
16071            Duration::from_secs(1),
16072            "single-`0` magnitude with `s` unit must parse to window=1s"
16073        );
16074    }
16075
16076    #[test]
16077    fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
16078        // The complementary boundary pin — every magnitude
16079        // `render` emits starts with `[1-9]` (or is the single byte
16080        // `"0"`), so the canonical-form predicate is `(len == 1) ||
16081        // (first byte != '0')`. Pinning the `len > 1 && first byte ==
16082        // '1'` case explicitly so a future tightening of the gate
16083        // (e.g. an over-eager "no leading digit < 5" rule, or a
16084        // mistakenly anchored start-of-magnitude byte check) lands
16085        // here before the canonical-forms-iterating test would catch
16086        // it.
16087        let payload = r#"{"rateLimit":"100/s"}"#;
16088        let policy: MeshPolicy = serde_json::from_str(payload)
16089            .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
16090        let rl = policy.rate_limit.expect("rate_limit must be Some");
16091        assert_eq!(
16092            rl.rate, 100,
16093            "canonical-100 magnitude must parse to rate=100"
16094        );
16095    }
16096
16097    #[test]
16098    fn rate_limit_serde_accepts_integer_canonical_forms() {
16099        // Pin the happy-path: every canonical author shape `render`
16100        // ever emits parses cleanly through the codec post-gate. The
16101        // codec's accepted set (post-gate) is exactly its emitted set
16102        // for the integer-magnitude class — same property
16103        // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
16104        // gates guarantee on the peer codecs. Iterating across rate
16105        // magnitudes (including `"0"`, which the codec accepts even
16106        // though `validate_politicas` rejects `rate == 0` at the typed
16107        // layer above) closes the codec contract at the parse layer
16108        // independently of the validate layer.
16109        for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
16110            for unit_lit in ["s", "m", "h"] {
16111                let lit = format!("{rate_lit}/{unit_lit}");
16112                let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
16113                let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
16114                    panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
16115                });
16116                let rl = policy.rate_limit.expect("rate_limit must be Some");
16117                assert_eq!(
16118                    rl.rate,
16119                    rate_lit.parse::<u32>().unwrap(),
16120                    "rate mismatch for {lit:?}"
16121                );
16122            }
16123        }
16124    }
16125
16126    #[test]
16127    fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
16128        // The structural property the gate enforces: serialize ∘
16129        // deserialize is the identity on every canonical author shape.
16130        // Peer of `parse_byte_size`'s and `parse_duration`'s
16131        // `_round_trips_through_render_for_every_canonical_form` tests
16132        // on the rate-limit axis. Before the gate, `"+100/s"` violated
16133        // this (`parse` → `RateLimit { 100, 1s }` → `render` →
16134        // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
16135        for rate in [1u32, 100, 5000, 1_000_000] {
16136            for (window, unit) in [
16137                (Duration::from_secs(1), "s"),
16138                (Duration::from_secs(60), "m"),
16139                (Duration::from_secs(3600), "h"),
16140            ] {
16141                let policy = MeshPolicy {
16142                    rate_limit: Some(RateLimit { rate, window }),
16143                    ..Default::default()
16144                };
16145                let json = serde_json::to_string(&policy).unwrap();
16146                let expected = format!("\"{rate}/{unit}\"");
16147                assert!(
16148                    json.contains(&expected),
16149                    "expected {expected:?} in {json:?}"
16150                );
16151                let back: MeshPolicy = serde_json::from_str(&json).unwrap();
16152                assert_eq!(
16153                    back.rate_limit, policy.rate_limit,
16154                    "round-trip for {json:?}"
16155                );
16156            }
16157        }
16158    }
16159
16160    // ── self-membership cross-slot gate ──────────────────────────────
16161
16162    #[test]
16163    fn validate_no_self_membership_rejects_self_named_membro() {
16164        // An Aplicacao whose `:membros` lists its own `:nome` is a
16165        // one-node lacre-closure recursion — rejected, naming the parent.
16166        let membros = vec![
16167            membro("catalog", "^0.1"),
16168            membro("checkout", "^0.1"),
16169            membro("cart", "^0.1"),
16170        ];
16171        let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
16172        assert!(
16173            matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
16174            "got {err:?}"
16175        );
16176    }
16177
16178    #[test]
16179    fn validate_no_self_membership_accepts_distinct_membros() {
16180        // Positive control: distinct member names (including a member
16181        // that is itself an Aplicacao — recursive composition is valid,
16182        // MESH-COMPOSITION §V) pass the gate.
16183        let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
16184        validate_no_self_membership(&membros, "checkout").unwrap();
16185    }
16186
16187    #[test]
16188    fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
16189        // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
16190        // `NoMembros` arm (the more-fundamental "graph must have nodes"
16191        // gate), not by this cross-slot self-edge gate. Keeping the
16192        // self-membership predicate vacuously-ok on the empty input
16193        // matches its supervisor-axis peer
16194        // (`validate_no_self_supervision_empty_children_is_ok`) and
16195        // makes the gate composable from any future call site (an M4
16196        // CR materializer's per-membros validator) without re-checking
16197        // emptiness.
16198        validate_no_self_membership(&[], "checkout").unwrap();
16199    }
16200
16201    #[test]
16202    fn validate_no_self_membership_diagnostic_names_offending_caixa() {
16203        // Pinning the Display: the self-membership diagnostic must name
16204        // the offending caixa verbatim + the "lists itself" framing the
16205        // author can grep for, so the cluster-far failure surfaces at
16206        // build time with one-line remediation. Same diagnostic shape
16207        // as the supervisor-axis `ChildSupervisesSelf` peer.
16208        let membros = vec![membro("orquestra", "^0.1")];
16209        let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
16210        let msg = err.to_string();
16211        assert!(
16212            msg.contains("orquestra"),
16213            "diagnostic must name the offending caixa nome (got: {msg:?})"
16214        );
16215        assert!(
16216            msg.contains("lists itself"),
16217            "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
16218        );
16219    }
16220
16221    #[test]
16222    fn default_servico_port_constant_pins_canonical_8080_literal() {
16223        // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
16224        // at the verbatim `8080` literal both consumers (the
16225        // `Entrada::port` serde default via [`default_port`] and the
16226        // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
16227        // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
16228        // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
16229        // discipline (a085b26) on the per-renderer canonical-K8s-axis
16230        // string-constant axis: a future refactor that drifts the
16231        // constant out from under either consumer surfaces here ahead
16232        // of every per-renderer's first emission. The literal value
16233        // matches the well-known HTTP-alt port the `pleme-computeunit`
16234        // library chart already emits as its `trigger.service.port`
16235        // default — by construction the same value the substrate
16236        // assumes about every Servico's in-cluster L4 listener.
16237        assert_eq!(
16238            DEFAULT_SERVICO_PORT, 8080,
16239            "canonical Servico port literal must remain `8080` verbatim — \
16240             this is the value both the `Entrada::port` serde default and the \
16241             caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
16242        );
16243    }
16244
16245    #[test]
16246    fn default_port_helper_returns_canonical_servico_port_constant() {
16247        // The bridge-arm — pins that the [`default_port`] helper
16248        // [`Entrada::port`]'s `#[serde(default = "default_port")]`
16249        // attribute hooks routes through the lifted
16250        // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
16251        // literal. A future refactor that re-introduces the `8080`
16252        // literal at the helper's return site (silently re-opening
16253        // the drift footgun this lift closed) surfaces here ahead of
16254        // every author-side `(:entrada (:host … :para …))` slot
16255        // without an explicit `:port`. Peer with the
16256        // `default_namespace_re_export_points_at_caixa_core_canonical`
16257        // pin on the caixa-mesh-side re-export axis.
16258        assert_eq!(
16259            default_port(),
16260            DEFAULT_SERVICO_PORT,
16261            "the serde-default helper must route through the lifted constant"
16262        );
16263    }
16264
16265    #[test]
16266    fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
16267        // The end-to-end pin — an author-surface `(:entrada (:host …
16268        // :para …))` without an explicit `:port` slot deserializes to
16269        // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
16270        // verbatim. Routes the canonical lifted constant through both
16271        // the serde-default machinery (the `#[serde(default =
16272        // "default_port")]` attribute) and the typed-value-shape
16273        // contract (the resulting [`Entrada::port`] value). A future
16274        // refactor that drifts either axis — replacing the serde
16275        // hook's helper, changing the typed slot's wire shape — would
16276        // surface here before any per-renderer's CNP / Gateway /
16277        // HTTPRoute emission consumed the drifted default.
16278        let entrada: Entrada =
16279            serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
16280        assert_eq!(
16281            entrada.port, DEFAULT_SERVICO_PORT,
16282            "the serde default must materialize as the lifted canonical Servico port"
16283        );
16284    }
16285
16286    #[test]
16287    fn servico_port_min_pins_canonical_accept_set_floor() {
16288        // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
16289        // verbatim `1` literal every typed `:entrada :port` acceptance
16290        // gate keys off. Peer with the
16291        // [`default_servico_port_constant_pins_canonical_8080_literal`]
16292        // discipline on the canonical-Servico-port-constant axis: a
16293        // future refactor that drifts the accept-set floor out from
16294        // under the sole consumer at [`AplicacaoSpec::validate`]'s
16295        // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
16296        // every per-`:entrada` `EntradaPortZero` diagnostic. The
16297        // literal value matches the IANA-registered TCP/UDP port
16298        // space floor (`1..=65535` — port `0` is the "any ephemeral"
16299        // sentinel, not a well-defined destination the substrate's
16300        // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
16301        // axis can honor).
16302        assert_eq!(
16303            SERVICO_PORT_MIN, 1,
16304            "canonical Servico port accept-set floor must remain `1` verbatim — \
16305             this is the value the `AplicacaoSpec::validate` gate at \
16306             `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
16307        );
16308    }
16309
16310    #[test]
16311    fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
16312        // The cross-const invariant pin — the substrate's canonical
16313        // default port must satisfy its own accept-set floor by
16314        // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
16315        // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
16316        // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
16317        // override the operator pins through a future
16318        // `:placement :default-port` slot that lands out-of-range, a
16319        // per-edition Servico-port migration that lifted the floor
16320        // above the previous default without coordinating the pair —
16321        // would silently invalidate the serde-default emission at
16322        // every author-side `(:entrada (:host … :para …))` slot
16323        // without an explicit `:port`: the default port would fall
16324        // below the accept-set floor, the `AplicacaoSpec::validate`
16325        // gate would reject every default-carrying Aplicacao as
16326        // `EntradaPortZero`, and the substrate's typed
16327        // `(defcaixa … :kind Aplicacao)` surface would fail validate
16328        // on every Aplicacao whose author omitted `:entrada :port`
16329        // for the substrate's chosen default — a class of authoring-
16330        // surface footguns the compile-time pin structurally closes.
16331        // Peer with the
16332        // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
16333        // (27f9b34) cross-const invariant pin discipline on the peer
16334        // canonical-Helm-per-values-block child-chart-enablement-toggle
16335        // axis pair.
16336        assert!(
16337            SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
16338            "the substrate's canonical default port ({DEFAULT_SERVICO_PORT}) must \
16339             satisfy its own accept-set floor (SERVICO_PORT_MIN = {SERVICO_PORT_MIN}) — \
16340             every default-carrying `(:entrada (:host … :para …))` slot without an \
16341             explicit `:port` inherits `DEFAULT_SERVICO_PORT` through the serde default \
16342             hook and must pass the `AplicacaoSpec::validate` floor gate by construction"
16343        );
16344    }
16345
16346    #[test]
16347    fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
16348        // The gate-site pin — asserts the `AplicacaoSpec::validate`
16349        // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
16350        // `EntradaPortZero` diagnostic on the below-floor input
16351        // `port: 0` (the only below-floor value the `u16` field can
16352        // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
16353        // is the singleton `{0}`). A future refactor that drifts the
16354        // gate off the lifted const (silently re-introducing an
16355        // inline `if e.port == 0` byte-check) surfaces here — the
16356        // pin cannot distinguish `< 1` from `== 0` on the current
16357        // floor, but it *does* pin that the diagnostic fires on `0`
16358        // through whichever gate is wired, so any future accept-set
16359        // floor migration (a hypothetical unprivileged-only
16360        // migration lifting `SERVICO_PORT_MIN` to `1024`) must
16361        // update this test alongside the const declaration —
16362        // structurally guaranteeing the gate + accept-set + pin
16363        // trio move together. Peer with the
16364        // [`rejects_zero_entrada_port`] behavioral pin on the same
16365        // per-`:entrada :port` axis — that pin asserts the pre-lift
16366        // behavioral contract (`port: 0` → `EntradaPortZero`); this
16367        // pin adds the structural link to the lifted floor const.
16368        assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
16369        let mut s = three_member_spec();
16370        s.entrada.as_mut().unwrap().port = 0;
16371        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
16372    }
16373
16374    // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
16375
16376    #[test]
16377    fn membro_serde_keys_match_lifted_membro_key_consts() {
16378        // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
16379        // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
16380        // name the exact camelCase JSON keys the
16381        // `#[serde(rename_all = "camelCase")]` attribute on
16382        // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
16383        // that each canonical byte-sequence appears verbatim in the
16384        // JSON — a future accidental `rename_all = "snake_case"` /
16385        // `"kebab-case"` / verbatim-field-name flip at the derive
16386        // attribute (any of which would silently break every downstream
16387        // JSON consumer that reaches for one of the two consts via
16388        // `Value::get(...)`) surfaces here as a build-time test failure
16389        // at `aplicacao.rs`, not as an apply-time
16390        // `.get(<stale-canonical-const>)` returning `None` far from the
16391        // derive-attr drift's commit. Peer with the sibling
16392        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
16393        // (40cc4e5) pin on the M2 supervision-tree top-level axis —
16394        // same discipline the SupervisorSpec top-level lift established,
16395        // extended here to the M3 [`Membro`] per-`:membros` axis.
16396        let m = Membro {
16397            caixa: "catalog".into(),
16398            versao: "^0.1".into(),
16399        };
16400        let json = serde_json::to_string(&m).unwrap();
16401        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
16402            let quoted = format!("\"{key}\"");
16403            assert!(
16404                json.contains(&quoted),
16405                "serialized Membro must carry the lifted MEMBRO_KEY_* \
16406                 byte-sequence {quoted} verbatim in the JSON emission \
16407                 (got: {json})",
16408            );
16409        }
16410    }
16411
16412    #[test]
16413    fn membro_key_consts_are_pairwise_distinct() {
16414        // Cross-axis drift-detection pin: a future collapse of the two
16415        // canonical [`Membro`] per-entry byte-strings onto the same
16416        // value (e.g. an accidental copy-paste flip of
16417        // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
16418        // silently reroute every downstream probe on one axis onto the
16419        // sibling axis's overlay entry and pass every propagation-probe
16420        // test that expected only the stale axis's value. Peer of the
16421        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
16422        // (40cc4e5).
16423        let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
16424        for (i, a) in all.iter().enumerate() {
16425            for b in all.iter().skip(i + 1) {
16426                assert_ne!(
16427                    a, b,
16428                    "MEMBRO_KEY_* consts must be pairwise-distinct \
16429                     canonical byte-sequences — got `{a}` == `{b}`",
16430                );
16431            }
16432        }
16433    }
16434
16435    // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
16436    //    URL-path fallback resolver every HTTPRoute-aware renderer
16437    //    reaching for a per-rule path-list resolution routes through.
16438    //    The four pin tests below fix the four-way accept-set the
16439    //    resolver must always honor: (:paths-non-empty-verbatim,
16440    //    :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
16441    //    :paths-preserves-order-across-multiple-entries) — drift on any
16442    //    arm surfaces at caixa-core build time rather than at cluster-
16443    //    apply time. Peer discipline with `MeshPolicy::is_empty` on the
16444    //    sibling `:politicas` typed-primitive dispatch axis.
16445
16446    fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
16447        Entrada {
16448            host: "example.com".into(),
16449            para: "cart".into(),
16450            paths: paths.into_iter().map(String::from).collect(),
16451            port: DEFAULT_SERVICO_PORT,
16452        }
16453    }
16454
16455    #[test]
16456    fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
16457        // The typed `:entrada :paths` slot carries an author-declared
16458        // list — the resolver returns each entry verbatim, no
16459        // catch-all substitution. The canonical "author declared
16460        // paths, honor them verbatim" arm of the path-list dispatch.
16461        let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
16462        assert_eq!(
16463            e.resolved_paths(),
16464            vec!["/api/cart", "/api/products"],
16465            "resolved_paths must return each `:entrada :paths` entry \
16466             verbatim when the typed slot is non-empty (got {:?})",
16467            e.resolved_paths(),
16468        );
16469    }
16470
16471    #[test]
16472    fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
16473        // Empty `:entrada :paths` slot — the resolver substitutes the
16474        // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
16475        // catch-all fallback verbatim. Pins the empty-arm of the
16476        // resolver's four-way accept-set against a future silent
16477        // detour that returned an empty Vec (which would emit an
16478        // HTTPRoute with zero rules — silently dropping every
16479        // external `:entrada` flow at admission time), routed to a
16480        // different fallback shape, or dropped the catch-all
16481        // altogether.
16482        let e = entrada_with_paths(vec![]);
16483        assert_eq!(
16484            e.resolved_paths(),
16485            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
16486            "resolved_paths on empty `:entrada :paths` must fall back \
16487             to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
16488             all — got {:?}",
16489            e.resolved_paths(),
16490        );
16491    }
16492
16493    #[test]
16494    fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
16495        // Single-entry `:entrada :paths` — the resolver returns the
16496        // single declared path verbatim, NOT the catch-all fallback
16497        // (author declared a path, honor it — the empty-arm and the
16498        // len-1 arm are semantically distinct axes of the resolver's
16499        // accept-set). Pins that the resolver treats "author declared
16500        // one path" as authored input, not as the empty case.
16501        let e = entrada_with_paths(vec!["/api/only"]);
16502        assert_eq!(
16503            e.resolved_paths(),
16504            vec!["/api/only"],
16505            "resolved_paths on single-entry `:entrada :paths` must \
16506             return the declared path verbatim, NOT the catch-all \
16507             fallback (got {:?})",
16508            e.resolved_paths(),
16509        );
16510    }
16511
16512    #[test]
16513    fn resolved_paths_preserves_author_declared_order() {
16514        // The `:entrada :paths` list is author-ordered — the resolver
16515        // preserves the author's declaration order verbatim, since
16516        // per-rule dispatch order at the K8s Gateway API HTTPRoute
16517        // consumer is significant (first-match-wins under the
16518        // path-prefix matcher). Pins against a future silent
16519        // re-sort / dedup / normalize detour that reordered author
16520        // input.
16521        let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
16522        assert_eq!(
16523            e.resolved_paths(),
16524            vec!["/z/last", "/a/first", "/m/mid"],
16525            "resolved_paths must preserve author-declared `:entrada \
16526             :paths` order verbatim — got {:?}",
16527            e.resolved_paths(),
16528        );
16529    }
16530
16531    // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
16532    //    slot `&[String]` slice accessor every per-`:entrada` consumer
16533    //    that must see the author's declaration verbatim (not the
16534    //    fallback-applied projection the sibling `resolved_paths`
16535    //    returns) routes through. The three pin tests below fix the
16536    //    accept-set the accessor must honor: (:non-empty-byte-equal,
16537    //    :empty-projects-empty-slice, :preserves-author-declared-order)
16538    //    — drift on any arm surfaces at caixa-core build time rather
16539    //    than at cluster-apply time. Peer discipline with the sibling
16540    //    [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
16541    //    peer M3 mesh-slot `Vec<String>`-carry axis.
16542
16543    #[test]
16544    fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
16545        // Byte-equal pin: [`Entrada::paths`] must project the raw
16546        // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
16547        // slice borrowed from the typed slot's own [`Vec<String>`]
16548        // storage — no re-ordering, no dedup, no per-entry normalization,
16549        // no fallback substitution (the fallback-applying projection is
16550        // the sibling [`Entrada::resolved_paths`] resolver). Pins against
16551        // a future silent detour that re-normalized the list, dropped
16552        // duplicates the [`AplicacaoSpec::validate`]
16553        // `EntradaPathDuplicate` refusal already rejects at build time,
16554        // or (most severe) accidentally routed through the fallback-
16555        // applying sibling and returned the substrate catch-all when
16556        // the author declared an empty list — collapsing the raw-slot
16557        // and fallback-applied axes into one and breaking the
16558        // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
16559        //
16560        // Peer of the sibling
16561        // [`Placement::clusters`]-shape byte-equal pin
16562        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
16563        // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
16564        let fixtures: Vec<Vec<String>> = vec![
16565            Vec::new(),
16566            vec!["/api/cart".into()],
16567            vec!["/api/cart".into(), "/api/products".into()],
16568            vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
16569        ];
16570        for paths in fixtures {
16571            let e = Entrada {
16572                host: "example.com".into(),
16573                para: "cart".into(),
16574                paths: paths.clone(),
16575                port: DEFAULT_SERVICO_PORT,
16576            };
16577            assert_eq!(
16578                e.paths(),
16579                paths.as_slice(),
16580                "Entrada::paths must return :entrada :paths verbatim \
16581                 (got {:?}, expected {:?})",
16582                e.paths(),
16583                paths.as_slice(),
16584            );
16585            assert_eq!(
16586                e.paths(),
16587                e.paths.as_slice(),
16588                "Entrada::paths accessor and .paths.as_slice() field \
16589                 access must byte-equal — the accessor is the substrate-\
16590                 primitive typed dispatch every downstream per-`:entrada` \
16591                 raw-slot path-list consumer must route through",
16592            );
16593            assert_eq!(
16594                e.paths().len(),
16595                e.paths.len(),
16596                "Entrada::paths().len() must byte-equal self.paths.len() \
16597                 — a length drift would silently split the paired \
16598                 pre-flight cascade-head `.is_empty()` probe input in \
16599                 the sibling [`Entrada::resolved_paths`] resolver from \
16600                 the per-entry validate loop's traversal input in \
16601                 [`AplicacaoSpec::validate`]",
16602            );
16603        }
16604    }
16605
16606    #[test]
16607    fn resolved_paths_reads_through_lifted_paths_accessor() {
16608        // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
16609        // pre-flight `.paths().is_empty()` cascade-head probe (which
16610        // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
16611        // catch-all fallback arm when the accessor projects the empty
16612        // slice) and the per-entry `.paths().iter().map(String::as_str)`
16613        // projection (which must reach every entry in the same order
16614        // the accessor projects, so the sibling
16615        // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
16616        // per-entry projection stay in lockstep by construction) must
16617        // both key off the lifted accessor. Pins the two-site coherence
16618        // by exercising each production consumer end-to-end: (1) the
16619        // catch-all-fallback arm under the empty slice, (2) the
16620        // author-declared-verbatim arm under a two-entry cohort whose
16621        // per-entry projection must byte-equal the input's per-entry
16622        // author-declared paths in the author's declared order.
16623        //
16624        // Peer of the sibling M3
16625        // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
16626        // `validate_placement_reads_through_lifted_clusters_accessor`
16627        // on the sibling `Placement::clusters` reader-site convergence.
16628        let empty = entrada_with_paths(vec![]);
16629        assert_eq!(
16630            empty.resolved_paths(),
16631            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
16632            "resolved_paths on empty :entrada :paths must trip the \
16633             lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
16634             catch-all fallback — routing through the lifted paths() \
16635             accessor must not silently drop the fallback arm",
16636        );
16637
16638        let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
16639        assert_eq!(
16640            declared.resolved_paths(),
16641            vec!["/api/cart", "/api/products"],
16642            "resolved_paths on non-empty :entrada :paths must return each \
16643             entry verbatim in the author's declared order — routing \
16644             through the lifted paths() accessor must not silently \
16645             reorder or drop entries",
16646        );
16647        // Byte-equal pin against the raw-slot accessor to keep the
16648        // fallback-applying resolver's per-entry projection input in
16649        // lockstep with the raw-slot accessor's projection.
16650        let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
16651        assert_eq!(
16652            declared.resolved_paths(),
16653            raw_projected,
16654            "resolved_paths non-empty projection must byte-equal the \
16655             lifted paths() accessor's per-entry String::as_str projection \
16656             — the two projections share the same input slice by \
16657             construction, so any drift here would surface a silent \
16658             re-ordering / dedup / normalization detour in the resolver",
16659        );
16660    }
16661
16662    #[test]
16663    fn validate_reads_through_lifted_entrada_paths_accessor() {
16664        // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
16665        // per-entry value-shape gate's `for p in e.paths()` traversal
16666        // (which must reach every entry in the same order the accessor
16667        // projects, so both the per-entry `EntradaPathEmpty` /
16668        // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
16669        // the duplicate-detection HashSet insert that trips
16670        // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
16671        // projection) must route through the lifted accessor. Pins the
16672        // coherence by exercising each production consumer end-to-end:
16673        // (1) the `EntradaPathEmpty` refusal fires on the second entry
16674        // of a two-entry cohort whose head is valid but tail is empty
16675        // (which requires the loop to reach the second entry through
16676        // the accessor), and (2) the `EntradaPathDuplicate` refusal
16677        // fires on the second entry of a two-entry cohort that shares
16678        // a path (which requires the loop to reach both entries — a
16679        // first-entry-only projection would silently pass since the
16680        // dedup HashSet has room for the first insert).
16681        //
16682        // Peer of the sibling
16683        // `validate_placement_reads_through_lifted_clusters_accessor`
16684        // on the sibling `Placement::clusters` reader-site convergence.
16685        let base = crate::AplicacaoSpec {
16686            membros: vec![crate::Membro {
16687                caixa: "cart".into(),
16688                versao: "^0.1".into(),
16689            }],
16690            contratos: Vec::new(),
16691            politicas: crate::MeshPolicy::default(),
16692            placement: crate::Placement {
16693                estrategia: crate::PlacementStrategy::SingleNode,
16694                clusters: vec!["rio".into()],
16695                shard_key: None,
16696                affinity: None,
16697            },
16698            entrada: Some(Entrada {
16699                host: "example.com".into(),
16700                para: "cart".into(),
16701                paths: vec!["/api/cart".into(), String::new()],
16702                port: DEFAULT_SERVICO_PORT,
16703            }),
16704        };
16705        assert_eq!(
16706            base.validate(),
16707            Err(crate::AplicacaoError::EntradaPathEmpty),
16708            "validate must trip EntradaPathEmpty on the second entry of \
16709             a two-entry cohort — routing through the lifted paths() \
16710             accessor must not silently short-circuit the loop at the \
16711             valid head entry",
16712        );
16713
16714        let mut dup = base;
16715        dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
16716        assert_eq!(
16717            dup.validate(),
16718            Err(crate::AplicacaoError::EntradaPathDuplicate {
16719                path: "/api/cart".into(),
16720            }),
16721            "validate must trip EntradaPathDuplicate on the second entry \
16722             of a two-entry cohort that shares a path — routing through \
16723             the lifted paths() accessor must not silently short-circuit \
16724             the dedup HashSet insert at the first entry",
16725        );
16726    }
16727
16728    // ── Entrada::hostname / Entrada::hostnames — the substrate-
16729    //    canonical per-`:entrada` DNS-hostname resolver pair every
16730    //    Gateway-API-aware renderer reaching for a per-listener
16731    //    singular `hostname:` filter (Gateway) or a per-route plural
16732    //    `spec.hostnames[]` filter list (HTTPRoute) routes through.
16733    //    The three pin tests below fix the two-way accept-set the pair
16734    //    must always honor: (:singular-byte-equal-to-host,
16735    //    :plural-is-singleton-of-singular, :plural-len-is-one) — drift
16736    //    on any arm surfaces at caixa-core build time rather than at
16737    //    cluster-apply time when the API server refuses the HTTPRoute
16738    //    for non-intersecting hostname filters. Peer discipline with
16739    //    the sibling `resolved_paths` accept-set pin block above on the
16740    //    per-`:entrada` path-list resolver axis.
16741
16742    fn entrada_with_host(host: &str) -> Entrada {
16743        Entrada {
16744            host: host.into(),
16745            para: "cart".into(),
16746            paths: Vec::new(),
16747            port: DEFAULT_SERVICO_PORT,
16748        }
16749    }
16750
16751    #[test]
16752    fn hostname_returns_entrada_host_byte_equal() {
16753        // The canonical singular-axis pin: [`Entrada::hostname`] must
16754        // return the `:entrada :host` field byte-for-byte, borrowed
16755        // from the typed slot's own [`String`] storage. Pins against a
16756        // future silent detour that re-normalized the host (an
16757        // accidental `.to_lowercase()` — validate_entrada_host already
16758        // enforces lowercase, so any re-normalization is redundant + a
16759        // drift surface between the validator and the accessor), a
16760        // trailing-`.` fully-qualified DNS shape substitution, or a
16761        // Punycode round-trip that lowered a Unicode host through IDNA.
16762        let e = entrada_with_host("checkout.quero.cloud");
16763        assert_eq!(
16764            e.hostname(),
16765            "checkout.quero.cloud",
16766            "Entrada::hostname must return :entrada :host verbatim \
16767             (got {:?})",
16768            e.hostname(),
16769        );
16770        assert_eq!(
16771            e.hostname(),
16772            e.host.as_str(),
16773            "Entrada::hostname must byte-equal the .host field access",
16774        );
16775    }
16776
16777    #[test]
16778    fn hostnames_returns_singleton_of_hostname_accessor() {
16779        // The pair-invariant pin: [`Entrada::hostnames`] must always
16780        // return exactly `vec![hostname()]` — the singleton list whose
16781        // sole entry is the substrate's canonical per-`:entrada`
16782        // singular hostname. Pins the two-consumer coherence axis: the
16783        // Gateway listener's singular `hostname:` filter and the
16784        // HTTPRoute's plural `spec.hostnames[]` filter list must
16785        // agree, else the Gateway API v1.x conformance layer rejects
16786        // the HTTPRoute at attach time with
16787        // `Accepted:False/NoMatchingParent` (the parent Gateway's
16788        // listener hostname doesn't intersect the route's hostname
16789        // filter list) — a divergence whose apply-time symptom is far
16790        // from any single-site commit and never surfaces in the
16791        // emitted YAML. Pinning the pair-invariant here makes any
16792        // future accidental split (an accidental `.to_string() + "."`
16793        // trailing-`.` on the plural side that didn't land on the
16794        // singular side, an accidental prefix stripping on one axis,
16795        // an accidental wildcard prepend the SNI fan-out overlay
16796        // authors on the plural side without a paired singular
16797        // migration) trip at caixa-core build time.
16798        let e = entrada_with_host("checkout.quero.cloud");
16799        assert_eq!(
16800            e.hostnames(),
16801            vec![e.hostname()],
16802            "Entrada::hostnames must return `vec![hostname()]` under \
16803             the pair-invariant — got {:?} vs. singleton {:?}",
16804            e.hostnames(),
16805            vec![e.hostname()],
16806        );
16807    }
16808
16809    #[test]
16810    fn hostnames_is_singleton_under_single_host_author_surface() {
16811        // The singleton-shape pin: under today's single-hostname-per-
16812        // `:entrada` author surface (the `:host` slot is a single
16813        // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
16814        // must always return a list of length exactly one. Pins
16815        // against a future silent detour that returned an empty list
16816        // (which would emit an HTTPRoute with `spec.hostnames: []` —
16817        // matching every incoming Host header regardless of the
16818        // Aplicacao's declared ingress apex, silently over-matching
16819        // every foreign VirtualHost the parent Gateway also fronts) or
16820        // a duplicated entry (which the Gateway API v1.x parser
16821        // accepts as a `[]-length-2 list of equal hostnames]` but
16822        // whose semantics differ from the intended singleton). The
16823        // author-surface extension point ("a future `:entrada
16824        // :alt-hosts` list overlay" the docstring names) is the sole
16825        // future axis that flips this pin — that migration will re-
16826        // author this test to pin the new plural cardinality.
16827        let e = entrada_with_host("checkout.quero.cloud");
16828        assert_eq!(
16829            e.hostnames().len(),
16830            1,
16831            "Entrada::hostnames must be a singleton under today's \
16832             single-hostname-per-`:entrada` author surface — got \
16833             length {}: {:?}",
16834            e.hostnames().len(),
16835            e.hostnames(),
16836        );
16837    }
16838
16839    // ── Entrada::destination — the substrate-canonical per-`:entrada`
16840    //    destination-Servico scalar accessor every Gateway-API
16841    //    HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
16842    //    discriminator arg (HTTPRoute name composer) or a per-rule
16843    //    `backendRefs[0].name` axis routes through. The two pin tests
16844    //    below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
16845    //    either arm surfaces at caixa-core build time rather than at
16846    //    cluster-apply time when an HTTPRoute's `metadata.name` and
16847    //    `backendRefs[]` silently disagree on which destination Servico
16848    //    the ingress fronts. Peer discipline with the sibling
16849    //    `resolved_paths` + `hostname` + `hostnames` accept-set pin
16850    //    blocks above on the per-`:entrada` path-list / DNS-hostname
16851    //    resolver axes.
16852
16853    #[test]
16854    fn destination_returns_entrada_para_byte_equal() {
16855        // The canonical destination-scalar pin: [`Entrada::destination`]
16856        // must return the `:entrada :para` field byte-for-byte, borrowed
16857        // from the typed slot's own [`String`] storage. Pins against a
16858        // future silent detour that re-normalized the destination (an
16859        // accidental `.to_lowercase()` — the destination Servico is
16860        // already validated as a DNS-1123 label upstream, so any
16861        // re-normalization is redundant + a drift surface between the
16862        // validator and the accessor), a namespace-prefix rewrite (an
16863        // accidental `format!("{namespace}/{para}")` per-CR fully-
16864        // qualified rewrite that didn't land on the peer axis), or a
16865        // per-cluster suffix stamp the operator authors on one
16866        // consumer without the other.
16867        for para in ["cart", "checkout", "catalog", "orders-v2"] {
16868            let e = Entrada {
16869                host: "checkout.quero.cloud".into(),
16870                para: para.into(),
16871                paths: Vec::new(),
16872                port: DEFAULT_SERVICO_PORT,
16873            };
16874            assert_eq!(
16875                e.destination(),
16876                para,
16877                "Entrada::destination must return :entrada :para verbatim \
16878                 (got {:?}, expected {para:?})",
16879                e.destination(),
16880            );
16881            assert_eq!(
16882                e.destination(),
16883                e.para.as_str(),
16884                "Entrada::destination must byte-equal the .para field access",
16885            );
16886        }
16887    }
16888
16889    #[test]
16890    fn destination_borrows_from_entrada_para_storage() {
16891        // The borrow-not-copy pin: [`Entrada::destination`] must
16892        // return a `&str` slice that borrows from the typed slot's
16893        // own [`String`] storage — same-address invariant with
16894        // `entrada.para.as_str()`. Pins against a future silent detour
16895        // that allocated a fresh `String` (`self.para.clone()` in the
16896        // body would type-check but silently drop the borrow, and
16897        // every downstream consumer that assumed the returned slice
16898        // outlives `&self` would break on a stale-reference use-after-
16899        // free). Peer with the sibling `hostname_returns_entrada_
16900        // host_byte_equal` on the singular-DNS-hostname axis.
16901        let e = entrada_with_host("checkout.quero.cloud");
16902        let dest = e.destination();
16903        let para_slice = e.para.as_str();
16904        assert_eq!(
16905            dest.as_ptr(),
16906            para_slice.as_ptr(),
16907            "Entrada::destination must borrow from the .para String's \
16908             backing storage — a fresh allocation here means the \
16909             accessor no longer names the substrate-primitive typed \
16910             dispatch and every downstream consumer would silently \
16911             carry a detached copy",
16912        );
16913        assert_eq!(
16914            dest.len(),
16915            para_slice.len(),
16916            "Entrada::destination and .para.as_str() must byte-equal in \
16917             length as well as in address",
16918        );
16919    }
16920
16921    #[test]
16922    fn port_returns_entrada_port_verbatim_across_permutations() {
16923        // The canonical L4-port-scalar pin: [`Entrada::port`] must
16924        // return the `:entrada :port` field verbatim as a `u16` across
16925        // every author-declared value in the validated accept-set
16926        // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
16927        // silent detour that clamped the port (an accidental
16928        // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
16929        // land on the peer [`AplicacaoSpec::port_for_destination`]
16930        // resolver), rewrote it through a per-cluster port-remap table
16931        // the operator authors on one consumer without the other, or
16932        // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
16933        // serde-default value (which would silently collapse the
16934        // distinction between "author explicitly declared `:port 8080`"
16935        // and "author omitted the slot and inherited the default" the
16936        // future per-cluster override slot depends on). Peer with the
16937        // sibling `destination_returns_entrada_para_byte_equal` +
16938        // `hostname_returns_entrada_host_byte_equal` pins on the
16939        // per-`:entrada` `&str` scalar axes.
16940        for port in [
16941            SERVICO_PORT_MIN,
16942            DEFAULT_SERVICO_PORT,
16943            8443u16,
16944            9090u16,
16945            u16::MAX,
16946        ] {
16947            let e = Entrada {
16948                host: "checkout.quero.cloud".into(),
16949                para: "cart".into(),
16950                paths: Vec::new(),
16951                port,
16952            };
16953            assert_eq!(
16954                e.port(),
16955                port,
16956                "Entrada::port must return :entrada :port verbatim \
16957                 (got {}, expected {port})",
16958                e.port(),
16959            );
16960            assert_eq!(
16961                e.port(),
16962                e.port,
16963                "Entrada::port accessor and .port field access must \
16964                 byte-equal — the accessor is the substrate-primitive \
16965                 typed dispatch every downstream L4-port consumer must \
16966                 route through",
16967            );
16968        }
16969    }
16970
16971    #[test]
16972    fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
16973        // Two-consumer coherence pin: the
16974        // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
16975        // (which reads through [`Entrada::port`] to compare against
16976        // [`SERVICO_PORT_MIN`]) and the
16977        // [`AplicacaoSpec::port_for_destination`] resolver (which reads
16978        // through [`Entrada::port`] to emit the per-destination
16979        // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
16980        // lifted accessor, so any future rebrand on the typed slot's
16981        // reader shape lands at exactly one place. Pins the two-site
16982        // coherence by exercising a below-floor port through validate
16983        // (which must reject) and a validated in-accept-set port through
16984        // port_for_destination (which must emit the same value the
16985        // accessor returns).
16986        let mut spec = three_member_spec();
16987        if let Some(e) = spec.entrada.as_mut() {
16988            e.port = 0;
16989        }
16990        assert_eq!(
16991            spec.validate().unwrap_err(),
16992            AplicacaoError::EntradaPortZero,
16993            "validate must reject `:entrada :port 0` through the lifted \
16994             Entrada::port accessor — port zero lies below \
16995             SERVICO_PORT_MIN and the validator routes through port() \
16996             to name the floor",
16997        );
16998
16999        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
17000            let mut spec = three_member_spec();
17001            if let Some(e) = spec.entrada.as_mut() {
17002                e.port = port;
17003            }
17004            spec.validate().expect(
17005                "entrada with in-accept-set :port must validate — the \
17006                 structural-floor gate reads through Entrada::port",
17007            );
17008            let entrada_ref = spec.entrada.as_ref().expect(":entrada present");
17009            assert_eq!(
17010                spec.port_for_destination(entrada_ref.destination()),
17011                entrada_ref.port(),
17012                "port_for_destination(entrada.destination()) must equal \
17013                 entrada.port() — the two consumers of the per-:entrada \
17014                 L4-port axis (validator, per-destination resolver) both \
17015                 route through Entrada::port",
17016            );
17017        }
17018    }
17019
17020    #[test]
17021    fn wit_contract_source_returns_de_byte_equal_across_permutations() {
17022        // The canonical caller-Servico-scalar pin: [`WitContract::source`]
17023        // must return the `:contratos :de` field byte-for-byte, borrowed
17024        // from the typed slot's own [`String`] storage. Peer of the
17025        // sibling `destination_returns_entrada_para_byte_equal` pin on
17026        // the per-`:entrada` axis — same "the substrate-primitive
17027        // accessor must byte-equal the raw field access verbatim across
17028        // every author-declared value" discipline extended to the
17029        // per-`:contratos` caller arm. Pins against a future silent
17030        // detour that re-normalized the caller (an accidental
17031        // `.to_lowercase()` — every `:contratos :de` is validated as a
17032        // DNS-1123 label upstream via `validate_contrato_caixa`, so any
17033        // re-normalization is redundant + a drift surface between the
17034        // validator and the accessor), a namespace-prefix rewrite (an
17035        // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
17036        // rewrite that didn't land on the peer axis), or a per-cluster
17037        // suffix stamp the operator authors on one consumer without the
17038        // other.
17039        for de in ["cart", "checkout", "catalog", "orders-v2"] {
17040            let c = WitContract {
17041                de: de.into(),
17042                para: "downstream".into(),
17043                wit: "wasi:http/proxy".into(),
17044                endpoint: Some("/lookup".into()),
17045                subject: None,
17046                slot: None,
17047            };
17048            assert_eq!(
17049                c.source(),
17050                de,
17051                "WitContract::source must return :contratos :de verbatim \
17052                 (got {:?}, expected {de:?})",
17053                c.source(),
17054            );
17055            assert_eq!(
17056                c.source(),
17057                c.de.as_str(),
17058                "WitContract::source must byte-equal the .de field access",
17059            );
17060        }
17061    }
17062
17063    #[test]
17064    fn wit_contract_source_borrows_from_de_storage() {
17065        // The borrow-not-copy pin: [`WitContract::source`] must return a
17066        // `&str` slice that borrows from the typed slot's own [`String`]
17067        // storage — same-address invariant with `c.de.as_str()`. Pins
17068        // against a future silent detour that allocated a fresh `String`
17069        // (`self.de.clone()` in the body would type-check but silently
17070        // drop the borrow, and every downstream consumer that assumed
17071        // the returned slice outlives `&self` would break on a stale-
17072        // reference use-after-free). Peer of the sibling
17073        // `destination_borrows_from_entrada_para_storage` on the
17074        // per-`:entrada` axis.
17075        let c = WitContract {
17076            de: "cart".into(),
17077            para: "catalog".into(),
17078            wit: "wasi:http/proxy".into(),
17079            endpoint: Some("/lookup".into()),
17080            subject: None,
17081            slot: None,
17082        };
17083        let src = c.source();
17084        let de_slice = c.de.as_str();
17085        assert_eq!(
17086            src.as_ptr(),
17087            de_slice.as_ptr(),
17088            "WitContract::source must borrow from the .de String's \
17089             backing storage — a fresh allocation here means the \
17090             accessor no longer names the substrate-primitive typed \
17091             dispatch and every downstream consumer would silently \
17092             carry a detached copy",
17093        );
17094        assert_eq!(
17095            src.len(),
17096            de_slice.len(),
17097            "WitContract::source and .de.as_str() must byte-equal in \
17098             length as well as in address",
17099        );
17100    }
17101
17102    #[test]
17103    fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
17104        // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
17105        // must return the `:contratos :para` field byte-for-byte,
17106        // borrowed from the typed slot's own [`String`] storage. Peer of
17107        // the sibling `destination_returns_entrada_para_byte_equal` on
17108        // the per-`:entrada` axis — both accessors name "the destination-
17109        // Servico byte-string" concept on their respective mesh-slot
17110        // atoms (per-ingress apex vs. per-typed-edge callee) and both
17111        // must project the underlying `.para` field verbatim so every
17112        // downstream renderer that composes them with peer accessors
17113        // (e.g. `spec.port_for_destination(c.destination())` at the CNP
17114        // per-edge L4 port emit site) reads the same byte-string the
17115        // author declared.
17116        for para in ["catalog", "payment", "orders", "inventory-v3"] {
17117            let c = WitContract {
17118                de: "cart".into(),
17119                para: para.into(),
17120                wit: "wasi:http/proxy".into(),
17121                endpoint: Some("/lookup".into()),
17122                subject: None,
17123                slot: None,
17124            };
17125            assert_eq!(
17126                c.destination(),
17127                para,
17128                "WitContract::destination must return :contratos :para \
17129                 verbatim (got {:?}, expected {para:?})",
17130                c.destination(),
17131            );
17132            assert_eq!(
17133                c.destination(),
17134                c.para.as_str(),
17135                "WitContract::destination must byte-equal the .para \
17136                 field access",
17137            );
17138        }
17139    }
17140
17141    #[test]
17142    fn wit_contract_destination_borrows_from_para_storage() {
17143        // The borrow-not-copy pin: [`WitContract::destination`] must
17144        // return a `&str` slice that borrows from the typed slot's own
17145        // [`String`] storage — same-address invariant with
17146        // `c.para.as_str()`. Peer of the sibling
17147        // `destination_borrows_from_entrada_para_storage` on the
17148        // per-`:entrada` axis.
17149        let c = WitContract {
17150            de: "cart".into(),
17151            para: "catalog".into(),
17152            wit: "wasi:http/proxy".into(),
17153            endpoint: Some("/lookup".into()),
17154            subject: None,
17155            slot: None,
17156        };
17157        let dest = c.destination();
17158        let para_slice = c.para.as_str();
17159        assert_eq!(
17160            dest.as_ptr(),
17161            para_slice.as_ptr(),
17162            "WitContract::destination must borrow from the .para \
17163             String's backing storage — a fresh allocation here means \
17164             the accessor no longer names the substrate-primitive typed \
17165             dispatch and every downstream consumer would silently \
17166             carry a detached copy",
17167        );
17168        assert_eq!(
17169            dest.len(),
17170            para_slice.len(),
17171            "WitContract::destination and .para.as_str() must byte-equal \
17172             in length as well as in address",
17173        );
17174    }
17175
17176    #[test]
17177    fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
17178        // The canonical per-`:contratos` WIT-world-reference scalar pin:
17179        // [`WitContract::world_ref`] must return the `:contratos :wit`
17180        // field byte-for-byte, borrowed from the typed slot's own
17181        // [`String`] storage. Sibling of the peer per-`:contratos`
17182        // [`WitContract::source`] / [`WitContract::destination`]
17183        // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
17184        // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
17185        // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
17186        // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
17187        // "the substrate-primitive accessor must byte-equal the raw
17188        // field access verbatim across every author-declared value"
17189        // discipline extended to the per-`:contratos` WIT-world arm.
17190        // Pins against a future silent detour that re-canonicalized the
17191        // WIT world reference (an accidental `.to_lowercase()` pass that
17192        // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
17193        // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
17194        // gate is already lowercase-prefixed so any re-normalization is
17195        // redundant + a drift surface between the validator and the
17196        // accessor), an M4-promotion-shape rewrite that formatted a
17197        // typed WIT-world enum through [`Display`] and silently drifted
17198        // the printer output from the source `caixa.lisp`, or a per-
17199        // cluster WIT-alias rewrite that didn't land on the peer field-
17200        // access sites. Five values sweep the shape-dispatch accept-set
17201        // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
17202        // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
17203        // `wasi:keyvalue/`).
17204        for (wit, endpoint, subject, slot) in [
17205            ("wasi:http/proxy", Some("/lookup"), None, None),
17206            ("http:proxy", Some("/health"), None, None),
17207            ("nats:pub-sub", None, Some("orders.paid"), None),
17208            ("kafka:events", None, Some("checkout-events"), None),
17209            ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
17210        ] {
17211            let c = WitContract {
17212                de: "cart".into(),
17213                para: "downstream".into(),
17214                wit: wit.into(),
17215                endpoint: endpoint.map(str::to_string),
17216                subject: subject.map(str::to_string),
17217                slot: slot.map(str::to_string),
17218            };
17219            assert_eq!(
17220                c.world_ref(),
17221                wit,
17222                "WitContract::world_ref must return :contratos :wit \
17223                 verbatim (got {:?}, expected {wit:?})",
17224                c.world_ref(),
17225            );
17226            assert_eq!(
17227                c.world_ref(),
17228                c.wit.as_str(),
17229                "WitContract::world_ref must byte-equal the .wit field \
17230                 access",
17231            );
17232        }
17233    }
17234
17235    #[test]
17236    fn wit_contract_world_ref_borrows_from_wit_storage() {
17237        // The borrow-not-copy pin: [`WitContract::world_ref`] must
17238        // return a `&str` slice that borrows from the typed slot's own
17239        // [`String`] storage — same-address invariant with
17240        // `c.wit.as_str()`. Pins against a future silent detour that
17241        // allocated a fresh `String` (`self.wit.clone()` in the body
17242        // would type-check but silently drop the borrow, and every
17243        // downstream consumer that assumed the returned slice outlives
17244        // `&self` would break on a stale-reference use-after-free — the
17245        // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
17246        // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
17247        // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
17248        // / [`is_pubsub`][WitContract::is_pubsub] /
17249        // [`is_store`][WitContract::is_store] methods route through —
17250        // each borrow from the WitContract's own storage and each would
17251        // silently misbehave if this accessor produced a detached copy).
17252        // Peer of the sibling per-`:contratos` [`WitContract::source`] /
17253        // [`WitContract::destination`] and per-`:entrada`
17254        // [`Entrada::destination`] / [`Entrada::hostname`] and
17255        // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
17256        // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
17257        let c = WitContract {
17258            de: "cart".into(),
17259            para: "catalog".into(),
17260            wit: "wasi:http/proxy".into(),
17261            endpoint: Some("/lookup".into()),
17262            subject: None,
17263            slot: None,
17264        };
17265        let world = c.world_ref();
17266        let wit_slice = c.wit.as_str();
17267        assert_eq!(
17268            world.as_ptr(),
17269            wit_slice.as_ptr(),
17270            "WitContract::world_ref must borrow from the .wit String's \
17271             backing storage — a fresh allocation here means the \
17272             accessor no longer names the substrate-primitive typed \
17273             dispatch and every downstream consumer would silently carry \
17274             a detached copy",
17275        );
17276        assert_eq!(
17277            world.len(),
17278            wit_slice.len(),
17279            "WitContract::world_ref and .wit.as_str() must byte-equal in \
17280             length as well as in address",
17281        );
17282    }
17283
17284    #[test]
17285    fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
17286        // Sibling-triple invariant pin composing all three per-`:contratos`
17287        // substrate-primitive typed dispatches — [`WitContract::source`]
17288        // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
17289        // [`WitContract::world_ref`] — at the joint
17290        // `(source(), destination(), world_ref())` call shape every
17291        // renderer that fans on per-edge caller-callee-shape identity
17292        // keys off. The invariant, evaluated per-contract:
17293        //
17294        //   (c.source(), c.destination(), c.world_ref())
17295        //   == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
17296        //
17297        // Closes the last unlifted per-`:contratos` scalar axis — every
17298        // downstream consumer that reads the triple now routes through
17299        // exactly three typed dispatches on the substrate primitive,
17300        // not two typed + one open-coded field access. A future refactor
17301        // that silently split any one accessor's projection (an
17302        // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
17303        // canonicalization that didn't reach the peer `source`/
17304        // `destination` arms, an accidental `source()` per-cluster
17305        // caller-alias rewrite that didn't land on the `world_ref` peer)
17306        // surfaces at caixa-core build time. Peer of the sibling per-
17307        // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
17308        // per-`:entrada` `(hostname(), destination())` (6db982c /
17309        // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
17310        // axes, extended to the per-`:contratos` triple.
17311        for (de, para, wit, endpoint, subject, slot) in [
17312            (
17313                "cart",
17314                "catalog",
17315                "wasi:http/proxy",
17316                Some("/lookup"),
17317                None,
17318                None,
17319            ),
17320            (
17321                "checkout",
17322                "orders",
17323                "nats:pub-sub",
17324                None,
17325                Some("orders.paid"),
17326                None,
17327            ),
17328            (
17329                "cart",
17330                "kv",
17331                "wasi:keyvalue/store",
17332                None,
17333                None,
17334                Some("carts/{cart_id}"),
17335            ),
17336            (
17337                "orders-v2",
17338                "inventory-v3",
17339                "http:proxy",
17340                Some("/reserve"),
17341                None,
17342                None,
17343            ),
17344        ] {
17345            let c = WitContract {
17346                de: de.into(),
17347                para: para.into(),
17348                wit: wit.into(),
17349                endpoint: endpoint.map(str::to_string),
17350                subject: subject.map(str::to_string),
17351                slot: slot.map(str::to_string),
17352            };
17353            assert_eq!(
17354                (c.source(), c.destination(), c.world_ref()),
17355                (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
17356                "(WitContract::source, ::destination, ::world_ref) must \
17357                 project (.de, .para, .wit) verbatim across every author-\
17358                 declared triple (got ({:?}, {:?}, {:?}), expected \
17359                 ({de:?}, {para:?}, {wit:?}))",
17360                c.source(),
17361                c.destination(),
17362                c.world_ref(),
17363            );
17364        }
17365    }
17366
17367    #[test]
17368    fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
17369        // The canonical per-`:contratos` owned-form caller-callee-pair
17370        // pin: [`WitContract::edge_pair`] must return the
17371        // `(source(), destination())` tuple in owned form byte-for-byte,
17372        // projected through the lifted [`WitContract::source`] /
17373        // [`WitContract::destination`] scalar accessors. Pins the
17374        // composite-projection invariant on the per-`:contratos`
17375        // mesh-slot atom — every author-declared `(de, para)` pair must
17376        // round-trip verbatim through the substrate primitive's typed
17377        // dispatch, so the nine [`AplicacaoError`] diagnostic-
17378        // construction sites the accessor now feeds
17379        // ([`AplicacaoError::EmptyWit`],
17380        // [`AplicacaoError::ContratoEndpointEmpty`],
17381        // [`AplicacaoError::ContratoEndpointNotAbsolute`],
17382        // [`AplicacaoError::ContratoEndpointInvalid`],
17383        // [`AplicacaoError::ContratoSubjectEmpty`],
17384        // [`AplicacaoError::ContratoSubjectInvalid`],
17385        // [`AplicacaoError::ContratoSlotEmpty`],
17386        // [`AplicacaoError::ContratoSlotInvalid`],
17387        // [`AplicacaoError::ContratoDuplicate`]) all read the same
17388        // `(de, para)` label pair every author sees at the source
17389        // `caixa.lisp`. Pins against a future silent detour that swapped
17390        // the `.0` / `.1` arms (an accidental `(destination(),
17391        // source())` re-order in the body would silently invert every
17392        // downstream diagnostic's `de:` / `para:` label pair, silently
17393        // reversing the direction of every operator-facing typed error
17394        // arrow), a fresh-allocation shape drift (an accidental
17395        // `.to_string()` on one arm but not the other would leave the
17396        // owned/borrowed pair mismatched vs. the sibling `source()` /
17397        // `destination()` returns), or an M4 per-cluster caller/callee-
17398        // alias rewrite that landed on `source()` without reaching
17399        // `destination()` (or vice versa). Peer of the sibling per-
17400        // `:contratos` `(source, destination, world_ref)` triple
17401        // pin above on the mesh-slot-atom scalar-value axes, extended
17402        // to the owned-form pair-projection axis.
17403        for (de, para, wit, endpoint, subject, slot) in [
17404            (
17405                "cart",
17406                "catalog",
17407                "wasi:http/proxy",
17408                Some("/lookup"),
17409                None,
17410                None,
17411            ),
17412            (
17413                "checkout",
17414                "orders",
17415                "nats:pub-sub",
17416                None,
17417                Some("orders.paid"),
17418                None,
17419            ),
17420            (
17421                "cart",
17422                "kv",
17423                "wasi:keyvalue/store",
17424                None,
17425                None,
17426                Some("carts/{cart_id}"),
17427            ),
17428            (
17429                "orders-v2",
17430                "inventory-v3",
17431                "http:proxy",
17432                Some("/reserve"),
17433                None,
17434                None,
17435            ),
17436        ] {
17437            let c = WitContract {
17438                de: de.into(),
17439                para: para.into(),
17440                wit: wit.into(),
17441                endpoint: endpoint.map(str::to_string),
17442                subject: subject.map(str::to_string),
17443                slot: slot.map(str::to_string),
17444            };
17445            assert_eq!(
17446                c.edge_pair(),
17447                (de.to_string(), para.to_string()),
17448                "WitContract::edge_pair must return (:contratos :de, \
17449                 :contratos :para) as an owned tuple verbatim (got {:?}, \
17450                 expected ({de:?}, {para:?}))",
17451                c.edge_pair(),
17452            );
17453        }
17454    }
17455
17456    #[test]
17457    fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
17458        // The composition pin: [`WitContract::edge_pair`] must return
17459        // exactly `(source().to_string(), destination().to_string())` —
17460        // the owned form of the sibling accessor pair — so any future
17461        // refactor that silently re-authored the caller-arm / callee-arm
17462        // projection to bypass the lifted scalar accessors (an accidental
17463        // `(self.de.clone(), self.para.clone())` regression back to the
17464        // raw field-access shape, an M4-typed-caller-enum `Display`
17465        // re-canonicalization on `source()` that didn't reach
17466        // `edge_pair()`, a per-cluster alias rewrite the operator lands
17467        // on `destination()` without reaching this composite projection)
17468        // trips at caixa-core build time. Pins the "typed dispatch
17469        // composes with typed dispatch, not with raw field access"
17470        // discipline every downstream diagnostic-construction site now
17471        // routes through — a `de:` / `para:` label pair whose
17472        // projection silently drifted off the substrate primitive's
17473        // scalar accessors would silently split the diagnostic's self-
17474        // locating signal from the source `caixa.lisp` author's view.
17475        // Peer of the sibling per-`:politicas` `is_empty` /
17476        // `validate_politicas` accessor-routing-pin family on the M3
17477        // mesh-slot family (18575, 18739, 18918, 19140, 19371).
17478        let c = WitContract {
17479            de: "cart".into(),
17480            para: "catalog".into(),
17481            wit: "wasi:http/proxy".into(),
17482            endpoint: Some("/lookup".into()),
17483            subject: None,
17484            slot: None,
17485        };
17486        assert_eq!(
17487            c.edge_pair(),
17488            (c.source().to_string(), c.destination().to_string()),
17489            "WitContract::edge_pair must compose exactly \
17490             (source().to_string(), destination().to_string()) — a \
17491             bypass of either sibling accessor here would silently \
17492             decouple the composite-projection axis from the \
17493             substrate-primitive scalar accessors every downstream \
17494             consumer routes through",
17495        );
17496    }
17497
17498    #[test]
17499    fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
17500     {
17501        // The canonical per-`:contratos` owned-form
17502        // caller-callee-world-ref-triple pin:
17503        // [`WitContract::edge_triple`] must return the
17504        // `(source(), destination(), world_ref())` tuple in owned form
17505        // byte-for-byte, projected through the lifted
17506        // [`WitContract::source`] / [`WitContract::destination`] /
17507        // [`WitContract::world_ref`] scalar accessors. Pins the
17508        // composite-projection invariant on the per-`:contratos`
17509        // mesh-slot atom — every author-declared `(de, para, wit)`
17510        // triple must round-trip verbatim through the substrate
17511        // primitive's typed dispatch, so the nine
17512        // [`AplicacaoError`] diagnostic-construction sites the
17513        // accessor now feeds (the [`WitTarget`]-dispatch's eight
17514        // wrong-target / missing-target / invalid-wit / capability-
17515        // with-payload arms in [`WitContract::target`], plus the
17516        // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
17517        // diagnostic constructor in [`AplicacaoSpec::validate`]) all
17518        // read the same `(de, para, wit)` triple every author sees at
17519        // the source `caixa.lisp`. Pins against a future silent
17520        // detour that swapped any two arms (an accidental `(destination(),
17521        // source(), world_ref())` re-order in the body would silently
17522        // invert every downstream diagnostic's `de:` / `para:` label
17523        // pair, silently reversing the direction of every operator-
17524        // facing typed error arrow), a fresh-allocation shape drift
17525        // (an accidental `.to_string()` skipped on one arm would leave
17526        // the owned/borrowed triple mismatched vs. the sibling
17527        // `source()` / `destination()` / `world_ref()` returns), or an
17528        // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
17529        // canonicalization pass that landed on one accessor without
17530        // reaching the peers. Peer of the sibling per-`:contratos`
17531        // caller-callee-pair
17532        // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
17533        // pin on the mesh-slot-atom composite-projection axis,
17534        // extended to the triple-projection axis.
17535        for (de, para, wit, endpoint, subject, slot) in [
17536            (
17537                "cart",
17538                "catalog",
17539                "wasi:http/proxy",
17540                Some("/lookup"),
17541                None,
17542                None,
17543            ),
17544            (
17545                "checkout",
17546                "orders",
17547                "nats:pub-sub",
17548                None,
17549                Some("orders.paid"),
17550                None,
17551            ),
17552            (
17553                "cart",
17554                "kv",
17555                "wasi:keyvalue/store",
17556                None,
17557                None,
17558                Some("carts/{cart_id}"),
17559            ),
17560            (
17561                "orders-v2",
17562                "inventory-v3",
17563                "http:proxy",
17564                Some("/reserve"),
17565                None,
17566                None,
17567            ),
17568        ] {
17569            let c = WitContract {
17570                de: de.into(),
17571                para: para.into(),
17572                wit: wit.into(),
17573                endpoint: endpoint.map(str::to_string),
17574                subject: subject.map(str::to_string),
17575                slot: slot.map(str::to_string),
17576            };
17577            assert_eq!(
17578                c.edge_triple(),
17579                (de.to_string(), para.to_string(), wit.to_string()),
17580                "WitContract::edge_triple must return (:contratos :de, \
17581                 :contratos :para, :contratos :wit) as an owned triple \
17582                 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
17583                c.edge_triple(),
17584            );
17585        }
17586    }
17587
17588    #[test]
17589    fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
17590        // The composition pin: [`WitContract::edge_triple`] must return
17591        // exactly `(source().to_string(), destination().to_string(),
17592        // world_ref().to_string())` — the owned form of the sibling
17593        // scalar-accessor triple — so any future refactor that silently
17594        // re-authored one arm's projection to bypass the lifted scalar
17595        // accessors (an accidental `(self.de.clone(), self.para.clone(),
17596        // self.wit.clone())` regression back to the raw field-access
17597        // shape the internal `edge` closure and the ContratoDuplicate
17598        // diagnostic both carried before this lift landed, an
17599        // M4-typed-caller-enum `Display` re-canonicalization on
17600        // `source()` that didn't reach `edge_triple()`, a per-cluster
17601        // alias rewrite the operator lands on `destination()` /
17602        // `world_ref()` without reaching this composite projection)
17603        // trips at caixa-core build time. Pins the "typed dispatch
17604        // composes with typed dispatch, not with raw field access"
17605        // discipline every downstream diagnostic-construction site now
17606        // routes through — a `de:` / `para:` / `wit:` triple whose
17607        // projection silently drifted off the substrate primitive's
17608        // scalar accessors would silently split the diagnostic's self-
17609        // locating signal from the source `caixa.lisp` author's view.
17610        // Peer of the sibling per-`:contratos` edge_pair composition-
17611        // pin above on the mesh-slot-atom composite-projection axis.
17612        let c = WitContract {
17613            de: "cart".into(),
17614            para: "catalog".into(),
17615            wit: "wasi:http/proxy".into(),
17616            endpoint: Some("/lookup".into()),
17617            subject: None,
17618            slot: None,
17619        };
17620        assert_eq!(
17621            c.edge_triple(),
17622            (
17623                c.source().to_string(),
17624                c.destination().to_string(),
17625                c.world_ref().to_string(),
17626            ),
17627            "WitContract::edge_triple must compose exactly \
17628             (source().to_string(), destination().to_string(), \
17629             world_ref().to_string()) — a bypass of any sibling accessor \
17630             here would silently decouple the composite-projection axis \
17631             from the substrate-primitive scalar accessors every \
17632             downstream consumer routes through",
17633        );
17634    }
17635
17636    #[test]
17637    fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
17638        // The canonical semantics-pin: [`WitContract::edge_triple`] must
17639        // project the full `(de, para, wit)` identity of a `:contratos`
17640        // edge — the sub-triple every triple-carrying
17641        // [`AplicacaoError::Contrato*`] diagnostic weaves into its
17642        // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
17643        // missing-target, capability-with-payload, invalid-wit, and the
17644        // duplicate-gate). Rejects a drift in shape (an accidental
17645        // silent detour that returned a `(de, para)` pair or added an
17646        // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
17647        // would trip here because the return type would no longer
17648        // pattern-match the eight `let (de, para, wit) = edge();`
17649        // destructures the [`WitContract::target`] dispatch feeds off
17650        // + the paired duplicate-gate `let (de, para, wit) =
17651        // c.edge_triple();` destructure in
17652        // [`AplicacaoSpec::validate`]). Peer of the sibling per-
17653        // `:contratos` caller-callee-pair pin above extended to the
17654        // triple projection surface: closes the "one composite
17655        // accessor per typed diagnostic-construction sub-tuple"
17656        // discipline on the per-`:contratos` mesh-slot-atom axis.
17657        let c = WitContract {
17658            de: "checkout".into(),
17659            para: "orders".into(),
17660            wit: "nats:pub-sub".into(),
17661            endpoint: None,
17662            subject: Some("orders.paid".into()),
17663            slot: None,
17664        };
17665        let (de, para, wit) = c.edge_triple();
17666        assert_eq!(de, "checkout");
17667        assert_eq!(para, "orders");
17668        assert_eq!(wit, "nats:pub-sub");
17669    }
17670
17671    #[test]
17672    fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
17673        // The canonical per-`:contratos` structural-self-edge pin:
17674        // [`WitContract::is_self_loop`] must return `true` when the
17675        // `:de` and `:para` fields agree byte-for-byte, across every
17676        // WIT-shape variant the per-edge shape family carries. Pins
17677        // the shape-agnostic identity-space partition the
17678        // [`AplicacaoSpec::validate`] self-edge gate at
17679        // caixa-core/src/aplicacao.rs:5559 fires against — all four
17680        // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
17681        // under the same one predicate. Four permutations sweep the
17682        // accept-set: HTTP with endpoint, pub-sub with subject, KV
17683        // store with slot, and payload-less capability.
17684        for (nome, wit, endpoint, subject, slot) in [
17685            ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
17686            ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
17687            (
17688                "kv",
17689                "wasi:keyvalue/store",
17690                None,
17691                None,
17692                Some("carts/{cart_id}"),
17693            ),
17694            ("audit", "wasi:logging", None, None, None),
17695        ] {
17696            let c = WitContract {
17697                de: nome.into(),
17698                para: nome.into(),
17699                wit: wit.into(),
17700                endpoint: endpoint.map(str::to_string),
17701                subject: subject.map(str::to_string),
17702                slot: slot.map(str::to_string),
17703            };
17704            assert!(
17705                c.is_self_loop(),
17706                "WitContract::is_self_loop must return true when \
17707                 :contratos :de == :contratos :para (got false on \
17708                 {nome:?} under {wit:?})",
17709            );
17710        }
17711    }
17712
17713    #[test]
17714    fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
17715        // The complement pin: [`WitContract::is_self_loop`] must return
17716        // `false` on every well-shaped inter-Servico contract (the
17717        // author-intended `:contratos` shape MESH-COMPOSITION §III.1
17718        // names — "Servico A calls Servico B" between two distinct
17719        // graph nodes). Pins against a future silent detour that
17720        // inverted the predicate (an accidental `!= ` swap for `==`
17721        // would silently reject every legitimate inter-Servico edge
17722        // and admit every self-edge — the exact inversion of the
17723        // author-intended shape). Four permutations sweep the same
17724        // WIT-shape accept-set the sibling positive-arm test carries.
17725        for (de, para, wit, endpoint, subject, slot) in [
17726            (
17727                "cart",
17728                "catalog",
17729                "wasi:http/proxy",
17730                Some("/lookup"),
17731                None,
17732                None,
17733            ),
17734            (
17735                "checkout",
17736                "orders",
17737                "nats:pub-sub",
17738                None,
17739                Some("orders.paid"),
17740                None,
17741            ),
17742            (
17743                "cart",
17744                "kv",
17745                "wasi:keyvalue/store",
17746                None,
17747                None,
17748                Some("carts/{cart_id}"),
17749            ),
17750            ("audit", "sink", "wasi:logging", None, None, None),
17751        ] {
17752            let c = WitContract {
17753                de: de.into(),
17754                para: para.into(),
17755                wit: wit.into(),
17756                endpoint: endpoint.map(str::to_string),
17757                subject: subject.map(str::to_string),
17758                slot: slot.map(str::to_string),
17759            };
17760            assert!(
17761                !c.is_self_loop(),
17762                "WitContract::is_self_loop must return false when \
17763                 :contratos :de differs from :contratos :para (got true \
17764                 on {de:?} → {para:?} under {wit:?})",
17765            );
17766        }
17767    }
17768
17769    #[test]
17770    fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
17771        // The composition pin: [`WitContract::is_self_loop`] must
17772        // resolve to exactly `self.source() == self.destination()` —
17773        // the equality probe of the sibling scalar-accessor pair — so
17774        // any future refactor that silently re-authored the predicate
17775        // to bypass the lifted scalar accessors (an accidental
17776        // `self.de == self.para` regression back to the raw field-
17777        // access shape, an M4-typed-caller-enum identity-comparison
17778        // rule that landed on `source()` without reaching
17779        // `destination()`, a per-cluster alias rewrite the operator
17780        // pins on `destination()` without reaching this predicate)
17781        // trips at caixa-core build time. Pins the "typed dispatch
17782        // composes with typed dispatch, not with raw field access"
17783        // discipline the sibling [`WitContract::edge_pair`] /
17784        // [`WitContract::edge_triple`] composite-projection accessors
17785        // already carry, extended onto the per-edge endpoint-equality
17786        // predicate axis. Positive and complement arms both fire.
17787        let self_edge = WitContract {
17788            de: "cart".into(),
17789            para: "cart".into(),
17790            wit: "wasi:http/proxy".into(),
17791            endpoint: Some("/lookup".into()),
17792            subject: None,
17793            slot: None,
17794        };
17795        assert_eq!(
17796            self_edge.is_self_loop(),
17797            self_edge.source() == self_edge.destination(),
17798            "WitContract::is_self_loop must compose exactly \
17799             `source() == destination()` — a bypass of either sibling \
17800             accessor here would silently decouple the endpoint-\
17801             equality predicate from the substrate-primitive scalar \
17802             accessors every downstream consumer routes through",
17803        );
17804        let inter_edge = WitContract {
17805            de: "cart".into(),
17806            para: "catalog".into(),
17807            wit: "wasi:http/proxy".into(),
17808            endpoint: Some("/lookup".into()),
17809            subject: None,
17810            slot: None,
17811        };
17812        assert_eq!(
17813            inter_edge.is_self_loop(),
17814            inter_edge.source() == inter_edge.destination(),
17815            "WitContract::is_self_loop must compose exactly \
17816             `source() == destination()` on the complement arm too",
17817        );
17818    }
17819
17820    #[test]
17821    fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
17822        // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
17823        // pin: [`WitContract::endpoint`] must return the `:contratos
17824        // :endpoint` field byte-for-byte, borrowed from the typed slot's
17825        // own `Option<String>` storage. Peer of the sibling
17826        // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
17827        // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
17828        // mesh-slot `Option<String>` optional-scalar axes — same "the
17829        // substrate-primitive accessor must byte-equal the raw field
17830        // access verbatim across every author-declared value" discipline
17831        // extended to the per-`:contratos` HTTP-payload-carrier arm.
17832        // Pins against a future silent detour that re-canonicalized the
17833        // endpoint (an accidental percent-encoding pass that didn't
17834        // reach the peer field-access site at the dedup key, a per-CR
17835        // fully-qualified prefix rewrite the operator authors on one
17836        // consumer without the other, or an M4 typed-path-template
17837        // `Display` re-canonicalization that silently drifted the
17838        // printer output from the source `caixa.lisp`). Four values
17839        // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
17840        // gate upstream admits (short root-path, dashed, param-shaped,
17841        // deep-hierarchy).
17842        for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
17843            let c = WitContract {
17844                de: "cart".into(),
17845                para: "catalog".into(),
17846                wit: "wasi:http/proxy".into(),
17847                endpoint: Some(endpoint.into()),
17848                subject: None,
17849                slot: None,
17850            };
17851            assert_eq!(
17852                c.endpoint(),
17853                Some(endpoint),
17854                "WitContract::endpoint must return :contratos :endpoint \
17855                 verbatim (got {:?}, expected Some({endpoint:?}))",
17856                c.endpoint(),
17857            );
17858            assert_eq!(
17859                c.endpoint(),
17860                c.endpoint.as_deref(),
17861                "WitContract::endpoint must byte-equal the .endpoint \
17862                 field's `.as_deref()` projection",
17863            );
17864        }
17865    }
17866
17867    #[test]
17868    fn wit_contract_endpoint_none_when_field_is_none() {
17869        // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
17870        // payload-carrier accessor pin: when the typed slot is absent —
17871        // the canonical shape under a non-HTTP `:wit` world per the
17872        // [`WitContract::target`]-enforced shape ↔ target partition
17873        // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
17874        // carries `:slot`, [`WitTarget::Capability`] carries none) —
17875        // [`WitContract::endpoint`] must return `None`. Pins against a
17876        // future silent detour that projected the absent slot to a
17877        // `Some("")` empty-string default (the canonical `Option<String>`
17878        // → `String` collapse footgun the sibling M2
17879        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
17880        // emptiness predicates already guard on the peer M2 typed-slot
17881        // surfaces), a `Some("None")` stringified-None round-trip, or a
17882        // `Some` arm whose contents were derived from a sibling slot (an
17883        // accidental fallback to the `:subject` / `:slot` payload that
17884        // read the pub-sub / store payload into the endpoint axis).
17885        // Three contracts sweep the accept-set every non-HTTP `:wit`
17886        // world lands on — pub-sub NATS, key/value, and payload-less
17887        // capability.
17888        for (wit, subject, slot) in [
17889            ("nats:pub-sub", Some("orders.paid"), None),
17890            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
17891            ("wasi:cli/environment", None, None),
17892        ] {
17893            let c = WitContract {
17894                de: "cart".into(),
17895                para: "downstream".into(),
17896                wit: wit.into(),
17897                endpoint: None,
17898                subject: subject.map(str::to_string),
17899                slot: slot.map(str::to_string),
17900            };
17901            assert!(
17902                c.endpoint().is_none(),
17903                "WitContract::endpoint must return None when the typed \
17904                 slot is absent under :wit {wit:?} (got {:?})",
17905                c.endpoint(),
17906            );
17907            assert_eq!(
17908                c.endpoint(),
17909                c.endpoint.as_deref(),
17910                "WitContract::endpoint must byte-equal the .endpoint \
17911                 field's `.as_deref()` projection in the absent arm",
17912            );
17913        }
17914    }
17915
17916    #[test]
17917    fn wit_contract_endpoint_borrows_from_endpoint_storage() {
17918        // The borrow-not-copy pin: [`WitContract::endpoint`] must return
17919        // an `Option<&str>` whose `Some` arm borrows from the typed
17920        // slot's own [`String`] storage — same-address invariant with
17921        // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
17922        // detour that allocated a fresh `String`
17923        // (`self.endpoint.clone().map(...)` in the body would type-check
17924        // but silently drop the borrow, and every downstream consumer
17925        // that assumed the returned slice outlives `&self` would break
17926        // on a stale-reference use-after-free — the [`WitContract::target`]
17927        // Http-arm payload extraction rebinds the returned `Option<&str>`
17928        // through `.ok_or_else(...)` and threads the `&str` payload into
17929        // [`WitTarget::Http { endpoint: &'a str }`], the
17930        // [`AplicacaoSpec::validate`] duplicate-`:contratos`
17931        // [`ContratoIdentity`] dedup key threads the returned
17932        // `Option<&str>` into the six-tuple's HTTP arm — each borrow
17933        // from the WitContract's own storage and each would silently
17934        // misbehave if this accessor produced a detached copy). Peer of
17935        // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
17936        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
17937        // shaped optional-scalar axes — first extension of the
17938        // `Option<&str>` borrow-not-copy discipline onto the
17939        // per-`:contratos` HTTP-shaped payload-carrier axis.
17940        let c = WitContract {
17941            de: "cart".into(),
17942            para: "catalog".into(),
17943            wit: "wasi:http/proxy".into(),
17944            endpoint: Some("/lookup".into()),
17945            subject: None,
17946            slot: None,
17947        };
17948        let ep = c.endpoint().expect("Some arm");
17949        let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
17950        assert_eq!(
17951            ep.as_ptr(),
17952            storage_slice.as_ptr(),
17953            "WitContract::endpoint must borrow from the .endpoint \
17954             String's backing storage — a fresh allocation here means \
17955             the accessor no longer names the substrate-primitive typed \
17956             dispatch and every downstream consumer would silently \
17957             carry a detached copy",
17958        );
17959        assert_eq!(
17960            ep.len(),
17961            storage_slice.len(),
17962            "WitContract::endpoint and .endpoint.as_deref() must byte-\
17963             equal in length as well as in address",
17964        );
17965    }
17966
17967    #[test]
17968    fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
17969        // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
17970        // pin: [`WitContract::subject`] must return the `:contratos
17971        // :subject` field byte-for-byte, borrowed from the typed slot's
17972        // own `Option<String>` storage. Peer of the sibling per-`:contratos`
17973        // [`WitContract::endpoint`] (7020470) accessor pin on the M3
17974        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
17975        // optional-scalar axis — same "the substrate-primitive accessor
17976        // must byte-equal the raw field access verbatim across every
17977        // author-declared value" discipline extended to the pub-sub arm.
17978        // Pins against a future silent detour that re-canonicalized the
17979        // subject (an accidental `.to_lowercase()` normalization that
17980        // didn't reach the peer field-access site at the dedup key, a
17981        // per-CR fully-qualified prefix rewrite the operator authors on
17982        // one consumer without the other, or an M4 typed-subject-template
17983        // `Display` re-canonicalization that silently drifted the printer
17984        // output from the source `caixa.lisp`). Four values sweep the
17985        // NATS accept-set every pub-sub author-declared subject lands on
17986        // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
17987        for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
17988            let c = WitContract {
17989                de: "cart".into(),
17990                para: "notifier".into(),
17991                wit: "nats:pub-sub".into(),
17992                endpoint: None,
17993                subject: Some(subject.into()),
17994                slot: None,
17995            };
17996            assert_eq!(
17997                c.subject(),
17998                Some(subject),
17999                "WitContract::subject must return :contratos :subject \
18000                 verbatim (got {:?}, expected Some({subject:?}))",
18001                c.subject(),
18002            );
18003            assert_eq!(
18004                c.subject(),
18005                c.subject.as_deref(),
18006                "WitContract::subject must byte-equal the .subject \
18007                 field's `.as_deref()` projection",
18008            );
18009        }
18010    }
18011
18012    #[test]
18013    fn wit_contract_subject_none_when_field_is_none() {
18014        // The absent-`:subject` arm of the per-`:contratos` pub-sub-
18015        // shaped payload-carrier accessor pin: when the typed slot is
18016        // absent — the canonical shape under a non-pub-sub `:wit` world
18017        // per the [`WitContract::target`]-enforced shape ↔ target
18018        // partition ([`WitTarget::Http`] carries `:endpoint`,
18019        // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
18020        // carries none) — [`WitContract::subject`] must return `None`.
18021        // Pins against a future silent detour that projected the absent
18022        // slot to a `Some("")` empty-string default (the canonical
18023        // `Option<String>` → `String` collapse footgun the sibling M2
18024        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
18025        // emptiness predicates already guard on the peer M2 typed-slot
18026        // surfaces), a `Some("None")` stringified-None round-trip, or a
18027        // `Some` arm whose contents were derived from a sibling slot (an
18028        // accidental fallback to the `:endpoint` / `:slot` payload that
18029        // read the HTTP / store payload into the subject axis). Three
18030        // contracts sweep the accept-set every non-pub-sub `:wit` world
18031        // lands on — HTTP proxy, key/value store, and payload-less
18032        // capability.
18033        for (wit, endpoint, slot) in [
18034            ("wasi:http/proxy", Some("/lookup"), None),
18035            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
18036            ("wasi:cli/environment", None, None),
18037        ] {
18038            let c = WitContract {
18039                de: "cart".into(),
18040                para: "downstream".into(),
18041                wit: wit.into(),
18042                endpoint: endpoint.map(str::to_string),
18043                subject: None,
18044                slot: slot.map(str::to_string),
18045            };
18046            assert!(
18047                c.subject().is_none(),
18048                "WitContract::subject must return None when the typed \
18049                 slot is absent under :wit {wit:?} (got {:?})",
18050                c.subject(),
18051            );
18052            assert_eq!(
18053                c.subject(),
18054                c.subject.as_deref(),
18055                "WitContract::subject must byte-equal the .subject \
18056                 field's `.as_deref()` projection in the absent arm",
18057            );
18058        }
18059    }
18060
18061    #[test]
18062    fn wit_contract_subject_borrows_from_subject_storage() {
18063        // The borrow-not-copy pin: [`WitContract::subject`] must return
18064        // an `Option<&str>` whose `Some` arm borrows from the typed
18065        // slot's own [`String`] storage — same-address invariant with
18066        // `c.subject.as_deref().unwrap()`. Pins against a future silent
18067        // detour that allocated a fresh `String`
18068        // (`self.subject.clone().map(...)` in the body would type-check
18069        // but silently drop the borrow, and every downstream consumer
18070        // that assumed the returned slice outlives `&self` would break
18071        // on a stale-reference use-after-free — the [`WitContract::target`]
18072        // PubSub-arm payload extraction rebinds the returned
18073        // `Option<&str>` through `.ok_or_else(...)` and threads the
18074        // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
18075        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
18076        // [`ContratoIdentity`] dedup key threads the returned
18077        // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
18078        // from the WitContract's own storage and each would silently
18079        // misbehave if this accessor produced a detached copy). Peer of
18080        // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
18081        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
18082        // shaped optional-scalar axis — second extension of the
18083        // `Option<&str>` borrow-not-copy discipline onto the
18084        // per-`:contratos` payload-carrier family, this time on the
18085        // pub-sub arm.
18086        let c = WitContract {
18087            de: "cart".into(),
18088            para: "notifier".into(),
18089            wit: "nats:pub-sub".into(),
18090            endpoint: None,
18091            subject: Some("orders.paid".into()),
18092            slot: None,
18093        };
18094        let sub = c.subject().expect("Some arm");
18095        let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
18096        assert_eq!(
18097            sub.as_ptr(),
18098            storage_slice.as_ptr(),
18099            "WitContract::subject must borrow from the .subject \
18100             String's backing storage — a fresh allocation here means \
18101             the accessor no longer names the substrate-primitive typed \
18102             dispatch and every downstream consumer would silently \
18103             carry a detached copy",
18104        );
18105        assert_eq!(
18106            sub.len(),
18107            storage_slice.len(),
18108            "WitContract::subject and .subject.as_deref() must byte-\
18109             equal in length as well as in address",
18110        );
18111    }
18112
18113    #[test]
18114    fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
18115        // The canonical per-`:contratos` key/value-store-shaped
18116        // `:slot`-scalar pin: [`WitContract::slot`] must return the
18117        // `:contratos :slot` field byte-for-byte, borrowed from the
18118        // typed slot's own `Option<String>` storage. Peer of the
18119        // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
18120        // [`WitContract::subject`] (90de675) accessor pins on the M3
18121        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
18122        // optional-scalar axis — same "the substrate-primitive
18123        // accessor must byte-equal the raw field access verbatim
18124        // across every author-declared value" discipline extended to
18125        // the store arm. Pins against a future silent detour that
18126        // re-canonicalized the slot template (an accidental
18127        // `.to_lowercase()` bucket-prefix normalization that didn't
18128        // reach the peer field-access site at the dedup key, a per-CR
18129        // fully-qualified prefix rewrite the operator authors on one
18130        // consumer without the other, or an M4 typed-key-template
18131        // `Display` re-canonicalization that silently drifted the
18132        // printer output from the source `caixa.lisp`). Four values
18133        // sweep the wasi:keyvalue accept-set every store-shaped
18134        // author-declared slot lands on (flat bucket, single-param
18135        // template, multi-param template, nested-hierarchy template).
18136        for slot in [
18137            "sessions",
18138            "carts/{cart_id}",
18139            "orders/{tenant}/{order_id}",
18140            "cache/tenant-a/orders/{id}",
18141        ] {
18142            let c = WitContract {
18143                de: "cart".into(),
18144                para: "kv".into(),
18145                wit: "wasi:keyvalue/store".into(),
18146                endpoint: None,
18147                subject: None,
18148                slot: Some(slot.into()),
18149            };
18150            assert_eq!(
18151                c.slot(),
18152                Some(slot),
18153                "WitContract::slot must return :contratos :slot \
18154                 verbatim (got {:?}, expected Some({slot:?}))",
18155                c.slot(),
18156            );
18157            assert_eq!(
18158                c.slot(),
18159                c.slot.as_deref(),
18160                "WitContract::slot must byte-equal the .slot field's \
18161                 `.as_deref()` projection",
18162            );
18163        }
18164    }
18165
18166    #[test]
18167    fn wit_contract_slot_none_when_field_is_none() {
18168        // The absent-`:slot` arm of the per-`:contratos` store-shaped
18169        // payload-carrier accessor pin: when the typed slot is absent —
18170        // the canonical shape under a non-store `:wit` world per the
18171        // [`WitContract::target`]-enforced shape ↔ target partition
18172        // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
18173        // carries `:subject`, [`WitTarget::Capability`] carries none) —
18174        // [`WitContract::slot`] must return `None`. Pins against a
18175        // future silent detour that projected the absent slot to a
18176        // `Some("")` empty-string default (the canonical
18177        // `Option<String>` → `String` collapse footgun the sibling M2
18178        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
18179        // emptiness predicates already guard on the peer M2 typed-slot
18180        // surfaces), a `Some("None")` stringified-None round-trip, or
18181        // a `Some` arm whose contents were derived from a sibling
18182        // slot (an accidental fallback to the `:endpoint` / `:subject`
18183        // payload that read the HTTP / pub-sub payload into the store
18184        // axis). Three contracts sweep the accept-set every non-store
18185        // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
18186        // payload-less capability.
18187        for (wit, endpoint, subject) in [
18188            ("wasi:http/proxy", Some("/lookup"), None),
18189            ("nats:pub-sub", None, Some("orders.paid")),
18190            ("wasi:cli/environment", None, None),
18191        ] {
18192            let c = WitContract {
18193                de: "cart".into(),
18194                para: "downstream".into(),
18195                wit: wit.into(),
18196                endpoint: endpoint.map(str::to_string),
18197                subject: subject.map(str::to_string),
18198                slot: None,
18199            };
18200            assert!(
18201                c.slot().is_none(),
18202                "WitContract::slot must return None when the typed \
18203                 slot is absent under :wit {wit:?} (got {:?})",
18204                c.slot(),
18205            );
18206            assert_eq!(
18207                c.slot(),
18208                c.slot.as_deref(),
18209                "WitContract::slot must byte-equal the .slot field's \
18210                 `.as_deref()` projection in the absent arm",
18211            );
18212        }
18213    }
18214
18215    #[test]
18216    fn wit_contract_slot_borrows_from_slot_storage() {
18217        // The borrow-not-copy pin: [`WitContract::slot`] must return
18218        // an `Option<&str>` whose `Some` arm borrows from the typed
18219        // slot's own [`String`] storage — same-address invariant with
18220        // `c.slot.as_deref().unwrap()`. Pins against a future silent
18221        // detour that allocated a fresh `String`
18222        // (`self.slot.clone().map(...)` in the body would type-check
18223        // but silently drop the borrow, and every downstream consumer
18224        // that assumed the returned slice outlives `&self` would
18225        // break on a stale-reference use-after-free — the
18226        // [`WitContract::target`] Store-arm payload extraction rebinds
18227        // the returned `Option<&str>` through `.ok_or_else(...)` and
18228        // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
18229        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
18230        // [`ContratoIdentity`] dedup key threads the returned
18231        // `Option<&str>` into the six-tuple's store arm — each borrow
18232        // from the WitContract's own storage and each would silently
18233        // misbehave if this accessor produced a detached copy). Peer
18234        // of the sibling per-`:contratos` [`WitContract::endpoint`]
18235        // (7020470) / [`WitContract::subject`] (90de675)
18236        // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
18237        // shaped optional-scalar axis — third and final extension of
18238        // the `Option<&str>` borrow-not-copy discipline onto the
18239        // per-`:contratos` payload-carrier family, this time on the
18240        // store arm.
18241        let c = WitContract {
18242            de: "cart".into(),
18243            para: "kv".into(),
18244            wit: "wasi:keyvalue/store".into(),
18245            endpoint: None,
18246            subject: None,
18247            slot: Some("carts/{cart_id}".into()),
18248        };
18249        let slot = c.slot().expect("Some arm");
18250        let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
18251        assert_eq!(
18252            slot.as_ptr(),
18253            storage_slice.as_ptr(),
18254            "WitContract::slot must borrow from the .slot String's \
18255             backing storage — a fresh allocation here means the \
18256             accessor no longer names the substrate-primitive typed \
18257             dispatch and every downstream consumer would silently \
18258             carry a detached copy",
18259        );
18260        assert_eq!(
18261            slot.len(),
18262            storage_slice.len(),
18263            "WitContract::slot and .slot.as_deref() must byte-equal \
18264             in length as well as in address",
18265        );
18266    }
18267
18268    #[test]
18269    fn membro_nome_returns_caixa_byte_equal_across_permutations() {
18270        // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
18271        // [`Membro::nome`] must return the `:membros :caixa` field
18272        // byte-for-byte, borrowed from the typed slot's own [`String`]
18273        // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
18274        // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
18275        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
18276        // slot-atom scalar-value axes — same "the substrate-primitive
18277        // accessor must byte-equal the raw field access verbatim across
18278        // every author-declared value" discipline extended to the
18279        // per-`:membros` member-identity arm. Pins against a future
18280        // silent detour that re-normalized the member identity (an
18281        // accidental `.to_lowercase()` — every `:membros :caixa` is
18282        // validated as a DNS-1123 label upstream via
18283        // [`validate_membro_caixa`], so any re-normalization is
18284        // redundant + a drift surface between the validator and the
18285        // accessor), a namespace-prefix rewrite (an accidental
18286        // `format!("{namespace}/{caixa}")` per-CR fully-qualified
18287        // rewrite that didn't land on the peer axes), or a per-cluster
18288        // alias stamp the operator authors on one consumer without the
18289        // other. Four values sweep the accept-set the DNS-1123 gate
18290        // upstream admits (short single-word / dashed / v-suffixed
18291        // member names).
18292        for name in ["cart", "checkout", "catalog", "orders-v2"] {
18293            let m = Membro {
18294                caixa: name.into(),
18295                versao: "^0.1".into(),
18296            };
18297            assert_eq!(
18298                m.nome(),
18299                name,
18300                "Membro::nome must return :membros :caixa verbatim \
18301                 (got {:?}, expected {name:?})",
18302                m.nome(),
18303            );
18304            assert_eq!(
18305                m.nome(),
18306                m.caixa.as_str(),
18307                "Membro::nome must byte-equal the .caixa field access",
18308            );
18309        }
18310    }
18311
18312    #[test]
18313    fn membro_nome_borrows_from_caixa_storage() {
18314        // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
18315        // slice that borrows from the typed slot's own [`String`]
18316        // storage — same-address invariant with `m.caixa.as_str()`. Pins
18317        // against a future silent detour that allocated a fresh `String`
18318        // (`self.caixa.clone()` in the body would type-check but
18319        // silently drop the borrow, and every downstream consumer that
18320        // assumed the returned slice outlives `&self` would break on a
18321        // stale-reference use-after-free — the `HashSet<&str>` collector
18322        // at [`AplicacaoSpec::validate`]'s `names` seed, the
18323        // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
18324        // [`AplicacaoSpec::detect_sync_cycles`], the
18325        // [`crate::render::insert_first_seen`] dedup key at
18326        // [`AplicacaoSpec::validate_membros`] — each borrow from the
18327        // Membro's own storage and each would silently misbehave if
18328        // this accessor produced a detached copy). Peer of the sibling
18329        // per-`:contratos` [`WitContract::source`] /
18330        // [`WitContract::destination`] and per-`:entrada`
18331        // [`Entrada::destination`] borrow-invariant pins on the mesh-
18332        // slot-atom scalar-value axes.
18333        let m = Membro {
18334            caixa: "checkout".into(),
18335            versao: "^0.1".into(),
18336        };
18337        let name = m.nome();
18338        let caixa_slice = m.caixa.as_str();
18339        assert_eq!(
18340            name.as_ptr(),
18341            caixa_slice.as_ptr(),
18342            "Membro::nome must borrow from the .caixa String's backing \
18343             storage — a fresh allocation here means the accessor no \
18344             longer names the substrate-primitive typed dispatch and \
18345             every downstream consumer would silently carry a detached \
18346             copy",
18347        );
18348        assert_eq!(
18349            name.len(),
18350            caixa_slice.len(),
18351            "Membro::nome and .caixa.as_str() must byte-equal in length \
18352             as well as in address",
18353        );
18354    }
18355
18356    #[test]
18357    fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
18358        // The canonical per-`:membros` member-`:versao`-scalar pin:
18359        // [`Membro::versao_requirement`] must return the
18360        // `:membros :versao` field byte-for-byte, borrowed from the typed
18361        // slot's own [`String`] storage. Sibling of the peer
18362        // `membro_nome_returns_caixa_byte_equal_across_permutations`
18363        // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
18364        // — same "the substrate-primitive accessor must byte-equal the
18365        // raw field access verbatim across every author-declared value"
18366        // discipline extended to the per-`:membros` member-`:versao`
18367        // requirement-string arm. Pins against a future silent detour
18368        // that re-canonicalized the requirement (an accidental
18369        // `.to_string()` via [`parse_requirement`] → [`Display`] round-
18370        // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
18371        // drifted the printer output away from the source `caixa.lisp`,
18372        // an accidental whitespace trim on `"^ 0.1"` that no consumer
18373        // ever produced from the field-access side, an accidental
18374        // per-cluster lacre-projected concrete-version rewrite that
18375        // didn't land on the peer field-access sites). Five values sweep
18376        // the accept-set the shared
18377        // [`crate::render::require_valid_versao_requirement`] gate
18378        // admits (caret / tilde / exact / wildcard / bare-major).
18379        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
18380            let m = Membro {
18381                caixa: "cart".into(),
18382                versao: req.into(),
18383            };
18384            assert_eq!(
18385                m.versao_requirement(),
18386                req,
18387                "Membro::versao_requirement must return :membros :versao \
18388                 verbatim (got {:?}, expected {req:?})",
18389                m.versao_requirement(),
18390            );
18391            assert_eq!(
18392                m.versao_requirement(),
18393                m.versao.as_str(),
18394                "Membro::versao_requirement must byte-equal the .versao \
18395                 field access",
18396            );
18397        }
18398    }
18399
18400    #[test]
18401    fn membro_versao_requirement_borrows_from_versao_storage() {
18402        // The borrow-not-copy pin: [`Membro::versao_requirement`] must
18403        // return a `&str` slice that borrows from the typed slot's own
18404        // [`String`] storage — same-address invariant with
18405        // `m.versao.as_str()`. Pins against a future silent detour that
18406        // allocated a fresh `String` (`self.versao.clone()` in the body
18407        // would type-check but silently drop the borrow, and every
18408        // downstream consumer that assumed the returned slice outlives
18409        // `&self` would break on a stale-reference use-after-free). Peer
18410        // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
18411        // per-`:contratos` [`WitContract::source`] /
18412        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
18413        // [`Entrada::destination`] (6db982c) borrow-invariant pins on
18414        // the mesh-slot-atom scalar-value axes.
18415        let m = Membro {
18416            caixa: "checkout".into(),
18417            versao: "^0.1".into(),
18418        };
18419        let req = m.versao_requirement();
18420        let versao_slice = m.versao.as_str();
18421        assert_eq!(
18422            req.as_ptr(),
18423            versao_slice.as_ptr(),
18424            "Membro::versao_requirement must borrow from the .versao \
18425             String's backing storage — a fresh allocation here means \
18426             the accessor no longer names the substrate-primitive typed \
18427             dispatch and every downstream consumer would silently carry \
18428             a detached copy",
18429        );
18430        assert_eq!(
18431            req.len(),
18432            versao_slice.len(),
18433            "Membro::versao_requirement and .versao.as_str() must byte-\
18434             equal in length as well as in address",
18435        );
18436    }
18437
18438    #[test]
18439    fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
18440        // Sibling-pair invariant pin composing both per-`:membros`
18441        // substrate-primitive typed dispatches — [`Membro::nome`]
18442        // (4a32abf) and [`Membro::versao_requirement`] — at the joint
18443        // `(nome(), versao_requirement())` call shape every renderer
18444        // that fans on per-member identity + version pin keys off. The
18445        // invariant, evaluated per-member:
18446        //
18447        //   (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
18448        //
18449        // Closes the last unlifted per-`:membros` scalar axis — every
18450        // downstream consumer that reads the pair now routes through
18451        // exactly two typed dispatches on the substrate primitive, not
18452        // one typed + one open-coded field access. A future refactor
18453        // that silently split either accessor's projection (an
18454        // accidental `nome()` namespace-prefix rewrite that didn't
18455        // reach the peer, an accidental `versao_requirement()` lacre-
18456        // projected concrete-version rewrite that didn't land on the
18457        // `nome()` peer) surfaces at caixa-core build time. Peer of the
18458        // sibling per-`:entrada` `(hostname(), destination())` and
18459        // per-`:contratos` `(source(), destination())` pair invariants
18460        // on the mesh-slot-atom scalar-value axes.
18461        for (caixa, versao) in [
18462            ("cart", "^0.1"),
18463            ("checkout", "~0.1.2"),
18464            ("catalog", "0.1.0"),
18465            ("orders-v2", "*"),
18466        ] {
18467            let m = Membro {
18468                caixa: caixa.into(),
18469                versao: versao.into(),
18470            };
18471            assert_eq!(
18472                (m.nome(), m.versao_requirement()),
18473                (m.caixa.as_str(), m.versao.as_str()),
18474                "(Membro::nome, Membro::versao_requirement) must project \
18475                 (.caixa, .versao) verbatim across every author-declared \
18476                 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
18477                m.nome(),
18478                m.versao_requirement(),
18479            );
18480        }
18481    }
18482
18483    #[test]
18484    fn validate_membros_empty_gate_routes_through_nome_accessor() {
18485        // Composition pin: [`AplicacaoSpec::validate_membros`]'s
18486        // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
18487        // not the raw `.caixa` field access. Structurally: setting
18488        // ONLY the `.caixa` field to `""` on an otherwise-well-formed
18489        // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
18490        // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
18491        // (i.e. the empty string) — so the emptiness predicate the
18492        // refusal arm reaches under is the accessor-projected value,
18493        // not a peer field that would silently drift under a future
18494        // accessor-side rewrite.
18495        //
18496        // Pins against a future silent detour that (a) re-derived the
18497        // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
18498        // instead of `self.nome().is_empty()`, silently disagreeing with
18499        // every peer consumer (the `validate_membro_caixa(m.nome())`
18500        // call one line below, the dedup-key `insert_first_seen(&mut
18501        // seen, m.nome(), …)` two lines below, the emit-side per-
18502        // `programs[]` entry-`name:` at caixa-mesh/src/lib.rs:133),
18503        // (b) accessor-side introduced a per-tenant alias arm the
18504        // caller was unaware of, silently rewriting an author-declared
18505        // `:caixa "checkout"` to `""` — the raw-field-access gate
18506        // would fail-open while the accessor-routed peer consumers
18507        // would fail-closed, splitting the diagnostic from the actual
18508        // failure surface.
18509        //
18510        // Peer of the sibling
18511        // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
18512        // (c0110f1) composition pin — same "the shape-gate predicate
18513        // must route through the substrate-primitive typed dispatch"
18514        // discipline extended onto the per-`:membros` empty-`:caixa`
18515        // refusal-arm axis. Closes the last unlifted `.caixa` production-
18516        // code read site on `Membro` — after this converge every
18517        // caixa-core `.caixa` field access outside the accessor's own
18518        // body is either a test-side field-setter (in-module tests
18519        // constructing invalid-shape inputs) or a doc-comment reference.
18520        let mut s = three_member_spec();
18521        s.membros[1].caixa = String::new();
18522        assert!(
18523            s.membros[1].nome().is_empty(),
18524            "Membro::nome must byte-equal the .caixa field access — an \
18525             accessor-side detour that no longer projects the raw field \
18526             would silently split this drift-detection test from the \
18527             validate() refusal arm",
18528        );
18529        assert_eq!(
18530            s.membros[1].nome(),
18531            s.membros[1].caixa.as_str(),
18532            "Membro::nome and .caixa.as_str() must byte-equal on an \
18533             empty-`:caixa` entry — the emptiness gate keys off the \
18534             accessor by construction",
18535        );
18536        assert_eq!(
18537            s.validate().unwrap_err(),
18538            AplicacaoError::MembroCaixaEmpty,
18539            "validate_membros' emptiness gate must fire MembroCaixaEmpty \
18540             on an entry whose accessor-projected `nome()` is empty",
18541        );
18542    }
18543
18544    #[test]
18545    fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
18546        // The canonical per-`:placement` Akka-cluster-sharding
18547        // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
18548        // the `:placement :shard-key` field byte-for-byte, borrowed
18549        // from the typed slot's own `Option<String>` storage. Peer of
18550        // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
18551        // per-`:contratos` [`WitContract::source`] /
18552        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
18553        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
18554        // slot-atom scalar-value axes — same "the substrate-primitive
18555        // accessor must byte-equal the raw field access verbatim across
18556        // every author-declared value" discipline extended to the
18557        // per-`:placement` Akka-cluster-sharding key extractor arm.
18558        // Pins against a future silent detour that re-normalized the
18559        // key (an accidental `.to_lowercase()` — every non-empty
18560        // `:shard-key` is validated as a printable-ASCII single-token
18561        // reference upstream via [`validate_placement_shard_key`], so
18562        // any re-normalization is redundant + a drift surface between
18563        // the validator and the accessor), a per-cluster alias rewrite
18564        // the operator authors on one consumer without the other, or an
18565        // accidental variable-prefix strip (`$tenantId` → `tenantId`)
18566        // that didn't land on the peer field-access sites. Four values
18567        // sweep the accept-set the shape gate admits — bare identifier,
18568        // `$`-prefixed variable, dotted path, `${}`-quoted variable —
18569        // the four canonical Akka-style entity-id extractor shapes the
18570        // future M4 cluster-sharding reconciler hashes.
18571        for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
18572            let p = Placement {
18573                estrategia: PlacementStrategy::Sharded,
18574                clusters: vec!["rio".into()],
18575                affinity: None,
18576                shard_key: Some(key.into()),
18577            };
18578            assert_eq!(
18579                p.shard_key(),
18580                Some(key),
18581                "Placement::shard_key must return :placement :shard-key \
18582                 verbatim (got {:?}, expected Some({key:?}))",
18583                p.shard_key(),
18584            );
18585            assert_eq!(
18586                p.shard_key(),
18587                p.shard_key.as_deref(),
18588                "Placement::shard_key must byte-equal the .shard_key \
18589                 field's `.as_deref()` projection",
18590            );
18591        }
18592    }
18593
18594    #[test]
18595    fn placement_shard_key_none_when_field_is_none() {
18596        // The absent-`:shard-key` arm of the per-`:placement`
18597        // Akka-cluster-sharding accessor pin: when the typed slot is
18598        // absent — the canonical shape under `:estrategia Replicated` /
18599        // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
18600        // enforced `shard_key.is_some() == matches!(estrategia,
18601        // Sharded)` partition — [`Placement::shard_key`] must return
18602        // `None`. Pins against a future silent detour that projected
18603        // the absent slot to a `Some("")` empty-string default (the
18604        // canonical `Option<String>` → `String` collapse footgun the
18605        // sibling M2 [`crate::LimitsSpec::is_empty`] /
18606        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
18607        // already guard on the peer M2 typed-slot surfaces), a
18608        // `Some("None")` stringified-None round-trip, or a `Some` arm
18609        // whose contents were derived from a sibling slot (an
18610        // accidental fallback to `estrategia.as_str()` that read the
18611        // strategy discriminator into the key axis). Two placements
18612        // sweep the accept-set every `validate`-passing non-`Sharded`
18613        // shape lands on — `Replicated` (Erlang/OTP distributed-app
18614        // takeover) and `SingleNode` (single-node hosting).
18615        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
18616            let p = Placement {
18617                estrategia,
18618                clusters: vec!["rio".into()],
18619                affinity: None,
18620                shard_key: None,
18621            };
18622            assert!(
18623                p.shard_key().is_none(),
18624                "Placement::shard_key must return None when the typed \
18625                 slot is absent under :estrategia {estrategia:?} (got {:?})",
18626                p.shard_key(),
18627            );
18628            assert_eq!(
18629                p.shard_key(),
18630                p.shard_key.as_deref(),
18631                "Placement::shard_key must byte-equal the .shard_key \
18632                 field's `.as_deref()` projection in the absent arm",
18633            );
18634        }
18635    }
18636
18637    #[test]
18638    fn placement_shard_key_borrows_from_shard_key_storage() {
18639        // The borrow-not-copy pin: [`Placement::shard_key`] must return
18640        // an `Option<&str>` whose `Some` arm borrows from the typed
18641        // slot's own [`String`] storage — same-address invariant with
18642        // `p.shard_key.as_deref().unwrap()`. Pins against a future
18643        // silent detour that allocated a fresh `String`
18644        // (`self.shard_key.clone().map(...)` in the body would type-
18645        // check but silently drop the borrow, and every downstream
18646        // consumer that assumed the returned slice outlives `&self`
18647        // would break on a stale-reference use-after-free — the
18648        // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
18649        // gate's `Some(k)`-bound match arm reads `k: &str` under the
18650        // accessor's return type and would silently misbehave if this
18651        // accessor produced a detached copy). Peer of the sibling
18652        // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
18653        // [`WitContract::source`] / [`WitContract::destination`]
18654        // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
18655        // (6db982c) borrow-invariant pins on the mesh-slot-atom
18656        // scalar-value axes — first extension of the discipline onto
18657        // an `Option<String>`-shaped optional-scalar axis.
18658        let p = Placement {
18659            estrategia: PlacementStrategy::Sharded,
18660            clusters: vec!["rio".into()],
18661            affinity: None,
18662            shard_key: Some("tenantId".into()),
18663        };
18664        let key = p.shard_key().expect("Some arm");
18665        let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
18666        assert_eq!(
18667            key.as_ptr(),
18668            storage_slice.as_ptr(),
18669            "Placement::shard_key must borrow from the .shard_key \
18670             String's backing storage — a fresh allocation here means \
18671             the accessor no longer names the substrate-primitive typed \
18672             dispatch and every downstream consumer would silently \
18673             carry a detached copy",
18674        );
18675        assert_eq!(
18676            key.len(),
18677            storage_slice.len(),
18678            "Placement::shard_key and .shard_key.as_deref() must byte-\
18679             equal in length as well as in address",
18680        );
18681    }
18682
18683    #[test]
18684    fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
18685        // The canonical per-`:placement` M3-Adaptive-compression-hint
18686        // scalar pin: [`Placement::affinity`] must return the
18687        // `:placement :affinity` field byte-for-byte, borrowed from the
18688        // typed slot's own `Option<String>` storage. Peer of the sibling
18689        // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
18690        // pin on the sibling `Option<&str>` optional-scalar axis — same
18691        // "the substrate-primitive accessor must byte-equal the raw
18692        // field access verbatim across every author-declared value"
18693        // discipline extended to the peer per-`:placement` M3-Adaptive-
18694        // compression-hint arm. Pins against a future silent detour
18695        // that re-normalized the hint (an accidental `.to_lowercase()`
18696        // — every `:affinity` is already validated as a DNS-1123 label
18697        // upstream via [`validate_placement_affinity`], so any re-
18698        // normalization is redundant + a drift surface between the
18699        // validator and the accessor), a per-cluster alias rewrite the
18700        // operator authors on one consumer without the other, or an
18701        // accidental hint-family collapse (`low-latency` → `latency`
18702        // that dropped the qualifier prefix). Four values sweep the
18703        // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
18704        // canonical adaptive-compression-weight biases the future M4
18705        // placement engine reads.
18706        for hint in [
18707            "data-locality",
18708            "low-latency",
18709            "high-throughput",
18710            "cost-optimized",
18711        ] {
18712            let p = Placement {
18713                estrategia: PlacementStrategy::Replicated,
18714                clusters: vec!["rio".into()],
18715                affinity: Some(hint.into()),
18716                shard_key: None,
18717            };
18718            assert_eq!(
18719                p.affinity(),
18720                Some(hint),
18721                "Placement::affinity must return :placement :affinity \
18722                 verbatim (got {:?}, expected Some({hint:?}))",
18723                p.affinity(),
18724            );
18725            assert_eq!(
18726                p.affinity(),
18727                p.affinity.as_deref(),
18728                "Placement::affinity must byte-equal the .affinity \
18729                 field's `.as_deref()` projection",
18730            );
18731        }
18732    }
18733
18734    #[test]
18735    fn placement_affinity_none_when_field_is_none() {
18736        // The absent-`:affinity` arm of the per-`:placement`
18737        // M3-Adaptive-compression-hint accessor pin: when the typed
18738        // slot is absent — the canonical shape of an Aplicacao that
18739        // leaves the compression weighting up to the placement engine's
18740        // cluster-default arm — [`Placement::affinity`] must return
18741        // `None`. Pins against a future silent detour that projected
18742        // the absent slot to a `Some("")` empty-string default (the
18743        // canonical `Option<String>` → `String` collapse footgun the
18744        // sibling M2 [`crate::LimitsSpec::is_empty`] /
18745        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
18746        // already guard on the peer M2 typed-slot surfaces), a
18747        // `Some("None")` stringified-None round-trip, a `Some` arm
18748        // whose contents were derived from a sibling slot (an
18749        // accidental fallback to `estrategia.as_str()` that read the
18750        // strategy discriminator into the hint axis), or a
18751        // `Some("default")` implicit-default that would silently biases
18752        // the routing without the author having written one. Three
18753        // placements sweep the accept-set every `validate`-passing
18754        // `:affinity None` shape lands on — one per PlacementStrategy
18755        // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
18756        // with a shard-key), since `:affinity` is orthogonal to
18757        // `:estrategia` in the typed grammar.
18758        for (estrategia, shard_key) in [
18759            (PlacementStrategy::SingleNode, None),
18760            (PlacementStrategy::Replicated, None),
18761            (PlacementStrategy::Sharded, Some("tenantId".to_string())),
18762        ] {
18763            let p = Placement {
18764                estrategia,
18765                clusters: vec!["rio".into()],
18766                affinity: None,
18767                shard_key,
18768            };
18769            assert!(
18770                p.affinity().is_none(),
18771                "Placement::affinity must return None when the typed \
18772                 slot is absent under :estrategia {estrategia:?} (got {:?})",
18773                p.affinity(),
18774            );
18775            assert_eq!(
18776                p.affinity(),
18777                p.affinity.as_deref(),
18778                "Placement::affinity must byte-equal the .affinity \
18779                 field's `.as_deref()` projection in the absent arm",
18780            );
18781        }
18782    }
18783
18784    #[test]
18785    fn placement_affinity_borrows_from_affinity_storage() {
18786        // The borrow-not-copy pin: [`Placement::affinity`] must return
18787        // an `Option<&str>` whose `Some` arm borrows from the typed
18788        // slot's own [`String`] storage — same-address invariant with
18789        // `p.affinity.as_deref().unwrap()`. Pins against a future
18790        // silent detour that allocated a fresh `String`
18791        // (`self.affinity.clone().map(...)` in the body would type-
18792        // check but silently drop the borrow, and every downstream
18793        // consumer that assumed the returned slice outlives `&self`
18794        // would break on a stale-reference use-after-free — the
18795        // [`AplicacaoSpec::validate_placement`] per-hint value-shape
18796        // gate reads the accessor's `&str` return through the
18797        // [`validate_placement_affinity`] `&str` parameter and would
18798        // silently misbehave if this accessor produced a detached
18799        // copy). Peer of the sibling per-`:placement`
18800        // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
18801        // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
18802        // extends the discipline onto the sibling per-`:placement`
18803        // M3-Adaptive-compression-hint arm.
18804        let p = Placement {
18805            estrategia: PlacementStrategy::Replicated,
18806            clusters: vec!["rio".into()],
18807            affinity: Some("data-locality".into()),
18808            shard_key: None,
18809        };
18810        let hint = p.affinity().expect("Some arm");
18811        let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
18812        assert_eq!(
18813            hint.as_ptr(),
18814            storage_slice.as_ptr(),
18815            "Placement::affinity must borrow from the .affinity \
18816             String's backing storage — a fresh allocation here means \
18817             the accessor no longer names the substrate-primitive typed \
18818             dispatch and every downstream consumer would silently \
18819             carry a detached copy",
18820        );
18821        assert_eq!(
18822            hint.len(),
18823            storage_slice.len(),
18824            "Placement::affinity and .affinity.as_deref() must byte-\
18825             equal in length as well as in address",
18826        );
18827    }
18828
18829    #[test]
18830    fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
18831        // The canonical per-`:placement` distribution-strategy-scalar
18832        // pin: [`Placement::estrategia`] must return the `:placement
18833        // :estrategia` field verbatim as a [`PlacementStrategy`],
18834        // `Copy`-projected from the typed slot's own `PlacementStrategy`
18835        // storage across every variant in the closed accept-set
18836        // (`SingleNode` — Erlang/OTP distributed-app takeover;
18837        // `Replicated` — active-active across every named cluster;
18838        // `Sharded` — Akka-style hash-keyed entity distribution). Pins
18839        // against a future silent detour that re-derived the strategy
18840        // from a peer axis (an accidental fallback to
18841        // `if shard_key.is_some() { Sharded } else { Replicated }`
18842        // collapse that read the shard-key axis into the strategy
18843        // discriminator), a variant remap the operator authors on one
18844        // consumer without the other, or a stale-derive detour that
18845        // substituted [`PlacementStrategy::default`] when the field
18846        // held any explicit variant (which would silently collapse the
18847        // distinction between "author explicitly declared `:estrategia
18848        // Replicated`" and "author omitted the slot and inherited the
18849        // default" the future per-cluster override slot depends on).
18850        // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
18851        // pin on the `Copy`-return `u16` scalar axis — same "the
18852        // substrate-primitive accessor must byte-equal the raw field
18853        // access verbatim across every author-declared value" discipline
18854        // extended onto the per-`:placement` distribution-strategy
18855        // `Copy`-composite-enum scalar axis.
18856        for estrategia in [
18857            PlacementStrategy::SingleNode,
18858            PlacementStrategy::Replicated,
18859            PlacementStrategy::Sharded,
18860        ] {
18861            let shard_key = estrategia.is_sharded().then(|| "tenantId".to_string());
18862            let p = Placement {
18863                estrategia,
18864                clusters: vec!["rio".into()],
18865                affinity: None,
18866                shard_key,
18867            };
18868            assert_eq!(
18869                p.estrategia(),
18870                estrategia,
18871                "Placement::estrategia must return :placement :estrategia \
18872                 verbatim (got {:?}, expected {estrategia:?})",
18873                p.estrategia(),
18874            );
18875            assert_eq!(
18876                p.estrategia(),
18877                p.estrategia,
18878                "Placement::estrategia accessor and .estrategia field \
18879                 access must byte-equal — the accessor is the substrate-\
18880                 primitive typed dispatch every downstream distribution-\
18881                 strategy consumer must route through",
18882            );
18883        }
18884    }
18885
18886    #[test]
18887    fn validate_placement_reads_through_lifted_estrategia_accessor() {
18888        // Three-consumer coherence pin: the
18889        // [`AplicacaoSpec::validate_placement`]
18890        // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
18891        // `estrategia:` field (which reads through
18892        // [`Placement::estrategia`] to name the strategy the empty
18893        // `:clusters` list was declared against), the same method's
18894        // `Sharded ↔ non-Sharded` `match` partition dispatch (which
18895        // reads through [`Placement::estrategia`] to fan across the
18896        // shape-gate cascades), and the non-`Sharded`-arm
18897        // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
18898        // `estrategia:` field (which reads through
18899        // [`Placement::estrategia`] to name the strategy the declared-
18900        // but-inert `:shard-key` was authored under) must all key off
18901        // the lifted accessor, so any future rebrand on the typed
18902        // slot's reader shape lands at exactly one place. Pins the
18903        // three-site coherence by exercising each error surface end-
18904        // to-end and asserting the surfaced `estrategia:` field byte-
18905        // equals the accessor's return. Peer of the sibling per-
18906        // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
18907        // pin on the M3 mesh-slot `Copy`-return scalar axis.
18908
18909        // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
18910        // whose `estrategia:` field must byte-equal the accessor's return
18911        // for every variant in the closed accept-set.
18912        for estrategia in [
18913            PlacementStrategy::SingleNode,
18914            PlacementStrategy::Replicated,
18915            PlacementStrategy::Sharded,
18916        ] {
18917            let mut spec = three_member_spec();
18918            spec.placement.estrategia = estrategia;
18919            spec.placement.clusters = Vec::new();
18920            spec.placement.shard_key = estrategia.is_sharded().then(|| "tenantId".to_string());
18921            let err = spec.validate().unwrap_err();
18922            match err {
18923                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
18924                    assert_eq!(
18925                        e,
18926                        spec.placement.estrategia(),
18927                        "PlacementWithoutClusters.estrategia must byte-equal \
18928                         Placement::estrategia() — the error carrier reads \
18929                         through the lifted accessor",
18930                    );
18931                }
18932                other => panic!(
18933                    "expected PlacementWithoutClusters, got {other:?} for \
18934                     estrategia={estrategia:?}"
18935                ),
18936            }
18937        }
18938
18939        // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
18940        // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
18941        // must byte-equal the accessor's return for both non-`Sharded`
18942        // strategies.
18943        for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
18944            let mut spec = three_member_spec();
18945            spec.placement.estrategia = estrategia;
18946            spec.placement.shard_key = Some("tenantId".into());
18947            let err = spec.validate().unwrap_err();
18948            match err {
18949                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
18950                    assert_eq!(
18951                        e,
18952                        spec.placement.estrategia(),
18953                        "ShardKeyOnNonSharded.estrategia must byte-equal \
18954                         Placement::estrategia() — the non-Sharded-arm \
18955                         refusal reads through the lifted accessor",
18956                    );
18957                }
18958                other => panic!(
18959                    "expected ShardKeyOnNonSharded, got {other:?} for \
18960                     estrategia={estrategia:?}"
18961                ),
18962            }
18963        }
18964    }
18965
18966    // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
18967    //
18968    // The [`Placement::clusters`] accessor lift is the second slice-return
18969    // (`&[T]`) accessor on any typed slot — sibling to the seed M2
18970    // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
18971    // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
18972    // below cover (1) the accessor's byte-equal projection against the raw
18973    // field access across the empty / singleton / cohort fixtures the
18974    // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
18975    // and the per-cluster validate loop fan between, and (2) the two-
18976    // consumer coherence of the paired pre-flight refusal probe and the
18977    // per-cluster validate loop routing through the accessor on both arms.
18978
18979    #[test]
18980    fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
18981        // The canonical per-`:placement` cluster-pool-scalar-shape pin:
18982        // [`Placement::clusters`] must return the `:placement :clusters`
18983        // typed `Vec<String>` verbatim as a `&[String]` slice-view over
18984        // the same backing buffer the raw `self.clusters.as_slice()`
18985        // field access borrows from, byte-equal across every
18986        // representative fixture in the accept-set — the empty slice
18987        // (the pre-validation sentinel every
18988        // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
18989        // the singleton slice (the minimal `SingleNode`-shape cohort),
18990        // and multi-entry cohorts (the peer `Replicated` / `Sharded`
18991        // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
18992        //
18993        // Pins against a future silent detour that returned
18994        // `&Vec<String>` (which would type-check but leak the storage-
18995        // side `Vec`'s grow/push/reserve surface no consumer of the
18996        // typed view reaches for), a fresh-allocated `Vec<String>` copy
18997        // (which would type-check via a coercion but silently break
18998        // every downstream caller that relied on the slice sharing the
18999        // backing buffer's identity), or an out-of-order or length-
19000        // drifted projection (which would silently split the paired
19001        // pre-flight `.is_empty()` refusal probe's input from the per-
19002        // cluster validate loop's traversal input).
19003        //
19004        // Peer of the sibling M2
19005        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
19006        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
19007        // `:supervisor` static-child-list axis, extended onto the M3
19008        // per-`:placement` distribution-target-list `Vec`-carry axis.
19009        let fixtures: Vec<Vec<String>> = vec![
19010            Vec::new(),
19011            vec!["rio".into()],
19012            vec!["rio".into(), "mar".into()],
19013            vec!["rio".into(), "mar".into(), "plo".into()],
19014        ];
19015        for clusters in fixtures {
19016            let p = Placement {
19017                clusters: clusters.clone(),
19018                ..Placement::default()
19019            };
19020            assert_eq!(
19021                p.clusters(),
19022                clusters.as_slice(),
19023                "Placement::clusters must return :placement :clusters \
19024                 verbatim (got {:?}, expected {:?})",
19025                p.clusters(),
19026                clusters.as_slice(),
19027            );
19028            assert_eq!(
19029                p.clusters(),
19030                p.clusters.as_slice(),
19031                "Placement::clusters accessor and .clusters.as_slice() \
19032                 field access must byte-equal — the accessor is the \
19033                 substrate-primitive typed dispatch every downstream \
19034                 cluster-pool consumer must route through",
19035            );
19036            assert_eq!(
19037                p.clusters().len(),
19038                p.clusters.len(),
19039                "Placement::clusters().len() must byte-equal \
19040                 self.clusters.len() — a length-drift would silently \
19041                 split the paired pre-flight `.is_empty()` refusal \
19042                 probe input from the per-cluster validate loop's \
19043                 traversal input",
19044            );
19045        }
19046    }
19047
19048    #[test]
19049    fn validate_placement_reads_through_lifted_clusters_accessor() {
19050        // Two-consumer coherence pin: the
19051        // [`AplicacaoSpec::validate_placement`] pre-flight
19052        // `self.placement.clusters().is_empty()` refusal probe (which
19053        // must trip [`AplicacaoError::PlacementWithoutClusters`] when
19054        // the accessor projects the empty slice) and the per-cluster
19055        // validate loop's `for c in self.placement.clusters()`
19056        // traversal (which must reach every entry in the same order
19057        // the accessor projects, so both the per-entry value-shape
19058        // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
19059        // and the duplicate-detection HashSet insert that trips
19060        // [`AplicacaoError::PlacementClusterDuplicate`] key off the
19061        // accessor's projection) must both key off the lifted
19062        // accessor, so any future rebrand on the typed slot's reader
19063        // shape lands at exactly one place. Pins the two-site
19064        // coherence by exercising each production consumer end-to-end:
19065        // (1) the `PlacementWithoutClusters` refusal under the empty
19066        // slice, (2) the `PlacementClusterInvalid` refusal fires on
19067        // the second entry of a two-cluster cohort whose head is
19068        // valid but tail is not (which requires the loop to reach the
19069        // second entry through the accessor), and (3) the
19070        // `PlacementClusterDuplicate` refusal fires on the second
19071        // entry of a two-cluster cohort that shares a name (which
19072        // requires the loop to reach both entries — a first-entry-only
19073        // projection would silently pass since the dedup HashSet has
19074        // room for the first insert).
19075        //
19076        // Peer of the sibling M2
19077        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
19078        // (bc92bce) coherence pin on the per-`:supervisor` static-
19079        // child-list axis, extended onto the M3 per-`:placement`
19080        // distribution-target-list `Vec`-carry axis.
19081
19082        // (1) Pre-flight `.is_empty()` probe: the empty slice must
19083        // trip `PlacementWithoutClusters`.
19084        let mut spec = three_member_spec();
19085        spec.placement.clusters = Vec::new();
19086        match spec.validate().unwrap_err() {
19087            AplicacaoError::PlacementWithoutClusters { .. } => {}
19088            other => panic!("expected PlacementWithoutClusters, got {other:?}"),
19089        }
19090        assert!(
19091            spec.placement.clusters().is_empty(),
19092            "the pre-flight refusal input must be the empty slice per \
19093             the accessor's projection",
19094        );
19095
19096        // (2) Per-cluster validate loop: a two-cluster cohort with an
19097        // invalid tail entry must trip `PlacementClusterInvalid` on
19098        // the tail — the loop must reach the second entry through
19099        // the accessor.
19100        let mut spec = three_member_spec();
19101        spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
19102        match spec.validate().unwrap_err() {
19103            AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
19104                assert_eq!(
19105                    cluster, "BAD_CLUSTER",
19106                    "PlacementClusterInvalid.cluster must carry the \
19107                     tail entry the loop reached through the accessor",
19108                );
19109            }
19110            other => panic!("expected PlacementClusterInvalid, got {other:?}"),
19111        }
19112        assert_eq!(
19113            spec.placement.clusters().len(),
19114            2,
19115            "the per-cluster validate loop's traversal input must be \
19116             a two-element slice per the accessor's projection",
19117        );
19118
19119        // (3) Per-cluster validate loop: a two-cluster cohort that
19120        // shares a name must trip `PlacementClusterDuplicate` on the
19121        // second entry — the loop must reach both entries through the
19122        // accessor for the dedup HashSet's second insert to collide.
19123        let mut spec = three_member_spec();
19124        spec.placement.clusters = vec!["rio".into(), "rio".into()];
19125        match spec.validate().unwrap_err() {
19126            AplicacaoError::PlacementClusterDuplicate { cluster } => {
19127                assert_eq!(
19128                    cluster, "rio",
19129                    "PlacementClusterDuplicate.cluster must carry the \
19130                     shared cluster name verbatim",
19131                );
19132            }
19133            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
19134        }
19135        assert_eq!(
19136            spec.placement.clusters().len(),
19137            2,
19138            "the per-cluster validate loop's traversal input must be \
19139             a two-element slice per the accessor's projection",
19140        );
19141    }
19142
19143    #[test]
19144    fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
19145        // The canonical per-`:membros` member-list-slice-shape pin:
19146        // [`AplicacaoSpec::membros`] must return the `:membros` typed
19147        // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
19148        // same backing buffer the raw `self.membros.as_slice()` field
19149        // access borrows from, byte-equal across every representative
19150        // fixture in the accept-set — the empty slice (the pre-
19151        // validation sentinel every [`AplicacaoError::NoMembros`]
19152        // refusal keys off), the singleton slice (the minimal one-
19153        // Servico Aplicacao shape), and multi-entry cohorts (the peer
19154        // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
19155        // load-bearing identity of the application graph).
19156        //
19157        // Pins against a future silent detour that returned
19158        // `&Vec<Membro>` (which would type-check but leak the storage-
19159        // side `Vec`'s grow/push/reserve surface no consumer of the
19160        // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
19161        // (which would type-check via a coercion but silently break
19162        // every downstream caller that relied on the slice sharing the
19163        // backing buffer's identity), or an out-of-order or length-
19164        // drifted projection (which would silently split the paired
19165        // `HashSet<&str>` name-set seed's collect input from the
19166        // pre-flight `.is_empty()` refusal probe's input from the per-
19167        // member validate loop's traversal input from the
19168        // programs.yaml emitter's per-entry fan-out loop's input from
19169        // the `feira app graph` per-member print traversal's input).
19170        //
19171        // Peer of the sibling M2
19172        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
19173        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
19174        // `:supervisor` static-child-list axis and the sibling M3
19175        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
19176        // (a6e18d7) `&[String]` byte-equal pin on the per-
19177        // `:placement` distribution-target-list axis — extends the
19178        // slice-return-accessor byte-equal-projection discipline onto
19179        // the outermost M3 mesh-slot type's per-Aplicacao member-list
19180        // `Vec`-carry axis.
19181        let fixtures: Vec<Vec<Membro>> = vec![
19182            Vec::new(),
19183            vec![membro("catalog", "^0.1")],
19184            vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
19185            vec![
19186                membro("catalog", "^0.1"),
19187                membro("cart", "^0.1"),
19188                membro("payment", "^0.2"),
19189            ],
19190        ];
19191        for membros in fixtures {
19192            let s = AplicacaoSpec {
19193                membros: membros.clone(),
19194                contratos: Vec::new(),
19195                politicas: MeshPolicy::default(),
19196                placement: Placement::default(),
19197                entrada: None,
19198            };
19199            assert_eq!(
19200                s.membros(),
19201                membros.as_slice(),
19202                "AplicacaoSpec::membros must return :membros verbatim \
19203                 (got {:?}, expected {:?})",
19204                s.membros(),
19205                membros.as_slice(),
19206            );
19207            assert_eq!(
19208                s.membros(),
19209                s.membros.as_slice(),
19210                "AplicacaoSpec::membros accessor and .membros.as_slice() \
19211                 field access must byte-equal — the accessor is the \
19212                 substrate-primitive typed dispatch every downstream \
19213                 member-list consumer must route through",
19214            );
19215            assert_eq!(
19216                s.membros().len(),
19217                s.membros.len(),
19218                "AplicacaoSpec::membros().len() must byte-equal \
19219                 self.membros.len() — a length-drift would silently \
19220                 split the paired `HashSet<&str>` name-set seed's \
19221                 collect input from the pre-flight `.is_empty()` \
19222                 refusal probe input from the per-member validate \
19223                 loop's traversal input",
19224            );
19225        }
19226    }
19227
19228    #[test]
19229    fn validate_reads_through_lifted_membros_accessor() {
19230        // Three-consumer coherence pin: the
19231        // [`AplicacaoSpec::validate_membros`] pre-flight
19232        // `self.membros().is_empty()` refusal probe (which must trip
19233        // [`AplicacaoError::NoMembros`] when the accessor projects the
19234        // empty slice), the same method's per-member validate loop's
19235        // `for m in self.membros()` traversal (which must reach every
19236        // entry in the same order the accessor projects, so both the
19237        // per-entry empty-`:caixa` gate that trips
19238        // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
19239        // detection `insert_first_seen` that trips
19240        // [`AplicacaoError::MembroDuplicate`] key off the accessor's
19241        // projection), and the peer [`AplicacaoSpec::validate`]'s
19242        // `HashSet<&str>` name-set seed's
19243        // `self.membros().iter().map(Membro::nome).collect()` collect
19244        // input (which every `:contratos` `:de` / `:para` membership
19245        // lookup rejects an unknown name against) must all three key
19246        // off the lifted accessor, so any future rebrand on the typed
19247        // slot's reader shape lands at exactly one place. Pins the
19248        // three-site coherence by exercising each production consumer
19249        // end-to-end: (1) the `NoMembros` refusal under the empty
19250        // slice, (2) the `MembroCaixaEmpty` refusal fires on the
19251        // second entry of a two-member cohort whose head is valid but
19252        // tail has an empty `:caixa` (which requires the loop to
19253        // reach the second entry through the accessor), and (3) the
19254        // `MembroDuplicate` refusal fires on the second entry of a
19255        // two-member cohort that shares a `:caixa` name (which
19256        // requires the loop to reach both entries through the
19257        // accessor for the dedup HashSet's second insert to collide).
19258        //
19259        // Peer of the sibling M2
19260        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
19261        // (bc92bce) coherence pin on the per-`:supervisor` static-
19262        // child-list axis and the sibling M3
19263        // `validate_placement_reads_through_lifted_clusters_accessor`
19264        // (a6e18d7) coherence pin on the per-`:placement` distribution-
19265        // target-list axis — extends the slice-return-accessor
19266        // multi-consumer coherence discipline onto the outermost M3
19267        // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
19268
19269        // (1) Pre-flight `.is_empty()` probe: the empty slice must
19270        // trip `NoMembros`.
19271        let mut spec = three_member_spec();
19272        spec.membros = Vec::new();
19273        assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
19274        assert!(
19275            spec.membros().is_empty(),
19276            "the pre-flight refusal input must be the empty slice per \
19277             the accessor's projection",
19278        );
19279
19280        // (2) Per-member validate loop: a two-member cohort with an
19281        // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
19282        // the tail — the loop must reach the second entry through
19283        // the accessor.
19284        let mut spec = three_member_spec();
19285        spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
19286        assert_eq!(
19287            spec.validate().unwrap_err(),
19288            AplicacaoError::MembroCaixaEmpty,
19289        );
19290        assert_eq!(
19291            spec.membros().len(),
19292            2,
19293            "the per-member validate loop's traversal input must be \
19294             a two-element slice per the accessor's projection",
19295        );
19296
19297        // (3) Per-member validate loop: a two-member cohort that
19298        // shares a `:caixa` name must trip `MembroDuplicate` on the
19299        // second entry — the loop must reach both entries through the
19300        // accessor for the dedup HashSet's second insert to collide.
19301        let mut spec = three_member_spec();
19302        spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
19303        match spec.validate().unwrap_err() {
19304            AplicacaoError::MembroDuplicate { caixa } => {
19305                assert_eq!(
19306                    caixa, "catalog",
19307                    "MembroDuplicate.caixa must carry the shared \
19308                     member name verbatim",
19309                );
19310            }
19311            other => panic!("expected MembroDuplicate, got {other:?}"),
19312        }
19313        assert_eq!(
19314            spec.membros().len(),
19315            2,
19316            "the per-member validate loop's traversal input must be \
19317             a two-element slice per the accessor's projection",
19318        );
19319    }
19320
19321    #[test]
19322    fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
19323        // The canonical per-`:contratos` contract-list-slice-shape pin:
19324        // [`AplicacaoSpec::contratos`] must return the `:contratos`
19325        // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
19326        // slice-view over the same backing buffer the raw
19327        // `self.contratos.as_slice()` field access borrows from, byte-
19328        // equal across every representative fixture in the accept-set —
19329        // the empty slice (the pre-validation "internal-only mesh" shape
19330        // an Aplicacao whose members exchange no typed edges renders
19331        // through), the singleton slice (the minimal one-edge Aplicacao
19332        // shape), and multi-entry cohorts (the peer multi-edge shapes
19333        // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
19334        // of the application graph).
19335        //
19336        // Pins against a future silent detour that returned
19337        // `&Vec<WitContract>` (which would type-check but leak the
19338        // storage-side `Vec`'s grow/push/reserve surface no consumer of
19339        // the typed view reaches for), a fresh-allocated
19340        // `Vec<WitContract>` copy (which would type-check via a coercion
19341        // but silently break every downstream caller that relied on the
19342        // slice sharing the backing buffer's identity), or an out-of-
19343        // order or length-drifted projection (which would silently split
19344        // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
19345        // seed's traversal input from the `detect_sync_cycles` per-edge
19346        // adjacency-list seed's traversal input from the
19347        // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
19348        // BTreeMap grouping loop's traversal input from the
19349        // `feira app graph` per-contract print traversal's input).
19350        //
19351        // Peer of the immediately-adjacent sibling M3
19352        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
19353        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
19354        // node-list axis, the sibling M3
19355        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
19356        // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
19357        // distribution-target-list axis, and the sibling M2
19358        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
19359        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
19360        // `:supervisor` static-child-list axis — extends the slice-
19361        // return-accessor byte-equal-projection discipline onto the
19362        // outermost M3 mesh-slot type's per-Aplicacao contract-list
19363        // `Vec`-carry axis, closing the last unlifted per-
19364        // `AplicacaoSpec` `Vec`-carry axis.
19365        let fixtures: Vec<Vec<WitContract>> = vec![
19366            Vec::new(),
19367            vec![contract_http("cart", "catalog", "/products/:id")],
19368            vec![
19369                contract_http("cart", "catalog", "/products/:id"),
19370                contract_http("cart", "payment", "/charge"),
19371            ],
19372            vec![
19373                contract_http("cart", "catalog", "/products/:id"),
19374                contract_http("cart", "payment", "/charge"),
19375                contract_http("payment", "catalog", "/audit"),
19376            ],
19377        ];
19378        for contratos in fixtures {
19379            let s = AplicacaoSpec {
19380                membros: vec![
19381                    membro("catalog", "^0.1"),
19382                    membro("cart", "^0.1"),
19383                    membro("payment", "^0.2"),
19384                ],
19385                contratos: contratos.clone(),
19386                politicas: MeshPolicy::default(),
19387                placement: Placement::default(),
19388                entrada: None,
19389            };
19390            assert_eq!(
19391                s.contratos(),
19392                contratos.as_slice(),
19393                "AplicacaoSpec::contratos must return :contratos verbatim \
19394                 (got {:?}, expected {:?})",
19395                s.contratos(),
19396                contratos.as_slice(),
19397            );
19398            assert_eq!(
19399                s.contratos(),
19400                s.contratos.as_slice(),
19401                "AplicacaoSpec::contratos accessor and \
19402                 .contratos.as_slice() field access must byte-equal — \
19403                 the accessor is the substrate-primitive typed dispatch \
19404                 every downstream contract-list consumer must route \
19405                 through",
19406            );
19407            assert_eq!(
19408                s.contratos().len(),
19409                s.contratos.len(),
19410                "AplicacaoSpec::contratos().len() must byte-equal \
19411                 self.contratos.len() — a length-drift would silently \
19412                 split the paired per-edge validate-loop's traversal \
19413                 input from the sync-cycle adjacency-list seed's \
19414                 traversal input from the cilium_network_policies \
19415                 per-`(:de, :para)` BTreeMap grouping loop's traversal \
19416                 input from the `feira app graph` per-contract print \
19417                 traversal's input",
19418            );
19419        }
19420    }
19421
19422    #[test]
19423    fn validate_reads_through_lifted_contratos_accessor() {
19424        // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
19425        // per-`:contratos` validate-loop's `for c in self.contratos()`
19426        // traversal (which must reach every entry in the same order the
19427        // accessor projects, so both the per-entry
19428        // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
19429        // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
19430        // dedup `HashSet` insert key off the accessor's projection),
19431        // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
19432        // `for c in self.contratos()` adjacency-list seed (which drives
19433        // the sync-subgraph deadlock-detection gate via
19434        // [`AplicacaoError::SyncCycle`]), and the peer
19435        // [`caixa_mesh::cilium_network_policies`]'s
19436        // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
19437        // grouping loop (which drives the per-CNP fan-out) must all
19438        // three key off the lifted accessor, so any future rebrand on
19439        // the typed slot's reader shape lands at exactly one place. Pins
19440        // the three-site coherence by exercising the two caixa-core
19441        // production consumers end-to-end: (1) the empty-`:contratos`
19442        // slice must validate without a per-edge diagnostic (the
19443        // per-edge loop is a no-op under the empty projection), (2) the
19444        // `ContratoMemberMissing` refusal fires on the second entry of a
19445        // two-edge cohort whose head references a valid member but tail
19446        // references a phantom name (which requires the loop to reach
19447        // the second entry through the accessor), and (3) the
19448        // `SyncCycle` refusal fires on a self-referential two-edge
19449        // cohort through the sync-cycle detector's peer projection
19450        // (which requires the detector to iterate the accessor's
19451        // projection to add the back-edge to its adjacency list).
19452        //
19453        // Peer of the sibling M3
19454        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
19455        // three-consumer coherence pin on the per-`:membros` node-list
19456        // axis and the sibling M3
19457        // `validate_placement_reads_through_lifted_clusters_accessor`
19458        // (a6e18d7) coherence pin on the per-`:placement` distribution-
19459        // target-list axis — extends the slice-return-accessor multi-
19460        // consumer coherence discipline onto the outermost M3 mesh-slot
19461        // type's per-Aplicacao contract-list `Vec`-carry axis.
19462
19463        // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
19464        // and no per-edge diagnostic surfaces. Validate succeeds on
19465        // the well-formed `:membros` head.
19466        let mut spec = three_member_spec();
19467        spec.contratos = Vec::new();
19468        assert!(
19469            spec.validate().is_ok(),
19470            "empty :contratos must validate — the per-edge loop is a \
19471             no-op under the accessor's empty projection",
19472        );
19473        assert!(
19474            spec.contratos().is_empty(),
19475            "the per-edge validate loop's traversal input must be the \
19476             empty slice per the accessor's projection",
19477        );
19478
19479        // (2) Per-edge validate loop: a two-edge cohort whose tail
19480        // references a phantom `:para` member must trip
19481        // `ContratoMemberMissing` on the tail — the loop must reach
19482        // the second entry through the accessor for the membership
19483        // lookup to fail on the phantom name.
19484        let mut spec = three_member_spec();
19485        spec.contratos = vec![
19486            contract_http("cart", "catalog", "/products/:id"),
19487            contract_http("cart", "phantom", "/x"),
19488        ];
19489        let err = spec.validate().unwrap_err();
19490        assert!(
19491            matches!(
19492                err,
19493                AplicacaoError::ContratoMemberMissing { ref caixa }
19494                    if caixa == "phantom"
19495            ),
19496            "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
19497        );
19498        assert_eq!(
19499            spec.contratos().len(),
19500            2,
19501            "the per-edge validate loop's traversal input must be \
19502             a two-element slice per the accessor's projection",
19503        );
19504
19505        // (3) Sync-cycle detector: a two-edge synchronous cohort
19506        // whose second edge closes the sync-subgraph back onto the
19507        // first must trip [`AplicacaoError::ContratoCycle`] — the
19508        // detector must iterate the accessor's projection to add
19509        // both edges to its adjacency list, so a length-drift on
19510        // the accessor's projection would silently disagree with
19511        // the sync-cycle detector on which edge closes the loop.
19512        // Peer projection to the `validate` per-edge loop above:
19513        // the sync-cycle detector routes through the same lifted
19514        // accessor, so a rebrand of the reader shape lands at one
19515        // place. Uses a two-edge cohort (cart → catalog → cart)
19516        // because the per-edge `ContratoSelfLoop` gate fires before
19517        // the sync-cycle detector on a single self-referential edge
19518        // (`cart → cart`) — the cycle-detector's input must be a
19519        // multi-edge cohort for its per-edge traversal input to be
19520        // observably wider than the per-edge validate loop's input.
19521        let mut spec = three_member_spec();
19522        spec.contratos = vec![
19523            contract_http("cart", "catalog", "/products/:id"),
19524            contract_http("catalog", "cart", "/callback"),
19525        ];
19526        let err = spec.validate().unwrap_err();
19527        assert!(
19528            matches!(err, AplicacaoError::ContratoCycle { .. }),
19529            "expected ContratoCycle from the sync-cycle detector on a \
19530             two-edge back-edge cohort, got {err:?}",
19531        );
19532        assert_eq!(
19533            spec.contratos().len(),
19534            2,
19535            "the sync-cycle detector's traversal input must be a \
19536             two-element slice per the accessor's projection",
19537        );
19538    }
19539
19540    #[test]
19541    fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
19542        // The canonical per-`:politicas` outer-composite-reference-shape
19543        // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
19544        // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
19545        // the same backing storage the raw `&self.politicas` field
19546        // access borrows from, byte-equal across every representative
19547        // fixture in the accept-set — the default `MeshPolicy` (the
19548        // author-empty "no policy on any axis" shape whose
19549        // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
19550        // shapes carrying one axis at a time
19551        // (`{mtls_required, timeout, retries, circuit_breaker,
19552        // rate_limit}` — the minimal five-axis fan-out over the
19553        // per-axis lifted accessor family every downstream mesh-artifact
19554        // emitter dispatches on), and the multi-axis composite (the
19555        // canonical `three_member_spec` fixture's `{timeout, retries,
19556        // mtls_required}` triple — the load-bearing shape every
19557        // Aplicacao-scoped fixture in this suite constructs).
19558        //
19559        // Pins against a future silent detour that returned a fresh-
19560        // cloned `MeshPolicy` copy (which would type-check via a `Clone`
19561        // impl but silently break every downstream caller that relied
19562        // on the reference sharing the composite's backing identity), a
19563        // reference to an operator-resolved overlay (the future
19564        // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
19565        // acknowledges — its resolution must land at exactly this
19566        // accessor body, not silently divert the raw slot away from a
19567        // second consumer), or an axis-shuffled projection (a future
19568        // detour that swapped `timeout` and `retries` through the
19569        // accessor would silently split the paired `validate_politicas`
19570        // per-axis bracket-dispatch's traversal input from the peer
19571        // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
19572        // emitter's fan-out input from the peer
19573        // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
19574        // overlay emitter's fan-out input).
19575        //
19576        // Peer of the sibling M3
19577        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
19578        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
19579        // node-list `Vec`-carry axis and the sibling M3
19580        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
19581        // (0dcc926) `&[WitContract]` byte-equal pin on the per-
19582        // `:contratos` edge-list `Vec`-carry axis — extends the outer-
19583        // accessor byte-equal-projection discipline onto the outermost
19584        // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
19585        // reference axis, the first `&Composite`-return accessor on the
19586        // outer [`AplicacaoSpec`] type.
19587        let fixtures: Vec<MeshPolicy> = vec![
19588            MeshPolicy::default(),
19589            MeshPolicy {
19590                mtls_required: Some(true),
19591                ..MeshPolicy::default()
19592            },
19593            MeshPolicy {
19594                mtls_required: Some(false),
19595                ..MeshPolicy::default()
19596            },
19597            MeshPolicy {
19598                timeout: Some(Duration::from_secs(30)),
19599                ..MeshPolicy::default()
19600            },
19601            MeshPolicy {
19602                retries: Some(3),
19603                ..MeshPolicy::default()
19604            },
19605            MeshPolicy {
19606                circuit_breaker: Some(CircuitBreaker {
19607                    max_failures: 5,
19608                    window: Duration::from_secs(30),
19609                }),
19610                ..MeshPolicy::default()
19611            },
19612            MeshPolicy {
19613                rate_limit: Some(RateLimit {
19614                    rate: 100,
19615                    window: Duration::from_secs(1),
19616                }),
19617                ..MeshPolicy::default()
19618            },
19619            MeshPolicy {
19620                timeout: Some(Duration::from_secs(30)),
19621                retries: Some(3),
19622                mtls_required: Some(true),
19623                ..MeshPolicy::default()
19624            },
19625        ];
19626        for politicas in fixtures {
19627            let s = AplicacaoSpec {
19628                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
19629                contratos: Vec::new(),
19630                politicas: politicas.clone(),
19631                placement: Placement::default(),
19632                entrada: None,
19633            };
19634            assert_eq!(
19635                *s.politicas(),
19636                politicas,
19637                "AplicacaoSpec::politicas must return :politicas verbatim \
19638                 (got {:?}, expected {:?})",
19639                s.politicas(),
19640                politicas,
19641            );
19642            assert!(
19643                std::ptr::eq(s.politicas(), &s.politicas),
19644                "AplicacaoSpec::politicas accessor and &self.politicas \
19645                 field access must borrow the same backing storage — \
19646                 the accessor is the substrate-primitive typed dispatch \
19647                 every downstream mesh-policy composite consumer must \
19648                 route through, and a reference-identity split would \
19649                 silently break every consumer that relied on the \
19650                 borrow sharing the composite's storage",
19651            );
19652            assert_eq!(
19653                s.politicas().is_empty(),
19654                s.politicas.is_empty(),
19655                "AplicacaoSpec::politicas().is_empty() must byte-equal \
19656                 self.politicas.is_empty() — an emptiness-drift would \
19657                 silently split the paired `validate_politicas` \
19658                 per-axis bracket-dispatch's seed from the peer \
19659                 caixa-mesh CNP mTLS-overlay emitter's key from the \
19660                 peer caixa-mesh HTTPRoute timeout+retry overlay \
19661                 emitter's key",
19662            );
19663        }
19664    }
19665
19666    #[test]
19667    fn validate_politicas_reads_through_lifted_politicas_accessor() {
19668        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
19669        // per-axis bracket-dispatch seed (`let p = self.politicas();`,
19670        // followed by the per-axis fan-out `p.timeout()` /
19671        // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
19672        // the lifted axis-level accessor family) must key off the
19673        // lifted outer accessor, so any future rebrand on the typed
19674        // slot's outer-composite reader shape lands at exactly one
19675        // place. Pins the multi-axis coherence by exercising each
19676        // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
19677        // a `Some(Duration::ZERO)` timeout under the outer accessor's
19678        // reference projection, (2) `PolicyRetriesZero` fires on a
19679        // `Some(0)` retries under the same projection, and (3) an
19680        // empty [`MeshPolicy::default`] passes `validate_politicas` —
19681        // the outer accessor's reference-projection reaches every
19682        // per-axis branch without silently short-circuiting any.
19683        //
19684        // Peer of the sibling M3
19685        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
19686        // three-consumer coherence pin on the per-`:membros` node-list
19687        // axis and the sibling M3
19688        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
19689        // three-consumer coherence pin on the per-`:contratos`
19690        // edge-list axis — extends the multi-consumer coherence
19691        // discipline onto the outermost M3 mesh-slot type's per-
19692        // Aplicacao mesh-policy composite-reference axis, the first
19693        // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
19694        // type.
19695
19696        // (1) `PolicyTimeoutZero` refusal under the outer accessor's
19697        // reference projection: a `Some(Duration::ZERO)` timeout must
19698        // trip the zero-floor gate. The bracket-dispatch's first arm
19699        // reads `p.timeout()` on the reference returned by the outer
19700        // accessor.
19701        let mut spec = three_member_spec();
19702        spec.politicas.timeout = Some(Duration::ZERO);
19703        spec.politicas.retries = None;
19704        spec.politicas.circuit_breaker = None;
19705        spec.politicas.rate_limit = None;
19706        assert_eq!(
19707            spec.validate().unwrap_err(),
19708            AplicacaoError::PolicyTimeoutZero,
19709        );
19710        assert!(
19711            std::ptr::eq(spec.politicas(), &spec.politicas),
19712            "the `validate_politicas` per-axis bracket-dispatch's \
19713             traversal input must be the same backing composite the \
19714             accessor's reference projection borrows from",
19715        );
19716
19717        // (2) `PolicyRetriesZero` refusal under the outer accessor's
19718        // reference projection: a `Some(0)` retries must trip the
19719        // zero-floor gate. The bracket-dispatch's second arm reads
19720        // `p.retries()` on the reference returned by the outer accessor.
19721        let mut spec = three_member_spec();
19722        spec.politicas.timeout = None;
19723        spec.politicas.retries = Some(0);
19724        spec.politicas.circuit_breaker = None;
19725        spec.politicas.rate_limit = None;
19726        assert_eq!(
19727            spec.validate().unwrap_err(),
19728            AplicacaoError::PolicyRetriesZero,
19729        );
19730
19731        // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
19732        // — every per-axis arm short-circuits on `None`, so the outer
19733        // accessor's reference projection reaches the fall-through
19734        // `Ok(())` without any per-axis refusal firing.
19735        let mut spec = three_member_spec();
19736        spec.politicas = MeshPolicy::default();
19737        assert!(
19738            spec.validate().is_ok(),
19739            "an empty `MeshPolicy` must pass `validate_politicas` — \
19740             every per-axis arm short-circuits on `None` under the \
19741             outer accessor's reference projection",
19742        );
19743        assert!(
19744            spec.politicas().is_empty(),
19745            "the outer accessor's reference projection must be the \
19746             empty composite per the `MeshPolicy::default()` fixture",
19747        );
19748    }
19749
19750    #[test]
19751    #[allow(clippy::too_many_lines)]
19752    fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
19753        // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
19754        // per-axis bracket-dispatch's `:timeout` and `:retries` arms
19755        // must both key off the lifted axis-level accessors
19756        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
19757        // the peer `:circuit-breaker` / `:rate-limit` arms already
19758        // routing through [`MeshPolicy::circuit_breaker`] /
19759        // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
19760        // per axis on the substrate primitive" shape at the fan-out
19761        // (four axes, four accessors, no raw-field-access site
19762        // anywhere on the bracket-dispatch). Pins the per-axis
19763        // coherence at the accept-set boundaries the bracket carves:
19764        //   1. accessor byte-equal to raw field on every representative
19765        //      accept-set value (`None`, sub-cap, at-cap, past-cap
19766        //      sentinel) — a future accessor drift that no longer
19767        //      shipped the raw slot verbatim would surface here,
19768        //   2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
19769        //      routed through the accessor's projection, proving the
19770        //      first arm reads through the accessor rather than a
19771        //      silent-detour peer-axis field access,
19772        //   3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
19773        //      through the accessor's projection, proving the second
19774        //      arm reads through the accessor,
19775        //   4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
19776        //      passes validate under the accessor projection (paired
19777        //      with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
19778        //      sibling axis), pinning the upper-boundary accept-arm
19779        //      also routes through the accessor.
19780        //
19781        // Peer of the sibling M3
19782        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
19783        // outer-composite-reference coherence pin (which asserts the
19784        // `let p = self.politicas()` seed); extends the discipline onto
19785        // the per-axis fan-out layer that consumes the seed's
19786        // reference. Same shape as
19787        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
19788        // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
19789        // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
19790        // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
19791
19792        // (1) Accessor byte-equal to raw field on the `:timeout` axis
19793        // across the accept-set boundaries the bracket dispatch's
19794        // three-arm gate carves out
19795        // ([`crate::render::require_positive_canonical_bounded_duration`]
19796        // — zero-floor + canonical-form + upper-cap).
19797        for timeout in [
19798            None,
19799            Some(Duration::ZERO),
19800            Some(Duration::from_millis(1)),
19801            Some(POLICY_TIMEOUT_MAX),
19802        ] {
19803            let p = MeshPolicy {
19804                timeout,
19805                ..MeshPolicy::default()
19806            };
19807            assert_eq!(
19808                p.timeout(),
19809                p.timeout,
19810                "MeshPolicy::timeout accessor must byte-equal the raw \
19811                 .timeout field across every accept-set boundary the \
19812                 validate_politicas :timeout arm carves out — a drift \
19813                 here would silently split the validate bracket's arm \
19814                 from the peer caixa-mesh HTTPRoute timeout-overlay \
19815                 emitter's read",
19816            );
19817        }
19818
19819        // (2) Accessor byte-equal to raw field on the `:retries` axis
19820        // across the accept-set boundaries the bracket dispatch's
19821        // two-arm gate carves out
19822        // ([`crate::render::require_positive_bounded_u32`] — zero-floor
19823        // + upper-cap).
19824        for retries in [
19825            None,
19826            Some(0u32),
19827            Some(1u32),
19828            Some(POLICY_RETRIES_MAX),
19829            Some(POLICY_RETRIES_MAX + 1),
19830            Some(u32::MAX),
19831        ] {
19832            let p = MeshPolicy {
19833                retries,
19834                ..MeshPolicy::default()
19835            };
19836            assert_eq!(
19837                p.retries(),
19838                p.retries,
19839                "MeshPolicy::retries accessor must byte-equal the raw \
19840                 .retries field across every accept-set boundary the \
19841                 validate_politicas :retries arm carves out — a drift \
19842                 here would silently split the validate bracket's arm \
19843                 from the peer caixa-mesh HTTPRoute retry-overlay \
19844                 emitter's read",
19845            );
19846        }
19847
19848        // (3) `PolicyTimeoutZero` fires on the accessor-projected
19849        // zero-floor boundary. A silent detour that no longer read
19850        // through `p.timeout()` (a peer-axis field read, an accidental
19851        // Option::and-then chain that collapsed the None arm to Some,
19852        // an accessor rebrand that clamped the return through the
19853        // upper cap) would fail to refuse here.
19854        let mut spec = three_member_spec();
19855        spec.politicas.timeout = Some(Duration::ZERO);
19856        spec.politicas.retries = None;
19857        spec.politicas.circuit_breaker = None;
19858        spec.politicas.rate_limit = None;
19859        assert_eq!(
19860            spec.politicas().timeout(),
19861            Some(Duration::ZERO),
19862            "the accessor projection must reflect the fixture's \
19863             `Some(Duration::ZERO)` :timeout verbatim",
19864        );
19865        assert_eq!(
19866            spec.validate().unwrap_err(),
19867            AplicacaoError::PolicyTimeoutZero,
19868            "the validate_politicas :timeout zero-floor arm must fire \
19869             through the lifted accessor's projection — a silent \
19870             detour to a peer-axis field would fail to refuse",
19871        );
19872
19873        // (4) `PolicyRetriesZero` fires on the accessor-projected
19874        // zero-floor boundary on the sibling `:retries` axis.
19875        let mut spec = three_member_spec();
19876        spec.politicas.timeout = None;
19877        spec.politicas.retries = Some(0);
19878        spec.politicas.circuit_breaker = None;
19879        spec.politicas.rate_limit = None;
19880        assert_eq!(
19881            spec.politicas().retries(),
19882            Some(0),
19883            "the accessor projection must reflect the fixture's \
19884             `Some(0)` :retries verbatim",
19885        );
19886        assert_eq!(
19887            spec.validate().unwrap_err(),
19888            AplicacaoError::PolicyRetriesZero,
19889            "the validate_politicas :retries zero-floor arm must fire \
19890             through the lifted accessor's projection — a silent \
19891             detour to a peer-axis field would fail to refuse",
19892        );
19893
19894        // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
19895        // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
19896        // must pass validate under the accessor projection — pins the
19897        // upper-boundary accept-arm also routes through the lifted
19898        // accessor (a drift that clamped or short-circuited at the
19899        // upper boundary would fail the whole-spec validate here).
19900        let mut spec = three_member_spec();
19901        spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
19902        spec.politicas.retries = Some(POLICY_RETRIES_MAX);
19903        spec.politicas.circuit_breaker = None;
19904        spec.politicas.rate_limit = None;
19905        assert_eq!(
19906            spec.politicas().timeout(),
19907            Some(POLICY_TIMEOUT_MAX),
19908            "the accessor projection must reflect the fixture's \
19909             at-cap :timeout verbatim",
19910        );
19911        assert_eq!(
19912            spec.politicas().retries(),
19913            Some(POLICY_RETRIES_MAX),
19914            "the accessor projection must reflect the fixture's \
19915             at-cap :retries verbatim",
19916        );
19917        assert!(
19918            spec.validate().is_ok(),
19919            "at-cap :timeout + :retries must pass validate under the \
19920             accessor projection — the upper-boundary accept-arm on \
19921             both axes routes through the lifted accessor",
19922        );
19923    }
19924
19925    #[test]
19926    fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
19927        // The canonical per-`:placement` outer-composite-reference-shape
19928        // pin: [`AplicacaoSpec::placement`] must return the `:placement`
19929        // typed `Placement` verbatim as a `&Placement` reference over the
19930        // same backing storage the raw `&self.placement` field access
19931        // borrows from, byte-equal across every representative fixture in
19932        // the accept-set — the default `Placement` (the substrate seed
19933        // shape whose [`PlacementStrategy::default`] evaluates to
19934        // `SingleNode` with an empty `:clusters` pool and both
19935        // optional-scalar axes `None`), and every canonical strategy /
19936        // cluster-pool / optional-scalar combination the
19937        // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
19938        // three [`PlacementStrategy`] variants — `SingleNode`,
19939        // `Replicated`, `Sharded` — cross-projected with a non-empty
19940        // `:clusters` pool and, on the `Sharded` arm, a non-empty
19941        // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
19942        // canonical `three_member_spec` `Replicated` fixture's
19943        // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
19944        //
19945        // Pins against a future silent detour that returned a fresh-
19946        // cloned `Placement` copy (which would type-check via a `Clone`
19947        // impl but silently break every downstream caller that relied on
19948        // the reference sharing the composite's backing identity), a
19949        // reference to an operator-resolved overlay (the future per-
19950        // cluster `:placement-overrides` slot MESH-COMPOSITION §V
19951        // acknowledges — its resolution must land at exactly this
19952        // accessor body, not silently divert the raw slot away from a
19953        // second consumer), or an axis-shuffled projection (a future
19954        // detour that swapped `clusters` and `affinity` through the
19955        // accessor would silently split the paired `validate_placement`
19956        // per-axis bracket-dispatch's traversal input from the peer
19957        // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
19958        // programs.yaml distribution-annotation emitter's fan-out input
19959        // from the peer `feira app graph` per-Aplicacao print line's
19960        // input).
19961        //
19962        // Peer of the sibling M3
19963        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
19964        // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
19965        // outer mesh-policy composite-reference axis, and of the sibling
19966        // slice-return `aplicacao_spec_membros_returns_membros_slice_
19967        // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
19968        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
19969        // across_permutations` (0dcc926) `&[WitContract]` pins — extends
19970        // the outer-accessor byte-equal-projection discipline onto the
19971        // outermost M3 mesh-slot type's per-Aplicacao distribution
19972        // composite-reference axis, the second `&Composite`-return
19973        // accessor on the outer [`AplicacaoSpec`] type.
19974        let fixtures: Vec<Placement> = vec![
19975            Placement::default(),
19976            Placement {
19977                estrategia: PlacementStrategy::SingleNode,
19978                clusters: vec!["rio".into()],
19979                affinity: None,
19980                shard_key: None,
19981            },
19982            Placement {
19983                estrategia: PlacementStrategy::Replicated,
19984                clusters: vec!["rio".into(), "mar".into()],
19985                affinity: None,
19986                shard_key: None,
19987            },
19988            Placement {
19989                estrategia: PlacementStrategy::Replicated,
19990                clusters: vec!["rio".into(), "mar".into()],
19991                affinity: Some("data-locality".into()),
19992                shard_key: None,
19993            },
19994            Placement {
19995                estrategia: PlacementStrategy::Sharded,
19996                clusters: vec!["rio".into(), "mar".into()],
19997                affinity: None,
19998                shard_key: Some("tenantId".into()),
19999            },
20000            Placement {
20001                estrategia: PlacementStrategy::Sharded,
20002                clusters: vec!["rio".into(), "mar".into(), "sol".into()],
20003                affinity: Some("low-latency".into()),
20004                shard_key: Some("metadata.tenantId".into()),
20005            },
20006        ];
20007        for placement in fixtures {
20008            let s = AplicacaoSpec {
20009                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
20010                contratos: Vec::new(),
20011                politicas: MeshPolicy::default(),
20012                placement: placement.clone(),
20013                entrada: None,
20014            };
20015            assert_eq!(
20016                *s.placement(),
20017                placement,
20018                "AplicacaoSpec::placement must return :placement verbatim \
20019                 (got {:?}, expected {:?})",
20020                s.placement(),
20021                placement,
20022            );
20023            assert!(
20024                std::ptr::eq(s.placement(), &s.placement),
20025                "AplicacaoSpec::placement accessor and &self.placement \
20026                 field access must borrow the same backing storage — the \
20027                 accessor is the substrate-primitive typed dispatch every \
20028                 downstream distribution-composite consumer must route \
20029                 through, and a reference-identity split would silently \
20030                 break every consumer that relied on the borrow sharing \
20031                 the composite's storage",
20032            );
20033            assert_eq!(
20034                s.placement().estrategia(),
20035                s.placement.estrategia,
20036                "AplicacaoSpec::placement().estrategia() must byte-equal \
20037                 self.placement.estrategia — a strategy-drift would \
20038                 silently split the paired `validate_placement` \
20039                 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
20040                 peer caixa-mesh programs.yaml `placement.estrategia` \
20041                 emitter's key from the peer `feira app graph` printer's \
20042                 strategy label",
20043            );
20044            assert_eq!(
20045                s.placement().clusters(),
20046                s.placement.clusters.as_slice(),
20047                "AplicacaoSpec::placement().clusters() must byte-equal \
20048                 self.placement.clusters — a cluster-pool drift would \
20049                 silently split the paired `validate_placement` \
20050                 pre-flight `.is_empty()` refusal probe's traversal from \
20051                 the peer caixa-mesh programs.yaml `placement.clusters` \
20052                 emitter's fan-out from the peer `feira app graph` \
20053                 printer's cluster list",
20054            );
20055        }
20056    }
20057
20058    #[test]
20059    fn validate_placement_reads_through_lifted_placement_accessor() {
20060        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
20061        // per-axis bracket-dispatch seed (`let p = self.placement();`,
20062        // followed by the per-axis fan-out `p.clusters()` /
20063        // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
20064        // lifted axis-level accessor family) must key off the lifted
20065        // outer accessor, so any future rebrand on the typed slot's
20066        // outer-composite reader shape lands at exactly one place. Pins
20067        // the multi-axis coherence by exercising each per-axis refusal
20068        // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
20069        // `:clusters` pool under the outer accessor's reference
20070        // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
20071        // strategy with a `None` `:shard-key` under the same projection,
20072        // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
20073        // with a `Some` `:shard-key` under the same projection, and
20074        // (4) the canonical `three_member_spec` `Replicated` fixture
20075        // passes `validate_placement` under the outer accessor's
20076        // reference projection — the accessor's reference-projection
20077        // reaches every per-axis branch (cluster-pool refusal, `Sharded`
20078        // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
20079        // without silently short-circuiting any.
20080        //
20081        // Peer of the sibling M3
20082        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
20083        // (534dc21) multi-axis coherence pin on the per-`:politicas`
20084        // outer mesh-policy composite-reference axis — extends the
20085        // multi-consumer coherence discipline onto the outermost M3
20086        // mesh-slot type's per-Aplicacao distribution composite-
20087        // reference axis, the second `&Composite`-return accessor on
20088        // the outer [`AplicacaoSpec`] type.
20089
20090        // (1) `PlacementWithoutClusters` refusal under the outer
20091        // accessor's reference projection: an empty `:clusters` pool
20092        // must trip the pre-flight refusal probe. The bracket-dispatch's
20093        // first arm reads `p.clusters()` on the reference returned by
20094        // the outer accessor.
20095        let mut spec = three_member_spec();
20096        spec.placement.clusters = Vec::new();
20097        assert_eq!(
20098            spec.validate().unwrap_err(),
20099            AplicacaoError::PlacementWithoutClusters {
20100                estrategia: PlacementStrategy::Replicated,
20101            },
20102        );
20103        assert!(
20104            std::ptr::eq(spec.placement(), &spec.placement),
20105            "the `validate_placement` per-axis bracket-dispatch's \
20106             traversal input must be the same backing composite the \
20107             accessor's reference projection borrows from",
20108        );
20109
20110        // (2) `ShardedWithoutKey` refusal under the outer accessor's
20111        // reference projection: a `Sharded` strategy with a `None`
20112        // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
20113        // The bracket-dispatch's third arm reads `p.estrategia()` for
20114        // the match scrutinee then `p.shard_key()` for the cascade
20115        // scrutinee, both on the reference returned by the outer
20116        // accessor.
20117        let mut spec = three_member_spec();
20118        spec.placement.estrategia = PlacementStrategy::Sharded;
20119        spec.placement.shard_key = None;
20120        assert_eq!(
20121            spec.validate().unwrap_err(),
20122            AplicacaoError::ShardedWithoutKey,
20123        );
20124
20125        // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
20126        // reference projection: a non-`Sharded` strategy with a `Some`
20127        // `:shard-key` must trip the declared-but-inert refusal. The
20128        // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
20129        // + `p.estrategia()` for the diagnostic on the reference
20130        // returned by the outer accessor.
20131        let mut spec = three_member_spec();
20132        spec.placement.estrategia = PlacementStrategy::Replicated;
20133        spec.placement.shard_key = Some("tenantId".into());
20134        assert_eq!(
20135            spec.validate().unwrap_err(),
20136            AplicacaoError::ShardKeyOnNonSharded {
20137                estrategia: PlacementStrategy::Replicated,
20138                shard_key: "tenantId".into(),
20139            },
20140        );
20141
20142        // (4) Canonical `three_member_spec` `Replicated` fixture passes
20143        // `validate_placement` — every per-axis arm reaches the fall-
20144        // through `Ok(())` without any per-axis refusal firing under the
20145        // outer accessor's reference projection.
20146        let spec = three_member_spec();
20147        assert!(
20148            spec.validate().is_ok(),
20149            "the canonical Replicated placement fixture must pass \
20150             `validate_placement` — every per-axis arm short-circuits on \
20151             valid input under the outer accessor's reference projection",
20152        );
20153        assert_eq!(
20154            spec.placement().estrategia(),
20155            PlacementStrategy::Replicated,
20156            "the outer accessor's reference projection must be the \
20157             canonical Replicated fixture's strategy",
20158        );
20159        assert_eq!(
20160            spec.placement().clusters(),
20161            &["rio", "mar"],
20162            "the outer accessor's reference projection must be the \
20163             canonical Replicated fixture's cluster pool",
20164        );
20165    }
20166
20167    #[test]
20168    fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
20169        // The canonical per-`:entrada` outer-composite-optional-
20170        // reference-shape pin: [`AplicacaoSpec::entrada`] must return
20171        // the `:entrada` typed `Option<Entrada>` verbatim as an
20172        // `Option<&Entrada>` reference over the same backing storage
20173        // the raw `self.entrada.as_ref()` field access borrows from,
20174        // byte-equal across every representative fixture in the
20175        // accept-set — the author-omitted `None` shape (the
20176        // "internal-only mesh" partition every downstream external-
20177        // gateway emitter treats as "emit nothing"), the minimal
20178        // singleton `:entrada` composite (host + destination + empty
20179        // paths + default port), the paths-carrying composite (the
20180        // canonical `three_member_spec` fixture's ["/api" "/health"]
20181        // path-list shape every HTTPRoute per-rule fan-out emitter
20182        // reads), and the non-default port composite (the canonical
20183        // custom-port shape the port-fallback resolver reads).
20184        //
20185        // Pins against a future silent detour that returned a fresh-
20186        // cloned `Entrada` copy (which would type-check via a `Clone`
20187        // impl but silently break every downstream caller that
20188        // relied on the reference sharing the composite's backing
20189        // identity), a reference to an operator-resolved overlay
20190        // (the future per-cluster `:entrada-overrides` slot the
20191        // MESH-COMPOSITION §V federation roadmap acknowledges — its
20192        // resolution must land at exactly this accessor body, not
20193        // silently divert the raw slot away from a second consumer),
20194        // a `None` → `Some(Entrada::default)` cluster-default
20195        // projection (which would collapse the load-bearing
20196        // "author-omitted `:entrada` ⇒ internal-only mesh" partition
20197        // the peer `gateway_routes` early-return + `feira app graph`
20198        // internal-only-mesh partition both read), or an axis-
20199        // shuffled projection (a future detour that swapped
20200        // `host` and `para` through the accessor would silently
20201        // split the paired `validate` per-`:entrada` shape-and-
20202        // membership gate's traversal input from the peer
20203        // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
20204        // fan-out input from the peer `feira app graph` external-
20205        // gateway summary line).
20206        //
20207        // Peer of the sibling M3
20208        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
20209        // (534dc21) `&MeshPolicy` byte-equal pin on the per-
20210        // `:politicas` outer mesh-policy composite-reference axis
20211        // and of the sibling M3
20212        // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
20213        // (9abb8f0) `&Placement` byte-equal pin on the per-
20214        // `:placement` outer distribution-composite composite-
20215        // reference axis — extends the outer-accessor byte-equal-
20216        // projection discipline onto the last unlifted outermost M3
20217        // mesh-slot type's per-Aplicacao external-gateway composite-
20218        // reference axis, the third and final `&Composite`-return
20219        // accessor on the outer [`AplicacaoSpec`] type.
20220        let fixtures: Vec<Option<Entrada>> = vec![
20221            None,
20222            Some(Entrada {
20223                host: "checkout.quero.cloud".into(),
20224                para: "cart".into(),
20225                paths: Vec::new(),
20226                port: DEFAULT_SERVICO_PORT,
20227            }),
20228            Some(Entrada {
20229                host: "checkout.quero.cloud".into(),
20230                para: "cart".into(),
20231                paths: vec!["/api".into(), "/health".into()],
20232                port: DEFAULT_SERVICO_PORT,
20233            }),
20234            Some(Entrada {
20235                host: "checkout.quero.cloud".into(),
20236                para: "cart".into(),
20237                paths: vec!["/api".into()],
20238                port: 9443,
20239            }),
20240        ];
20241        for entrada in fixtures {
20242            let s = AplicacaoSpec {
20243                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
20244                contratos: Vec::new(),
20245                politicas: MeshPolicy::default(),
20246                placement: Placement::default(),
20247                entrada: entrada.clone(),
20248            };
20249            assert_eq!(
20250                s.entrada(),
20251                entrada.as_ref(),
20252                "AplicacaoSpec::entrada must return :entrada verbatim \
20253                 (got {:?}, expected {:?})",
20254                s.entrada(),
20255                entrada.as_ref(),
20256            );
20257            match (s.entrada(), s.entrada.as_ref()) {
20258                (Some(a), Some(b)) => assert!(
20259                    std::ptr::eq(a, b),
20260                    "AplicacaoSpec::entrada accessor and \
20261                     self.entrada.as_ref() field access must borrow \
20262                     the same backing storage — the accessor is the \
20263                     substrate-primitive typed dispatch every \
20264                     downstream external-gateway composite consumer \
20265                     must route through, and a reference-identity \
20266                     split would silently break every consumer that \
20267                     relied on the borrow sharing the composite's \
20268                     storage",
20269                ),
20270                (None, None) => {}
20271                _ => panic!(
20272                    "AplicacaoSpec::entrada presence bit must byte-\
20273                     equal self.entrada.is_some() — a presence-bit \
20274                     drift would silently split the paired `validate` \
20275                     per-`:entrada` shape-and-membership gate's \
20276                     traversal head from the peer \
20277                     caixa-mesh gateway_routes early-return partition \
20278                     from the peer `feira app graph` internal-only-\
20279                     mesh partition",
20280                ),
20281            }
20282            assert_eq!(
20283                s.entrada().is_some(),
20284                s.entrada.is_some(),
20285                "AplicacaoSpec::entrada().is_some() must byte-equal \
20286                 self.entrada.is_some() — a presence-bit drift would \
20287                 silently split every downstream `Option<&Entrada>` \
20288                 consumer's partition on the internal-only-mesh arm",
20289            );
20290        }
20291    }
20292
20293    #[test]
20294    fn validate_reads_through_lifted_entrada_accessor() {
20295        // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
20296        // per-`:entrada` shape-and-membership gate (`if let Some(e) =
20297        // self.entrada() { … }`, followed by the per-axis fan-out
20298        // `validate_entrada_para(&e.para)` /
20299        // `EntradaMemberMissing` membership lookup /
20300        // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
20301        // per-`e.paths` `validate_entrada_path` traversal) must key
20302        // off the lifted outer accessor, so any future rebrand on
20303        // the typed slot's outer-composite reader shape lands at
20304        // exactly one place. Pins the multi-axis coherence by
20305        // exercising each per-axis refusal end-to-end: (1) the
20306        // author-omitted `None` shape short-circuits past every
20307        // per-`:entrada` refusal (the internal-only mesh partition
20308        // the accessor's `None` arm names), (2) `EntradaMemberMissing`
20309        // fires on a well-shaped but phantom `:para` under the outer
20310        // accessor's reference projection, and (3) the canonical
20311        // `three_member_spec` `:entrada` fixture passes `validate`
20312        // under the outer accessor's reference projection.
20313        //
20314        // Peer of the sibling M3
20315        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
20316        // (534dc21) multi-axis coherence pin on the per-`:politicas`
20317        // outer mesh-policy composite-reference axis and the sibling
20318        // M3
20319        // [`validate_placement_reads_through_lifted_placement_accessor`]
20320        // (9abb8f0) multi-axis coherence pin on the per-`:placement`
20321        // outer distribution-composite composite-reference axis —
20322        // extends the multi-consumer coherence discipline onto the
20323        // last unlifted outermost M3 mesh-slot type's per-Aplicacao
20324        // external-gateway composite-reference axis, the third and
20325        // final `&Composite`-return accessor on the outer
20326        // [`AplicacaoSpec`] type.
20327
20328        // (1) `None` :entrada — the internal-only-mesh partition
20329        // short-circuits past every per-`:entrada` refusal. The outer
20330        // accessor's reference projection reaches the fall-through
20331        // `Ok(())` on the `None` arm without any per-axis refusal
20332        // firing.
20333        let mut spec = three_member_spec();
20334        spec.entrada = None;
20335        assert!(
20336            spec.validate().is_ok(),
20337            "an author-omitted `:entrada` must pass `validate` — the \
20338             internal-only-mesh partition short-circuits past every \
20339             per-`:entrada` refusal under the outer accessor's \
20340             reference projection",
20341        );
20342        assert!(
20343            spec.entrada().is_none(),
20344            "the outer accessor's reference projection must name the \
20345             internal-only-mesh partition per the `None` fixture",
20346        );
20347
20348        // (2) `EntradaMemberMissing` refusal under the outer accessor's
20349        // reference projection: a well-shaped but phantom `:para` must
20350        // trip the membership-lookup refusal. The gate's second arm
20351        // reads `e.para` on the reference returned by the outer
20352        // accessor.
20353        let mut spec = three_member_spec();
20354        if let Some(e) = spec.entrada.as_mut() {
20355            e.para = "phantom".into();
20356        }
20357        assert_eq!(
20358            spec.validate().unwrap_err(),
20359            AplicacaoError::EntradaMemberMissing {
20360                para: "phantom".into(),
20361            },
20362        );
20363        match (spec.entrada(), spec.entrada.as_ref()) {
20364            (Some(a), Some(b)) => assert!(
20365                std::ptr::eq(a, b),
20366                "the `validate` per-`:entrada` gate's traversal head \
20367                 must be the same backing composite the accessor's \
20368                 reference projection borrows from",
20369            ),
20370            _ => panic!("fixture must carry Some(:entrada)"),
20371        }
20372
20373        // (3) Canonical `three_member_spec` `:entrada` fixture passes
20374        // `validate` — every per-axis arm reaches the fall-through
20375        // `Ok(())` without any per-axis refusal firing under the
20376        // outer accessor's reference projection.
20377        let spec = three_member_spec();
20378        assert!(
20379            spec.validate().is_ok(),
20380            "the canonical `:entrada` fixture must pass `validate` — \
20381             every per-axis arm short-circuits on valid input under \
20382             the outer accessor's reference projection",
20383        );
20384        assert!(
20385            spec.entrada().is_some(),
20386            "the outer accessor's reference projection must be the \
20387             canonical `:entrada` fixture's composite",
20388        );
20389    }
20390
20391    #[test]
20392    fn port_for_destination_reads_through_lifted_entrada_accessor() {
20393        // Peer coherence pin: the
20394        // [`AplicacaoSpec::port_for_destination`] per-destination
20395        // L4-port fallback resolver's composite-projection seed
20396        // (`self.entrada().filter(…).map_or(…)`) must key off the
20397        // lifted outer accessor. Pins the coherence by exercising
20398        // the resolver end-to-end: (1) the `None` `:entrada` shape
20399        // falls through to `DEFAULT_SERVICO_PORT` under the outer
20400        // accessor's reference projection, (2) a non-matching
20401        // destination falls through to `DEFAULT_SERVICO_PORT` under
20402        // the outer accessor's reference projection, and (3) the
20403        // matching destination resolves to the `:entrada :port`
20404        // value under the outer accessor's reference projection.
20405        //
20406        // Peer of the sibling
20407        // [`validate_reads_through_lifted_entrada_accessor`] multi-
20408        // consumer coherence pin on the same per-`:entrada` outer-
20409        // composite axis — extends the multi-consumer coherence
20410        // discipline onto the second per-`:entrada` production
20411        // consumer, the L4-port fallback resolver.
20412
20413        // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
20414        // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
20415        // arm under the outer accessor's reference projection.
20416        let mut spec = three_member_spec();
20417        spec.entrada = None;
20418        assert_eq!(
20419            spec.port_for_destination("cart"),
20420            DEFAULT_SERVICO_PORT,
20421            "the port-fallback resolver must fall through to \
20422             DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
20423             under the outer accessor's reference projection",
20424        );
20425
20426        // (2) Non-matching destination — the resolver's `filter(…)`
20427        // arm rejects a mismatched destination and falls through
20428        // to `DEFAULT_SERVICO_PORT` under the outer accessor's
20429        // reference projection.
20430        let mut spec = three_member_spec();
20431        if let Some(e) = spec.entrada.as_mut() {
20432            e.para = "cart".into();
20433            e.port = 9443;
20434        }
20435        assert_eq!(
20436            spec.port_for_destination("catalog"),
20437            DEFAULT_SERVICO_PORT,
20438            "the port-fallback resolver must fall through to \
20439             DEFAULT_SERVICO_PORT on a non-matching destination \
20440             under the outer accessor's reference projection",
20441        );
20442
20443        // (3) Matching destination — the resolver's `map_or(…)` arm
20444        // returns the `:entrada :port` value under the outer
20445        // accessor's reference projection.
20446        let mut spec = three_member_spec();
20447        if let Some(e) = spec.entrada.as_mut() {
20448            e.para = "cart".into();
20449            e.port = 9443;
20450        }
20451        assert_eq!(
20452            spec.port_for_destination("cart"),
20453            9443,
20454            "the port-fallback resolver must return the \
20455             `:entrada :port` value on a matching destination \
20456             under the outer accessor's reference projection",
20457        );
20458    }
20459
20460    #[test]
20461    fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
20462        // The canonical per-`:politicas` `:mtls-required` mTLS-
20463        // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
20464        // must return the `:politicas :mtls-required` typed bool
20465        // verbatim as an `Option<bool>`, byte-equal to the raw field
20466        // access across every value in the three-way accept-set —
20467        // `None` (cluster default applies), `Some(true)` (mTLS
20468        // handshake enforced — the sandboxing-by-default arm the
20469        // MeshPolicy's docstring names), `Some(false)` (handshake
20470        // skipped — the explicit debug-edge opt-out).
20471        //
20472        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
20473        // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
20474        // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
20475        // shape — first `Option<Copy-T>`-return accessor on the M3
20476        // mesh-slot family. Pins against a future silent detour that
20477        // re-derived the toggle from a peer axis (an accidental
20478        // `.circuit_breaker.is_some()` collapse that assumed mTLS on
20479        // whenever a breaker is set), a `None` → `Some(false)` cluster-
20480        // default projection (the canonical `Option<bool>` → `bool`
20481        // collapse footgun the surrounding `is_empty()` predicate
20482        // guards on the peer emptiness axis), or a `Some(true)` /
20483        // `Some(false)` variant swap that landed on one consumer
20484        // without the other.
20485        for required in [None, Some(true), Some(false)] {
20486            let p = MeshPolicy {
20487                mtls_required: required,
20488                ..MeshPolicy::default()
20489            };
20490            assert_eq!(
20491                p.mtls_required(),
20492                required,
20493                "MeshPolicy::mtls_required must return :politicas \
20494                 :mtls-required verbatim (got {:?}, expected {required:?})",
20495                p.mtls_required(),
20496            );
20497            assert_eq!(
20498                p.mtls_required(),
20499                p.mtls_required,
20500                "MeshPolicy::mtls_required must byte-equal the raw \
20501                 .mtls_required field access across every value in the \
20502                 three-way accept-set",
20503            );
20504        }
20505    }
20506
20507    #[test]
20508    fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
20509        // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
20510        // arm must key off [`MeshPolicy::mtls_required`], not the raw
20511        // `.mtls_required` field access. Structurally: toggling ONLY
20512        // the `mtls_required` slot on an otherwise-default MeshPolicy
20513        // must flip `is_empty()` from `true` (all-`None`) to `false`
20514        // (one axis carries a value); the flip must be observed for
20515        // both `Some(true)` and `Some(false)` since the emptiness
20516        // semantic reads "any axis carries a value" — not "any axis
20517        // carries a truthy value" — the same non-collapsing shape the
20518        // sibling M2 [`crate::LimitsSpec::is_empty`] /
20519        // [`crate::BehaviorSpec::is_empty`] predicates carry on their
20520        // peer `Option<T>`-typed slot surfaces.
20521        //
20522        // Pins against a future silent detour that re-derived the
20523        // emptiness predicate off a peer axis (an accidental
20524        // `.rate_limit.is_none()`-only chain that dropped the
20525        // `mtls_required` arm entirely), a `mtls_required == Some(_)`
20526        // collapse to a truthy-only check (which would silently
20527        // classify `Some(false)` as empty), or an accessor-side
20528        // detour that no longer names the substrate-primitive typed
20529        // dispatch (an accidental `self.mtls_required.unwrap_or(false)
20530        // == false` fallback in the accessor that would silently
20531        // classify both `None` and `Some(false)` as the same value).
20532        //
20533        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
20534        // (7cd2a28) accessor-composition pin on the sibling optional-
20535        // scalar axis — same "the emptiness / shape-gate predicate
20536        // must route through the substrate-primitive typed dispatch"
20537        // discipline extended onto the peer per-`:politicas` emptiness
20538        // predicate.
20539        let empty = MeshPolicy::default();
20540        assert!(
20541            empty.is_empty(),
20542            "MeshPolicy::default() must be is_empty() — every axis \
20543             defaults to None",
20544        );
20545        for required in [Some(true), Some(false)] {
20546            let p = MeshPolicy {
20547                mtls_required: required,
20548                ..MeshPolicy::default()
20549            };
20550            assert!(
20551                !p.is_empty(),
20552                "MeshPolicy::is_empty must return false when \
20553                 :mtls-required is {required:?} — the emptiness \
20554                 predicate reads \"any axis carries a value\", not \
20555                 \"any axis carries a truthy value\"",
20556            );
20557            assert_eq!(
20558                p.mtls_required().is_none(),
20559                p.is_empty(),
20560                "when :mtls-required is the only set axis, \
20561                 is_empty() must equal mtls_required().is_none() — \
20562                 the accessor and the emptiness predicate must \
20563                 route through the same substrate-primitive typed \
20564                 dispatch on the :mtls-required arm",
20565            );
20566        }
20567    }
20568
20569    #[test]
20570    fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
20571        // The by-copy pin: [`MeshPolicy::mtls_required`] returns
20572        // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
20573        // accessor must return by value, not by reference. Peer of the
20574        // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
20575        // borrow-invariant pin on the sibling `Option<String>` slot,
20576        // but extended onto the peer `Option<bool>` copy-invariant
20577        // shape — the accessor's returned `Option<bool>` must outlive
20578        // `&self` (multiple calls must return equal values from a
20579        // dropped-`&self` copy, since the returned Option carries no
20580        // borrow), and calling the accessor twice on the same
20581        // MeshPolicy must yield the same `Option<bool>` verbatim
20582        // (idempotent, no side effects on `&self`).
20583        //
20584        // Pins against a future silent detour that returned
20585        // `Option<&bool>` (which would type-check but silently break
20586        // every downstream caller — [`single_field_overlay`]'s first
20587        // parameter is `Option<T: Clone>`, and `&bool` would fold to a
20588        // detached copy at the call site), an accidental
20589        // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
20590        // would also type-check but return `Option<&bool>`), or a
20591        // one-arm-only accessor that reads `Some(*b)` in the Some arm
20592        // but reads a fresh Default::default() in the None arm.
20593        for required in [None, Some(true), Some(false)] {
20594            let p = MeshPolicy {
20595                mtls_required: required,
20596                ..MeshPolicy::default()
20597            };
20598            let first = p.mtls_required();
20599            let second = p.mtls_required();
20600            assert_eq!(
20601                first, second,
20602                "MeshPolicy::mtls_required must be idempotent — two \
20603                 successive calls on the same &self must return the \
20604                 same Option<bool>",
20605            );
20606            assert_eq!(
20607                first, required,
20608                "MeshPolicy::mtls_required must return :politicas \
20609                 :mtls-required verbatim by copy — got {first:?}, \
20610                 expected {required:?}",
20611            );
20612        }
20613    }
20614
20615    #[test]
20616    fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
20617        // The canonical per-`:politicas` `:retries` transient-failure-
20618        // retry-budget scalar pin: [`MeshPolicy::retries`] must return
20619        // the `:politicas :retries` typed `u32` verbatim as an
20620        // `Option<u32>`, byte-equal to the raw field access across every
20621        // representative value in the accept-set — `None` (cluster
20622        // default applies — typically "no retries beyond a single
20623        // dispatch attempt" the caixa-mesh `retry_overlay` builder
20624        // documents), `Some(1)` (the lower boundary of the
20625        // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
20626        // `AplicacaoSpec::validate_politicas` gate carves out on the
20627        // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
20628        // (the upper boundary the same gate carves out on the sibling
20629        // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
20630        // past-the-guard sentinel that pins the accessor doesn't perform
20631        // a silent bounds-collapse at the return path).
20632        //
20633        // Sibling of the peer per-`:politicas`
20634        // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
20635        // sibling `Option<Copy-T>` optional-scalar axis, extended to the
20636        // peer per-`:politicas` `Option<u32>` shape — second
20637        // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
20638        // Pins against a future silent detour that re-derived the retry
20639        // cap from a peer axis (an accidental `.circuit_breaker
20640        // .as_ref().map(|b| b.max_failures)` collapse that read the
20641        // breaker's max-failure count as a retry budget), a
20642        // `None → Some(0)` cluster-default projection (which would
20643        // silently re-introduce the `PolicyRetriesZero` refusal case at
20644        // the emit boundary), or a bounds-collapsing accessor that
20645        // clamped the return through `POLICY_RETRIES_MAX` (the
20646        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
20647        // must ship the raw slot verbatim so a validate-time gate
20648        // regression surfaces at the emit boundary rather than being
20649        // silently absorbed).
20650        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
20651            let p = MeshPolicy {
20652                retries,
20653                ..MeshPolicy::default()
20654            };
20655            assert_eq!(
20656                p.retries(),
20657                retries,
20658                "MeshPolicy::retries must return :politicas :retries \
20659                 verbatim (got {:?}, expected {retries:?})",
20660                p.retries(),
20661            );
20662            assert_eq!(
20663                p.retries(),
20664                p.retries,
20665                "MeshPolicy::retries must byte-equal the raw .retries \
20666                 field access across every value in the accept-set",
20667            );
20668        }
20669    }
20670
20671    #[test]
20672    fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
20673        // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
20674        // must key off [`MeshPolicy::retries`], not the raw `.retries`
20675        // field access. Structurally: toggling ONLY the `retries` slot
20676        // on an otherwise-default MeshPolicy must flip `is_empty()`
20677        // from `true` (all-`None`) to `false` (one axis carries a
20678        // value); the flip must be observed for every value in the
20679        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
20680        // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
20681        // the emptiness semantic reads "any axis carries a value" —
20682        // not "any axis carries a value the validate gate accepts" —
20683        // the same non-collapsing shape the peer M2
20684        // [`crate::LimitsSpec::is_empty`] /
20685        // [`crate::BehaviorSpec::is_empty`] predicates carry.
20686        //
20687        // Pins against a future silent detour that re-derived the
20688        // emptiness predicate off a peer axis (an accidental
20689        // `.rate_limit.is_none()`-only chain that dropped the
20690        // `retries` arm entirely), a `retries == Some(_)` collapse
20691        // that key-off a validate-gate-clamped bounds check (which
20692        // would silently classify a past-the-guard `Some(u32::MAX)`
20693        // as empty because it fails the `1..=POLICY_RETRIES_MAX`
20694        // check), or an accessor-side detour that no longer names the
20695        // substrate-primitive typed dispatch.
20696        //
20697        // Sibling of the peer per-`:politicas`
20698        // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
20699        // pin on the sibling `Option<Copy-T>` optional-scalar axis —
20700        // same "the emptiness predicate must route through the
20701        // substrate-primitive typed dispatch" discipline extended onto
20702        // the peer per-`:politicas` `Option<u32>` axis.
20703        let empty = MeshPolicy::default();
20704        assert!(
20705            empty.is_empty(),
20706            "MeshPolicy::default() must be is_empty() — every axis \
20707             defaults to None",
20708        );
20709        for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
20710            let p = MeshPolicy {
20711                retries,
20712                ..MeshPolicy::default()
20713            };
20714            assert!(
20715                !p.is_empty(),
20716                "MeshPolicy::is_empty must return false when \
20717                 :retries is {retries:?} — the emptiness \
20718                 predicate reads \"any axis carries a value\", not \
20719                 \"any axis carries a value the validate gate \
20720                 accepts\"",
20721            );
20722            assert_eq!(
20723                p.retries().is_none(),
20724                p.is_empty(),
20725                "when :retries is the only set axis, is_empty() \
20726                 must equal retries().is_none() — the accessor and \
20727                 the emptiness predicate must route through the same \
20728                 substrate-primitive typed dispatch on the :retries \
20729                 arm",
20730            );
20731        }
20732    }
20733
20734    #[test]
20735    fn mesh_policy_retries_projects_option_u32_by_copy() {
20736        // The by-copy pin: [`MeshPolicy::retries`] returns
20737        // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
20738        // accessor must return by value, not by reference. Sibling of
20739        // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
20740        // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
20741        // extended onto the sibling `Option<u32>` copy-invariant
20742        // shape — the accessor's returned `Option<u32>` must outlive
20743        // `&self` (multiple calls must return equal values from a
20744        // dropped-`&self` copy, since the returned Option carries no
20745        // borrow), and calling the accessor twice on the same
20746        // MeshPolicy must yield the same `Option<u32>` verbatim
20747        // (idempotent, no side effects on `&self`).
20748        //
20749        // Pins against a future silent detour that returned
20750        // `Option<&u32>` (which would type-check but silently break
20751        // every downstream caller — [`crate::render::single_field_overlay`]'s
20752        // first parameter is `Option<T: Clone>`, and `&u32` would
20753        // fold to a detached copy at the call site), an accidental
20754        // `Option::as_ref()` projection (`self.retries.as_ref()` would
20755        // also type-check but return `Option<&u32>`), or a one-arm-
20756        // only accessor that reads `Some(*n)` in the Some arm but
20757        // reads a fresh `Default::default()` (`0_u32`) in the None
20758        // arm.
20759        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
20760            let p = MeshPolicy {
20761                retries,
20762                ..MeshPolicy::default()
20763            };
20764            let first = p.retries();
20765            let second = p.retries();
20766            assert_eq!(
20767                first, second,
20768                "MeshPolicy::retries must be idempotent — two \
20769                 successive calls on the same &self must return the \
20770                 same Option<u32>",
20771            );
20772            assert_eq!(
20773                first, retries,
20774                "MeshPolicy::retries must return :politicas :retries \
20775                 verbatim by copy — got {first:?}, expected {retries:?}",
20776            );
20777        }
20778    }
20779
20780    #[test]
20781    fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
20782        // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
20783        // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
20784        // return the `:politicas :timeout` typed [`Duration`] verbatim
20785        // as an `Option<Duration>`, byte-equal to the raw field access
20786        // across every representative value in the accept-set — `None`
20787        // (cluster default applies — typically the gateway class's
20788        // implementation-side per-request wall-clock cap the caixa-mesh
20789        // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
20790        // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
20791        // set the surrounding `AplicacaoSpec::validate_politicas` gate
20792        // carves out on the sibling `PolicyTimeoutZero` /
20793        // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
20794        // (the upper boundary the same gate carves out on the sibling
20795        // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
20796        // (a past-the-guard sentinel that pins the accessor doesn't
20797        // perform a silent bounds-collapse into `None` on the zero-
20798        // Duration arm — validate rejects zero but the accessor must
20799        // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
20800        // past-the-guard sentinel that pins the accessor doesn't
20801        // perform a silent bounds-collapse at the return path).
20802        //
20803        // Sibling of the peer per-`:politicas`
20804        // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
20805        // `Option<u32>` optional-scalar axis and the peer per-
20806        // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
20807        // pin on the sibling `Option<bool>` optional-scalar axis,
20808        // extended onto the peer per-`:politicas` `Option<Duration>`
20809        // shape — third `Option<Copy-T>`-return accessor on the M3
20810        // mesh-slot family. Pins against a future silent detour that
20811        // re-derived the per-call cap from a peer axis (an accidental
20812        // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
20813        // read the breaker's rolling-window duration as a per-call
20814        // deadline), a `None → Some(Duration::MAX)` cluster-default
20815        // projection (which would silently re-introduce the
20816        // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
20817        // blocking" arm at the emit boundary), or a bounds-collapsing
20818        // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
20819        // (the `AplicacaoSpec::validate` gate owns the bounds; the
20820        // accessor must ship the raw slot verbatim so a validate-time
20821        // gate regression surfaces at the emit boundary rather than
20822        // being silently absorbed).
20823        for timeout in [
20824            None,
20825            Some(Duration::from_millis(1)),
20826            Some(POLICY_TIMEOUT_MAX),
20827            Some(Duration::ZERO),
20828            Some(Duration::MAX),
20829        ] {
20830            let p = MeshPolicy {
20831                timeout,
20832                ..MeshPolicy::default()
20833            };
20834            assert_eq!(
20835                p.timeout(),
20836                timeout,
20837                "MeshPolicy::timeout must return :politicas :timeout \
20838                 verbatim (got {:?}, expected {timeout:?})",
20839                p.timeout(),
20840            );
20841            assert_eq!(
20842                p.timeout(),
20843                p.timeout,
20844                "MeshPolicy::timeout must byte-equal the raw .timeout \
20845                 field access across every value in the accept-set",
20846            );
20847        }
20848    }
20849
20850    #[test]
20851    fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
20852        // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
20853        // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
20854        // field access. Structurally: toggling ONLY the `timeout` slot
20855        // on an otherwise-default MeshPolicy must flip `is_empty()`
20856        // from `true` (all-`None`) to `false` (one axis carries a
20857        // value); the flip must be observed for every value in the
20858        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
20859        // gate accepts (`Some(Duration::from_millis(1))`,
20860        // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
20861        // reads "any axis carries a value" — not "any axis carries a
20862        // value the validate gate accepts" — the same non-collapsing
20863        // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
20864        // [`crate::BehaviorSpec::is_empty`] predicates carry.
20865        //
20866        // Pins against a future silent detour that re-derived the
20867        // emptiness predicate off a peer axis (an accidental
20868        // `.rate_limit.is_none()`-only chain that dropped the
20869        // `timeout` arm entirely), a `timeout == Some(_)` collapse
20870        // that key-off a validate-gate-clamped bounds check (which
20871        // would silently classify a past-the-guard `Some(Duration::MAX)`
20872        // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
20873        // check), or an accessor-side detour that no longer names the
20874        // substrate-primitive typed dispatch.
20875        //
20876        // Sibling of the peer per-`:politicas`
20877        // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
20878        // the sibling `Option<u32>` optional-scalar axis and the peer
20879        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
20880        // accessor-composition pin on the sibling `Option<bool>`
20881        // optional-scalar axis — same "the emptiness predicate must
20882        // route through the substrate-primitive typed dispatch"
20883        // discipline extended onto the peer per-`:politicas`
20884        // `Option<Duration>` axis.
20885        let empty = MeshPolicy::default();
20886        assert!(
20887            empty.is_empty(),
20888            "MeshPolicy::default() must be is_empty() — every axis \
20889             defaults to None",
20890        );
20891        for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
20892            let p = MeshPolicy {
20893                timeout,
20894                ..MeshPolicy::default()
20895            };
20896            assert!(
20897                !p.is_empty(),
20898                "MeshPolicy::is_empty must return false when \
20899                 :timeout is {timeout:?} — the emptiness \
20900                 predicate reads \"any axis carries a value\", not \
20901                 \"any axis carries a value the validate gate \
20902                 accepts\"",
20903            );
20904            assert_eq!(
20905                p.timeout().is_none(),
20906                p.is_empty(),
20907                "when :timeout is the only set axis, is_empty() \
20908                 must equal timeout().is_none() — the accessor and \
20909                 the emptiness predicate must route through the same \
20910                 substrate-primitive typed dispatch on the :timeout \
20911                 arm",
20912            );
20913        }
20914    }
20915
20916    #[test]
20917    fn mesh_policy_timeout_projects_option_duration_by_copy() {
20918        // The by-copy pin: [`MeshPolicy::timeout`] returns
20919        // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
20920        // and the accessor must return by value, not by reference.
20921        // Sibling of the peer per-`:politicas`
20922        // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
20923        // sibling `Option<u32>` optional-scalar axis and the peer
20924        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
20925        // by-copy pin on the sibling `Option<bool>` optional-scalar
20926        // axis, extended onto the peer per-`:politicas`
20927        // `Option<Duration>` copy-invariant shape — the accessor's
20928        // returned `Option<Duration>` must outlive `&self` (multiple
20929        // calls must return equal values from a dropped-`&self`
20930        // copy, since the returned Option carries no borrow), and
20931        // calling the accessor twice on the same MeshPolicy must
20932        // yield the same `Option<Duration>` verbatim (idempotent, no
20933        // side effects on `&self`).
20934        //
20935        // Pins against a future silent detour that returned
20936        // `Option<&Duration>` (which would type-check but silently
20937        // break every downstream caller — [`crate::render::single_field_overlay`]'s
20938        // first parameter is `Option<T: Clone>`, and `&Duration`
20939        // would fold to a detached copy at the call site), an
20940        // accidental `Option::as_ref()` projection
20941        // (`self.timeout.as_ref()` would also type-check but return
20942        // `Option<&Duration>`), or a one-arm-only accessor that
20943        // reads `Some(*d)` in the Some arm but reads a fresh
20944        // `Default::default()` (`Duration::ZERO`) in the None arm
20945        // (which would silently re-classify every unset `:timeout`
20946        // as the `PolicyTimeoutZero`-refused zero-Duration value at
20947        // the accessor boundary).
20948        for timeout in [
20949            None,
20950            Some(Duration::from_millis(1)),
20951            Some(POLICY_TIMEOUT_MAX),
20952            Some(Duration::ZERO),
20953            Some(Duration::MAX),
20954        ] {
20955            let p = MeshPolicy {
20956                timeout,
20957                ..MeshPolicy::default()
20958            };
20959            let first = p.timeout();
20960            let second = p.timeout();
20961            assert_eq!(
20962                first, second,
20963                "MeshPolicy::timeout must be idempotent — two \
20964                 successive calls on the same &self must return the \
20965                 same Option<Duration>",
20966            );
20967            assert_eq!(
20968                first, timeout,
20969                "MeshPolicy::timeout must return :politicas :timeout \
20970                 verbatim by copy — got {first:?}, expected {timeout:?}",
20971            );
20972        }
20973    }
20974
20975    #[test]
20976    fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
20977        // The canonical per-`:politicas` `:rate-limit` Envoy-
20978        // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
20979        // [`MeshPolicy::rate_limit`] must return the `:politicas
20980        // :rate-limit` typed [`RateLimit`] verbatim as an
20981        // `Option<RateLimit>`, byte-equal to the raw field access
20982        // across every representative value in the accept-set — `None`
20983        // (cluster default applies — no per-Aplicacao rate declaration,
20984        // the gateway-class per-listener default arm the future caixa-
20985        // mesh `local_rate_limit_overlay` emitter documents),
20986        // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
20987        // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
20988        // accept-set the surrounding
20989        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
20990        // sibling `PolicyRateLimitZero` refusal, paired with the
20991        // canonical-window "1 second" arm of the three-unit
20992        // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
20993        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
20994        // (the upper boundary the same gate carves out on the sibling
20995        // `PolicyRateLimitExceedsCap` refusal, paired with the
20996        // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
20997        // (a past-the-guard sentinel that pins the accessor doesn't
20998        // perform a silent bounds-collapse into `None` on the
20999        // zero-rate/zero-window arm — validate rejects zero but the
21000        // accessor must ship the raw slot verbatim so a validate-time
21001        // gate regression surfaces at the emit boundary rather than
21002        // being silently absorbed), and
21003        // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
21004        // (a past-the-guard sentinel that pins the accessor doesn't
21005        // perform a silent bounds-collapse at the return path).
21006        //
21007        // First `Option<Copy-composite-T>`-return accessor pin on the
21008        // M3 mesh-slot family (peer of the sibling per-`:politicas`
21009        // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
21010        // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
21011        // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
21012        // Copy accessor pins, extended onto the peer per-`:politicas`
21013        // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
21014        // and the accessor returns by value). Pins against a future
21015        // silent detour that re-derived the rate declaration from a
21016        // peer axis (an accidental
21017        // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
21018        // collapse that read the breaker's trip threshold + rolling
21019        // window as a rate declaration), a `None → Some(default())`
21020        // cluster-default projection (which would silently re-
21021        // introduce a "cluster default is 0/s" arm the emit boundary
21022        // would take as "declared but inert" — the canonical
21023        // declared-but-inert footgun the sibling
21024        // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
21025        // amplification-shape axis), a bounds-collapsing accessor
21026        // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
21027        // clamped `rl.window` through [`is_canonical_rate_limit_window`]
21028        // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
21029        // accessor must ship the raw slot verbatim), or a
21030        // by-reference detour (`Option<&RateLimit>`) that broke every
21031        // downstream consumer keying off `Option<RateLimit>` by-copy.
21032        for rl in [
21033            None,
21034            Some(RateLimit {
21035                rate: 1,
21036                window: Duration::from_secs(1),
21037            }),
21038            Some(RateLimit {
21039                rate: POLICY_RATE_LIMIT_MAX,
21040                window: Duration::from_secs(3600),
21041            }),
21042            Some(RateLimit {
21043                rate: 0,
21044                window: Duration::ZERO,
21045            }),
21046            Some(RateLimit {
21047                rate: u32::MAX,
21048                window: Duration::MAX,
21049            }),
21050        ] {
21051            let p = MeshPolicy {
21052                rate_limit: rl,
21053                ..MeshPolicy::default()
21054            };
21055            assert_eq!(
21056                p.rate_limit(),
21057                rl,
21058                "MeshPolicy::rate_limit must return :politicas :rate-limit \
21059                 verbatim (got {:?}, expected {rl:?})",
21060                p.rate_limit(),
21061            );
21062            assert_eq!(
21063                p.rate_limit(),
21064                p.rate_limit,
21065                "MeshPolicy::rate_limit must byte-equal the raw \
21066                 .rate_limit field access across every value in the \
21067                 accept-set",
21068            );
21069        }
21070    }
21071
21072    #[test]
21073    fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
21074        // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
21075        // must key off [`MeshPolicy::rate_limit`], not the raw
21076        // `.rate_limit` field access. Structurally: toggling ONLY the
21077        // `rate_limit` slot on an otherwise-default MeshPolicy must
21078        // flip `is_empty()` from `true` (all-`None`) to `false` (one
21079        // axis carries a value); the flip must be observed for every
21080        // representative value in the accept-set the surrounding
21081        // [`AplicacaoSpec::validate_politicas`] gate accepts
21082        // (`Some(RateLimit { rate: 1, window: 1s })`,
21083        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
21084        // since the emptiness semantic reads "any axis carries a
21085        // value" — not "any axis carries a value the validate gate
21086        // accepts" — the same non-collapsing shape the peer M2
21087        // [`crate::LimitsSpec::is_empty`] /
21088        // [`crate::BehaviorSpec::is_empty`] predicates carry.
21089        //
21090        // Pins against a future silent detour that re-derived the
21091        // emptiness predicate off a peer axis (an accidental
21092        // `.timeout.is_none()`-only chain that dropped the
21093        // `rate_limit` arm entirely — the last unlifted inline field
21094        // access on `is_empty` before this lift), a `rate_limit ==
21095        // Some(_)` collapse that key-off a validate-gate-clamped
21096        // bounds check (which would silently classify a past-the-
21097        // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
21098        // because it fails the value-shape gate), or an accessor-
21099        // side detour that no longer names the substrate-primitive
21100        // typed dispatch.
21101        //
21102        // Fourth "the emptiness predicate must route through the
21103        // substrate-primitive typed dispatch" composition pin on the
21104        // M3 mesh-slot family — closes the last unlifted composition
21105        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
21106        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
21107        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
21108        // 7073d0f is_empty-composition pins on the sibling primitive-
21109        // Copy axes, extended onto the peer per-`:politicas`
21110        // composite-Copy `Option<RateLimit>` axis).
21111        let empty = MeshPolicy::default();
21112        assert!(
21113            empty.is_empty(),
21114            "MeshPolicy::default() must be is_empty() — every axis \
21115             defaults to None",
21116        );
21117        for rl in [
21118            RateLimit {
21119                rate: 1,
21120                window: Duration::from_secs(1),
21121            },
21122            RateLimit {
21123                rate: POLICY_RATE_LIMIT_MAX,
21124                window: Duration::from_secs(3600),
21125            },
21126        ] {
21127            let p = MeshPolicy {
21128                rate_limit: Some(rl),
21129                ..MeshPolicy::default()
21130            };
21131            assert!(
21132                !p.is_empty(),
21133                "MeshPolicy::is_empty must return false when \
21134                 :rate-limit is {rl:?} — the emptiness predicate \
21135                 reads \"any axis carries a value\", not \"any axis \
21136                 carries a value the validate gate accepts\"",
21137            );
21138            assert_eq!(
21139                p.rate_limit().is_none(),
21140                p.is_empty(),
21141                "when :rate-limit is the only set axis, is_empty() \
21142                 must equal rate_limit().is_none() — the accessor \
21143                 and the emptiness predicate must route through the \
21144                 same substrate-primitive typed dispatch on the \
21145                 :rate-limit arm",
21146            );
21147        }
21148    }
21149
21150    #[test]
21151    fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
21152        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
21153        // `:rate-limit` value-shape gate must key off
21154        // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
21155        // field bind. Structurally: a `MeshPolicy` whose only set
21156        // axis is a `Some(RateLimit { rate: 0, .. })` must surface
21157        // the `PolicyRateLimitZero` refusal exactly, and the same
21158        // MeshPolicy with the rate at the canonical lower boundary
21159        // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
21160        // The pair jointly pins the accessor + validate-gate
21161        // composition: any future silent detour that had the accessor
21162        // omit the `Some(RateLimit { rate: 0, .. })` arm (a
21163        // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
21164        // silently absorb the `PolicyRateLimitZero` refusal at the
21165        // accessor boundary — the composition pin catches that at
21166        // caixa-core build time.
21167        //
21168        // Sibling of the peer [`validate_politicas`]
21169        // `:mtls-required` / `:retries` / `:timeout` composition pins
21170        // on the sibling primitive-Copy optional-scalar axes — same
21171        // "the validate / shape-gate predicate must route through the
21172        // substrate-primitive typed dispatch" discipline extended
21173        // onto the peer per-`:politicas` composite-Copy
21174        // `Option<RateLimit>` axis. Second composition-with-accessor
21175        // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
21176        // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
21177        let mut spec = three_member_spec();
21178        spec.politicas = MeshPolicy {
21179            rate_limit: Some(RateLimit {
21180                rate: 0,
21181                window: Duration::from_secs(1),
21182            }),
21183            ..MeshPolicy::default()
21184        };
21185        assert!(
21186            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
21187            "validate_politicas must reject rate == 0 with \
21188             PolicyRateLimitZero — the accessor and the validate gate \
21189             must route through the same substrate-primitive typed \
21190             dispatch on the :rate-limit zero-floor arm",
21191        );
21192        spec.politicas = MeshPolicy {
21193            rate_limit: Some(RateLimit {
21194                rate: 1,
21195                window: Duration::from_secs(1),
21196            }),
21197            ..MeshPolicy::default()
21198        };
21199        assert!(
21200            spec.validate().is_ok(),
21201            "validate_politicas must accept rate == 1 (the canonical \
21202             lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
21203             set) with a canonical 1s window",
21204        );
21205    }
21206
21207    #[test]
21208    fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
21209        // The canonical per-`:politicas` `:circuit-breaker` Envoy-
21210        // `outlier_detection`-mesh consecutive-failure-ejection scalar
21211        // pin: [`MeshPolicy::circuit_breaker`] must return the
21212        // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
21213        // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
21214        // raw field access across every representative value in the
21215        // accept-set — `None` (cluster default applies — no
21216        // per-Aplicacao breaker declaration, the gateway-class per-
21217        // listener default arm the future caixa-mesh
21218        // `outlier_detection_overlay` emitter documents),
21219        // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
21220        // (the lower boundary of the accept-set the surrounding
21221        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
21222        // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
21223        // refusals),
21224        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
21225        // (the upper boundary the same gate carves out on the sibling
21226        // `PolicyBreakerMaxFailuresExceedsCap` /
21227        // `PolicyBreakerWindowExceedsCap` refusals),
21228        // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
21229        // (a past-the-guard sentinel that pins the accessor doesn't
21230        // perform a silent bounds-collapse into `None` on the
21231        // zero-failures/zero-window arm — validate rejects zero but
21232        // the accessor must ship the raw slot verbatim so a validate-
21233        // time gate regression surfaces at the emit boundary rather
21234        // than being silently absorbed), and
21235        // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
21236        // (a past-the-guard sentinel that pins the accessor doesn't
21237        // perform a silent bounds-collapse at the return path).
21238        //
21239        // Second `Option<Copy-composite-T>`-return accessor pin on the
21240        // M3 mesh-slot family (peer of the sibling per-`:politicas`
21241        // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
21242        // composite-Copy accessor pin, and of the sibling per-
21243        // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
21244        // [`MeshPolicy::retries`] bdfb399 /
21245        // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
21246        // accessor pins). Pins against a future silent detour that
21247        // re-derived the breaker declaration from a peer axis (an
21248        // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
21249        // collapse that read the rate-limit's bucket capacity + refill
21250        // period as a breaker declaration), a `None → Some(default())`
21251        // cluster-default projection (which would silently re-
21252        // introduce the `PolicyBreakerZeroFailures` /
21253        // `PolicyBreakerZeroWindow` refusal cases at the emit
21254        // boundary), a bounds-collapsing accessor that clamped
21255        // `cb.max_failures` through
21256        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
21257        // through [`POLICY_BREAKER_WINDOW_MAX`] (the
21258        // [`AplicacaoSpec::validate`] gate owns the bounds; the
21259        // accessor must ship the raw slot verbatim), or a
21260        // by-reference detour (`Option<&CircuitBreaker>`) that broke
21261        // every downstream consumer keying off `Option<CircuitBreaker>`
21262        // by-copy.
21263        for cb in [
21264            None,
21265            Some(CircuitBreaker {
21266                max_failures: 1,
21267                window: Duration::from_millis(1),
21268            }),
21269            Some(CircuitBreaker {
21270                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
21271                window: POLICY_BREAKER_WINDOW_MAX,
21272            }),
21273            Some(CircuitBreaker {
21274                max_failures: 0,
21275                window: Duration::ZERO,
21276            }),
21277            Some(CircuitBreaker {
21278                max_failures: u32::MAX,
21279                window: Duration::MAX,
21280            }),
21281        ] {
21282            let p = MeshPolicy {
21283                circuit_breaker: cb,
21284                ..MeshPolicy::default()
21285            };
21286            assert_eq!(
21287                p.circuit_breaker(),
21288                cb,
21289                "MeshPolicy::circuit_breaker must return :politicas \
21290                 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
21291                p.circuit_breaker(),
21292            );
21293            assert_eq!(
21294                p.circuit_breaker(),
21295                p.circuit_breaker,
21296                "MeshPolicy::circuit_breaker must byte-equal the raw \
21297                 .circuit_breaker field access across every value in \
21298                 the accept-set",
21299            );
21300        }
21301    }
21302
21303    #[test]
21304    fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
21305        // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
21306        // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
21307        // `.circuit_breaker` field access. Structurally: toggling ONLY
21308        // the `circuit_breaker` slot on an otherwise-default MeshPolicy
21309        // must flip `is_empty()` from `true` (all-`None`) to `false`
21310        // (one axis carries a value); the flip must be observed for
21311        // every representative value in the accept-set the surrounding
21312        // [`AplicacaoSpec::validate_politicas`] gate accepts
21313        // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
21314        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
21315        // since the emptiness semantic reads "any axis carries a
21316        // value" — not "any axis carries a value the validate gate
21317        // accepts" — the same non-collapsing shape the peer M2
21318        // [`crate::LimitsSpec::is_empty`] /
21319        // [`crate::BehaviorSpec::is_empty`] predicates carry.
21320        //
21321        // Pins against a future silent detour that re-derived the
21322        // emptiness predicate off a peer axis (an accidental
21323        // `.rate_limit.is_none()`-only chain that dropped the
21324        // `circuit_breaker` arm entirely — the last unlifted inline
21325        // field access on `is_empty` before this lift), a
21326        // `circuit_breaker == Some(_)` collapse that key-off a
21327        // validate-gate-clamped bounds check (which would silently
21328        // classify a past-the-guard `Some(CircuitBreaker { max_failures:
21329        // 0, window: 0s })` as empty because it fails the value-shape
21330        // gate), or an accessor-side detour that no longer names the
21331        // substrate-primitive typed dispatch.
21332        //
21333        // Fifth "the emptiness predicate must route through the
21334        // substrate-primitive typed dispatch" composition pin on the
21335        // M3 mesh-slot family — closes the last unlifted composition
21336        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
21337        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
21338        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
21339        // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
21340        // composition pins on the sibling primitive-Copy + composite-
21341        // Copy axes, extended onto the peer per-`:politicas`
21342        // composite-Copy `Option<CircuitBreaker>` axis).
21343        let empty = MeshPolicy::default();
21344        assert!(
21345            empty.is_empty(),
21346            "MeshPolicy::default() must be is_empty() — every axis \
21347             defaults to None",
21348        );
21349        for cb in [
21350            CircuitBreaker {
21351                max_failures: 1,
21352                window: Duration::from_millis(1),
21353            },
21354            CircuitBreaker {
21355                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
21356                window: POLICY_BREAKER_WINDOW_MAX,
21357            },
21358        ] {
21359            let p = MeshPolicy {
21360                circuit_breaker: Some(cb),
21361                ..MeshPolicy::default()
21362            };
21363            assert!(
21364                !p.is_empty(),
21365                "MeshPolicy::is_empty must return false when \
21366                 :circuit-breaker is {cb:?} — the emptiness predicate \
21367                 reads \"any axis carries a value\", not \"any axis \
21368                 carries a value the validate gate accepts\"",
21369            );
21370            assert_eq!(
21371                p.circuit_breaker().is_none(),
21372                p.is_empty(),
21373                "when :circuit-breaker is the only set axis, \
21374                 is_empty() must equal circuit_breaker().is_none() — \
21375                 the accessor and the emptiness predicate must route \
21376                 through the same substrate-primitive typed dispatch \
21377                 on the :circuit-breaker arm",
21378            );
21379        }
21380    }
21381
21382    #[test]
21383    fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
21384        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
21385        // `:circuit-breaker` value-shape gate must key off
21386        // [`MeshPolicy::circuit_breaker`], not the raw
21387        // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
21388        // whose only set axis is a `Some(CircuitBreaker { max_failures:
21389        // 0, .. })` must surface the `PolicyBreakerZeroFailures`
21390        // refusal exactly, and the same MeshPolicy with the breaker at
21391        // the canonical lower boundary
21392        // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
21393        // pass validate. The pair jointly pins the accessor +
21394        // validate-gate composition: any future silent detour that had
21395        // the accessor omit the `Some(CircuitBreaker { max_failures:
21396        // 0, .. })` arm (a
21397        // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
21398        // collapse) would silently absorb the
21399        // `PolicyBreakerZeroFailures` refusal at the accessor
21400        // boundary — the composition pin catches that at caixa-core
21401        // build time.
21402        //
21403        // Sibling of the peer [`validate_politicas`]
21404        // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
21405        // composition pins on the sibling primitive-Copy + composite-
21406        // Copy optional-scalar axes — same "the validate / shape-gate
21407        // predicate must route through the substrate-primitive typed
21408        // dispatch" discipline extended onto the peer per-`:politicas`
21409        // composite-Copy `Option<CircuitBreaker>` axis. Second
21410        // composition-with-accessor pin on the M3 mesh-slot
21411        // `Option<CircuitBreaker>` arm alongside the
21412        // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
21413        let mut spec = three_member_spec();
21414        spec.politicas = MeshPolicy {
21415            circuit_breaker: Some(CircuitBreaker {
21416                max_failures: 0,
21417                window: Duration::from_millis(1),
21418            }),
21419            ..MeshPolicy::default()
21420        };
21421        assert!(
21422            matches!(
21423                spec.validate(),
21424                Err(AplicacaoError::PolicyBreakerZeroFailures)
21425            ),
21426            "validate_politicas must reject max_failures == 0 with \
21427             PolicyBreakerZeroFailures — the accessor and the validate \
21428             gate must route through the same substrate-primitive \
21429             typed dispatch on the :circuit-breaker zero-floor arm",
21430        );
21431        spec.politicas = MeshPolicy {
21432            circuit_breaker: Some(CircuitBreaker {
21433                max_failures: 1,
21434                window: Duration::from_millis(1),
21435            }),
21436            ..MeshPolicy::default()
21437        };
21438        assert!(
21439            spec.validate().is_ok(),
21440            "validate_politicas must accept a CircuitBreaker at the \
21441             canonical lower boundary (max_failures = 1, window = \
21442             1ms) — the accessor and the validate gate must route \
21443             through the same substrate-primitive typed dispatch on \
21444             the :circuit-breaker arm",
21445        );
21446    }
21447
21448    #[test]
21449    fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
21450        // The canonical per-`:politicas :circuit-breaker` `:max-failures`
21451        // Envoy-outlier-detection trip-threshold scalar pin:
21452        // [`CircuitBreaker::max_failures`] must return the
21453        // `:politicas :circuit-breaker :max-failures` typed `u32`
21454        // verbatim, byte-equal to the raw field access across every
21455        // representative value in the accept-set — `1` (the lower
21456        // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
21457        // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
21458        // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
21459        // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
21460        // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
21461        // refusal), `0` (a past-the-guard sentinel that pins the accessor
21462        // doesn't perform a silent bounds-collapse into `1` on the zero
21463        // arm — validate rejects zero but the accessor must ship the
21464        // raw slot verbatim so a validate-time gate regression surfaces
21465        // at the emit boundary rather than being silently absorbed),
21466        // `u32::MAX` (a past-the-guard sentinel that pins the accessor
21467        // doesn't perform a silent bounds-collapse through
21468        // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
21469        //
21470        // First sub-struct required-scalar accessor pin on the M3
21471        // mesh-slot family — sibling in shape to the peer per-`:membros`
21472        // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
21473        // (a40b0e3) required-`String`-carry accessor pins and the peer
21474        // per-`:contratos` [`WitContract::source`] /
21475        // [`WitContract::destination`] (7f0fd43) required-`String`-carry
21476        // accessor pins, extended onto the peer per-`CircuitBreaker`
21477        // required-`u32` scalar-value axis. Pins against a future silent
21478        // detour that re-derived the trip threshold from a peer axis (an
21479        // accidental `self.window.as_secs() as u32` collapse that read
21480        // the breaker's rolling-window duration as a failure count), a
21481        // `0 → 1` cluster-default projection (which would silently absorb
21482        // the `PolicyBreakerZeroFailures` refusal case at the accessor
21483        // boundary), or a bounds-collapsing accessor that clamped the
21484        // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
21485        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
21486        // must ship the raw slot verbatim).
21487        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
21488            let cb = CircuitBreaker {
21489                max_failures,
21490                window: Duration::from_secs(60),
21491            };
21492            assert_eq!(
21493                cb.max_failures(),
21494                max_failures,
21495                "CircuitBreaker::max_failures must return :politicas \
21496                 :circuit-breaker :max-failures verbatim (got {}, \
21497                 expected {max_failures})",
21498                cb.max_failures(),
21499            );
21500            assert_eq!(
21501                cb.max_failures(),
21502                cb.max_failures,
21503                "CircuitBreaker::max_failures must byte-equal the raw \
21504                 .max_failures field access across every value in the \
21505                 u32 accept-set",
21506            );
21507        }
21508    }
21509
21510    #[test]
21511    fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
21512        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
21513        // `:circuit-breaker :max-failures` zero-floor arm must key off
21514        // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
21515        // field access. Structurally: a `CircuitBreaker { max_failures:
21516        // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
21517        // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
21518        // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
21519        // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
21520        // pass validate. The pair jointly pins the accessor +
21521        // validate-gate composition: any future silent detour that had
21522        // the accessor return a fresh `1` on the zero arm (a
21523        // `.max_failures().max(1)` collapse) would silently absorb the
21524        // `PolicyBreakerZeroFailures` refusal at the accessor boundary
21525        // and the validate gate would accept a struct-literal
21526        // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
21527        // catches that at caixa-core build time.
21528        //
21529        // Peer of the sibling per-`:politicas`
21530        // [`MeshPolicy::mtls_required`] (c0110f1) /
21531        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
21532        // (7073d0f) accessor-composition pins on the sibling optional-
21533        // scalar axes — same "the validate / shape-gate predicate must
21534        // route through the substrate-primitive typed dispatch"
21535        // discipline extended onto the peer per-`CircuitBreaker`
21536        // required-scalar composition axis.
21537        let mut spec = three_member_spec();
21538        spec.politicas = MeshPolicy {
21539            circuit_breaker: Some(CircuitBreaker {
21540                max_failures: 0,
21541                window: Duration::from_secs(60),
21542            }),
21543            ..MeshPolicy::default()
21544        };
21545        assert!(
21546            matches!(
21547                spec.validate(),
21548                Err(AplicacaoError::PolicyBreakerZeroFailures)
21549            ),
21550            "validate_politicas must reject max_failures == 0 with \
21551             PolicyBreakerZeroFailures — the accessor and the validate \
21552             gate must route through the same substrate-primitive typed \
21553             dispatch on the :max-failures zero-floor arm",
21554        );
21555        spec.politicas = MeshPolicy {
21556            circuit_breaker: Some(CircuitBreaker {
21557                max_failures: 1,
21558                window: Duration::from_secs(60),
21559            }),
21560            ..MeshPolicy::default()
21561        };
21562        assert!(
21563            spec.validate().is_ok(),
21564            "validate_politicas must accept max_failures == 1 (the \
21565             lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
21566             accept-set)",
21567        );
21568    }
21569
21570    #[test]
21571    fn circuit_breaker_max_failures_projects_u32_by_copy() {
21572        // The by-copy pin: [`CircuitBreaker::max_failures`] returns
21573        // `u32` by copy — `u32` is `Copy` and the accessor must return
21574        // by value, not by reference. Peer of the sibling
21575        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
21576        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
21577        // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
21578        // optional-scalar axes, extended onto the peer
21579        // per-`CircuitBreaker` required-`u32` copy-invariant shape —
21580        // the accessor's returned `u32` must outlive `&self` (multiple
21581        // calls must return equal values from a dropped-`&self` copy,
21582        // since the returned scalar carries no borrow), and calling
21583        // the accessor twice on the same CircuitBreaker must yield the
21584        // same `u32` verbatim (idempotent, no side effects on `&self`).
21585        //
21586        // Pins against a future silent detour that returned `&u32`
21587        // (which would type-check but silently break every downstream
21588        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
21589        // first parameter is `u32`, and `&u32` would fold to a detached
21590        // copy at the call site with a `*` deref the sibling accessors
21591        // don't need), an accidental `.max_failures.wrapping_add(0)`
21592        // detour that returned a fresh copy through an arithmetic
21593        // no-op (breaking a future `const fn` regression), or a
21594        // one-arm-only accessor that returned a saturating value on
21595        // some sentinel input (breaking the pass-through invariant the
21596        // sibling required-scalar accessors carry).
21597        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
21598            let cb = CircuitBreaker {
21599                max_failures,
21600                window: Duration::from_secs(60),
21601            };
21602            let first = cb.max_failures();
21603            let second = cb.max_failures();
21604            assert_eq!(
21605                first, second,
21606                "CircuitBreaker::max_failures must be idempotent — two \
21607                 successive calls on the same &self must return the \
21608                 same u32",
21609            );
21610            assert_eq!(
21611                first, max_failures,
21612                "CircuitBreaker::max_failures must return :politicas \
21613                 :circuit-breaker :max-failures verbatim by copy — \
21614                 got {first}, expected {max_failures}",
21615            );
21616        }
21617    }
21618
21619    #[test]
21620    fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
21621        // The canonical per-`:politicas :circuit-breaker` `:window`
21622        // Envoy-outlier-detection rolling-observation-interval scalar
21623        // pin: [`CircuitBreaker::window`] must return the
21624        // `:politicas :circuit-breaker :window` typed `Duration`
21625        // verbatim, byte-equal to the raw field access across every
21626        // representative value in the accept-set — `Duration::from_millis(1)`
21627        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
21628        // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
21629        // gate carves out on the sibling `PolicyBreakerZeroWindow`
21630        // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
21631        // same gate carves out on the sibling
21632        // `PolicyBreakerWindowExceedsCap` refusal),
21633        // `Duration::ZERO` (a past-the-guard sentinel that pins the
21634        // accessor doesn't perform a silent bounds-collapse into
21635        // `Duration::from_millis(1)` on the zero arm — validate rejects
21636        // zero but the accessor must ship the raw slot verbatim so a
21637        // validate-time gate regression surfaces at the emit boundary
21638        // rather than being silently absorbed),
21639        // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
21640        // far above the 1h cap — that pins the accessor doesn't perform
21641        // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
21642        // at the return path).
21643        //
21644        // Second sub-struct required-scalar accessor pin on the M3
21645        // mesh-slot family — sibling in shape to the just-landed
21646        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
21647        // (3a74062) required-`u32` accessor pin on the peer
21648        // per-`CircuitBreaker` required-axis, extended onto the
21649        // per-sub-struct required-`Duration` axis. Pins against a
21650        // future silent detour that re-derived the observation window
21651        // from a peer axis (an accidental
21652        // `Duration::from_secs(self.max_failures as u64)` collapse that
21653        // read the breaker's trip count as an observation-interval
21654        // duration), a `Duration::ZERO → Duration::from_millis(1)`
21655        // cluster-default projection (which would silently absorb the
21656        // `PolicyBreakerZeroWindow` refusal case at the accessor
21657        // boundary), or a bounds-collapsing accessor that clamped the
21658        // return through `POLICY_BREAKER_WINDOW_MAX` (the
21659        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
21660        // must ship the raw slot verbatim).
21661        for window in [
21662            Duration::from_millis(1),
21663            POLICY_BREAKER_WINDOW_MAX,
21664            Duration::ZERO,
21665            Duration::from_secs(86_400),
21666        ] {
21667            let cb = CircuitBreaker {
21668                max_failures: 5,
21669                window,
21670            };
21671            assert_eq!(
21672                cb.window(),
21673                window,
21674                "CircuitBreaker::window must return :politicas \
21675                 :circuit-breaker :window verbatim (got {:?}, \
21676                 expected {window:?})",
21677                cb.window(),
21678            );
21679            assert_eq!(
21680                cb.window(),
21681                cb.window,
21682                "CircuitBreaker::window must byte-equal the raw \
21683                 .window field access across every value in the \
21684                 Duration accept-set",
21685            );
21686        }
21687    }
21688
21689    #[test]
21690    fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
21691        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
21692        // `:circuit-breaker :window` zero-floor arm must key off
21693        // [`CircuitBreaker::window`], not the raw `.window` field
21694        // access. Structurally: a `CircuitBreaker { window:
21695        // Duration::ZERO, .. }` embedded in a
21696        // `:politicas :circuit-breaker` slot must surface the
21697        // `PolicyBreakerZeroWindow` refusal exactly, and a
21698        // `CircuitBreaker { window: Duration::from_millis(1), .. }`
21699        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
21700        // accept-set) must pass validate. The pair jointly pins the
21701        // accessor + validate-gate composition: any future silent
21702        // detour that had the accessor return a fresh
21703        // `Duration::from_millis(1)` on the zero arm (a
21704        // `.window().max(Duration::from_millis(1))` collapse) would
21705        // silently absorb the `PolicyBreakerZeroWindow` refusal at the
21706        // accessor boundary and the validate gate would accept a
21707        // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
21708        // — the composition pin catches that at caixa-core build time.
21709        //
21710        // Peer of the sibling per-`CircuitBreaker`
21711        // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
21712        // pin on the peer required-scalar `:max-failures` axis — same
21713        // "the validate / shape-gate predicate must route through the
21714        // substrate-primitive typed dispatch" discipline extended onto
21715        // the peer per-`CircuitBreaker` required-`Duration` composition
21716        // axis.
21717        let mut spec = three_member_spec();
21718        spec.politicas = MeshPolicy {
21719            circuit_breaker: Some(CircuitBreaker {
21720                max_failures: 5,
21721                window: Duration::ZERO,
21722            }),
21723            ..MeshPolicy::default()
21724        };
21725        assert!(
21726            matches!(
21727                spec.validate(),
21728                Err(AplicacaoError::PolicyBreakerZeroWindow)
21729            ),
21730            "validate_politicas must reject window == Duration::ZERO \
21731             with PolicyBreakerZeroWindow — the accessor and the \
21732             validate gate must route through the same substrate-\
21733             primitive typed dispatch on the :window zero-floor arm",
21734        );
21735        spec.politicas = MeshPolicy {
21736            circuit_breaker: Some(CircuitBreaker {
21737                max_failures: 5,
21738                window: Duration::from_millis(1),
21739            }),
21740            ..MeshPolicy::default()
21741        };
21742        assert!(
21743            spec.validate().is_ok(),
21744            "validate_politicas must accept window == \
21745             Duration::from_millis(1) (the lower boundary of the \
21746             1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
21747        );
21748    }
21749
21750    #[test]
21751    fn circuit_breaker_window_projects_duration_by_copy() {
21752        // The by-copy pin: [`CircuitBreaker::window`] returns
21753        // `Duration` by copy — `Duration` is `Copy` and the accessor
21754        // must return by value, not by reference. Peer of the sibling
21755        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
21756        // (3a74062) by-copy pin on the peer required-scalar
21757        // `:max-failures` axis, extended onto the peer
21758        // per-`CircuitBreaker` required-`Duration` copy-invariant shape
21759        // — the accessor's returned `Duration` must outlive `&self`
21760        // (multiple calls must return equal values from a
21761        // dropped-`&self` copy, since the returned scalar carries no
21762        // borrow), and calling the accessor twice on the same
21763        // CircuitBreaker must yield the same `Duration` verbatim
21764        // (idempotent, no side effects on `&self`).
21765        //
21766        // Pins against a future silent detour that returned
21767        // `&Duration` (which would type-check but silently break every
21768        // downstream `Duration`-by-value consumer —
21769        // [`crate::render::require_positive_canonical_bounded_duration`]'s
21770        // first parameter is `Duration`, and `&Duration` would fold to
21771        // a detached copy at the call site with a `*` deref the sibling
21772        // accessors don't need), an accidental `.window + Duration::ZERO`
21773        // detour that returned a fresh copy through an arithmetic
21774        // no-op (breaking a future `const fn` regression), or a
21775        // one-arm-only accessor that returned a saturating value on
21776        // some sentinel input (breaking the pass-through invariant the
21777        // sibling required-scalar accessors carry).
21778        for window in [
21779            Duration::from_millis(1),
21780            POLICY_BREAKER_WINDOW_MAX,
21781            Duration::ZERO,
21782            Duration::from_secs(86_400),
21783        ] {
21784            let cb = CircuitBreaker {
21785                max_failures: 5,
21786                window,
21787            };
21788            let first = cb.window();
21789            let second = cb.window();
21790            assert_eq!(
21791                first, second,
21792                "CircuitBreaker::window must be idempotent — two \
21793                 successive calls on the same &self must return the \
21794                 same Duration",
21795            );
21796            assert_eq!(
21797                first, window,
21798                "CircuitBreaker::window must return :politicas \
21799                 :circuit-breaker :window verbatim by copy — \
21800                 got {first:?}, expected {window:?}",
21801            );
21802        }
21803    }
21804
21805    #[test]
21806    fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
21807        // Apex-identity pair-invariant pin composing both substrate-
21808        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
21809        // and [`WitContract::destination`] — at the emit-side call shape
21810        // every per-`(:de, :para)` CNP L4 port reader now takes. The
21811        // invariant, evaluated per-edge:
21812        //
21813        //   spec.port_for_destination(c.destination()) == expected_port
21814        //
21815        // where `expected_port` is `entrada.port` when
21816        // `c.destination() == entrada.destination()` and
21817        // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
21818        // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
21819        // pin on the per-`:entrada` axis — that pin encodes the apex
21820        // ingress L4 identity via `entrada.destination()`; this pin
21821        // encodes the per-edge L4 identity via `c.destination()`, and
21822        // both compose on the same substrate-primitive resolver so a
21823        // future refactor that silently split either accessor's apex
21824        // behavior surfaces at caixa-core build time.
21825        let mut spec = three_member_spec();
21826        if let Some(e) = spec.entrada.as_mut() {
21827            e.para = "cart".into();
21828            e.port = 8443;
21829        }
21830        let apex_contract = WitContract {
21831            de: "checkout".into(),
21832            para: "cart".into(),
21833            wit: "wasi:http/proxy".into(),
21834            endpoint: Some("/hello".into()),
21835            subject: None,
21836            slot: None,
21837        };
21838        assert_eq!(
21839            spec.port_for_destination(apex_contract.destination()),
21840            8443,
21841            "`spec.port_for_destination(c.destination())` must equal \
21842             `entrada.port` when the contract callee names the ingress \
21843             apex — the CNP per-edge L4 port and the HTTPRoute apex \
21844             backendRef port share this substrate-primitive resolver.",
21845        );
21846        let non_apex_contract = WitContract {
21847            de: "cart".into(),
21848            para: "payment".into(),
21849            wit: "wasi:http/proxy".into(),
21850            endpoint: Some("/charge".into()),
21851            subject: None,
21852            slot: None,
21853        };
21854        assert_eq!(
21855            spec.port_for_destination(non_apex_contract.destination()),
21856            DEFAULT_SERVICO_PORT,
21857            "`spec.port_for_destination(c.destination())` must fall back \
21858             to the substrate-canonical port floor when the contract \
21859             callee is not the ingress apex — the resolver's non-apex \
21860             arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
21861        );
21862    }
21863
21864    #[test]
21865    fn membro_key_consts_are_lower_camel_case_shape() {
21866        // Shape-pin: every `MEMBRO_KEY_*` const must be a
21867        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
21868        // `kebab-case` hyphens, no leading colon, no `PascalCase`
21869        // leading capital, no whitespace / dots) — the canonical shape
21870        // the `#[serde(rename_all = "camelCase")]` derive produces on
21871        // [`Membro`]. A future flip to a non-camelCase attribute at
21872        // the derive surfaces both here (this test fails on the
21873        // stale-constant shape) and at
21874        // `membro_serde_keys_match_lifted_membro_key_consts` (that test
21875        // fails on the mismatch between const and derive). Peer with
21876        // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
21877        // on the sibling `SupervisorSpec` top-level axis.
21878        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
21879            assert!(
21880                !key.is_empty(),
21881                "MEMBRO_KEY_* must be non-empty (got {key:?})"
21882            );
21883            let first = key.chars().next().unwrap();
21884            assert!(
21885                first.is_ascii_lowercase(),
21886                "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
21887                 (got {key:?}, leads with {first:?})",
21888            );
21889            assert!(
21890                key.chars().all(|c| c.is_ascii_alphanumeric()),
21891                "MEMBRO_KEY_* must be ASCII-alphanumeric only \
21892                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
21893            );
21894        }
21895    }
21896
21897    // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
21898
21899    #[test]
21900    fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
21901        // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
21902        // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
21903        // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
21904        // keys the `#[serde(rename_all = "camelCase")]` attribute on
21905        // [`WitContract`] emits for the required-triad. The three
21906        // sibling payload-arm keys already pin under
21907        // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
21908        // `STORE_FIELD_NAME` — pin all six alongside so a future
21909        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
21910        // verbatim-field-name flip at the derive attribute (any of which
21911        // would silently break every downstream JSON consumer that
21912        // reaches for one of the six via `Value::get(...)`) surfaces
21913        // here as a build-time test failure at `aplicacao.rs`, not as an
21914        // apply-time `.get(<stale-canonical-const>)` returning `None`
21915        // far from the derive-attr drift's commit. Peer with the sibling
21916        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
21917        // pin on the M3 `:membros` per-entry axis — same discipline the
21918        // `Membro` per-entry lift established, extended here to the
21919        // sibling M3 `WitContract` per-`:contratos` entry axis, the last
21920        // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
21921        // axis on the Aplicacao surface without a lifted serde-key peer.
21922        let c = WitContract {
21923            de: "cart".into(),
21924            para: "catalog".into(),
21925            wit: "wasi:http/proxy".into(),
21926            endpoint: Some("/lookup".into()),
21927            subject: None,
21928            slot: None,
21929        };
21930        let json = serde_json::to_string(&c).unwrap();
21931        for key in [
21932            crate::CONTRATO_KEY_DE,
21933            crate::CONTRATO_KEY_PARA,
21934            crate::CONTRATO_KEY_WIT,
21935            WitTarget::HTTP_FIELD_NAME,
21936        ] {
21937            let quoted = format!("\"{key}\"");
21938            assert!(
21939                json.contains(&quoted),
21940                "serialized WitContract must carry the lifted \
21941                 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
21942                 {quoted} verbatim in the JSON emission (got: {json})",
21943            );
21944        }
21945
21946        // Pin the two remaining payload-arm keys by round-tripping a
21947        // `WitContract` under each payload-shape (pub-sub, store) — the
21948        // required-triad appears on every emission but the payload arms
21949        // only surface when their `Option<String>` field is `Some`.
21950        let pubsub = WitContract {
21951            de: "cart".into(),
21952            para: "events".into(),
21953            wit: "nats:pub-sub".into(),
21954            endpoint: None,
21955            subject: Some("orders.placed".into()),
21956            slot: None,
21957        };
21958        let pubsub_json = serde_json::to_string(&pubsub).unwrap();
21959        let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
21960        assert!(
21961            pubsub_json.contains(&pubsub_quoted),
21962            "serialized pub-sub WitContract must carry the lifted \
21963             WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
21964             verbatim in the JSON emission (got: {pubsub_json})",
21965        );
21966        let store = WitContract {
21967            de: "cart".into(),
21968            para: "sessions".into(),
21969            wit: "wasi:keyvalue/store".into(),
21970            endpoint: None,
21971            subject: None,
21972            slot: Some("cart/$id".into()),
21973        };
21974        let store_json = serde_json::to_string(&store).unwrap();
21975        let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
21976        assert!(
21977            store_json.contains(&store_quoted),
21978            "serialized store WitContract must carry the lifted \
21979             WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
21980             verbatim in the JSON emission (got: {store_json})",
21981        );
21982    }
21983
21984    #[test]
21985    fn contrato_key_consts_are_pairwise_distinct() {
21986        // Cross-axis drift-detection pin: a future collapse of the six
21987        // canonical [`WitContract`] per-entry byte-strings onto the same
21988        // value (e.g. an accidental copy-paste flip of
21989        // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
21990        // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
21991        // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
21992        // every downstream probe on one axis onto the sibling axis's
21993        // overlay entry and pass every propagation-probe test that
21994        // expected only the stale axis's value. Peer of the sibling
21995        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
21996        // widened here to the six-way axis the `WitContract`
21997        // required-triad + `WitTarget` payload-triad jointly cover.
21998        let all = [
21999            crate::CONTRATO_KEY_DE,
22000            crate::CONTRATO_KEY_PARA,
22001            crate::CONTRATO_KEY_WIT,
22002            WitTarget::HTTP_FIELD_NAME,
22003            WitTarget::PUBSUB_FIELD_NAME,
22004            WitTarget::STORE_FIELD_NAME,
22005        ];
22006        for (i, a) in all.iter().enumerate() {
22007            for b in all.iter().skip(i + 1) {
22008                assert_ne!(
22009                    a, b,
22010                    "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
22011                     must be pairwise-distinct canonical byte-sequences \
22012                     — got `{a}` == `{b}`",
22013                );
22014            }
22015        }
22016    }
22017
22018    #[test]
22019    fn contrato_key_consts_are_lower_camel_case_shape() {
22020        // Shape-pin: every `CONTRATO_KEY_*` (and every peer
22021        // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
22022        // byte-sequence (no `snake_case` underscores, no `kebab-case`
22023        // hyphens, no leading colon, no `PascalCase` leading capital, no
22024        // whitespace / dots) — the canonical shape the
22025        // `#[serde(rename_all = "camelCase")]` derive produces on
22026        // [`WitContract`]. A future flip to a non-camelCase attribute at
22027        // the derive surfaces both here (this test fails on the
22028        // stale-constant shape) and at
22029        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
22030        // (that test fails on the mismatch between const and derive).
22031        // Peer with `membro_key_consts_are_lower_camel_case_shape`
22032        // (ce80ca0) on the sibling `Membro` per-entry axis.
22033        for key in [
22034            crate::CONTRATO_KEY_DE,
22035            crate::CONTRATO_KEY_PARA,
22036            crate::CONTRATO_KEY_WIT,
22037            WitTarget::HTTP_FIELD_NAME,
22038            WitTarget::PUBSUB_FIELD_NAME,
22039            WitTarget::STORE_FIELD_NAME,
22040        ] {
22041            assert!(
22042                !key.is_empty(),
22043                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
22044                 non-empty (got {key:?})"
22045            );
22046            let first = key.chars().next().unwrap();
22047            assert!(
22048                first.is_ascii_lowercase(),
22049                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
22050                 with an ASCII-lowercase byte (got {key:?}, leads with \
22051                 {first:?})",
22052            );
22053            assert!(
22054                key.chars().all(|c| c.is_ascii_alphanumeric()),
22055                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
22056                 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
22057                 whitespace (got {key:?})",
22058            );
22059        }
22060    }
22061
22062    // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
22063
22064    #[test]
22065    fn entrada_serde_keys_match_lifted_entrada_key_consts() {
22066        // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
22067        // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
22068        // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
22069        // name the exact camelCase JSON keys the
22070        // `#[serde(rename_all = "camelCase")]` attribute on
22071        // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
22072        // pin that each canonical byte-sequence appears verbatim in the
22073        // JSON — a future accidental `rename_all = "snake_case"` /
22074        // `"kebab-case"` / verbatim-field-name flip at the derive
22075        // attribute (any of which would silently break every downstream
22076        // JSON consumer that reaches for one of the four consts via
22077        // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
22078        // emitter's per-Aplicacao hostname/paths/port projection, the
22079        // future `app-operator` reconciler's per-Aplicacao ingress
22080        // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
22081        // materializer's admission-time cross-check) surfaces here as
22082        // a build-time test failure at `aplicacao.rs`, not as an
22083        // apply-time `.get(<stale-canonical-const>)` returning `None`
22084        // far from the derive-attr drift's commit. Peer with the
22085        // sibling
22086        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
22087        // (ca463a4) and
22088        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
22089        // pins on the M3 collection-slot atom axes — same discipline
22090        // both collection-slot lifts established, extended here to the
22091        // singleton `:entrada` mesh-slot atom axis, the last M3
22092        // typed-struct top-level `#[serde(rename_all = "camelCase")]`
22093        // axis on the Aplicacao surface without a lifted serde-key
22094        // peer.
22095        let e = Entrada {
22096            host: "checkout.quero.cloud".into(),
22097            para: "cart".into(),
22098            paths: vec!["/cart".into()],
22099            port: 8080,
22100        };
22101        let json = serde_json::to_string(&e).unwrap();
22102        for key in [
22103            crate::ENTRADA_KEY_HOST,
22104            crate::ENTRADA_KEY_PARA,
22105            crate::ENTRADA_KEY_PATHS,
22106            crate::ENTRADA_KEY_PORT,
22107        ] {
22108            let quoted = format!("\"{key}\"");
22109            assert!(
22110                json.contains(&quoted),
22111                "serialized Entrada must carry the lifted ENTRADA_KEY_* \
22112                 byte-sequence {quoted} verbatim in the JSON emission \
22113                 (got: {json})",
22114            );
22115        }
22116    }
22117
22118    #[test]
22119    fn entrada_key_consts_are_pairwise_distinct() {
22120        // Cross-axis drift-detection pin: a future collapse of the four
22121        // canonical [`Entrada`] singleton byte-strings onto the same
22122        // value (e.g. an accidental copy-paste flip of
22123        // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
22124        // silently reroute every downstream probe on one axis onto the
22125        // sibling axis's overlay entry and pass every propagation-probe
22126        // test that expected only the stale axis's value — the
22127        // Gateway/HTTPRoute emitter would read the hostname string
22128        // where the destination-Servico name was expected (or vice
22129        // versa), the admission-webhook cross-check would compare the
22130        // wrong pair of values, and the resulting Gateway resource
22131        // would either be admitted with garbage or rejected at the
22132        // controller far from the rebrand commit's source. Peer of the
22133        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
22134        // tetrad (40cc4e5), the two-way distinct pin on the
22135        // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
22136        // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
22137        // triad (ca463a4).
22138        let all = [
22139            crate::ENTRADA_KEY_HOST,
22140            crate::ENTRADA_KEY_PARA,
22141            crate::ENTRADA_KEY_PATHS,
22142            crate::ENTRADA_KEY_PORT,
22143        ];
22144        for (i, a) in all.iter().enumerate() {
22145            for b in all.iter().skip(i + 1) {
22146                assert_ne!(
22147                    a, b,
22148                    "ENTRADA_KEY_* consts must be pairwise-distinct \
22149                     canonical byte-sequences — got `{a}` == `{b}`",
22150                );
22151            }
22152        }
22153    }
22154
22155    #[test]
22156    fn entrada_key_consts_are_lower_camel_case_shape() {
22157        // Shape-pin: every `ENTRADA_KEY_*` const must be a
22158        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
22159        // `kebab-case` hyphens, no leading colon, no `PascalCase`
22160        // leading capital, no whitespace / dots) — the canonical shape
22161        // the `#[serde(rename_all = "camelCase")]` derive produces on
22162        // [`Entrada`]. A future flip to a non-camelCase attribute at
22163        // the derive surfaces both here (this test fails on the
22164        // stale-constant shape) and at
22165        // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
22166        // test fails on the mismatch between const and derive). Peer
22167        // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
22168        // and `contrato_key_consts_are_lower_camel_case_shape`
22169        // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
22170        // entry axes.
22171        for key in [
22172            crate::ENTRADA_KEY_HOST,
22173            crate::ENTRADA_KEY_PARA,
22174            crate::ENTRADA_KEY_PATHS,
22175            crate::ENTRADA_KEY_PORT,
22176        ] {
22177            assert!(
22178                !key.is_empty(),
22179                "ENTRADA_KEY_* must be non-empty (got {key:?})"
22180            );
22181            let first = key.chars().next().unwrap();
22182            assert!(
22183                first.is_ascii_lowercase(),
22184                "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
22185                 (got {key:?}, leads with {first:?})",
22186            );
22187            assert!(
22188                key.chars().all(|c| c.is_ascii_alphanumeric()),
22189                "ENTRADA_KEY_* must be ASCII-alphanumeric only \
22190                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
22191            );
22192        }
22193    }
22194
22195    // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
22196
22197    #[test]
22198    fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
22199        // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
22200        // ([`crate::POLITICAS_KEY_TIMEOUT`] /
22201        // [`crate::POLITICAS_KEY_RETRIES`] /
22202        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
22203        // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
22204        // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
22205        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
22206        // on [`MeshPolicy`] emits. Three of the five axes
22207        // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
22208        // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
22209        // camelCase transforms — the derive-attribute is load-bearing
22210        // on those, unlike the sibling `Entrada` / `Membro` /
22211        // `WitContract` structs whose fields are all lowercase-single-
22212        // word and where the derive is a no-op on every axis.
22213        // Serialize a fully-populated [`MeshPolicy`] (every axis
22214        // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
22215        // on none of the five slots) and pin that each canonical
22216        // byte-sequence appears verbatim in the JSON — a future
22217        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
22218        // verbatim-field-name flip at the derive attribute (any of
22219        // which would silently break every downstream JSON consumer
22220        // that reaches for one of the five consts via
22221        // `Value::get(...)` — the future M4 per-edge `:politicas`
22222        // overlay projection onto Cilium `L7Rules` and Gateway API
22223        // `HTTPRoute` backend timeouts, the future
22224        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
22225        // admission-time mesh-policy cross-check, the future
22226        // `feira lint` per-`:politicas` bound-check gate) surfaces here
22227        // as a build-time test failure at `aplicacao.rs`, not as an
22228        // apply-time `.get(<stale-canonical-const>)` returning `None`
22229        // far from the derive-attr drift's commit. Peer with the
22230        // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
22231        // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
22232        // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
22233        // (ce80ca0) pins on the M3 collection-slot / singleton-slot
22234        // atom axes — same discipline every M3 sibling lift
22235        // established, extended here to the singleton `:politicas`
22236        // mesh-slot atom axis, closing the last M3 typed-struct
22237        // top-level `#[serde(rename_all = "camelCase")]` axis on the
22238        // Aplicacao surface without a lifted serde-key peer.
22239        let p = MeshPolicy {
22240            timeout: Some(Duration::from_secs(30)),
22241            retries: Some(3),
22242            circuit_breaker: Some(CircuitBreaker {
22243                max_failures: 5,
22244                window: Duration::from_secs(60),
22245            }),
22246            mtls_required: Some(true),
22247            rate_limit: Some(RateLimit {
22248                rate: 100,
22249                window: Duration::from_secs(1),
22250            }),
22251        };
22252        let json = serde_json::to_string(&p).unwrap();
22253        for key in [
22254            crate::POLITICAS_KEY_TIMEOUT,
22255            crate::POLITICAS_KEY_RETRIES,
22256            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
22257            crate::POLITICAS_KEY_MTLS_REQUIRED,
22258            crate::POLITICAS_KEY_RATE_LIMIT,
22259        ] {
22260            let quoted = format!("\"{key}\"");
22261            assert!(
22262                json.contains(&quoted),
22263                "serialized MeshPolicy must carry the lifted \
22264                 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
22265                 JSON emission (got: {json})",
22266            );
22267        }
22268    }
22269
22270    #[test]
22271    fn politicas_key_consts_are_pairwise_distinct() {
22272        // Cross-axis drift-detection pin: a future collapse of the five
22273        // canonical [`MeshPolicy`] singleton byte-strings onto the same
22274        // value (e.g. an accidental copy-paste flip of
22275        // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
22276        // would silently reroute every downstream probe on one axis
22277        // onto the sibling axis's overlay entry and pass every
22278        // propagation-probe test that expected only the stale axis's
22279        // value — the M4 per-edge `:politicas` overlay projection would
22280        // read the retry-count string where the timeout duration was
22281        // expected (or vice versa), the CR materializer's admission
22282        // cross-check would compare the wrong pair of values, and the
22283        // resulting mesh reconciler would either bind the wrong axis
22284        // or reject the resource at reconcile far from the rebrand
22285        // commit's source. Peer of the sibling four-way distinct pin
22286        // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
22287        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
22288        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
22289        // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
22290        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
22291        let all = [
22292            crate::POLITICAS_KEY_TIMEOUT,
22293            crate::POLITICAS_KEY_RETRIES,
22294            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
22295            crate::POLITICAS_KEY_MTLS_REQUIRED,
22296            crate::POLITICAS_KEY_RATE_LIMIT,
22297        ];
22298        for (i, a) in all.iter().enumerate() {
22299            for b in all.iter().skip(i + 1) {
22300                assert_ne!(
22301                    a, b,
22302                    "POLITICAS_KEY_* consts must be pairwise-distinct \
22303                     canonical byte-sequences — got `{a}` == `{b}`",
22304                );
22305            }
22306        }
22307    }
22308
22309    #[test]
22310    fn politicas_key_consts_are_lower_camel_case_shape() {
22311        // Shape-pin: every `POLITICAS_KEY_*` const must be a
22312        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
22313        // `kebab-case` hyphens, no leading colon, no `PascalCase`
22314        // leading capital, no whitespace / dots) — the canonical shape
22315        // the `#[serde(rename_all = "camelCase")]` derive produces on
22316        // [`MeshPolicy`]. A future flip to a non-camelCase attribute
22317        // at the derive surfaces both here (this test fails on the
22318        // stale-constant shape) and at
22319        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
22320        // (that test fails on the mismatch between const and derive).
22321        // Peer with `entrada_key_consts_are_lower_camel_case_shape`
22322        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
22323        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
22324        // (ca463a4) on the sibling M3 typed-struct axes.
22325        for key in [
22326            crate::POLITICAS_KEY_TIMEOUT,
22327            crate::POLITICAS_KEY_RETRIES,
22328            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
22329            crate::POLITICAS_KEY_MTLS_REQUIRED,
22330            crate::POLITICAS_KEY_RATE_LIMIT,
22331        ] {
22332            assert!(
22333                !key.is_empty(),
22334                "POLITICAS_KEY_* must be non-empty (got {key:?})"
22335            );
22336            let first = key.chars().next().unwrap();
22337            assert!(
22338                first.is_ascii_lowercase(),
22339                "POLITICAS_KEY_* must lead with an ASCII-lowercase \
22340                 byte (got {key:?}, leads with {first:?})",
22341            );
22342            assert!(
22343                key.chars().all(|c| c.is_ascii_alphanumeric()),
22344                "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
22345                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
22346            );
22347        }
22348    }
22349
22350    // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
22351
22352    #[test]
22353    fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
22354        // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
22355        // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
22356        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
22357        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
22358        // [`CircuitBreaker`] emits inside the
22359        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
22360        // two axes (`max_failures` → `maxFailures`) is a non-trivial
22361        // camelCase transform — the derive-attribute is load-bearing on
22362        // that axis, unlike the sibling `window` field where the derive
22363        // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
22364        // pin that each canonical byte-sequence appears verbatim in the
22365        // JSON — a future accidental `rename_all = "snake_case"` /
22366        // `"kebab-case"` / verbatim-field-name flip at the derive
22367        // attribute (any of which would silently break every downstream
22368        // JSON consumer that reaches for one of the two consts via
22369        // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
22370        // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
22371        // per-edge `:politicas` overlay projection onto the mesh's
22372        // per-backend consecutive-failure-counter tripping threshold, the
22373        // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
22374        // admission-time breaker cross-check, the future `feira lint`
22375        // per-`:politicas :circuit-breaker` bound-check gate) surfaces
22376        // here as a build-time test failure at `aplicacao.rs`, not as an
22377        // apply-time `.get(<stale-canonical-const>)` returning `None`
22378        // far from the derive-attr drift's commit. Peer with the sibling
22379        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
22380        // (b55cca7) parent-axis pin — that test pins the outer
22381        // sub-block key the derive on [`MeshPolicy`] emits, this test
22382        // pins the inner keys the derive on the payload type emits, so
22383        // the two together lock the whole [`MeshPolicy`] breaker-tuning
22384        // shape end-to-end at build time.
22385        let cb = CircuitBreaker {
22386            max_failures: 5,
22387            window: Duration::from_secs(60),
22388        };
22389        let json = serde_json::to_string(&cb).unwrap();
22390        for key in [
22391            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
22392            crate::CIRCUIT_BREAKER_KEY_WINDOW,
22393        ] {
22394            let quoted = format!("\"{key}\"");
22395            assert!(
22396                json.contains(&quoted),
22397                "serialized CircuitBreaker must carry the lifted \
22398                 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
22399                 in the JSON emission (got: {json})",
22400            );
22401        }
22402    }
22403
22404    #[test]
22405    fn circuit_breaker_key_consts_are_pairwise_distinct() {
22406        // Cross-axis drift-detection pin: a future collapse of the two
22407        // canonical [`CircuitBreaker`] sub-block byte-strings onto the
22408        // same value (e.g. an accidental copy-paste flip of
22409        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
22410        // `"maxFailures"`) would silently reroute every downstream
22411        // probe on one axis onto the sibling axis's overlay entry and
22412        // pass every propagation-probe test that expected only the
22413        // stale axis's value — the M4 per-edge `:politicas` overlay
22414        // projection would read the failure-count where the window
22415        // duration was expected (or vice versa), the CR materializer's
22416        // admission cross-check would compare the wrong pair of values,
22417        // and the resulting mesh reconciler would either bind the wrong
22418        // axis or reject the resource at reconcile far from the rebrand
22419        // commit's source. Peer of the sibling five-way distinct pin on
22420        // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
22421        // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
22422        // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
22423        // six-way distinct pin on the `CONTRATO_KEY_*` triad +
22424        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
22425        let all = [
22426            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
22427            crate::CIRCUIT_BREAKER_KEY_WINDOW,
22428        ];
22429        for (i, a) in all.iter().enumerate() {
22430            for b in all.iter().skip(i + 1) {
22431                assert_ne!(
22432                    a, b,
22433                    "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
22434                     canonical byte-sequences — got `{a}` == `{b}`",
22435                );
22436            }
22437        }
22438    }
22439
22440    #[test]
22441    fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
22442        // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
22443        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
22444        // `kebab-case` hyphens, no leading colon, no `PascalCase`
22445        // leading capital, no whitespace / dots) — the canonical shape
22446        // the `#[serde(rename_all = "camelCase")]` derive produces on
22447        // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
22448        // at the derive surfaces both here (this test fails on the
22449        // stale-constant shape) and at
22450        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
22451        // (that test fails on the mismatch between const and derive).
22452        // Peer with `politicas_key_consts_are_lower_camel_case_shape`
22453        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
22454        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
22455        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
22456        // (ca463a4) on the sibling M3 typed-struct axes.
22457        for key in [
22458            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
22459            crate::CIRCUIT_BREAKER_KEY_WINDOW,
22460        ] {
22461            assert!(
22462                !key.is_empty(),
22463                "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
22464            );
22465            let first = key.chars().next().unwrap();
22466            assert!(
22467                first.is_ascii_lowercase(),
22468                "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
22469                 byte (got {key:?}, leads with {first:?})",
22470            );
22471            assert!(
22472                key.chars().all(|c| c.is_ascii_alphanumeric()),
22473                "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
22474                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
22475            );
22476        }
22477    }
22478
22479    // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
22480
22481    #[test]
22482    fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
22483        // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
22484        // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
22485        // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
22486        // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
22487        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
22488        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
22489        // [`Placement`] emits. One of the four axes (`shard_key` →
22490        // `shardKey`) is a non-trivial camelCase transform — the
22491        // derive-attribute is load-bearing on that axis, unlike the
22492        // sibling `estrategia` / `clusters` / `affinity` axes whose
22493        // source-side field names carry no `_` and where the derive is a
22494        // no-op. Serialize a fully-populated [`Placement`] (both
22495        // `Option`-carrying axes `Some(_)` so
22496        // `skip_serializing_if = "Option::is_none"` fires on neither of
22497        // the two optional slots) and pin that each canonical
22498        // byte-sequence appears verbatim in the JSON — a future
22499        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
22500        // verbatim-field-name flip at the derive attribute (any of which
22501        // would silently break every downstream consumer that reaches
22502        // for one of the four consts via
22503        // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
22504        // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
22505        // aggregator's per-cluster fanout filter keying off
22506        // `placement.clusters`, the M3 shard-pool dispatch materializer
22507        // keying off `placement.shardKey`, the M3 Adaptive compression
22508        // pass weighting off `placement.affinity`, every downstream
22509        // dispatcher branching on `placement.estrategia`, the future
22510        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
22511        // admission-time placement cross-check, the future `feira lint`
22512        // per-`:placement` bound-check gate) surfaces here as a
22513        // build-time test failure at `aplicacao.rs`, not as an
22514        // apply-time `.get(<stale-canonical-const>)` returning `None`
22515        // far from the derive-attr drift's commit. Peer with the sibling
22516        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
22517        // (b55cca7),
22518        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
22519        // (468e959),
22520        // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
22521        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
22522        // (ca463a4), and
22523        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
22524        // pins on the M3 collection-slot / singleton-slot atom axes —
22525        // closes the last M3 typed-struct top-level
22526        // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
22527        // surface without a drift-detection pin.
22528        let p = Placement {
22529            estrategia: PlacementStrategy::Sharded,
22530            clusters: vec!["rio".into(), "mar".into()],
22531            affinity: Some("data-locality".into()),
22532            shard_key: Some("$tenantId".into()),
22533        };
22534        let json = serde_json::to_string(&p).unwrap();
22535        for key in [
22536            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
22537            crate::M3_PLACEMENT_KEY_CLUSTERS,
22538            crate::M3_PLACEMENT_KEY_AFFINITY,
22539            crate::M3_PLACEMENT_KEY_SHARD_KEY,
22540        ] {
22541            let quoted = format!("\"{key}\"");
22542            assert!(
22543                json.contains(&quoted),
22544                "serialized Placement must carry the lifted \
22545                 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
22546                 the JSON emission (got: {json})",
22547            );
22548        }
22549    }
22550
22551    #[test]
22552    fn m3_placement_key_consts_are_pairwise_distinct() {
22553        // Cross-axis drift-detection pin: a future collapse of the four
22554        // canonical [`Placement`] sub-block byte-strings onto the same
22555        // value (e.g. an accidental copy-paste flip of
22556        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
22557        // `"affinity"`) would silently reroute every downstream probe on
22558        // one axis onto the sibling axis's overlay entry and pass every
22559        // propagation-probe test that expected only the stale axis's
22560        // value — the M3 shard-pool dispatch materializer would read the
22561        // affinity placement-hint where the shard-selection template was
22562        // expected (or vice versa), the M3 Adaptive compression pass's
22563        // cross-check would compare the wrong pair of values, and the
22564        // resulting placement engine would either bind the wrong axis or
22565        // reject the resource at reconcile far from the rebrand commit's
22566        // source. Peer of the sibling two-way distinct pin on the
22567        // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
22568        // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
22569        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
22570        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
22571        // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
22572        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
22573        let all = [
22574            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
22575            crate::M3_PLACEMENT_KEY_CLUSTERS,
22576            crate::M3_PLACEMENT_KEY_AFFINITY,
22577            crate::M3_PLACEMENT_KEY_SHARD_KEY,
22578        ];
22579        for (i, a) in all.iter().enumerate() {
22580            for b in all.iter().skip(i + 1) {
22581                assert_ne!(
22582                    a, b,
22583                    "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
22584                     canonical byte-sequences — got `{a}` == `{b}`",
22585                );
22586            }
22587        }
22588    }
22589
22590    #[test]
22591    fn m3_placement_key_consts_are_lower_camel_case_shape() {
22592        // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
22593        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
22594        // `kebab-case` hyphens, no leading colon, no `PascalCase`
22595        // leading capital, no whitespace / dots) — the canonical shape
22596        // the `#[serde(rename_all = "camelCase")]` derive produces on
22597        // [`Placement`]. A future flip to a non-camelCase attribute at
22598        // the derive surfaces both here (this test fails on the stale-
22599        // constant shape) and at
22600        // `placement_serde_keys_match_lifted_m3_placement_key_consts`
22601        // (that test fails on the mismatch between const and derive).
22602        // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
22603        // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
22604        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
22605        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
22606        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
22607        // (ca463a4) on the sibling M3 typed-struct axes.
22608        for key in [
22609            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
22610            crate::M3_PLACEMENT_KEY_CLUSTERS,
22611            crate::M3_PLACEMENT_KEY_AFFINITY,
22612            crate::M3_PLACEMENT_KEY_SHARD_KEY,
22613        ] {
22614            assert!(
22615                !key.is_empty(),
22616                "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
22617            );
22618            let first = key.chars().next().unwrap();
22619            assert!(
22620                first.is_ascii_lowercase(),
22621                "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
22622                 byte (got {key:?}, leads with {first:?})",
22623            );
22624            assert!(
22625                key.chars().all(|c| c.is_ascii_alphanumeric()),
22626                "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
22627                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
22628            );
22629        }
22630    }
22631
22632    // ── AplicacaoSpec::port_for_destination — the substrate-canonical
22633    //    destination-facing L4 port resolver every per-Aplicacao renderer
22634    //    reaching for a per-destination Servico TCP port axis routes
22635    //    through. The four pin tests below fix the four-way accept-set
22636    //    the resolver must always honor: (:entrada-para-matches,
22637    //    :entrada-para-mismatches, :entrada-none-so-fallback,
22638    //    :entrada-port-non-default-honored) — drift on any arm surfaces
22639    //    at caixa-core build time rather than at cluster-apply time.
22640
22641    #[test]
22642    fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
22643        // The typed `:entrada` block's `:para "cart"` matches the
22644        // queried destination, so the resolver returns the author-
22645        // declared `:port` scalar verbatim — the canonical "the
22646        // destination Servico IS the ingress apex, honor the typed
22647        // listener port" arm of the port-resolution dispatch.
22648        let mut spec = three_member_spec();
22649        if let Some(e) = spec.entrada.as_mut() {
22650            e.para = "cart".into();
22651            e.port = 9090;
22652        }
22653        assert_eq!(
22654            spec.port_for_destination("cart"),
22655            9090,
22656            "port_for_destination(entrada.para) must return entrada.port \
22657             verbatim, not the DEFAULT_SERVICO_PORT fallback"
22658        );
22659    }
22660
22661    #[test]
22662    fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
22663        // The typed `:entrada` block names `:para "cart"`, but the
22664        // queried destination is `"payment"` — a Servico that
22665        // participates in the mesh graph but is not the ingress apex.
22666        // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
22667        // canonical port floor, closing the "non-apex destination reads
22668        // the substrate default" arm. Same fixture the peer
22669        // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
22670        // pin at caixa-mesh exercises through the CNP emit-side path;
22671        // this pin exercises the shared underlying resolver directly.
22672        let spec = three_member_spec();
22673        assert_eq!(
22674            spec.port_for_destination("payment"),
22675            DEFAULT_SERVICO_PORT,
22676            "port_for_destination(non-apex-destination) must route \
22677             through the lifted DEFAULT_SERVICO_PORT canonical port floor"
22678        );
22679    }
22680
22681    #[test]
22682    fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
22683        // Internal-only Aplicacao — no `:entrada` block declared. Every
22684        // per-destination port query falls back to the lifted
22685        // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
22686        // the Aplicacao surface admits `:entrada None` (internal mesh
22687        // with no external gateway); every downstream renderer's per-
22688        // destination port axis must still resolve to a well-defined
22689        // scalar even without an ingress apex.
22690        let mut spec = three_member_spec();
22691        spec.entrada = None;
22692        assert_eq!(
22693            spec.port_for_destination("cart"),
22694            DEFAULT_SERVICO_PORT,
22695            "port_for_destination on an internal-only Aplicacao must \
22696             fall back to the lifted DEFAULT_SERVICO_PORT floor for \
22697             every destination"
22698        );
22699        assert_eq!(
22700            spec.port_for_destination("payment"),
22701            DEFAULT_SERVICO_PORT,
22702            "port_for_destination on an internal-only Aplicacao must \
22703             fall back uniformly across every destination — the fallback \
22704             is not entrada-shape-conditional"
22705        );
22706    }
22707
22708    #[test]
22709    fn port_for_destination_honors_non_default_entrada_port_verbatim() {
22710        // Structural pin against a hypothetical future refactor that
22711        // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
22712        // the resolver (a "normalize to the default when the author's
22713        // port matches the substrate default" collapse) — that would
22714        // break renderer sites that carry meaning on the emitted port
22715        // value beyond bare equality (a future per-cluster listener-
22716        // audit that keys off the author-declared port, not the
22717        // resolved-with-fallback port). Pin that a non-default
22718        // entrada.port is returned verbatim so drift here surfaces at
22719        // caixa-core build time.
22720        let mut spec = three_member_spec();
22721        if let Some(e) = spec.entrada.as_mut() {
22722            e.para = "cart".into();
22723            e.port = 8443;
22724        }
22725        assert_ne!(
22726            8443, DEFAULT_SERVICO_PORT,
22727            "test fixture must probe a port distinct from \
22728             DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
22729        );
22730        assert_eq!(
22731            spec.port_for_destination("cart"),
22732            8443,
22733            "port_for_destination(entrada.para) must return entrada.port \
22734             verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
22735        );
22736    }
22737
22738    #[test]
22739    fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
22740        // Apex-identity pair-invariant pin composing both substrate-
22741        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
22742        // and [`Entrada::destination`] — at the emit-side call shape
22743        // every per-Aplicacao renderer's ingress-apex L4 port reader
22744        // now takes. The invariant:
22745        //
22746        //   spec.port_for_destination(entrada.destination()) == entrada.port
22747        //
22748        // holds by construction under today's single-destination
22749        // `:entrada` slot (`destination()` returns `entrada.para`, and
22750        // the resolver's apex arm matches `para == destination` and
22751        // returns `entrada.port`), and every downstream consumer that
22752        // composes the two accessors at the ingress apex — the
22753        // `caixa_mesh::gateway_routes` HTTPRoute per-rule
22754        // `backendRefs[0].port` emit-site path, the peer future M4 CR
22755        // materializer's admission-webhook that promotes the scalar to
22756        // a per-CR override overlay, every future per-Aplicacao snapshot
22757        // renderer's apex-facing L4 port reader — reaches through the
22758        // same composition. Pin the identity across four permutations
22759        // (`:para` × `:port` including a non-default port to exercise
22760        // the honor-verbatim arm and a non-cart `:para` to exercise
22761        // destination-agnostic identity) so a future refactor that
22762        // silently split either accessor's apex behavior surfaces at
22763        // caixa-core build time — a subtle `destination()` renaming
22764        // that returned `entrada.host.as_str()` instead of
22765        // `entrada.para.as_str()` would blow this pin loudly, closing
22766        // the last quiet failure mode the two lifts admit in composition.
22767        //
22768        // Peer discipline with the sibling caixa-mesh cross-crate pin
22769        // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
22770        // on the two-renderer pair-invariant axis; this pin encodes the
22771        // same two-consumer coherence rule at the substrate-primitive
22772        // level so the invariant survives even if every renderer is
22773        // deleted.
22774        for (para, port) in [
22775            ("cart", DEFAULT_SERVICO_PORT),
22776            ("cart", 8443u16),
22777            ("payment", 9090u16),
22778            ("catalog", 443u16),
22779        ] {
22780            let mut spec = three_member_spec();
22781            if let Some(e) = spec.entrada.as_mut() {
22782                e.para = para.into();
22783                e.port = port;
22784            }
22785            let expected_port = spec
22786                .entrada
22787                .as_ref()
22788                .expect("three_member_spec carries a typed `:entrada` block")
22789                .port;
22790            let composed_port = {
22791                let entrada = spec.entrada.as_ref().expect("entrada present");
22792                spec.port_for_destination(entrada.destination())
22793            };
22794            assert_eq!(
22795                composed_port, expected_port,
22796                "`spec.port_for_destination(entrada.destination())` must \
22797                 equal `entrada.port` under today's single-destination \
22798                 `:entrada` slot — this is the apex-identity contract \
22799                 every downstream ingress-apex L4 port reader relies on. \
22800                 Input :entrada :para: {para:?}, :entrada :port: {port}"
22801            );
22802        }
22803    }
22804
22805    #[test]
22806    fn port_for_destination_apex_arm_routes_through_destination_accessor() {
22807        // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
22808        // per-`:entrada` apex-arm membership probe must key off
22809        // [`Entrada::destination`], not the raw `.para` field access.
22810        // Structurally: setting ONLY the `:entrada :para` field to a
22811        // fresh non-cart destination on an otherwise-well-formed
22812        // Aplicacao must (1) leave `e.destination()` byte-equal to
22813        // `e.para.as_str()` (the accessor is byte-projective by
22814        // definition), and (2) cause the resolver's apex arm to fire
22815        // and return `entrada.port` at exactly that new destination
22816        // while every other destination string falls through to
22817        // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
22818        // membership check. Pins against a future silent detour that
22819        // (a) re-derived the apex-arm membership probe off
22820        // `e.para == destination` in `port_for_destination` instead of
22821        // `e.destination() == destination`, silently disagreeing with
22822        // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
22823        // consumers (`entrada.destination()` at
22824        // caixa-mesh/src/lib.rs:3173, `c.destination()` at
22825        // caixa-mesh/src/lib.rs:2739) that already reach through the
22826        // accessor, (b) accessor-side introduced a per-tenant alias
22827        // arm the caller was unaware of, silently rewriting an
22828        // author-declared `:para "cart"` value to a canary-aliased
22829        // form — the raw-field-access resolver would fall through to
22830        // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
22831        // while the peer emit-site consumers landed on the aliased
22832        // destination, splitting the ingress-apex L4 port at
22833        // cluster-apply time.
22834        //
22835        // Peer of the sibling
22836        // [`validate_membros_empty_gate_routes_through_nome_accessor`]
22837        // (d0de220) composition pin on the per-`:membros` refusal-arm
22838        // axis — same "the shape-gate predicate must route through the
22839        // substrate-primitive typed dispatch" discipline extended onto
22840        // the per-`:entrada` apex-arm membership-probe axis. Closes
22841        // the last unlifted `.para` production-code read site on
22842        // `Entrada` in `caixa-core` — after this converge every
22843        // `caixa-core` `.para` field access outside the accessor's own
22844        // body and outside the `WitContract` per-`:contratos` sibling
22845        // axis is either a test-side field-setter or a doc-comment
22846        // reference.
22847        for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
22848            let mut spec = three_member_spec();
22849            if let Some(e) = spec.entrada.as_mut() {
22850                e.para = para.into();
22851                e.port = port;
22852            }
22853            let e = spec
22854                .entrada
22855                .as_ref()
22856                .expect("three_member_spec carries a typed `:entrada` block");
22857            assert_eq!(
22858                e.destination(),
22859                e.para.as_str(),
22860                "Entrada::destination must byte-equal the .para field \
22861                 access — an accessor-side detour that no longer \
22862                 projects the raw field would silently split this \
22863                 drift-detection test from the port_for_destination \
22864                 apex-arm membership probe",
22865            );
22866            assert_eq!(
22867                spec.port_for_destination(para),
22868                port,
22869                "port_for_destination must key off the accessor-projected \
22870                 destination and return `entrada.port` on the apex arm — \
22871                 input :entrada :para: {para:?}, :entrada :port: {port}",
22872            );
22873            assert_eq!(
22874                spec.port_for_destination("ghost-destination-never-a-member"),
22875                DEFAULT_SERVICO_PORT,
22876                "port_for_destination must fall through to \
22877                 DEFAULT_SERVICO_PORT on a non-matching destination \
22878                 under the accessor-projected membership check — input \
22879                 :entrada :para: {para:?}, :entrada :port: {port}",
22880            );
22881        }
22882    }
22883
22884    #[test]
22885    fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
22886        // The canonical per-`:politicas :rate-limit` `:rate`
22887        // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
22888        // [`RateLimit::rate`] must return the `:politicas :rate-limit`
22889        // typed `u32` verbatim, byte-equal to the raw field access
22890        // across every representative value in the accept-set — `1` (the
22891        // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
22892        // the surrounding [`AplicacaoSpec::validate_politicas`] gate
22893        // carves out on the sibling `PolicyRateLimitZero` refusal),
22894        // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
22895        // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
22896        // `0` (a past-the-guard sentinel that pins the accessor doesn't
22897        // perform a silent bounds-collapse into `1` on the zero arm —
22898        // validate rejects zero but the accessor must ship the raw slot
22899        // verbatim so a validate-time gate regression surfaces at the
22900        // emit boundary rather than being silently absorbed), `u32::MAX`
22901        // (a past-the-guard sentinel that pins the accessor doesn't
22902        // perform a silent bounds-collapse through
22903        // `POLICY_RATE_LIMIT_MAX` at the return path).
22904        //
22905        // First sub-struct required-scalar accessor pin on the
22906        // `RateLimit` axis — sibling in shape to the peer
22907        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
22908        // required-`u32` accessor pin on the peer per-sub-struct
22909        // required-axis. Pins against a future silent detour that
22910        // re-derived the token capacity from a peer axis (an accidental
22911        // `self.window.as_secs() as u32` collapse that read the
22912        // rate-limit window duration as a token count), a `0 → 1`
22913        // cluster-default projection (which would silently absorb the
22914        // `PolicyRateLimitZero` refusal case at the accessor boundary),
22915        // or a bounds-collapsing accessor that clamped the return
22916        // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
22917        // gate owns the bounds; the accessor must ship the raw slot
22918        // verbatim).
22919        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
22920            let rl = RateLimit {
22921                rate,
22922                window: Duration::from_secs(1),
22923            };
22924            assert_eq!(
22925                rl.rate(),
22926                rate,
22927                "RateLimit::rate must return :politicas :rate-limit :rate \
22928                 verbatim (got {}, expected {rate})",
22929                rl.rate(),
22930            );
22931            assert_eq!(
22932                rl.rate(),
22933                rl.rate,
22934                "RateLimit::rate must byte-equal the raw .rate field \
22935                 access across every value in the u32 accept-set",
22936            );
22937        }
22938    }
22939
22940    #[test]
22941    fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
22942        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
22943        // `:rate-limit :rate` zero-floor arm must key off
22944        // [`RateLimit::rate`], not the raw `.rate` field access.
22945        // Structurally: a `RateLimit { rate: 0, window:
22946        // Duration::from_secs(1) }` embedded in a `:politicas
22947        // :rate-limit` slot must surface the `PolicyRateLimitZero`
22948        // refusal exactly, and a `RateLimit { rate: 1, window:
22949        // Duration::from_secs(1) }` (the lower boundary of the
22950        // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
22951        // The pair jointly pins the accessor + validate-gate composition:
22952        // any future silent detour that had the accessor return a fresh
22953        // `1` on the zero arm (a `.rate().max(1)` collapse) would
22954        // silently absorb the `PolicyRateLimitZero` refusal at the
22955        // accessor boundary and the validate gate would accept a
22956        // struct-literal `RateLimit { rate: 0, .. }` — the composition
22957        // pin catches that at caixa-core build time.
22958        //
22959        // Peer of the sibling per-`CircuitBreaker`
22960        // [`CircuitBreaker::max_failures`] (3a74062) /
22961        // [`CircuitBreaker::window`] (373957f) accessor-composition
22962        // pins on the peer required-scalar axes — same "the validate /
22963        // shape-gate predicate must route through the substrate-primitive
22964        // typed dispatch" discipline extended onto the peer
22965        // per-`RateLimit` required-`u32` composition axis.
22966        let mut spec = three_member_spec();
22967        spec.politicas = MeshPolicy {
22968            rate_limit: Some(RateLimit {
22969                rate: 0,
22970                window: Duration::from_secs(1),
22971            }),
22972            ..MeshPolicy::default()
22973        };
22974        assert!(
22975            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
22976            "validate_politicas must reject rate == 0 with \
22977             PolicyRateLimitZero — the accessor and the validate gate \
22978             must route through the same substrate-primitive typed \
22979             dispatch on the :rate zero-floor arm",
22980        );
22981        spec.politicas = MeshPolicy {
22982            rate_limit: Some(RateLimit {
22983                rate: 1,
22984                window: Duration::from_secs(1),
22985            }),
22986            ..MeshPolicy::default()
22987        };
22988        assert!(
22989            spec.validate().is_ok(),
22990            "validate_politicas must accept rate == 1 (the lower \
22991             boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
22992        );
22993    }
22994
22995    #[test]
22996    fn rate_limit_rate_projects_u32_by_copy() {
22997        // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
22998        // `u32` is `Copy` and the accessor must return by value, not by
22999        // reference. Peer of the sibling per-`CircuitBreaker`
23000        // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
23001        // peer required-scalar `:max-failures` axis, extended onto the
23002        // peer per-`RateLimit` required-`u32` copy-invariant shape —
23003        // the accessor's returned `u32` must outlive `&self` (multiple
23004        // calls must return equal values from a dropped-`&self` copy,
23005        // since the returned scalar carries no borrow), and calling the
23006        // accessor twice on the same RateLimit must yield the same
23007        // `u32` verbatim (idempotent, no side effects on `&self`).
23008        //
23009        // Pins against a future silent detour that returned `&u32`
23010        // (which would type-check but silently break every downstream
23011        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
23012        // first parameter is `u32`, and `&u32` would fold to a detached
23013        // copy at the call site with a `*` deref the sibling accessors
23014        // don't need), an accidental `.rate.wrapping_add(0)` detour that
23015        // returned a fresh copy through an arithmetic no-op (breaking a
23016        // future `const fn` regression), or a one-arm-only accessor
23017        // that returned a saturating value on some sentinel input
23018        // (breaking the pass-through invariant the sibling required-
23019        // scalar accessors carry).
23020        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
23021            let rl = RateLimit {
23022                rate,
23023                window: Duration::from_secs(1),
23024            };
23025            let first = rl.rate();
23026            let second = rl.rate();
23027            assert_eq!(
23028                first, second,
23029                "RateLimit::rate must be idempotent — two successive \
23030                 calls on the same &self must return the same u32",
23031            );
23032            assert_eq!(
23033                first, rate,
23034                "RateLimit::rate must return :politicas :rate-limit :rate \
23035                 verbatim by copy — got {first}, expected {rate}",
23036            );
23037        }
23038    }
23039
23040    #[test]
23041    fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
23042        // The canonical per-`:politicas :rate-limit` `:window`
23043        // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
23044        // pin: [`RateLimit::window`] must return the
23045        // `:politicas :rate-limit :window` typed `Duration` verbatim,
23046        // byte-equal to the raw field access across every
23047        // representative value in the accept-set — `Duration::from_secs(1)`
23048        // (the `"s"` canonical window, the lower row of
23049        // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
23050        // [`AplicacaoSpec::validate_politicas`] gate accepts via
23051        // [`is_canonical_rate_limit_window`]),
23052        // `Duration::from_secs(60)` (the `"m"` canonical window, the
23053        // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
23054        // window, the upper row), `Duration::ZERO` (a past-the-guard
23055        // sentinel that pins the accessor doesn't perform a silent
23056        // bounds-collapse into `Duration::from_secs(1)` on the zero
23057        // arm — validate rejects an off-set window through
23058        // `PolicyRateLimitWindowNotCanonical` but the accessor must
23059        // ship the raw slot verbatim so a validate-time gate
23060        // regression surfaces at the emit boundary rather than being
23061        // silently absorbed), `Duration::from_millis(500)` (a
23062        // sub-canonical past-the-guard sentinel that pins the accessor
23063        // doesn't silently normalize a non-canonical fractional
23064        // magnitude onto the nearest canonical row).
23065        //
23066        // Second sub-struct required-scalar accessor pin on the
23067        // `RateLimit` axis — sibling in shape to the just-landed
23068        // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
23069        // accessor pin on the peer per-sub-struct required-axis,
23070        // extended onto the per-`RateLimit` required-`Duration` axis.
23071        // Pins against a future silent detour that re-derived the
23072        // refill period from a peer axis (an accidental
23073        // `Duration::from_secs(self.rate as u64)` collapse that read
23074        // the rate-limit token capacity as a refill-interval
23075        // duration), a `Duration::ZERO → Duration::from_secs(1)`
23076        // canonical-default projection (which would silently absorb
23077        // the `PolicyRateLimitWindowNotCanonical` refusal case at the
23078        // accessor boundary), or a canonical-set-collapsing accessor
23079        // that clamped the return through [`rate_limit_window_unit`]
23080        // (the `AplicacaoSpec::validate` gate owns the canonical-set
23081        // membership; the accessor must ship the raw slot verbatim).
23082        for window in [
23083            Duration::from_secs(1),
23084            Duration::from_secs(60),
23085            Duration::from_secs(3600),
23086            Duration::ZERO,
23087            Duration::from_millis(500),
23088        ] {
23089            let rl = RateLimit { rate: 100, window };
23090            assert_eq!(
23091                rl.window(),
23092                window,
23093                "RateLimit::window must return :politicas :rate-limit :window \
23094                 verbatim (got {:?}, expected {window:?})",
23095                rl.window(),
23096            );
23097            assert_eq!(
23098                rl.window(),
23099                rl.window,
23100                "RateLimit::window must byte-equal the raw .window field \
23101                 access across every value in the Duration accept-set",
23102            );
23103        }
23104    }
23105
23106    #[test]
23107    fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
23108        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
23109        // `:rate-limit :window` canonical-set arm must key off
23110        // [`RateLimit::window`], not the raw `.window` field access.
23111        // Structurally: a `RateLimit { window: Duration::from_millis(500),
23112        // .. }` embedded in a `:politicas :rate-limit` slot must
23113        // surface the `PolicyRateLimitWindowNotCanonical` refusal
23114        // exactly (with the sub-canonical `Duration::from_millis(500)`
23115        // magnitude carried through verbatim), and a `RateLimit
23116        // { window: Duration::from_secs(1), .. }` (the lower row of
23117        // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
23118        // The pair jointly pins the accessor + validate-gate
23119        // composition: any future silent detour that had the accessor
23120        // normalize the off-set window to the nearest canonical row
23121        // (a `.window().max(Duration::from_secs(1))` collapse, or a
23122        // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
23123        // collapse) would silently absorb the
23124        // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
23125        // boundary — including a drift in the error's `window` payload
23126        // (the emit-side diagnostic reader keys off the offending
23127        // magnitude verbatim, so a normalization at the accessor
23128        // boundary would silently pin the wrong magnitude in the
23129        // refusal). The composition pin catches that at caixa-core
23130        // build time.
23131        //
23132        // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
23133        // (7f81a60) accessor-composition pin on the peer required-
23134        // scalar `:rate` axis — same "the validate / shape-gate
23135        // predicate must route through the substrate-primitive typed
23136        // dispatch, and the error payload must project through the
23137        // same accessor" discipline extended onto the peer
23138        // per-`RateLimit` required-`Duration` composition axis.
23139        let mut spec = three_member_spec();
23140        spec.politicas = MeshPolicy {
23141            rate_limit: Some(RateLimit {
23142                rate: 100,
23143                window: Duration::from_millis(500),
23144            }),
23145            ..MeshPolicy::default()
23146        };
23147        match spec.validate() {
23148            Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
23149                assert_eq!(
23150                    window,
23151                    Duration::from_millis(500),
23152                    "PolicyRateLimitWindowNotCanonical must carry the \
23153                     offending :window magnitude verbatim through the \
23154                     accessor — got {window:?}, expected 500ms",
23155                );
23156            }
23157            other => panic!(
23158                "validate_politicas must reject non-canonical :window \
23159                 with PolicyRateLimitWindowNotCanonical — the accessor \
23160                 and the validate gate must route through the same \
23161                 substrate-primitive typed dispatch on the :window \
23162                 canonical-set arm; got {other:?}",
23163            ),
23164        }
23165        spec.politicas = MeshPolicy {
23166            rate_limit: Some(RateLimit {
23167                rate: 100,
23168                window: Duration::from_secs(1),
23169            }),
23170            ..MeshPolicy::default()
23171        };
23172        assert!(
23173            spec.validate().is_ok(),
23174            "validate_politicas must accept window == Duration::from_secs(1) \
23175             (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
23176        );
23177    }
23178
23179    #[test]
23180    fn rate_limit_window_projects_duration_by_copy() {
23181        // The by-copy pin: [`RateLimit::window`] returns `Duration`
23182        // by copy — `Duration` is `Copy` and the accessor must return
23183        // by value, not by reference. Peer of the sibling per-`RateLimit`
23184        // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
23185        // required-scalar `:rate` axis, extended onto the peer
23186        // per-`RateLimit` required-`Duration` copy-invariant shape —
23187        // the accessor's returned `Duration` must outlive `&self`
23188        // (multiple calls must return equal values from a
23189        // dropped-`&self` copy, since the returned scalar carries no
23190        // borrow), and calling the accessor twice on the same
23191        // RateLimit must yield the same `Duration` verbatim
23192        // (idempotent, no side effects on `&self`).
23193        //
23194        // Pins against a future silent detour that returned
23195        // `&Duration` (which would type-check but silently break every
23196        // downstream `Duration`-by-value consumer —
23197        // [`is_canonical_rate_limit_window`]'s first parameter is
23198        // `Duration`, and `&Duration` would fold to a detached copy at
23199        // the call site with a `*` deref the sibling accessors don't
23200        // need), an accidental `.window + Duration::ZERO` detour that
23201        // returned a fresh copy through an arithmetic no-op (breaking
23202        // a future `const fn` regression), or a one-arm-only accessor
23203        // that returned a canonical fallback on some sentinel input
23204        // (breaking the pass-through invariant the sibling required-
23205        // scalar accessors carry).
23206        for window in [
23207            Duration::from_secs(1),
23208            Duration::from_secs(60),
23209            Duration::from_secs(3600),
23210            Duration::ZERO,
23211            Duration::from_millis(500),
23212        ] {
23213            let rl = RateLimit { rate: 100, window };
23214            let first = rl.window();
23215            let second = rl.window();
23216            assert_eq!(
23217                first, second,
23218                "RateLimit::window must be idempotent — two successive \
23219                 calls on the same &self must return the same Duration",
23220            );
23221            assert_eq!(
23222                first, window,
23223                "RateLimit::window must return :politicas :rate-limit :window \
23224                 verbatim by copy — got {first:?}, expected {window:?}",
23225            );
23226        }
23227    }
23228}