Skip to main content

caixa_core/
aplicacao.rs

1//! Typed Aplicacao — the fourth caixa kind that turns a graph of
2//! Servicos into a single declarative application (mesh).
3//!
4//! See `theory/MESH-COMPOSITION.md` for the design frame: an
5//! Aplicacao composes [`crate::CaixaKind::Servico`] caixas via WIT-typed
6//! `:contratos` (inter-Servico edges), declares mesh-level
7//! `:politicas` (timeouts, retries, breakers, mTLS), pins
8//! `:placement` strategy (single-node / replicated / sharded), and
9//! exposes `:entrada` (gateway).
10//!
11//! ```lisp
12//! (defcaixa
13//!   :nome      "checkout"
14//!   :versao    "0.1.0"
15//!   :kind      Aplicacao
16//!   :membros   ((:caixa "catalog"     :versao "^0.1")
17//!               (:caixa "cart"        :versao "^0.1")
18//!               (:caixa "payment"     :versao "^0.2"))
19//!   :contratos ((:de "cart" :para "catalog"
20//!                :wit "wasi:http/proxy" :endpoint "/products/:id")
21//!               (:de "cart" :para "payment"
22//!                :wit "wasi:http/proxy" :endpoint "/charge"))
23//!   :politicas ((:timeout "30s")
24//!               (:retries 3)
25//!               (:circuit-breaker (:max-failures 5 :window "60s"))
26//!               (:mtls-required t))
27//!   :placement (:estrategia replicated
28//!               :clusters   ("rio" "mar" "plo"))
29//!   :entrada   (:host  "checkout.quero.cloud"
30//!               :para  "cart"
31//!               :paths ("/api/cart" "/api/products")))
32//! ```
33//!
34//! All the typed slots compose with the M2 primitives the Servicos
35//! they reference already declare (`:limits`, `:behavior`,
36//! `:upgrade-from`). The Aplicacao adds the *graph-level*
37//! standardization on top.
38
39use std::time::Duration;
40
41use serde::{Deserialize, Serialize};
42use thiserror::Error;
43
44use crate::supervisor; // we reuse the duration-string codec at module scope
45
46// ── inter-Servico contracts ──────────────────────────────────────────
47
48/// One typed edge in the Aplicacao graph. The build refuses any
49/// contract whose `:de` or `:para` doesn't appear in `:membros`, and
50/// (M3+) cross-checks the `:wit` shape against both Servicos'
51/// declared imports/exports.
52#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
53#[serde(rename_all = "camelCase")]
54pub struct WitContract {
55    /// Caller Servico — must reference an entry in the Aplicacao's
56    /// `:membros`. The Servico's caixa.lisp must declare a matching
57    /// `:capabilities` import for the `:wit` world.
58    pub de: String,
59
60    /// Callee Servico — must reference an entry in `:membros`. The
61    /// Servico must declare a matching `:capabilities` export.
62    pub para: String,
63
64    /// WIT world reference — e.g. `"wasi:http/proxy"`,
65    /// `"wasi:keyvalue/store"`, `"nats:pub-sub"`. Strings for V0;
66    /// M4 promotes these to a typed enum once the WIT registry
67    /// stabilizes in tatara-lisp.
68    pub wit: String,
69
70    /// HTTP endpoint path, present when `:wit` is HTTP-shaped.
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub endpoint: Option<String>,
73
74    /// NATS / event-stream subject, present when `:wit` is pub-sub-shaped.
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub subject: Option<String>,
77
78    /// Key/value or queue slot, present when `:wit` is store-shaped.
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub slot: Option<String>,
81}
82
83/// Canonical lowercase byte-prefix set the substrate's WIT-shape
84/// dispatch routes `wasi:http/*` / `http:*` values through as the
85/// HTTP-shaped arm. The single source of truth every consumer that
86/// classifies a `:wit` value as HTTP-shaped consults —
87/// [`WitContract::is_http`] on the typed contract, the
88/// `AplicacaoSpec::validate` positive-sweep test's payload-dispatch
89/// helper, and every future renderer that routes an L7 emission off a
90/// bare `&str` (the M4 per-edge WIT registry resolver, the future
91/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer). Spelled
92/// exactly as the [`is_wit_world_ref`][iwr] predicate documents the
93/// canonical lowercase prefixes ("`wasi:http/`, `nats:`,
94/// `wasi:keyvalue/`, `kafka:`, `kv:`, `http:`") so drift between the
95/// substrate's accept-set and this crate's dispatch-set is a
96/// build-time compile error (unused-import), not a per-renderer
97/// silent L7-→-L4 demotion at apply time.
98///
99/// [iwr]: crate::render::is_wit_world_ref
100pub const WIT_HTTP_SHAPE_PREFIXES: &[&str] = &["wasi:http/", "http:"];
101
102/// Canonical lowercase byte-prefix set the substrate's WIT-shape
103/// dispatch routes `nats:*` / `kafka:*` values through as the
104/// pub-sub-shaped arm. Peer of [`WIT_HTTP_SHAPE_PREFIXES`] /
105/// [`WIT_STORE_SHAPE_PREFIXES`] on the shape-dispatch axis; see the
106/// HTTP constant's docstring for the full lift rationale.
107pub const WIT_PUBSUB_SHAPE_PREFIXES: &[&str] = &["nats:", "kafka:"];
108
109/// Canonical lowercase byte-prefix set the substrate's WIT-shape
110/// dispatch routes `wasi:keyvalue/*` / `kv:*` values through as the
111/// key/value-store-shaped arm. Peer of [`WIT_HTTP_SHAPE_PREFIXES`] /
112/// [`WIT_PUBSUB_SHAPE_PREFIXES`] on the shape-dispatch axis; see the
113/// HTTP constant's docstring for the full lift rationale.
114pub const WIT_STORE_SHAPE_PREFIXES: &[&str] = &["wasi:keyvalue/", "kv:"];
115
116/// True when `wit` — a raw `:contratos :wit` value — starts with any
117/// entry in the `prefixes` accept-set. The single canonical
118/// prefix-driven WIT-shape classification combinator every peer
119/// per-shape predicate ([`wit_shape_is_http`], [`wit_shape_is_pubsub`],
120/// [`wit_shape_is_store`]) routes through, closing the 3-site
121/// duplication of the `PREFIXES.iter().any(|p| wit.starts_with(p))`
122/// combinator the prior open-coded implementations each carried.
123///
124/// A future 4th WIT-shape dispatch arm (a hypothetical `wasi:sockets/*`
125/// / `tcp:*` transport-layer shape, an `oci:*` capability-import
126/// carrier) becomes exactly one new [`WIT_*_SHAPE_PREFIXES`] const +
127/// one new `wit_shape_is_<name>` one-liner routing through this
128/// combinator, not a fourth copy of the `iter().any(starts_with)`
129/// combinator paired to its own prefix-set. Same "one canonical
130/// combinator, thin per-arm projections" discipline the peer
131/// [`WitTarget::payload_pair`] (6788ed6) already established for the
132/// downstream per-arm `(field, payload)` dispatch, extended to the
133/// upstream per-arm `PREFIXES → bool` dispatch.
134#[must_use]
135pub fn wit_shape_matches(wit: &str, prefixes: &[&str]) -> bool {
136    prefixes.iter().any(|p| wit.starts_with(p))
137}
138
139/// True when `wit` — a raw `:contratos :wit` value — targets an
140/// HTTP-shaped WIT world (starts with any prefix in
141/// [`WIT_HTTP_SHAPE_PREFIXES`]). The single dispatch predicate every
142/// consumer routes L7-HTTP emission through, whether they carry a
143/// full [`WitContract`] on hand ([`WitContract::is_http`] delegates
144/// here) or only the raw `wit` string (the positive-sweep test's
145/// payload-dispatch helper, future renderers that classify off a
146/// bare `&str`). Lifting to a free function makes the shape-dispatch
147/// arm reachable without materializing a scratch [`WitContract`] at
148/// every classification point, and pins the six-prefix accept-set at
149/// one place so future additions (e.g. an `"https:"` peer of
150/// `"http:"`) reach every consumer by construction. Routes through
151/// the lifted [`wit_shape_matches`] combinator so the
152/// `PREFIXES.iter().any(|p| wit.starts_with(p))` scan lives at one
153/// canonical primitive, not one open-coded copy per peer arm.
154#[must_use]
155pub fn wit_shape_is_http(wit: &str) -> bool {
156    wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES)
157}
158
159/// True when `wit` — a raw `:contratos :wit` value — targets a
160/// pub-sub-shaped WIT world (starts with any prefix in
161/// [`WIT_PUBSUB_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
162/// [`wit_shape_is_store`] on the shape-dispatch axis; see
163/// [`wit_shape_is_http`] for the lift rationale. Routes through the
164/// lifted [`wit_shape_matches`] combinator.
165#[must_use]
166pub fn wit_shape_is_pubsub(wit: &str) -> bool {
167    wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES)
168}
169
170/// True when `wit` — a raw `:contratos :wit` value — targets a
171/// key/value-store-shaped WIT world (starts with any prefix in
172/// [`WIT_STORE_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
173/// [`wit_shape_is_pubsub`] on the shape-dispatch axis; see
174/// [`wit_shape_is_http`] for the lift rationale. Routes through the
175/// lifted [`wit_shape_matches`] combinator.
176#[must_use]
177pub fn wit_shape_is_store(wit: &str) -> bool {
178    wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES)
179}
180
181impl WitContract {
182    /// Substrate-canonical per-`:contratos` caller-Servico scalar
183    /// accessor every consumer that reads the edge's source endpoint
184    /// keys off — returns the author-declared `:contratos :de`
185    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
186    /// own [`String`] storage.
187    ///
188    /// The `:contratos :de` slot names the caller-side member Servico
189    /// on a typed inter-Servico edge (validated by
190    /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
191    /// Aplicacao declares — a stray `:de` that doesn't name a member is
192    /// [`AplicacaoError::ContratoMemberMissing`], not a silent
193    /// caller-attachment miss at cluster-apply time). Peer of the
194    /// sibling [`WitContract::destination`] accessor on the same
195    /// per-`:contratos` entry — the pair `( source(), destination() )`
196    /// jointly names the typed edge every renderer that fans on the
197    /// caller-callee identity keys off (the
198    /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)`
199    /// grouping, the [`AplicacaoSpec::detect_sync_cycles`] adjacency
200    /// map, the per-edge dedup key, the per-edge membership-lookup
201    /// diagnostic).
202    ///
203    /// Prior to this lift the `.de` byte-string was accessed inline at
204    /// four caixa-core sites (the two validate-side membership lookups
205    /// at `!names.contains(c.de.as_str())`, the per-edge dedup-key
206    /// tuple's caller-arm at
207    /// `(c.de.as_str(), c.para.as_str(), c.wit.as_str(), ...)`, the
208    /// `detect_sync_cycles` adjacency `adj.entry(c.de.as_str())`) and
209    /// one caixa-mesh site (the per-`(:de, :para)` CNP grouping's
210    /// caller-arm at `groups.entry((c.de.as_str(), c.para.as_str()))`)
211    /// — five open-coded `.de.as_str()` field-accesses that expressed
212    /// no compile-time link back to the typed slot. A future extension
213    /// of the `:contratos :de` axis to a richer author surface (a
214    /// multi-caller weighted-fan-in overlay per MESH-COMPOSITION §III.2
215    /// canary flow, a per-cluster caller-alias table the operator pins
216    /// through a future `:placement`-scoped slot, the M4
217    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
218    /// admission-webhook that promotes the scalar to a caller-set
219    /// projection) would have had to be threaded through every
220    /// open-coded copy in lockstep or one consumer would silently
221    /// disagree with the peers on which caller Servico a given edge
222    /// resolves to. Lifting the resolution rule to a typed method on
223    /// the substrate primitive means every downstream caller-facing
224    /// consumer reaches for one typed dispatch — the resolver's
225    /// accept-set migrates as a unit on any future axis addition.
226    ///
227    /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
228    /// (6db982c) accessor on the analogous per-ingress-Servico scalar
229    /// axis — same "one typed dispatch on the substrate primitive,
230    /// thin projections at each consumer" discipline extended onto the
231    /// per-`:contratos` caller-Servico byte-string axis.
232    #[must_use]
233    pub fn source(&self) -> &str {
234        self.de.as_str()
235    }
236
237    /// Substrate-canonical per-`:contratos` callee-Servico scalar
238    /// accessor every consumer that reads the edge's destination
239    /// endpoint keys off — returns the author-declared
240    /// `:contratos :para` byte-string verbatim as a `&str`, borrowed
241    /// from the typed slot's own [`String`] storage.
242    ///
243    /// The `:contratos :para` slot names the callee-side member Servico
244    /// on a typed inter-Servico edge (validated by
245    /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
246    /// Aplicacao declares — a stray `:para` that doesn't name a member
247    /// is [`AplicacaoError::ContratoMemberMissing`], not a silent
248    /// callee-attachment miss at cluster-apply time). Callee-side twin
249    /// of the sibling [`WitContract::source`] accessor — the pair
250    /// jointly names the typed edge every renderer that fans on the
251    /// caller-callee identity keys off, and this accessor is also the
252    /// per-`(:de, :para)` L4 port resolver's canonical destination arg:
253    /// under today's typed surface [`AplicacaoSpec::port_for_destination`]
254    /// composes with `destination()` at every emit site that projects a
255    /// per-edge destination Servico's L4 listener port.
256    ///
257    /// Prior to this lift the `.para` byte-string was accessed inline
258    /// at five sites — four caixa-core (the validate-side membership
259    /// lookup at `!names.contains(c.para.as_str())`, the per-edge
260    /// dedup-key tuple's callee-arm, the `detect_sync_cycles`
261    /// adjacency `.insert(c.para.as_str())`, the CNP grouping's
262    /// callee-arm) and one caixa-mesh (the per-`(:de, :para)` CNP L4
263    /// port resolver's destination arg `spec.port_for_destination(&c.para)`)
264    /// — with no compile-time link back to the typed slot. A future
265    /// extension of the `:contratos :para` axis to a richer author
266    /// surface (a multi-callee weighted-fan-out overlay for canary /
267    /// blue-green routing on typed edges, a per-cluster callee-alias
268    /// table the operator pins through a future `:placement`-scoped
269    /// slot, the M4 CR materializer's per-CR admission-webhook that
270    /// promotes the scalar to a callee-set projection) would have had
271    /// to be threaded through every open-coded copy in lockstep or one
272    /// consumer would silently disagree on which callee Servico a given
273    /// edge resolves to (a per-CNP `endpointSelector` that names a
274    /// different destination than its L4 port resolver reads for, a
275    /// dedup-key that treats `(cart, catalog-v2)` and `(cart, catalog)`
276    /// as distinct while the adjacency map collapses them, or vice
277    /// versa). Lifting to a typed method on the substrate primitive
278    /// means every downstream callee-facing consumer reaches for one
279    /// typed dispatch.
280    ///
281    /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
282    /// (6db982c) accessor — both name the "destination-Servico
283    /// byte-string" concept on their respective mesh-slot atoms (per-
284    /// ingress apex vs. per-typed-edge callee), and both extend the
285    /// substrate-primitive-owns-the-resolver discipline onto the
286    /// per-slot destination-Servico scalar axis. Composes with
287    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) at every
288    /// emit-side per-edge L4 port reader — the composition
289    /// `spec.port_for_destination(c.destination())` pins the CNP per-
290    /// `(:de, :para)` L4 port axis to the same typed dispatch the peer
291    /// `HTTPRoute` `backendRefs[0].port` axis reaches through with
292    /// `spec.port_for_destination(entrada.destination())`.
293    #[must_use]
294    pub fn destination(&self) -> &str {
295        self.para.as_str()
296    }
297
298    /// Substrate-canonical per-`:contratos` WIT-world-reference scalar
299    /// accessor every consumer that reads the edge's WIT world
300    /// discriminator keys off — returns the author-declared
301    /// `:contratos :wit` byte-string verbatim as a `&str`, borrowed from
302    /// the typed slot's own [`String`] storage.
303    ///
304    /// The `:contratos :wit` slot names the WIT world the typed edge
305    /// carries (e.g. `"wasi:http/proxy"`, `"nats:pub-sub"`,
306    /// `"wasi:keyvalue/store"`); validated by [`WitContract::target`] to
307    /// be a well-shaped WIT world reference via
308    /// [`crate::render::is_wit_world_ref`] and by
309    /// [`AplicacaoSpec::validate`] to be non-empty via the narrower
310    /// [`AplicacaoError::EmptyWit`] variant. Peer of the sibling
311    /// [`WitContract::source`] / [`WitContract::destination`] accessors
312    /// on the same per-`:contratos` entry — the triple
313    /// `( source(), destination(), world_ref() )` jointly names the
314    /// typed edge every renderer that fans on the caller-callee-shape
315    /// identity keys off (the per-edge dedup key at
316    /// [`AplicacaoSpec::validate`]'s duplicate-`:contratos` gate, the
317    /// per-`(:de, :para)` CNP grouping's shape-arm classifier at
318    /// [`caixa_mesh::cilium_network_policies`], the
319    /// [`WitContract::is_http`] / [`is_pubsub`][WitContract::is_pubsub]
320    /// / [`is_store`][WitContract::is_store] shape-dispatch predicates,
321    /// the [`feira app graph`][fag] per-edge printer's WIT-shape label).
322    ///
323    /// Prior to this lift the `.wit` byte-string was accessed inline at
324    /// five sites — three caixa-core (the `WitContract::is_*` shape-
325    /// dispatch predicates' `&self.wit` arg, the validate-side empty
326    /// check at `if c.wit.is_empty()`, the per-edge dedup-key tuple's
327    /// shape arm at `c.wit.as_str()`) and one caixa-feira (the app-graph
328    /// printer's `{}` format-slot at `c.wit`) — five open-coded
329    /// `.wit` field-accesses that expressed no compile-time link back to
330    /// the typed slot. A future extension of the `:contratos :wit` axis
331    /// to a richer author surface (an M4 promotion from `String` to a
332    /// typed WIT-world enum once the WIT registry stabilizes in tatara-
333    /// lisp per this struct's own `:wit` field docstring, a per-cluster
334    /// WIT-alias table the operator pins through a future
335    /// `:placement`-scoped slot, a canonicalization pass that lowercases
336    /// `wasi:*` prefixes) would have had to be threaded through every
337    /// open-coded copy in lockstep or one consumer would silently
338    /// disagree with the peers on which WIT shape a given edge resolves
339    /// to (a per-CNP L7 emission that read `wasi:http/proxy` while the
340    /// dedup key read the pre-canonicalized `WASI:HTTP/proxy`, an
341    /// empty-check that missed a whitespace-only string a peer accessor
342    /// stripped, or vice versa). Lifting to a typed method on the
343    /// substrate primitive means every downstream WIT-shape-facing
344    /// consumer reaches for one typed dispatch — the resolver's
345    /// accept-set migrates as a unit on any future axis addition.
346    ///
347    /// Sibling of the peer per-`:contratos` [`WitContract::source`] /
348    /// [`WitContract::destination`] (7f0fd43), per-`:entrada`
349    /// [`Entrada::hostname`] / [`Entrada::destination`] (11f3dfe /
350    /// 6db982c), per-`:membros` [`Membro::nome`] /
351    /// [`Membro::versao_requirement`] (4a32abf / a40b0e3) accessors on
352    /// the mesh-slot-atom scalar-value axes — same "one typed dispatch
353    /// on the substrate primitive, thin projections at each consumer"
354    /// discipline extended onto the last unlifted per-`:contratos`
355    /// scalar (the WIT-world-reference arm).
356    ///
357    /// [fag]: caixa-feira/src/cmd/app.rs
358    #[must_use]
359    pub fn world_ref(&self) -> &str {
360        self.wit.as_str()
361    }
362
363    /// Substrate-canonical per-`:contratos` `:endpoint` HTTP-shaped
364    /// payload-target scalar accessor every consumer that reads the
365    /// edge's L7 HTTP request path payload keys off — returns the
366    /// author-declared `:contratos :endpoint` byte-string verbatim as
367    /// an `Option<&str>`, borrowed from the typed slot's own
368    /// `Option<String>` storage; `None` when the slot is absent (the
369    /// canonical shape of a non-HTTP-`:wit`-world edge — pub-sub
370    /// `nats:*`/`kafka:*` carries `:subject` instead, key/value
371    /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
372    /// [`WitTarget::Capability`] edge carries none of the three).
373    ///
374    /// The `:contratos :endpoint` slot carries the HTTP request path
375    /// payload (Cilium L7 `path:` + Gateway API v1 `PathPrefix` grammar
376    /// — same shape required of `:entrada :paths`, gated by the shared
377    /// [`crate::render::is_gateway_api_http_path`] predicate) that
378    /// [`WitContract::target`] projects onto the [`WitTarget::Http`]
379    /// arm's `endpoint: &'a str` payload when the edge's `:wit` world
380    /// matches the [`WIT_HTTP_SHAPE_PREFIXES`] accept-set. Every
381    /// downstream consumer that reads the payload keys off this scalar
382    /// (the [`WitContract::target`] Http-arm payload extraction that
383    /// materializes [`WitTarget::Http { endpoint }`] under the paired
384    /// [`WitTarget::HTTP_FIELD_NAME`] label, the
385    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
386    /// key's endpoint arm that pins the payload as part of the six-tuple
387    /// dedup key alongside the sibling `:subject`/`:slot` arms, the
388    /// future M4 per-edge WIT registry resolver's HTTP-arm materializer,
389    /// the future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
390    /// per-edge L7 admission webhook, the future caixa-mesh L7 CNP
391    /// emission path that lands the payload verbatim as a Cilium L7
392    /// `path:` rule).
393    ///
394    /// Prior to this lift the `.endpoint` field was accessed inline at
395    /// two production sites in `caixa-core/src/aplicacao.rs` — the
396    /// [`WitContract::target`] payload-shape dispatch's `let endpoint =
397    /// self.endpoint.as_deref();` binding at the top of the method, and
398    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
399    /// tuple's `c.endpoint.as_deref()` HTTP-arm slot — two open-coded
400    /// field-accesses that expressed no compile-time link back to the
401    /// typed slot. A future extension of the `:contratos :endpoint`
402    /// axis to a richer author surface (an M4 promotion from
403    /// `Option<String>` to a typed HTTP path-template enum once the
404    /// WIT registry stabilizes path-parameter shapes in tatara-lisp per
405    /// this struct's own `:wit` field docstring, a per-cluster endpoint-
406    /// alias table the operator pins through a future `:placement`-
407    /// scoped slot, a canonicalization pass that percent-encodes non-
408    /// ASCII path segments, a per-CR fully-qualified rewrite the M4 CR
409    /// materializer applies per-tenant) would have had to be threaded
410    /// through both open-coded copies in lockstep or the two consumers
411    /// would silently disagree on which HTTP path a given edge resolves
412    /// to — the [`WitContract::target`] payload-extraction reading
413    /// `"/lookup"` while the [`AplicacaoSpec::validate`] dedup key read
414    /// the operator-resolved `"/tenant-a/lookup"` would silently split
415    /// the [`WitTarget::Http`]-arm rendered payload from the actual
416    /// dedup-key uniqueness axis, a two-consumer split at the validator
417    /// far from the source `caixa.lisp` with no field naming the
418    /// payload-drift root cause. Lifting the resolution rule to a typed
419    /// method on the substrate primitive means every downstream
420    /// HTTP-payload-facing consumer of the Aplicacao's per-`:contratos`
421    /// L7-payload surface reaches for exactly one typed dispatch — the
422    /// resolver's accept-set migrates as a unit on any future axis
423    /// addition.
424    ///
425    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
426    /// (7cd2a28) / [`Placement::affinity`] (74ec2d3) `Option<&str>`
427    /// accessors on the M3 mesh-slot family — same "one typed dispatch
428    /// on the substrate primitive, thin projections at each consumer"
429    /// discipline extended onto the per-`:contratos` HTTP-shaped
430    /// payload-carrier `Option<String>` optional-scalar axis. First
431    /// `Option<&str>`-return accessor on the per-`:contratos` mesh-slot
432    /// atom — opens the "optional per-slot payload-carrier scalar"
433    /// projection pattern the sibling per-`:contratos` `:subject` /
434    /// `:slot` future lifts fold on, matching the closed
435    /// per-`:contratos` scalar-value accessor family
436    /// ([`WitContract::source`] / [`WitContract::destination`] /
437    /// [`WitContract::world_ref`]) already lifted onto the mandatory-
438    /// scalar `String` axes. Named `endpoint()` to match the storage
439    /// field's name and the paired [`WitTarget::HTTP_FIELD_NAME`]
440    /// author-facing label const; the accessor's identity name maps
441    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
442    /// docstring already carries.
443    #[must_use]
444    pub fn endpoint(&self) -> Option<&str> {
445        self.endpoint.as_deref()
446    }
447
448    /// Substrate-canonical per-`:contratos` `:subject` pub-sub-shaped
449    /// payload-target scalar accessor every consumer that reads the
450    /// edge's NATS / Kafka publish subject payload keys off — returns
451    /// the author-declared `:contratos :subject` byte-string verbatim
452    /// as an `Option<&str>`, borrowed from the typed slot's own
453    /// `Option<String>` storage; `None` when the slot is absent (the
454    /// canonical shape of a non-pub-sub-`:wit`-world edge — HTTP
455    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, key/value
456    /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
457    /// [`WitTarget::Capability`] edge carries none of the three).
458    ///
459    /// The `:contratos :subject` slot carries the NATS / Kafka publish
460    /// subject payload (the [`WIT_PUBSUB_SHAPE_PREFIXES`] dispatch arm's
461    /// per-edge target selector — `orders.paid`, `events.>`, whatever
462    /// subject namespace the author names on the pub-sub edge) that
463    /// [`WitContract::target`] projects onto the [`WitTarget::PubSub`]
464    /// arm's `subject: &'a str` payload when the edge's `:wit` world
465    /// matches the [`WIT_PUBSUB_SHAPE_PREFIXES`] accept-set. Every
466    /// downstream consumer that reads the payload keys off this scalar
467    /// (the [`WitContract::target`] PubSub-arm payload extraction that
468    /// materializes [`WitTarget::PubSub { subject }`] under the paired
469    /// [`WitTarget::PUBSUB_FIELD_NAME`] label, the
470    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
471    /// key's subject arm that pins the payload as part of the six-tuple
472    /// dedup key alongside the sibling `:endpoint`/`:slot` arms, the
473    /// future M4 per-edge WIT registry resolver's pub-sub-arm
474    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
475    /// materializer's per-edge NATS admission webhook, the future
476    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
477    /// as a NATS subject the operator pins per-CR).
478    ///
479    /// Prior to this lift the `.subject` field was accessed inline at
480    /// two production sites in `caixa-core/src/aplicacao.rs` — the
481    /// [`WitContract::target`] payload-shape dispatch's `let subject =
482    /// self.subject.as_deref();` binding at the top of the method, and
483    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
484    /// tuple's `c.subject.as_deref()` pub-sub-arm slot — two open-coded
485    /// field-accesses that expressed no compile-time link back to the
486    /// typed slot. A future extension of the `:contratos :subject` axis
487    /// to a richer author surface (an M4 promotion from `Option<String>`
488    /// to a typed NATS-subject-template enum once the WIT registry
489    /// stabilizes wildcard / hierarchy shapes in tatara-lisp per this
490    /// struct's own `:wit` field docstring, a per-cluster subject-alias
491    /// table the operator pins through a future `:placement`-scoped
492    /// slot, a canonicalization pass that lowercases / dedupes wildcard
493    /// segments, a per-CR fully-qualified rewrite the M4 CR materializer
494    /// applies per-tenant) would have had to be threaded through both
495    /// open-coded copies in lockstep or the two consumers would silently
496    /// disagree on which NATS subject a given edge resolves to — the
497    /// [`WitContract::target`] payload-extraction reading `"orders.paid"`
498    /// while the [`AplicacaoSpec::validate`] dedup key read the operator-
499    /// resolved `"tenant-a.orders.paid"` would silently split the
500    /// [`WitTarget::PubSub`]-arm rendered payload from the actual dedup-
501    /// key uniqueness axis, a two-consumer split at the validator far
502    /// from the source `caixa.lisp` with no field naming the payload-
503    /// drift root cause. Lifting the resolution rule to a typed method
504    /// on the substrate primitive means every downstream pub-sub-payload-
505    /// facing consumer of the Aplicacao's per-`:contratos` L4-payload
506    /// surface reaches for exactly one typed dispatch — the resolver's
507    /// accept-set migrates as a unit on any future axis addition.
508    ///
509    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
510    /// (7020470) `Option<&str>` accessor on the M3 mesh-slot payload-
511    /// carrier axis — second `Option<&str>`-return accessor on the
512    /// per-`:contratos` mesh-slot atom, extending the "optional per-slot
513    /// payload-carrier scalar" projection pattern the [`WitContract::endpoint`]
514    /// HTTP-arm lift opened onto the pub-sub arm; leaves the [`WitContract::slot`]
515    /// key/value-store arm as the last unlifted per-`:contratos`
516    /// `Option<String>` axis. Named `subject()` to match the storage
517    /// field's name and the paired [`WitTarget::PUBSUB_FIELD_NAME`]
518    /// author-facing label const; the accessor's identity name maps
519    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
520    /// docstring already carries.
521    #[must_use]
522    pub fn subject(&self) -> Option<&str> {
523        self.subject.as_deref()
524    }
525
526    /// Substrate-canonical per-`:contratos` `:slot` key/value-store-
527    /// shaped payload-target scalar accessor every consumer that reads
528    /// the edge's `wasi:keyvalue/*` / `kv:*` key-template payload keys
529    /// off — returns the author-declared `:contratos :slot` byte-string
530    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
531    /// own `Option<String>` storage; `None` when the slot is absent
532    /// (the canonical shape of a non-store-`:wit`-world edge — HTTP
533    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, pub-sub
534    /// `nats:*`/`kafka:*` carries `:subject` instead, and a plain
535    /// [`WitTarget::Capability`] edge carries none of the three).
536    ///
537    /// The `:contratos :slot` slot carries the key/value store
538    /// key-template payload (the [`WIT_STORE_SHAPE_PREFIXES`] dispatch
539    /// arm's per-edge target selector — `carts/{cart_id}`,
540    /// `sessions/{tenant}/{sid}`, whatever key-template the author
541    /// names on the store edge) that [`WitContract::target`] projects
542    /// onto the [`WitTarget::Store`] arm's `slot: &'a str` payload when
543    /// the edge's `:wit` world matches the [`WIT_STORE_SHAPE_PREFIXES`]
544    /// accept-set. Every downstream consumer that reads the payload
545    /// keys off this scalar (the [`WitContract::target`] Store-arm
546    /// payload extraction that materializes [`WitTarget::Store { slot }`]
547    /// under the paired [`WitTarget::STORE_FIELD_NAME`] label, the
548    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
549    /// key's store arm that pins the payload as part of the six-tuple
550    /// dedup key alongside the sibling `:endpoint`/`:subject` arms,
551    /// the future M4 per-edge WIT registry resolver's store-arm
552    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
553    /// materializer's per-edge key/value admission webhook, the future
554    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
555    /// as a key-template the operator pins per-CR).
556    ///
557    /// Prior to this lift the `.slot` field was accessed inline at two
558    /// production sites in `caixa-core/src/aplicacao.rs` — the
559    /// [`WitContract::target`] payload-shape dispatch's `let slot =
560    /// self.slot.as_deref();` binding at the top of the method, and
561    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
562    /// tuple's `c.slot.as_deref()` store-arm slot — two open-coded
563    /// field-accesses that expressed no compile-time link back to the
564    /// typed slot. A future extension of the `:contratos :slot` axis
565    /// to a richer author surface (an M4 promotion from `Option<String>`
566    /// to a typed key-template enum once the WIT registry stabilizes
567    /// key-template parameter shapes in tatara-lisp per this struct's
568    /// own `:wit` field docstring, a per-cluster slot-alias table the
569    /// operator pins through a future `:placement`-scoped slot, a
570    /// canonicalization pass that lowercases the bucket prefix, a
571    /// per-CR fully-qualified rewrite the M4 CR materializer applies
572    /// per-tenant) would have had to be threaded through both
573    /// open-coded copies in lockstep or the two consumers would
574    /// silently disagree on which key-template a given edge resolves
575    /// to — the [`WitContract::target`] payload-extraction reading
576    /// `"carts/{cart_id}"` while the [`AplicacaoSpec::validate`] dedup
577    /// key read the operator-resolved `"tenant-a/carts/{cart_id}"`
578    /// would silently split the [`WitTarget::Store`]-arm rendered
579    /// payload from the actual dedup-key uniqueness axis, a
580    /// two-consumer split at the validator far from the source
581    /// `caixa.lisp` with no field naming the payload-drift root cause.
582    /// Lifting the resolution rule to a typed method on the substrate
583    /// primitive means every downstream store-payload-facing consumer
584    /// of the Aplicacao's per-`:contratos` payload surface reaches for
585    /// exactly one typed dispatch — the resolver's accept-set migrates
586    /// as a unit on any future axis addition.
587    ///
588    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
589    /// (7020470) / [`WitContract::subject`] (90de675) `Option<&str>`
590    /// accessors on the M3 mesh-slot payload-carrier axis — third and
591    /// final `Option<&str>`-return accessor on the per-`:contratos`
592    /// mesh-slot atom, closes the last unlifted per-`:contratos`
593    /// `Option<String>` axis and completes the "optional per-slot
594    /// payload-carrier scalar" projection pattern the peer HTTP /
595    /// pub-sub arms established across the three payload-shape
596    /// dispatch arms. Named `slot()` to match the storage field's
597    /// name and the paired [`WitTarget::STORE_FIELD_NAME`]
598    /// author-facing label const; the accessor's identity name maps
599    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
600    /// docstring already carries.
601    #[must_use]
602    pub fn slot(&self) -> Option<&str> {
603        self.slot.as_deref()
604    }
605
606    /// Substrate-canonical per-`:contratos` `(caller, callee)` owned-form
607    /// caller-callee-pair accessor every consumer that constructs an
608    /// [`AplicacaoError`] variant carrying the per-edge `(de, para)`
609    /// caller-callee pair keys off — returns the author-declared
610    /// `:contratos :de` / `:contratos :para` byte-strings verbatim as an
611    /// owned `(String, String)` tuple, projected through the lifted
612    /// [`WitContract::source`] / [`WitContract::destination`] scalar
613    /// accessors so any future rebrand on the caller-arm / callee-arm
614    /// projection axis (an M4 per-cluster caller-alias table the
615    /// operator pins through a future `:placement`-scoped slot, a
616    /// namespace-qualified rewrite the M4 CR materializer applies per-CR,
617    /// a per-`:membros` alias overlay from the future `:membros
618    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
619    /// acknowledges) reaches every diagnostic-construction site by
620    /// construction.
621    ///
622    /// The `(de, para)` pair is the "typed-edge caller-callee identity in
623    /// owned form" primitive every per-`:contratos` diagnostic variant on
624    /// [`AplicacaoError`] carries alongside its payload-shape arm — the
625    /// nine variants [`AplicacaoError::EmptyWit`],
626    /// [`AplicacaoError::ContratoEndpointEmpty`],
627    /// [`AplicacaoError::ContratoEndpointNotAbsolute`],
628    /// [`AplicacaoError::ContratoEndpointInvalid`],
629    /// [`AplicacaoError::ContratoSubjectEmpty`],
630    /// [`AplicacaoError::ContratoSubjectInvalid`],
631    /// [`AplicacaoError::ContratoSlotEmpty`],
632    /// [`AplicacaoError::ContratoSlotInvalid`], and
633    /// [`AplicacaoError::ContratoDuplicate`] each carry a `de: String,
634    /// para: String` field pair the constructor site reads verbatim off
635    /// the [`WitContract`] the diagnostic points at, so a diagnostic
636    /// whose `de:` and `para:` labels silently drift off the source
637    /// caller/callee — a per-cluster caller-alias rewrite that landed on
638    /// one variant's inline `de: c.de.clone()` field access but not on
639    /// its sibling variant's, an accidental swap of the `de:` and `para:`
640    /// arms in a copy-paste of the constructor block — would emit a
641    /// build-time error whose "which caixa is at fault" question the
642    /// operator answers wrongly, far from the source `caixa.lisp`.
643    ///
644    /// Prior to this lift the `(self.de.clone(), self.para.clone())`
645    /// pair was inlined at seven [`WitContract::target`] error-
646    /// construction sites (the [`AplicacaoError::ContratoEndpointEmpty`]
647    /// / [`AplicacaoError::ContratoEndpointNotAbsolute`] /
648    /// [`AplicacaoError::ContratoEndpointInvalid`] HTTP-arm variants,
649    /// the [`AplicacaoError::ContratoSubjectEmpty`] /
650    /// [`AplicacaoError::ContratoSubjectInvalid`] pub-sub-arm variants,
651    /// the [`AplicacaoError::ContratoSlotEmpty`] /
652    /// [`AplicacaoError::ContratoSlotInvalid`] store-arm variants) and
653    /// two [`AplicacaoSpec::validate`] error-construction sites (the
654    /// [`AplicacaoError::EmptyWit`] empty-`:wit` gate, the
655    /// [`AplicacaoError::ContratoDuplicate`] duplicate-`:contratos`
656    /// insert-first-seen closure) — nine open-coded `.de.clone() +
657    /// .para.clone()` pairs that expressed no compile-time contract that
658    /// the caller-arm and callee-arm arms of the same diagnostic
659    /// construction reach for the same [`WitContract`] instance or that
660    /// the `de:` and `para:` label pair binds to the fields the author
661    /// declared. Any future rebrand on the axis — an M4 per-cluster
662    /// caller/callee-alias rewrite the operator pins through a future
663    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
664    /// per-CR fully-qualified namespace prefix the M4
665    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
666    /// per-tenant, a canonicalization pass that lowercases the caller +
667    /// callee identifiers post-parse — would have had to be threaded
668    /// through every open-coded copy in lockstep or one variant's
669    /// diagnostic would silently name a different caller/callee pair
670    /// than its peer, silently degrading the "which caixa is at fault"
671    /// self-locating signal every operator-facing typed diagnostic
672    /// exists to carry. Lifting the pair to a typed method on the
673    /// substrate primitive means every downstream diagnostic-construction
674    /// site reaches for exactly one typed dispatch — the resolver's
675    /// projection migrates as a unit on any future axis addition.
676    ///
677    /// Peer of the sibling per-`:contratos` scalar accessor family
678    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43)
679    /// / [`WitContract::world_ref`] (6226bf4) on the mesh-slot-atom
680    /// scalar-value axes — first composite-projection accessor on the
681    /// per-`:contratos` mesh-slot atom, folds the two open-coded owned-
682    /// form `.clone()` field-accesses that pair the sibling
683    /// caller/callee accessors' `&str`-return borrowed-form outputs onto
684    /// one typed dispatch. Named `edge_pair()` to reflect the identity
685    /// name of the projected tuple (the typed-edge caller-callee pair,
686    /// distinct from the sibling triple-projection
687    /// [`WitContract::edge_triple`] accessor that folds the local `edge`
688    /// closure in [`WitContract::target`] + the paired
689    /// [`AplicacaoError::ContratoDuplicate`] diagnostic constructor
690    /// site's `(de, para, wit)` triple onto one typed dispatch).
691    #[must_use]
692    pub fn edge_pair(&self) -> (String, String) {
693        (self.source().to_string(), self.destination().to_string())
694    }
695
696    /// Owned form of the `(:contratos :de, :contratos :para, :contratos
697    /// :wit)` triple every per-edge diagnostic constructor that names
698    /// all three axes threads verbatim into its `de:` / `para:` /
699    /// `wit:` fields — the [`WitTarget::target`] dispatch's wrong-target
700    /// / missing-target / invalid-wit / capability-with-payload arms
701    /// (eight sites all shape `let (de, para, wit) = edge();
702    /// AplicacaoError::Contrato* { de, para, wit, .. }` before this
703    /// accessor landed) and the sibling
704    /// [`AplicacaoError::ContratoDuplicate`] duplicate-gate diagnostic
705    /// constructor (which paired `edge_pair()` for the `(de, para)`
706    /// prefix with a raw `c.wit.clone()` for the `wit:` tail — a mixed
707    /// typed-dispatch + raw-field-access shape the sibling accessor
708    /// family already flagged as a drift risk). Nine total call sites
709    /// collapse onto this helper.
710    ///
711    /// Lifted with the same one-source-of-truth discipline
712    /// [`WitContract::edge_pair`] carries on the paired
713    /// caller-callee-only axis: the returned tuple's `.0` / `.1` / `.2`
714    /// arms compose through the lifted [`WitContract::source`] /
715    /// [`WitContract::destination`] / [`WitContract::world_ref`]
716    /// scalar accessors byte-for-byte (pinned by the paired
717    /// [`tests::wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`]
718    /// composition-pin), so any future rebrand on the per-`:contratos`
719    /// caller / callee / world-ref axis (an M4 per-cluster
720    /// caller/callee-alias rewrite the operator pins through a future
721    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
722    /// per-CR fully-qualified namespace prefix the M4
723    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
724    /// per-tenant, an M4-typed-caller-enum `Display` re-canonicalization
725    /// on `source()` / `destination()`, a per-CR canonicalization pass
726    /// that lowercases the WIT world ref post-parse) migrates as a
727    /// single caixa-core edit rather than a coordinated rewrite of
728    /// nine open-coded triple-constructors.
729    ///
730    /// Peer of the sibling per-`:contratos` composite-projection
731    /// [`WitContract::edge_pair`] accessor on the mesh-slot-atom
732    /// composite-value axes — closes the last unlifted owned-form
733    /// composite-tuple axis on the per-`:contratos` diagnostic-
734    /// construction surface. Named `edge_triple()` to reflect the
735    /// identity name of the projected tuple (the typed-edge
736    /// caller-callee-wit triple, sibling to the caller-callee-only
737    /// pair `edge_pair()` returns).
738    #[must_use]
739    pub fn edge_triple(&self) -> (String, String, String) {
740        (
741            self.source().to_string(),
742            self.destination().to_string(),
743            self.world_ref().to_string(),
744        )
745    }
746
747    /// Borrowed [`ContratoIdentity`] six-tuple every consumer that
748    /// dedups typed edges keys off — routes through the lifted
749    /// [`WitContract::source`] / [`WitContract::destination`] /
750    /// [`WitContract::world_ref`] / [`WitContract::endpoint`] /
751    /// [`WitContract::subject`] / [`WitContract::slot`] scalar
752    /// accessors so the tuple's six arms and the [`ContratoIdentity`]
753    /// type alias's six axes migrate as a unit on any future axis
754    /// addition (adding a seventh field to [`WitContract`] is one
755    /// [`ContratoIdentity`] alias edit + one accessor addition + one
756    /// arm here, not a coordinated rewrite of every open-coded
757    /// six-tuple builder that dedups on the identity axis).
758    ///
759    /// Sibling of [`WitContract::edge_pair`] /
760    /// [`WitContract::edge_triple`] on the composite-projection axis:
761    /// the pair projects the caller-callee axes, the triple extends it
762    /// with the world-ref, this method extends it with the three
763    /// payload-carrier axes. Every projection returns the same six
764    /// scalar accessors' outputs; the three methods differ only in
765    /// which arms they surface.
766    #[must_use]
767    pub fn identity(&self) -> ContratoIdentity<'_> {
768        (
769            self.source(),
770            self.destination(),
771            self.world_ref(),
772            self.endpoint(),
773            self.subject(),
774            self.slot(),
775        )
776    }
777
778    /// True when this contract targets an HTTP-shaped WIT world.
779    #[must_use]
780    pub fn is_http(&self) -> bool {
781        wit_shape_is_http(self.world_ref())
782    }
783
784    /// True when this contract targets a pub-sub-shaped WIT world.
785    #[must_use]
786    pub fn is_pubsub(&self) -> bool {
787        wit_shape_is_pubsub(self.world_ref())
788    }
789
790    /// True when this contract targets a key/value-shaped WIT world.
791    #[must_use]
792    pub fn is_store(&self) -> bool {
793        wit_shape_is_store(self.world_ref())
794    }
795
796    /// True when this contract's caller equals its callee — a
797    /// structurally degenerate typed edge that no `:contratos` entry can
798    /// legitimately carry (MESH-COMPOSITION §III.1 — "Servico A calls
799    /// Servico B" is an *inter*-Servico contract between two distinct
800    /// graph nodes). A Servico contracting with itself resolves to an
801    /// in-process call the wasm-engine never routes through the mesh at
802    /// all, so no rendered `CiliumNetworkPolicy` / `HTTPRoute` /
803    /// per-edge policy can express the intended shape — the pub-sub
804    /// path silently rendered a self-allow rule that is a no-op (intra-
805    /// pod traffic bypasses the mesh entirely), and the synchronous
806    /// paths surfaced as a misleading `ContratoCycle` whose path was
807    /// `["cart", "cart"]` — framing a self-edge as a multi-node
808    /// deadlock. Every downstream consumer that must reject the shape
809    /// (the [`AplicacaoSpec::validate`] per-`:contratos` self-loop
810    /// gate at caixa-core/src/aplicacao.rs:5559, every future
811    /// per-`:contratos`-edge policy resolver on the M4 CR materializer
812    /// axis, every future adjacency-graph builder that must skip self-
813    /// edges rather than fold them into an incidental cycle) now keys
814    /// off exactly one typed dispatch on the substrate primitive, so
815    /// any future rebrand on the axis (an M4-typed-caller enum whose
816    /// identity comparison rule the accessor could route through, an
817    /// operator-side per-cluster caller/callee-alias table the
818    /// materializer resolves per-CR before the equality probe, a
819    /// promotion of the pointwise `==` to a set-membership check once
820    /// SimpleOneForOne-shaped dynamic replicas come into typed scope
821    /// so a per-replica self-edge is rejected under the same predicate)
822    /// migrates as a single caixa-core edit rather than a coordinated
823    /// rewrite of every downstream self-edge consumer. Composes
824    /// byte-for-byte through the lifted [`Self::source`] /
825    /// [`Self::destination`] scalar accessors — the accessor pair every
826    /// per-`:contratos` scalar-value axis already routes through — so
827    /// any future rebrand of the underlying `:de` / `:para` storage
828    /// (a lift from `String` to a typed `ServicoName(String)` newtype,
829    /// a per-Aplicacao interning arena the M4 CR materializer authors,
830    /// a `smol_str::SmolStr` inline-buffer swap) flows through the
831    /// same one body without a coordinated per-consumer rewrite.
832    ///
833    /// Sibling in shape to the peer per-`:contratos` shape-predicate
834    /// family [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
835    /// on the `:wit` world-ref axis — extended onto the per-edge
836    /// endpoint-equality axis: `is_http` / `is_pubsub` / `is_store`
837    /// partition the WIT-shape-space; `is_self_loop` partitions the
838    /// caller-callee identity-space. Named `is_self_loop()` to reflect
839    /// the graph-theoretic identity of the shape (a loop from a graph
840    /// node to itself, distinct from the sibling multi-node
841    /// `ContratoCycle` shape [`Self::detect_sync_cycles`] rejects) and
842    /// to match the [`AplicacaoError::ContratoSelfLoop`] diagnostic
843    /// variant already carrying the term.
844    #[must_use]
845    pub fn is_self_loop(&self) -> bool {
846        self.source() == self.destination()
847    }
848
849    /// Typed view of the contract's payload target. Enforces that the
850    /// `:wit` shape and the carried `:endpoint`/`:subject`/`:slot`
851    /// fields agree, and that each carried value is itself
852    /// value-shape valid:
853    ///
854    ///   - HTTP world (`wasi:http/*`, `http:*`) ⇒ exactly `:endpoint`,
855    ///     non-empty, leading-`/` (Cilium L7 `path` + Gateway API
856    ///     `PathPrefix` invariant — same shape required of `:entrada
857    ///     :paths`)
858    ///   - `PubSub` world (`nats:*`, `kafka:*`) ⇒ exactly `:subject`,
859    ///     non-empty (NATS / Kafka publish without a subject is a
860    ///     no-op subscribe, never the author's intent)
861    ///   - Store world (`wasi:keyvalue/*`, `kv:*`) ⇒ exactly `:slot`,
862    ///     non-empty (an empty slot template addresses the bucket
863    ///     root, defeating the per-key isolation the slot exists for)
864    ///   - Anything else ⇒ none of the three; the contract is a pure
865    ///     typed capability edge with no payload selector.
866    ///
867    /// Translates the Apollo Federation discipline ("conflicts are
868    /// errors at compile time, not warnings at runtime";
869    /// MESH-COMPOSITION §II.3) onto pleme-io's typed Aplicacao surface:
870    /// a contract whose WIT shape disagrees with its target field, or
871    /// whose target field carries a value-shape-invalid string, is a
872    /// build error — not a silent renderer drop. The returned
873    /// [`WitTarget`] view's `&str` payload is therefore guaranteed
874    /// non-empty (and absolute, for `Http`); every downstream consumer
875    /// (caixa-mesh's L7 emission, the M3 Gateway/HTTPRoute renderer,
876    /// the M4 per-edge policy resolver) can rely on that without
877    /// re-checking.
878    pub fn target(&self) -> Result<WitTarget<'_>, AplicacaoError> {
879        // Route the HTTP-shaped payload-target extraction through the
880        // lifted [`WitContract::endpoint`] accessor rather than the raw
881        // `self.endpoint.as_deref()` field access — the two production
882        // consumers of the per-`:contratos :endpoint` HTTP-shaped
883        // payload-carrier scalar (this method's Http-arm payload
884        // extraction, the [`AplicacaoSpec::validate`] duplicate-
885        // `:contratos` [`ContratoIdentity`] dedup-key HTTP arm) now key
886        // off exactly one typed dispatch on the substrate primitive, so
887        // any future rebrand on the axis (an M4 per-cluster endpoint-
888        // alias rewrite, a per-CR fully-qualified path prefix the M4
889        // materializer applies per-tenant, an M4 promotion from
890        // `Option<String>` to a typed HTTP path-template enum) migrates
891        // as a single caixa-core edit rather than a coordinated rewrite
892        // of the two call sites — peer of the sibling M3 per-`:placement`
893        // [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
894        // (74ec2d3) `Option<&str>` typed-dispatch discipline extended
895        // onto the per-`:contratos` HTTP-shaped payload-carrier axis.
896        let endpoint = self.endpoint();
897        let subject = self.subject();
898        // Route the store-arm payload-carrier scalar through the
899        // lifted [`WitContract::slot`] accessor rather than the raw
900        // `self.slot.as_deref()` field access — the two production
901        // consumers of the per-`:contratos :slot` key/value-store-
902        // shaped payload-carrier scalar (this method's Store-arm
903        // payload extraction, the [`AplicacaoSpec::validate`]
904        // duplicate-`:contratos` [`ContratoIdentity`] dedup-key store
905        // arm) now key off exactly one typed dispatch on the substrate
906        // primitive. Closes the last unlifted per-`:contratos`
907        // `Option<String>` axis, completing the payload-carrier
908        // accessor family peer of the sibling per-`:contratos`
909        // [`WitContract::endpoint`] (7020470) / [`WitContract::subject`]
910        // (90de675) lifts across the HTTP / pub-sub arms.
911        let slot = self.slot();
912        // Route the local `(de, para, wit)` triple-projection closure
913        // through the lifted [`WitContract::edge_triple`] typed accessor
914        // rather than re-inlining `(self.de.clone(), self.para.clone(),
915        // self.wit.clone())` — the eight [`AplicacaoError::Contrato*`]
916        // triple-carrying diagnostic constructors below (wrong-target /
917        // missing-target on all three payload arms + capability-with-
918        // payload + invalid-wit) now key off exactly one typed dispatch
919        // on the substrate-primitive composite projection, sibling to
920        // the peer [`WitContract::edge_pair`]-routed
921        // [`AplicacaoError::Empty*`]/`ContratoEndpointEmpty`/
922        // `ContratoSubjectEmpty`/`ContratoSlotEmpty` pair-carrying
923        // diagnostic constructors on the same per-`:contratos`
924        // diagnostic-construction surface.
925        let edge = || self.edge_triple();
926
927        // The `:wit` value drives every downstream dispatch — the
928        // is_http/is_pubsub/is_store prefix matchers below, the
929        // caixa-mesh L7-vs-L4 emission, the cycle-detector's pub-sub
930        // exclusion. Until this gate landed `target()` accepted any
931        // non-empty string and silently demoted unrecognized shapes to
932        // a capability-only edge (`:wit "WASI:HTTP/proxy"` — uppercase
933        // typo, `:wit "wasi-http/proxy"` — hyphen-instead-of-colon typo,
934        // `:wit "wasi:http proxy"` — whitespace, `:wit "wasi:"` — empty
935        // package, the paste-from-binary footgun a multi-line blob
936        // accidentally landing in the slot, the un-percent-encoded
937        // non-ASCII byte) — the canonical "I thought I had L7 HTTP
938        // routing, got L4-only" footgun. Empty is still pre-checked at
939        // the [`AplicacaoSpec::validate`] call site via the narrower
940        // [`AplicacaoError::EmptyWit`] variant (and fires first at the
941        // validate layer); the value-shape gate here picks up the
942        // structurally-invalid non-empty cases the empty check misses,
943        // and remains correct under direct `target()` calls outside
944        // validate (the predicate's defensive empty arm returns a
945        // parser-shaped reason rather than silently falling through to
946        // the Capability arm). Same trajectory as c4213a4 (WitContract
947        // endpoint/subject/slot value-shape gates lifted into
948        // `target()`) on the peer payload axes.
949        if let Err(reason) = crate::render::is_wit_world_ref(&self.wit) {
950            let (de, para, wit) = edge();
951            return Err(AplicacaoError::ContratoWitInvalid {
952                de,
953                para,
954                wit,
955                reason,
956            });
957        }
958
959        if self.is_http() {
960            if subject.is_some() || slot.is_some() {
961                let (de, para, wit) = edge();
962                return Err(AplicacaoError::ContratoWrongTarget {
963                    de,
964                    para,
965                    wit,
966                    expected: WitTarget::HTTP_FIELD_NAME,
967                });
968            }
969            let ep = endpoint.ok_or_else(|| {
970                let (de, para, wit) = edge();
971                AplicacaoError::ContratoMissingTarget {
972                    de,
973                    para,
974                    wit,
975                    expected: WitTarget::HTTP_FIELD_NAME,
976                }
977            })?;
978            if ep.is_empty() {
979                let (de, para) = self.edge_pair();
980                return Err(AplicacaoError::ContratoEndpointEmpty { de, para });
981            }
982            if !ep.starts_with('/') {
983                let (de, para) = self.edge_pair();
984                return Err(AplicacaoError::ContratoEndpointNotAbsolute {
985                    de,
986                    para,
987                    endpoint: ep.to_string(),
988                });
989            }
990            // The `:endpoint` lands verbatim as a Cilium L7 `path:` rule
991            // (caixa-mesh/src/lib.rs:311) and shares the K8s Gateway
992            // API v1 HTTPPathMatch.value admission grammar with the
993            // sibling `:entrada :paths` axis. Until this gate landed
994            // `target()` only refused the empty string + the missing-
995            // leading-`/` form; a structurally invalid endpoint
996            // (`"/charge?token=X"` — query in path slot, `"/foo bar"` —
997            // un-percent-encoded whitespace, `"/api/café"` — non-ASCII,
998            // `"/api//bar"` — consecutive slash, `"/api/../etc"` —
999            // path-traversal segment, the >1024-byte slug) silently
1000            // passed validate and the failure surfaced at apply time
1001            // as a Cilium policy rejection / silent traffic drop, far
1002            // from the source caixa.lisp. Same Gateway API HTTPPathMatch
1003            // grammar `:entrada :paths` already gates (55410e4), now
1004            // shared with `:contratos :endpoint` through the lifted
1005            // `crate::render::is_gateway_api_http_path` predicate.
1006            if let Err(reason) = crate::render::is_gateway_api_http_path(ep) {
1007                let (de, para) = self.edge_pair();
1008                return Err(AplicacaoError::ContratoEndpointInvalid {
1009                    de,
1010                    para,
1011                    endpoint: ep.to_string(),
1012                    reason,
1013                });
1014            }
1015            return Ok(WitTarget::Http { endpoint: ep });
1016        }
1017        if self.is_pubsub() {
1018            if endpoint.is_some() || slot.is_some() {
1019                let (de, para, wit) = edge();
1020                return Err(AplicacaoError::ContratoWrongTarget {
1021                    de,
1022                    para,
1023                    wit,
1024                    expected: WitTarget::PUBSUB_FIELD_NAME,
1025                });
1026            }
1027            let s = subject.ok_or_else(|| {
1028                let (de, para, wit) = edge();
1029                AplicacaoError::ContratoMissingTarget {
1030                    de,
1031                    para,
1032                    wit,
1033                    expected: WitTarget::PUBSUB_FIELD_NAME,
1034                }
1035            })?;
1036            if s.is_empty() {
1037                let (de, para) = self.edge_pair();
1038                return Err(AplicacaoError::ContratoSubjectEmpty { de, para });
1039            }
1040            // The `:subject` lands at runtime as the NATS subject the
1041            // producer publishes to and the consumer subscribes from.
1042            // Until this gate landed `target()` only refused the
1043            // empty string; a structurally invalid subject
1044            // (`"foo..bar"` — empty token between separators,
1045            // `"foo.>.bar"` — non-trailing `>` wildcard the NATS
1046            // server's subject parser rejects, `"foo bar"` —
1047            // un-percent-encoded whitespace, `"foo.café"` —
1048            // un-percent-encoded non-ASCII, `".foo"` / `"foo."` —
1049            // empty leading/trailing tokens, the >256-byte
1050            // paste-from-binary slug) silently passed validate and
1051            // the failure surfaced at runtime as a NATS server-side
1052            // `-ERR 'Invalid Subject'` on publish / subscribe, or as
1053            // a silent message drop, far from the source caixa.lisp.
1054            // Same Gateway API HTTPPathMatch / WIT-IDL grammar
1055            // trajectory `:contratos :endpoint` (4f0390b) and
1056            // `:contratos :wit` (6226bf4) already gate, now shared
1057            // with `:contratos :subject` through the lifted
1058            // `crate::render::is_nats_subject` predicate.
1059            if let Err(reason) = crate::render::is_nats_subject(s) {
1060                let (de, para) = self.edge_pair();
1061                return Err(AplicacaoError::ContratoSubjectInvalid {
1062                    de,
1063                    para,
1064                    subject: s.to_string(),
1065                    reason,
1066                });
1067            }
1068            return Ok(WitTarget::PubSub { subject: s });
1069        }
1070        if self.is_store() {
1071            if endpoint.is_some() || subject.is_some() {
1072                let (de, para, wit) = edge();
1073                return Err(AplicacaoError::ContratoWrongTarget {
1074                    de,
1075                    para,
1076                    wit,
1077                    expected: WitTarget::STORE_FIELD_NAME,
1078                });
1079            }
1080            let sl = slot.ok_or_else(|| {
1081                let (de, para, wit) = edge();
1082                AplicacaoError::ContratoMissingTarget {
1083                    de,
1084                    para,
1085                    wit,
1086                    expected: WitTarget::STORE_FIELD_NAME,
1087                }
1088            })?;
1089            if sl.is_empty() {
1090                let (de, para) = self.edge_pair();
1091                return Err(AplicacaoError::ContratoSlotEmpty { de, para });
1092            }
1093            // Value-shape gate on the third (and last) typed payload
1094            // axis the `WitContract::target` dispatch carries — the
1095            // peer of [`crate::render::is_gateway_api_http_path`] for
1096            // `:endpoint` (4f0390b) and [`crate::render::is_nats_subject`]
1097            // for `:subject` (63e18a0). Until this gate landed
1098            // `target()` only refused the empty string; a structurally
1099            // invalid slot (`"check out/$order"` — un-percent-encoded
1100            // whitespace whose runtime behavior varies unpredictably
1101            // across kv backends, `"checkout/\x01order"` — control
1102            // character that Redis admits but corrupts on next read
1103            // and DynamoDB rejects outright, `"chéckout/$order"` —
1104            // un-percent-encoded non-ASCII byte each backend re-encodes
1105            // differently, `"checkout\n/$order"` — embedded newline,
1106            // the 513-byte paste-from-binary slug) silently passed
1107            // validate and surfaced at runtime as a per-backend kv
1108            // write rejection (DynamoDB / etcd) or as a silent
1109            // next-read corruption (Redis-via-RESP3), far from the
1110            // source caixa.lisp with no field naming which `:contratos`
1111            // edge carried the typo. The lifted predicate makes the
1112            // kv-backend intersection-floor a substrate-level
1113            // invariant at validate time, not a runtime "this passed
1114            // validate but the kv backend rejected on first write"
1115            // surprise — closes the typed payload-axis value-shape
1116            // trajectory across all three legs of the four
1117            // [`WitTarget`] arms (HTTP / PubSub / Store / Capability)
1118            // that caixa-mesh + the future kv emitters land in.
1119            if let Err(reason) = crate::render::is_wasi_keyvalue_slot(sl) {
1120                let (de, para) = self.edge_pair();
1121                return Err(AplicacaoError::ContratoSlotInvalid {
1122                    de,
1123                    para,
1124                    slot: sl.to_string(),
1125                    reason,
1126                });
1127            }
1128            return Ok(WitTarget::Store { slot: sl });
1129        }
1130
1131        // Unrecognized WIT world — must not carry any payload target.
1132        if endpoint.is_some() || subject.is_some() || slot.is_some() {
1133            let (de, para, wit) = edge();
1134            return Err(AplicacaoError::ContratoWrongTarget {
1135                de,
1136                para,
1137                wit,
1138                expected: WitTarget::CAPABILITY_EXPECTED,
1139            });
1140        }
1141        Ok(WitTarget::Capability)
1142    }
1143}
1144
1145/// Borrowed identity key for the typed-graph duplicate-`:contratos`
1146/// gate (see [`AplicacaoSpec::validate`]): every field that
1147/// distinguishes one contract from another, in declaration order
1148/// (`(de, para, wit, endpoint, subject, slot)`). Two [`WitContract`]s
1149/// with equal [`ContratoIdentity`]s are the same typed edge declared
1150/// twice — the graph-edge analogue of duplicate `:membros` /
1151/// `:placement :clusters` / `:entrada :paths` entries. Lifted as a
1152/// type alias so the duplicate-gate's `HashSet<…>` type doesn't trip
1153/// clippy's `type_complexity` lint (and so a future axis added to
1154/// `WitContract` is one alias edit, not a coordinated rewrite of
1155/// every set instantiation).
1156pub type ContratoIdentity<'a> = (
1157    &'a str,
1158    &'a str,
1159    &'a str,
1160    Option<&'a str>,
1161    Option<&'a str>,
1162    Option<&'a str>,
1163);
1164
1165/// Typed view of a [`WitContract`]'s payload target. Each variant
1166/// carries the field its WIT shape requires; constructing a `Http`
1167/// view without an endpoint is impossible by the type system.
1168///
1169/// Renderers (caixa-mesh L7 rules, feira app graph) match on this
1170/// instead of probing `Option<String>` fields one by one — the
1171/// "which payload field is set?" question is answered once, at
1172/// validation time.
1173#[derive(Debug, Clone, Copy, PartialEq, Eq, gen_platform::IsVariant)]
1174pub enum WitTarget<'a> {
1175    /// HTTP-shaped WIT world. Carries the configured request path.
1176    Http { endpoint: &'a str },
1177    /// Pub-sub-shaped WIT world. Carries the event-stream subject.
1178    ///
1179    /// The `IsVariant` derive would auto-name the predicate `is_pub_sub`
1180    /// (`discriminant_to_snake("PubSub") == "pub_sub"`); the explicit
1181    /// `#[is_variant(name = "pubsub")]` override keeps the emitted
1182    /// method name byte-identical to the sibling
1183    /// [`WitContract::is_pubsub`] predicate (the paired shape-side
1184    /// arm-discriminator that routes through
1185    /// [`wit_shape_is_pubsub`] on the wit-world-ref scalar rather than
1186    /// through `matches!` on the variant), so the two arm-discriminator
1187    /// axes — target-side variant-arm and shape-side ref-prefix — reach
1188    /// every downstream consumer through the same `is_pubsub()` name.
1189    #[is_variant(name = "pubsub")]
1190    PubSub { subject: &'a str },
1191    /// Key-value-shaped WIT world. Carries the slot template.
1192    Store { slot: &'a str },
1193    /// A typed capability edge with no payload selector — the WIT
1194    /// world stands on its own (rare; reserved for plain capability
1195    /// imports or M4-and-later WIT worlds we haven't shaped yet).
1196    Capability,
1197}
1198
1199impl<'a> WitTarget<'a> {
1200    /// Canonical author-facing `:contratos` payload field name for the
1201    /// HTTP-shaped arm — the `expected: &'static str` scalar the
1202    /// [`AplicacaoError::ContratoMissingTarget`] /
1203    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1204    /// through, the `:endpoint "…"` keyword the [`WitTarget::label`]
1205    /// duplicate-edge diagnostic emits, and the `endpoint=…` prefix
1206    /// the `feira app graph` verb prints. Peer of
1207    /// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
1208    /// on the payload-field-name axis; declared as a peer const next
1209    /// to the [`WitTarget::Http`] variant so a future rename on the
1210    /// author-surface `(defcaixa … :contratos ((:de … :para … :wit …
1211    /// :endpoint …)))` field lands in exactly one place, not scattered
1212    /// across the [`WitContract::target`] gate's six `expected:`
1213    /// literals, the label template, and every downstream consumer
1214    /// that prints a per-arm prefix. Same trajectory as the peer
1215    /// [`WitTarget::label`] lift (174e96a): a single source of truth
1216    /// for the arm's shape, next to the variant declaration.
1217    pub const HTTP_FIELD_NAME: &'static str = "endpoint";
1218    /// Canonical author-facing `:contratos` payload field name for the
1219    /// pub-sub-shaped arm. Peer of [`WitTarget::HTTP_FIELD_NAME`] /
1220    /// [`WitTarget::STORE_FIELD_NAME`] on the payload-field-name axis;
1221    /// see [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1222    pub const PUBSUB_FIELD_NAME: &'static str = "subject";
1223    /// Canonical author-facing `:contratos` payload field name for the
1224    /// key/value-store-shaped arm. Peer of
1225    /// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`]
1226    /// on the payload-field-name axis; see
1227    /// [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1228    pub const STORE_FIELD_NAME: &'static str = "slot";
1229
1230    /// Canonical stable human-readable label the payload-less
1231    /// [`WitTarget::Capability`] arm renders as under [`Self::label`] —
1232    /// the byte-string every consumer that formats a payload-less
1233    /// typed capability edge as text lands on (the
1234    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` diagnostic
1235    /// naming which identical edge was declared twice, the future
1236    /// `feira app graph` verb's per-arm prefix, the future M4 per-edge
1237    /// policy resolver's audit view, the operator's mesh-graph audit).
1238    /// Peer of the payload-arm [`Self::HTTP_FIELD_NAME`] /
1239    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`]
1240    /// author-facing label-scalar consts — the same
1241    /// "one canonical declaration per arm, next to the variant, so a
1242    /// future rename lands in one place" discipline extended to the
1243    /// payload-less arm. Until this lift landed the byte-string sat
1244    /// twice — once inline in [`Self::label`]'s [`WitTarget::Capability`]
1245    /// match arm, once in the pin test asserting the label's
1246    /// [`WitTarget::Capability`] output — with no compile-time link
1247    /// between the two: a rebrand on either side (an operator-facing
1248    /// vocabulary shift, a per-consumer disambiguation like
1249    /// `"(capability — no payload; typed edge only)"`) would silently
1250    /// desynchronize until a downstream consumer surfaced the drift at
1251    /// runtime.
1252    pub const CAPABILITY_LABEL: &'static str = "(capability — no payload)";
1253
1254    /// Canonical `expected:` scalar the
1255    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1256    /// through for the payload-less [`WitTarget::Capability`] arm — the
1257    /// byte-string authors read as "this WIT world's shape is not one
1258    /// of {`HTTP`, `PubSub`, `Store`}, so it must not carry
1259    /// `:endpoint` / `:subject` / `:slot`". Peer of the payload-arm
1260    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1261    /// [`Self::STORE_FIELD_NAME`] consts on the
1262    /// `ContratoWrongTarget::expected` axis — the fourth arm of the
1263    /// same "which payload field name goes in the diagnostic" dispatch
1264    /// the three payload-arm consts cover, extended to the payload-less
1265    /// arm. Until this lift landed the byte-string sat twice — once
1266    /// inline in the [`Self::target`] Capability-arm rejection at the
1267    /// production dispatch, once in the pin test asserting the
1268    /// diagnostic's `expected:` scalar carries `"none"` verbatim — with
1269    /// no compile-time link between the two: a rebrand on either side
1270    /// (an author-facing vocabulary shift to `"capability"` /
1271    /// `"(none)"` / `"no-payload"` as the WIT registry's shape
1272    /// vocabulary sharpens, a per-consumer disambiguation as M4 splits
1273    /// [`WitTarget::Capability`] into per-shape peers) would silently
1274    /// desynchronize until a downstream consumer surfaced the drift at
1275    /// runtime. Same "one canonical declaration per arm, next to the
1276    /// variant, so a future rename lands in one place" discipline the
1277    /// peer [`Self::CAPABILITY_LABEL`] lift (7ed03a3-era) already
1278    /// established for the payload-less arm's human-readable label
1279    /// axis; this lift extends it onto the peer diagnostic-scalar axis
1280    /// so both halves of the "how does the Capability arm surface at
1281    /// its two consumer axes (human-readable label, wrong-target
1282    /// diagnostic)" pipeline route through peer consts declared next
1283    /// to the variant.
1284    ///
1285    /// Pairwise-distinctness against the three payload-arm scalars
1286    /// ([`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1287    /// [`Self::STORE_FIELD_NAME`]) is pinned by the sibling
1288    /// `wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`
1289    /// test — the 4-way closure of the 3-way
1290    /// `wit_target_field_names_are_pairwise_distinct` sibling pin onto
1291    /// the `ContratoWrongTarget::expected` axis, matching the peer
1292    /// `m3_placement_estrategia_consts_are_pairwise_distinct` closed-set
1293    /// scalar-value distinctness discipline the sibling M3 typed-enum
1294    /// discriminator axis already carries.
1295    pub const CAPABILITY_EXPECTED: &'static str = "none";
1296
1297    /// The `(author-facing field name, payload)` pair this typed target
1298    /// arm carries — `Some((HTTP_FIELD_NAME, endpoint))` for
1299    /// [`Self::Http`], `Some((PUBSUB_FIELD_NAME, subject))` for
1300    /// [`Self::PubSub`], `Some((STORE_FIELD_NAME, slot))` for
1301    /// [`Self::Store`], `None` for the payload-less
1302    /// [`Self::Capability`] arm.
1303    ///
1304    /// Lifted as the single 4-arm dispatch that both [`Self::label`]
1305    /// (formats `":{field} {payload:?}"` on `Some`, falls to
1306    /// [`Self::CAPABILITY_LABEL`] on `None`) and [`Self::field_name`]
1307    /// (returns the first component) route through, so a future
1308    /// [`WitTarget`] variant addition — the M4-and-later per-edge WIT
1309    /// registry may split [`Self::Http`] into `Rest` / `Grpc` peers,
1310    /// or extend [`Self::Store`] with a `Queue`-shaped peer — becomes
1311    /// exactly one new match-arm here (a compile-time exhaustiveness
1312    /// error otherwise), not a coordinated three-way rewrite of the
1313    /// prior [`Self::label`] template + [`Self::field_name`] dispatch
1314    /// + every downstream consumer that reaches for the pair.
1315    ///
1316    /// Until this lift landed the three payload arms sat in
1317    /// [`Self::label`] as three near-identical `format!(":{} {…:?}", …)`
1318    /// invocations (one per variant, each hand-quoting the paired
1319    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1320    /// [`Self::STORE_FIELD_NAME`] const) — the canonical
1321    /// "same shape, written N times" duplication THEORY.md §I.3.5
1322    /// ("Generation first, composition second, hand-authoring last;
1323    /// the duplication budget is zero") promotes to a build-time
1324    /// concern, with each per-arm site paired to its own const with no
1325    /// compile-time link between the format template and the arm's
1326    /// payload extraction.
1327    #[must_use]
1328    pub const fn payload_pair(&self) -> Option<(&'static str, &'a str)> {
1329        match *self {
1330            WitTarget::Http { endpoint } => Some((Self::HTTP_FIELD_NAME, endpoint)),
1331            WitTarget::PubSub { subject } => Some((Self::PUBSUB_FIELD_NAME, subject)),
1332            WitTarget::Store { slot } => Some((Self::STORE_FIELD_NAME, slot)),
1333            WitTarget::Capability => None,
1334        }
1335    }
1336
1337    /// The canonical author-facing `:contratos` payload field name
1338    /// this typed target arm carries (`Http` → `Some("endpoint")`,
1339    /// `PubSub` → `Some("subject")`, `Store` → `Some("slot")`), or
1340    /// `None` for the payload-less `Capability` arm.
1341    ///
1342    /// Routes through [`Self::payload_pair`] — the single 4-arm
1343    /// dispatch [`Self::label`] also reads — so a future variant
1344    /// addition is one match-arm edit at [`Self::payload_pair`], not a
1345    /// per-consumer rewrite. Same "exhaustive-match at one canonical
1346    /// dispatch, thin projections at each consumer" trajectory the
1347    /// peer [`PlacementStrategy::as_str`] / [`std::fmt::Display`]
1348    /// pair (0a2f653) landed on the sibling M3 typed-enum axis.
1349    #[must_use]
1350    pub const fn field_name(&self) -> Option<&'static str> {
1351        match self.payload_pair() {
1352            Some((f, _)) => Some(f),
1353            None => None,
1354        }
1355    }
1356
1357    /// Render this typed target as a stable human-readable label
1358    /// (`:endpoint "/charge"`, `:subject "events.x"`,
1359    /// `:slot "checkout/$order"`, or `(capability — no payload)` when
1360    /// the WIT world is a pure capability edge).
1361    ///
1362    /// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
1363    /// gate so the diagnostic names *which* identical edge was
1364    /// declared twice (not just which `(de, para, wit)` triple).
1365    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
1366    /// on the payload-carrying arms (`Some((field, payload)) →
1367    /// format!(":{field} {payload:?}")`) and through the lifted
1368    /// [`Self::CAPABILITY_LABEL`] const on the payload-less
1369    /// [`Self::Capability`] arm — so a future variant addition (the
1370    /// M4-and-later per-edge WIT registry may split [`Self::Http`]
1371    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
1372    /// `Queue`-shaped peer) becomes a single new match-arm on
1373    /// [`Self::payload_pair`] rather than a rewrite of this template
1374    /// (and every downstream consumer that reaches for the label
1375    /// shape: the per-edge policy resolver in M4, the `feira app
1376    /// graph` view, the operator's mesh-graph audit). Until this
1377    /// lift landed the three payload arms carried three near-identical
1378    /// per-arm `format!(":{} {…:?}", …)` invocations, and the
1379    /// [`Self::Capability`] arm carried the payload-less byte-string
1380    /// twice (once inline here, once in the pin test) — closing the
1381    /// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
1382    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
1383    /// / 4a1e490) peer-const lifts already established for the
1384    /// payload-carrying arms.
1385    #[must_use]
1386    pub fn label(&self) -> String {
1387        match self.payload_pair() {
1388            Some((field, payload)) => format!(":{field} {payload:?}"),
1389            None => Self::CAPABILITY_LABEL.to_string(),
1390        }
1391    }
1392}
1393
1394/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
1395/// pretty-printed byte-string every consumer that formats a typed
1396/// payload target as user-facing text lands on (the
1397/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
1398/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
1399/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
1400/// graph` per-`:contratos`-edge payload column that reaches the graph
1401/// verb through `format!("{target}")`, the future M4 per-edge policy
1402/// resolver's per-edge audit-log line, the operator's mesh-graph
1403/// per-edge inspection view) reaches for the same lifted
1404/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
1405/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
1406/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
1407/// routes through — extending the three-path-convergence
1408/// (`Debug` for structural inspection, `Display` for user-facing text,
1409/// per-arm typed accessor for the canonical byte-string) discipline the
1410/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
1411/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
1412/// onto the fourth (and only remaining) typed-shape-discriminator axis
1413/// on the caixa surface.
1414///
1415/// Pre-lift the two paths were structurally independent — every consumer
1416/// reaching for a payload byte-string past the [`WitTarget::label`]
1417/// helper had to pick between three paths ([`WitTarget::label`],
1418/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
1419/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
1420/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
1421/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
1422/// that reached for `format!("{target}")` — the canonical shape every
1423/// user-facing pretty-print site on the sibling typed-enum axes already
1424/// uses — would silently land on the `Debug` derive's structural output
1425/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
1426/// than the `label()` helper's stable byte-string (`:endpoint
1427/// "/charge"` — the author-facing `:contratos` keyword form) the
1428/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
1429/// already threads through. The two spellings would diverge silently in
1430/// every downstream diagnostic / graph / audit line reached through
1431/// `format!` rather than through the `label()` helper. Routing
1432/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
1433/// path: every `format!("{v}")` call reaches the same
1434/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
1435/// and the duplicate-`:contratos` gate already route through, so a
1436/// future variant addition (the M4-and-later per-edge WIT registry may
1437/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
1438/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
1439/// consumer at exactly one place — the [`WitTarget::payload_pair`]
1440/// match — rather than fanning out through hand-rolled per-arm
1441/// [`std::fmt::Display`] arms.
1442///
1443/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
1444/// is the typed view returned by [`WitContract::target`], not a
1445/// closed-set discriminator enum with a gen-platform Discriminant
1446/// registration, so the `Debug` derive's structural output (which every
1447/// `{v:?}` consumer still reaches) stays distinct from the `Display`
1448/// helper's stable pretty-printed byte-string. `Debug` reveals variant
1449/// shape for structural inspection; `Display` (via `label`) reveals the
1450/// stable author-facing payload projection.
1451///
1452/// Pin tests
1453/// [`tests::wit_target_display_routes_through_label_helper`] and
1454/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
1455/// assert the two paths agree byte-for-byte on every variant, so a
1456/// future variant addition or `label()` reimplementation that hand-rolls
1457/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
1458/// build error visible at caixa-core test time, not a silent
1459/// per-consumer dispatch miss at diagnostic / audit / graph time.
1460impl std::fmt::Display for WitTarget<'_> {
1461    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1462        f.write_str(&self.label())
1463    }
1464}
1465
1466// ── one Aplicacao member ─────────────────────────────────────────────
1467
1468/// A Servico participating in the Aplicacao. Same shape as
1469/// `crate::supervisor::ChildSpec` but without a restart policy —
1470/// supervision is per-Servico (each member has its own
1471/// `:supervisor`), the Aplicacao orchestrates *placement*.
1472#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1473#[serde(rename_all = "camelCase")]
1474pub struct Membro {
1475    /// Member caixa's `:nome`. Resolves through the same dep
1476    /// resolution path as `crate::dep::Dep`.
1477    pub caixa: String,
1478
1479    /// Semver constraint.
1480    pub versao: String,
1481}
1482
1483impl Membro {
1484    /// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
1485    /// accessor every consumer that reads the member's Servico identity
1486    /// keys off — returns the author-declared `:membros :caixa`
1487    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
1488    /// own [`String`] storage.
1489    ///
1490    /// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
1491    /// participating in the Aplicacao — validated by
1492    /// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
1493    /// (via [`validate_membro_caixa`]), unique across the Aplicacao's
1494    /// `:membros` list, distinct from the Aplicacao's own `:nome` (via
1495    /// [`validate_no_self_membership`]) — and every downstream consumer
1496    /// that fans on the member's identity keys off this scalar (the
1497    /// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
1498    /// lookup, the per-`:membros` duplicate gate's dedup key, the
1499    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
1500    /// identity, the self-membership gate, the
1501    /// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
1502    /// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
1503    /// CR materializer's per-member resolver).
1504    ///
1505    /// Prior to this lift the `.caixa` byte-string was read inline at
1506    /// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
1507    /// set collector at
1508    /// `self.membros.iter().map(|m| m.caixa.as_str())`, the
1509    /// [`validate_membros`] validation-side member-caixa gate at
1510    /// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
1511    /// per-member duplicate-gate dedup key at
1512    /// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
1513    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
1514    /// `adj.entry(m.caixa.as_str()).or_default()`, and the
1515    /// [`validate_no_self_membership`] self-loop gate at
1516    /// `m.caixa == parent_nome`) — five open-coded field-accesses that
1517    /// expressed no compile-time link back to the typed slot. Every
1518    /// caixa-mesh `metadata.name` derived from a `:membros :caixa`
1519    /// value flows through the [`caixa_mesh::fleet_programs`] per-entry
1520    /// `name:` axis, so a future extension of the `:membros :caixa`
1521    /// axis to a richer author surface — a per-cluster alias table the
1522    /// operator pins through a future `:placement`-scoped slot, a
1523    /// namespace-qualified rewrite the M4 CR materializer applies
1524    /// per-CR, a per-member overlay from the future `:membros
1525    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
1526    /// acknowledges — would have had to be threaded through every
1527    /// open-coded copy in lockstep or one consumer would silently
1528    /// disagree with the peers on which caixa a given member resolves
1529    /// to. A member-set lookup that treated the name as `"cart"` while
1530    /// the peer adjacency map treated it as `"tenant-a/cart"` would
1531    /// silently split the `:contratos` membership-lookup diagnostic from
1532    /// the cycle-detector's node identity — a two-consumer split at the
1533    /// validator far from the source `caixa.lisp` with no field naming
1534    /// the identity-drift root cause. Lifting the resolution rule to a
1535    /// typed method on the substrate primitive means every downstream
1536    /// consumer of the Aplicacao's per-`:membros` identity surface
1537    /// reaches for exactly one typed dispatch — the resolver's
1538    /// accept-set migrates as a unit on any future axis addition.
1539    ///
1540    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
1541    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
1542    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
1543    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
1544    /// destination-Servico scalar accessors — same "one typed dispatch
1545    /// on the substrate primitive, thin projections at each consumer"
1546    /// discipline extended onto the per-`:membros` member-caixa `:nome`
1547    /// byte-string axis. Named `nome()` to match the tatara-lisp
1548    /// author-surface term the field's docstring already reaches for
1549    /// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
1550    /// [`crate::dep::Dep::nome`] field-name discipline the substrate
1551    /// already carries — the accessor's name maps directly onto the
1552    /// canonical caixa-identity vocabulary rather than shadowing the
1553    /// field's storage-side `caixa` label.
1554    #[must_use]
1555    pub fn nome(&self) -> &str {
1556        self.caixa.as_str()
1557    }
1558
1559    /// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
1560    /// requirement scalar accessor every consumer that reads the
1561    /// member's version pin keys off — returns the author-declared
1562    /// `:membros :versao` byte-string verbatim as a `&str`, borrowed
1563    /// from the typed slot's own [`String`] storage.
1564    ///
1565    /// The `:membros :versao` slot carries the Cargo-shaped semver
1566    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
1567    /// pins which release of the member-caixa the Aplicacao composes
1568    /// against — the same requirement grammar the peer `:deps :versao`
1569    /// / `:children :versao` axes carry, resolved through the shared
1570    /// [`crate::render::require_valid_versao_requirement`] cascade and
1571    /// the shared [`crate::version::parse_requirement`] parser. Every
1572    /// downstream consumer that fans on the member's version pin keys
1573    /// off this scalar (the [`validate_membros`] per-member requirement
1574    /// gate at `require_valid_versao_requirement(m.versao_requirement(),
1575    /// …)`, the [`feira app graph`] per-member `println!("    - {} {}",
1576    /// m.nome(), m.versao_requirement())` line, every future per-cluster
1577    /// version-lock overlay the operator pins through a future
1578    /// `:placement`-scoped slot, the future
1579    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
1580    /// version resolver, the future `feira app deploy` pipeline's
1581    /// per-member lacre BLAKE3-closure lookup).
1582    ///
1583    /// Prior to this lift the `.versao` byte-string was accessed inline
1584    /// at two `&str`-shaped sites — the [`validate_membros`]
1585    /// requirement-gate call `require_valid_versao_requirement(&m.versao,
1586    /// …)` and the `feira app graph` per-member printer's `println!(
1587    /// "    - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
1588    /// prior to this lift) — two open-coded field-accesses that expressed
1589    /// no compile-time link back to the typed slot. A future extension of
1590    /// the `:membros :versao` axis to a richer author surface (a
1591    /// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
1592    /// flow, a lacre-projected concrete-version rewrite the operator
1593    /// materializes at CR-admission time, a future `:membros :versao-lock`
1594    /// per-cluster override slot) would have had to be threaded through
1595    /// every open-coded copy in lockstep or one consumer would silently
1596    /// disagree with the peers on which release constraint a given
1597    /// member resolves to. Lifting the resolution rule to a typed method
1598    /// on the substrate primitive means every downstream requirement-
1599    /// facing consumer reaches for exactly one typed dispatch — the
1600    /// resolver's accept-set migrates as a unit on any future axis
1601    /// addition.
1602    ///
1603    /// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
1604    /// member-caixa `:nome` scalar accessor — the pair
1605    /// `(nome(), versao_requirement())` jointly projects the
1606    /// `(caixa, versao)` field pair every renderer that fans on
1607    /// per-member identity + version pin keys off, closing the last
1608    /// unlifted per-`:membros` scalar axis so every downstream
1609    /// per-`:membros` reader now routes through a typed dispatch on the
1610    /// substrate primitive. Named `versao_requirement()` rather than
1611    /// `versao()` because the field's storage-side `.versao` label is
1612    /// already the author-surface term (`:versao`); the accessor's name
1613    /// carries the semantic role — the semver *requirement* string the
1614    /// shared [`crate::version::parse_requirement`] entry-point consumes
1615    /// — so a raw field access and a typed dispatch read differently at
1616    /// every consumer site.
1617    ///
1618    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
1619    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
1620    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
1621    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
1622    /// destination-Servico scalar accessors — same "one typed dispatch
1623    /// on the substrate primitive, thin projections at each consumer"
1624    /// discipline extended onto the per-`:membros` member-`:versao`
1625    /// semver-requirement byte-string axis.
1626    #[must_use]
1627    pub fn versao_requirement(&self) -> &str {
1628        self.versao.as_str()
1629    }
1630}
1631
1632// ── mesh-level policies ──────────────────────────────────────────────
1633
1634/// Mesh policies that apply to every `:contratos` edge unless
1635/// overridden per-edge in M4. V0 is a single global policy block.
1636#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
1637#[serde(rename_all = "camelCase")]
1638pub struct MeshPolicy {
1639    /// Per-call timeout. Authored as a duration string (`"30s"`).
1640    #[serde(
1641        default,
1642        skip_serializing_if = "Option::is_none",
1643        with = "supervisor::duration_codec"
1644    )]
1645    pub timeout: Option<Duration>,
1646
1647    /// Number of retries on transient failure. None = no retries.
1648    #[serde(default, skip_serializing_if = "Option::is_none")]
1649    pub retries: Option<u32>,
1650
1651    /// Circuit breaker config. Trips after N failures within W
1652    /// duration; closes after a cooldown.
1653    #[serde(default, skip_serializing_if = "Option::is_none")]
1654    pub circuit_breaker: Option<CircuitBreaker>,
1655
1656    /// Whether mTLS is required for every contrato. Default: true
1657    /// (sandboxing-by-default; explicit opt-out only).
1658    #[serde(default, skip_serializing_if = "Option::is_none")]
1659    pub mtls_required: Option<bool>,
1660
1661    /// Token-bucket rate limit. Authored as `"100/s"` or
1662    /// `"5000/m"`; stored as `(rate, window)`.
1663    #[serde(
1664        default,
1665        skip_serializing_if = "Option::is_none",
1666        with = "rate_limit_codec"
1667    )]
1668    pub rate_limit: Option<RateLimit>,
1669}
1670
1671impl MeshPolicy {
1672    /// True when no `:politicas` axis carries a value — every field is
1673    /// `None`. The same emptiness contract every other M2/M3 typed
1674    /// surface carries ([`crate::LimitsSpec::is_empty`],
1675    /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
1676    /// typed slot onto a cluster artifact key off this predicate to
1677    /// decide "emit the slot" vs "skip the slot entirely", so an
1678    /// authored-but-unset `:politicas (())` round-trips to a rendered
1679    /// artifact that's structurally identical to one that omits the
1680    /// slot. Lifted as a typed predicate (rather than per-renderer
1681    /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
1682    /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
1683    /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
1684    /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
1685    /// not a coordinated rewrite of every consumer that's reaching
1686    /// for the emptiness semantic.
1687    #[must_use]
1688    pub const fn is_empty(&self) -> bool {
1689        self.timeout().is_none()
1690            && self.retries().is_none()
1691            && self.circuit_breaker().is_none()
1692            && self.mtls_required().is_none()
1693            && self.rate_limit().is_none()
1694    }
1695
1696    /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
1697    /// per-call-deadline scalar accessor every consumer of the
1698    /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
1699    /// returns the author-declared `:politicas :timeout` typed
1700    /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
1701    /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
1702    /// is `Copy`, so the accessor returns by value; no borrow of
1703    /// `&self` past the call). `None` when the slot is absent (the
1704    /// "cluster default applies — typically the gateway class's
1705    /// implementation-side per-request wall-clock cap" arm caixa-mesh's
1706    /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
1707    /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
1708    /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
1709    /// round-trips to a rendered `HTTPRoute` structurally identical to
1710    /// one that omits the slot).
1711    ///
1712    /// The `:politicas :timeout` slot carries the "no infinite blocking"
1713    /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
1714    /// the typed slot's `Option<Duration>` accept-set (zero-floor
1715    /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
1716    /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
1717    /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
1718    /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
1719    /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
1720    /// Every downstream consumer that reads the per-call cap keys off
1721    /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
1722    /// renderers key off to decide "emit :politicas overlay" vs "skip
1723    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
1724    /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
1725    /// fans the deadline into every rule via
1726    /// [`crate::render::single_field_overlay`], the future M4 per-
1727    /// Aplicacao Gateway API reconciler materialization pass, the
1728    /// future per-`:contratos`-edge timeout-override overlay the
1729    /// MESH-COMPOSITION §III.2 roadmap acknowledges).
1730    ///
1731    /// Prior to this lift the `.timeout` field was accessed inline at
1732    /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
1733    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
1734    /// …)` call — two open-coded field-accesses that expressed no
1735    /// compile-time link back to the typed slot. A future extension of
1736    /// the `:politicas :timeout` axis to a richer author surface — a
1737    /// per-`:contratos`-edge timeout override the operator pins through
1738    /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
1739    /// roadmap acknowledges, a per-cluster timeout-default overlay the
1740    /// M4 CR materializer resolves per-CR, a split of the single
1741    /// per-call `Duration` into a richer `{request, backendRequest}`
1742    /// pair once the Gateway API's per-rule `timeouts` block grows the
1743    /// upstream-facing backendRequest arm alongside the client-facing
1744    /// request arm — would have had to be threaded through both open-
1745    /// coded copies in lockstep or the emptiness predicate and the
1746    /// caixa-mesh emit path would silently disagree on which per-call
1747    /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
1748    /// whose only axis is a `Some :timeout` would satisfy `is_empty()
1749    /// == false` while the renderer's overlay-emit path silently read
1750    /// a drifted other value, or vice versa: an author's `:timeout
1751    /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
1752    /// the emptiness predicate still classified the policy as non-
1753    /// empty, and every `kubectl -n tatara-system get httproute -o yaml
1754    /// | grep -A2 timeouts` audit would land on a route whose author's
1755    /// typed slot value silently vanished at the renderer layer).
1756    /// Lifting the resolution to a typed method on the substrate
1757    /// primitive means every downstream consumer of the Aplicacao's
1758    /// per-`:politicas` deadline surface reaches for exactly one typed
1759    /// dispatch — the resolver's accept-set migrates as a unit on any
1760    /// future axis addition.
1761    ///
1762    /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
1763    /// family (sibling of the peer per-`:politicas`
1764    /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
1765    /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
1766    /// `Option<bool>` accessor — same "one typed dispatch on the
1767    /// substrate primitive, thin projections at each consumer"
1768    /// discipline extended onto the peer per-`:politicas` typed-
1769    /// [`Duration`] optional-scalar axis; closes the "optional per-slot
1770    /// numeric-Copy-T scalar" projection pattern the sibling
1771    /// `Option<u32>` / `Option<bool>` lifts opened, since every
1772    /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
1773    /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
1774    /// than a scalar). Named `timeout()` to match the storage field's
1775    /// name; the accessor's identity maps onto the canonical MESH-
1776    /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
1777    #[must_use]
1778    pub const fn timeout(&self) -> Option<Duration> {
1779        self.timeout
1780    }
1781
1782    /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
1783    /// retry-budget scalar accessor every consumer of the Aplicacao's
1784    /// Gateway API v1.x per-rule retry-cap keys off — returns the
1785    /// author-declared `:politicas :retries` typed `u32` verbatim as an
1786    /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
1787    /// storage (`Option<u32>` is `Copy`, so the accessor returns by
1788    /// value; no borrow of `&self` past the call). `None` when the slot
1789    /// is absent (the "cluster default applies — typically 'no retries
1790    /// beyond a single dispatch attempt'" arm the caixa-mesh
1791    /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
1792    /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
1793    /// this predicate too, so an authored-but-unset `:politicas
1794    /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
1795    /// identical to one that omits the slot).
1796    ///
1797    /// The `:politicas :retries` slot carries the "transient failure
1798    /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
1799    /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
1800    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
1801    /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
1802    /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
1803    /// count scalar the caixa-mesh `retry_overlay` builder writes.
1804    /// Every downstream consumer that reads the retry cap keys off this
1805    /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
1806    /// renderers key off to decide "emit :politicas overlay" vs "skip
1807    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
1808    /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
1809    /// the value into every rule via [`crate::render::single_field_overlay`],
1810    /// the future M4 per-Aplicacao Gateway API reconciler
1811    /// materialization pass, the future per-`:contratos`-edge retry-
1812    /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
1813    /// acknowledges).
1814    ///
1815    /// Prior to this lift the `.retries` field was accessed inline at
1816    /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
1817    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
1818    /// …)` call — two open-coded field-accesses that expressed no
1819    /// compile-time link back to the typed slot. A future extension of
1820    /// the `:politicas :retries` axis to a richer author surface — a
1821    /// per-`:contratos`-edge retry override the operator pins through a
1822    /// future `:contratos :retries` slot, a per-cluster retry-default
1823    /// overlay the M4 CR materializer resolves per-CR, a promotion of
1824    /// the plain `u32` attempt-count to a richer `{attempts, codes,
1825    /// backoff}` sub-block once the Gateway API grows the peer
1826    /// `retry.codes` / `retry.backoff` axes — would have had to be
1827    /// threaded through both open-coded copies in lockstep or the
1828    /// emptiness predicate and the caixa-mesh emit path would silently
1829    /// disagree on which retry budget a given [`MeshPolicy`] resolves to
1830    /// (a `:politicas` block whose only axis is a `Some :retries` would
1831    /// satisfy `is_empty() == false` while the renderer's overlay-emit
1832    /// path silently read a drifted other value, or vice versa: an
1833    /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
1834    /// block while the emptiness predicate still classified the policy
1835    /// as non-empty). Lifting the resolution to a typed method on the
1836    /// substrate primitive means every downstream consumer of the
1837    /// Aplicacao's per-`:politicas` retry surface reaches for exactly
1838    /// one typed dispatch — the resolver's accept-set migrates as a
1839    /// unit on any future axis addition.
1840    ///
1841    /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
1842    /// family (sibling of the peer per-`:politicas`
1843    /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
1844    /// same "one typed dispatch on the substrate primitive, thin
1845    /// projections at each consumer" discipline extended onto the
1846    /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
1847    /// the "optional per-slot numeric-Copy-T scalar" projection pattern
1848    /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
1849    /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
1850    /// fold on). Named `retries()` to match the storage field's name;
1851    /// the accessor's identity maps onto the canonical MESH-COMPOSITION
1852    /// §III.2 vocabulary the slot's docstring already carries.
1853    #[must_use]
1854    pub const fn retries(&self) -> Option<u32> {
1855        self.retries
1856    }
1857
1858    /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
1859    /// enforcement-toggle scalar accessor every consumer of the
1860    /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
1861    /// — returns the author-declared `:politicas :mtls-required` typed
1862    /// bool verbatim as an `Option<bool>`, copied out of the typed
1863    /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
1864    /// the accessor returns by value; no borrow of `&self` past the
1865    /// call). `None` when the slot is absent (the "cluster default
1866    /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
1867    /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
1868    /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
1869    /// this predicate too, so an authored-but-unset `:politicas
1870    /// (:mtls-required ())` round-trips to a rendered
1871    /// `CiliumNetworkPolicy` structurally identical to one that omits
1872    /// the slot).
1873    ///
1874    /// The `:politicas :mtls-required` slot carries the "explicit opt-
1875    /// out only, sandboxing-by-default" mTLS-enforcement toggle
1876    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
1877    /// `{None, Some(true), Some(false)}` accept-set maps onto the
1878    /// Cilium `authentication.mode` bijection through
1879    /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
1880    /// handshake enforced), `Some(false) → "disabled"` (handshake
1881    /// skipped — the debug-edge opt-out), `None` → omit the block
1882    /// (cluster default applies). Every downstream consumer that
1883    /// reads the toggle keys off this scalar (the
1884    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
1885    /// off to decide "emit :politicas overlay" vs "skip entirely", the
1886    /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
1887    /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
1888    /// ingress rule via [`crate::render::single_field_overlay`], the
1889    /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
1890    /// materialization pass, the future per-`:contratos`-edge mTLS
1891    /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
1892    ///
1893    /// Prior to this lift the `.mtls_required` field was accessed
1894    /// inline at two sites — [`MeshPolicy::is_empty`]'s
1895    /// `self.mtls_required.is_none()` arm and caixa-mesh's
1896    /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
1897    /// two open-coded field-accesses that expressed no compile-time
1898    /// link back to the typed slot. A future extension of the
1899    /// `:politicas :mtls-required` axis to a richer author surface —
1900    /// a per-`:contratos`-edge mTLS override the operator pins through
1901    /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
1902    /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
1903    /// M4 CR materializer resolves per-CR, a three-valued
1904    /// `{None, Some(true), Some(false), Some(Optional)}` promotion
1905    /// once Cilium's `authentication.mode` grows an `"optional"` arm —
1906    /// would have had to be threaded through both open-coded copies in
1907    /// lockstep or the emptiness predicate and the caixa-mesh emit
1908    /// path would silently disagree on which toggle a given
1909    /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
1910    /// axis is a `Some`
1911    /// `:mtls-required` would satisfy `is_empty() == false` while the
1912    /// renderer's overlay-emit path silently read a drifted other
1913    /// value, or vice versa). Lifting the resolution to a typed method
1914    /// on the substrate primitive means every downstream consumer of
1915    /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
1916    /// for exactly one typed dispatch — the resolver's accept-set
1917    /// migrates as a unit on any future axis addition.
1918    ///
1919    /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
1920    /// family (peer of the sibling per-`:placement`
1921    /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
1922    /// same "one typed dispatch on the substrate primitive, thin
1923    /// projections at each consumer" discipline extended onto the
1924    /// peer per-`:politicas` typed-bool optional-scalar axis; opens
1925    /// the "optional per-slot Copy-T scalar" projection pattern the
1926    /// sibling per-`:politicas` `:retries` (Option<u32>) /
1927    /// `:timeout` (Option<Duration>) future lifts fold on). Named
1928    /// `mtls_required()` to match the storage field's name; the
1929    /// accessor's identity maps onto the canonical MESH-COMPOSITION
1930    /// §III.2 vocabulary the slot's docstring already carries.
1931    #[must_use]
1932    pub const fn mtls_required(&self) -> Option<bool> {
1933        self.mtls_required
1934    }
1935
1936    /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
1937    /// `local_rate_limit`-mesh token-bucket-declaration scalar
1938    /// accessor every consumer of the Aplicacao's per-`:politicas`
1939    /// per-`(rate, window)` rate-limit surface keys off — returns the
1940    /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
1941    /// verbatim as an `Option<RateLimit>`, copied out of the typed
1942    /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
1943    /// `Copy`, so the accessor returns by value; no borrow of `&self`
1944    /// past the call). `None` when the slot is absent (the "cluster
1945    /// default applies — typically 'no per-Aplicacao rate declaration,
1946    /// gateway-class per-listener default applies'" arm the future
1947    /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
1948    /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
1949    /// `rate_limit().is_none()` arm reads this predicate too, so an
1950    /// authored-but-unset `:politicas (:rate-limit ())` round-trips
1951    /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
1952    /// identical to one that omits the slot).
1953    ///
1954    /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
1955    /// token-bucket rate declaration" contract (MESH-COMPOSITION
1956    /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
1957    /// (rate lower-bounded by 1 through
1958    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
1959    /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
1960    /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
1961    /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
1962    /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
1963    /// bijection the future `CiliumClusterwideEnvoyConfig` per-
1964    /// `:politicas` overlay emits. Every downstream consumer that
1965    /// reads the rate declaration keys off this scalar (the
1966    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
1967    /// off to decide "emit :politicas overlay" vs "skip entirely", the
1968    /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
1969    /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
1970    /// `rl.window` against [`is_canonical_rate_limit_window`], the
1971    /// future M4 per-Aplicacao Envoy reconciler materialization pass,
1972    /// the future per-`:contratos`-edge rate-limit override the
1973    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
1974    ///
1975    /// Prior to this lift the `.rate_limit` field was accessed inline
1976    /// at two sites — [`MeshPolicy::is_empty`]'s
1977    /// `self.rate_limit.is_none()` arm and the `validate_politicas`
1978    /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
1979    /// field-accesses that expressed no compile-time link back to the
1980    /// typed slot. A future extension of the `:politicas :rate-limit`
1981    /// axis to a richer author surface — a per-`:contratos`-edge
1982    /// rate-limit override the operator pins through a future
1983    /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
1984    /// roadmap acknowledges, a per-cluster rate-limit-default overlay
1985    /// the M4 CR materializer resolves per-CR, a promotion of the
1986    /// plain `(rate, window)` scalar pair to a richer
1987    /// `{rate, window, burst, key}` sub-block once Envoy's
1988    /// `local_rate_limit` grows the peer `burst_size` /
1989    /// `descriptor_key` axes — would have had to be threaded through
1990    /// both open-coded copies in lockstep or the emptiness predicate
1991    /// and the validate gate would silently disagree on which rate
1992    /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
1993    /// block whose only axis is a `Some :rate-limit` would satisfy
1994    /// `is_empty() == false` while the validate path silently read a
1995    /// drifted other value, or vice versa: an author's
1996    /// `:rate-limit "100/s"` would omit the value-shape gate while the
1997    /// emptiness predicate still classified the policy as non-empty).
1998    /// Lifting the resolution to a typed method on the substrate
1999    /// primitive means every downstream consumer of the Aplicacao's
2000    /// per-`:politicas` rate-limit surface reaches for exactly one
2001    /// typed dispatch — the resolver's accept-set migrates as a unit
2002    /// on any future axis addition.
2003    ///
2004    /// First `Option<Copy-composite-T>`-return accessor on the M3
2005    /// mesh-slot family — closes the last un-lifted per-`:politicas`
2006    /// scalar-value axis. Peer of the sibling per-`:politicas`
2007    /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
2008    /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
2009    /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
2010    /// "one typed dispatch on the substrate primitive, thin
2011    /// projections at each consumer" discipline extended onto the
2012    /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
2013    /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
2014    /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
2015    /// sub-accessors rather than a top-level accessor because
2016    /// consumers reach for the axes not the aggregate). Named
2017    /// `rate_limit()` to match the storage field's name; the
2018    /// accessor's identity maps onto the canonical MESH-COMPOSITION
2019    /// §III.2 vocabulary the slot's docstring already carries.
2020    #[must_use]
2021    pub const fn rate_limit(&self) -> Option<RateLimit> {
2022        self.rate_limit
2023    }
2024
2025    /// Substrate-canonical per-`:politicas` `:circuit-breaker`
2026    /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
2027    /// declaration scalar accessor every consumer of the Aplicacao's
2028    /// per-`:politicas` breaker declaration keys off — returns the
2029    /// author-declared `:politicas :circuit-breaker` typed
2030    /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
2031    /// copied out of the typed slot's own `Option<CircuitBreaker>`
2032    /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
2033    /// by value; no borrow of `&self` past the call). `None` when the
2034    /// slot is absent (the "cluster default applies — typically 'no
2035    /// per-Aplicacao breaker declaration, gateway-class per-listener
2036    /// default applies'" arm the future caixa-mesh
2037    /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
2038    /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
2039    /// arm reads this predicate too, so an authored-but-unset
2040    /// `:politicas (:circuit-breaker ())` round-trips to a rendered
2041    /// `CiliumClusterwideEnvoyConfig` structurally identical to one
2042    /// that omits the slot).
2043    ///
2044    /// The `:politicas :circuit-breaker` slot carries the
2045    /// "per-Aplicacao consecutive-transient-failure trip declaration"
2046    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2047    /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
2048    /// zero-floor rejected through
2049    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2050    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
2051    /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
2052    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
2053    /// canonical-form pinned through
2054    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
2055    /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
2056    /// bijection the future `CiliumClusterwideEnvoyConfig`
2057    /// per-`:politicas` overlay emits. Every downstream consumer that
2058    /// reads the breaker declaration keys off this scalar (the
2059    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2060    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2061    /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
2062    /// that brackets `cb.max_failures()` against
2063    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
2064    /// [`POLICY_BREAKER_WINDOW_MAX`] via
2065    /// [`crate::render::require_positive_canonical_bounded_duration`],
2066    /// the future M4 per-Aplicacao Envoy reconciler materialization
2067    /// pass, the future per-`:contratos`-edge breaker override the
2068    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2069    ///
2070    /// Prior to this lift the `.circuit_breaker` field was accessed
2071    /// inline at two sites — [`MeshPolicy::is_empty`]'s
2072    /// `self.circuit_breaker.is_none()` arm and the
2073    /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
2074    /// bind — two open-coded field-accesses that expressed no
2075    /// compile-time link back to the typed slot. A future extension of
2076    /// the `:politicas :circuit-breaker` axis to a richer author
2077    /// surface — a per-`:contratos`-edge breaker override the operator
2078    /// pins through a future `:contratos :circuit-breaker` slot the
2079    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
2080    /// breaker-default overlay the M4 CR materializer resolves per-CR,
2081    /// a promotion of the plain `(max_failures, window)` scalar pair to
2082    /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
2083    /// sub-block once Envoy's `outlier_detection` grows the peer
2084    /// ejection-percentage / ejection-time axes — would have had to be
2085    /// threaded through both open-coded copies in lockstep or the
2086    /// emptiness predicate and the validate gate would silently
2087    /// disagree on which breaker declaration a given [`MeshPolicy`]
2088    /// resolves to (a `:politicas` block whose only axis is a
2089    /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
2090    /// the validate path silently read a drifted other value, or vice
2091    /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
2092    /// "60s"))` would omit the value-shape gate while the emptiness
2093    /// predicate still classified the policy as non-empty). Lifting
2094    /// the resolution to a typed method on the substrate primitive
2095    /// means every downstream consumer of the Aplicacao's
2096    /// per-`:politicas` breaker surface reaches for exactly one typed
2097    /// dispatch — the resolver's accept-set migrates as a unit on any
2098    /// future axis addition.
2099    ///
2100    /// Second `Option<Copy-composite-T>`-return accessor on the M3
2101    /// mesh-slot family (sibling of the peer per-`:politicas`
2102    /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
2103    /// on the same composite-Copy shape, and of the sibling per-
2104    /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
2105    /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
2106    /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
2107    /// `Option<bool>` accessors on the sibling primitive-Copy axes —
2108    /// same "one typed dispatch on the substrate primitive, thin
2109    /// projections at each consumer" discipline extended onto the last
2110    /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
2111    /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
2112    /// match the storage field's name; the accessor's identity maps
2113    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2114    /// docstring already carries. Closes the last unlifted
2115    /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
2116    /// reader now routes through a typed dispatch on the substrate
2117    /// primitive.
2118    #[must_use]
2119    pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
2120        self.circuit_breaker
2121    }
2122}
2123
2124#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2125#[serde(rename_all = "camelCase")]
2126pub struct CircuitBreaker {
2127    pub max_failures: u32,
2128    #[serde(with = "supervisor::duration_codec_required")]
2129    pub window: Duration,
2130}
2131
2132impl CircuitBreaker {
2133    /// Substrate-canonical per-`:politicas :circuit-breaker`
2134    /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
2135    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2136    /// breaker trip-count keys off — returns the author-declared
2137    /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
2138    /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
2139    /// so the accessor returns by value; no borrow of `&self` past the
2140    /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
2141    /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
2142    /// axis; a `CircuitBreaker` past pattern-match is definitionally
2143    /// present, and its `:max-failures` field carries the trip count as a
2144    /// required-axis scalar).
2145    ///
2146    /// The `:politicas :circuit-breaker :max-failures` axis carries the
2147    /// "consecutive-transient-failure trip threshold" contract
2148    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
2149    /// (zero-floor rejected through
2150    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2151    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
2152    /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
2153    /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
2154    /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
2155    /// Every downstream consumer that reads the trip threshold keys off
2156    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2157    /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
2158    /// canonical `require_positive_bounded_u32` helper, the future M4
2159    /// per-Aplicacao Envoy config reconciler materialization pass, the
2160    /// future per-`:contratos`-edge breaker-override overlay the
2161    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2162    ///
2163    /// Prior to this lift the `.max_failures` field was accessed inline
2164    /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
2165    /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
2166    /// open-coded field-access that expressed no compile-time link back
2167    /// to the typed sub-struct axis. A future extension of the
2168    /// `:max-failures` axis to a richer author surface — a
2169    /// per-`:contratos`-edge breaker override the operator pins through a
2170    /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
2171    /// #3 roadmap acknowledges, a per-cluster max-failures-default
2172    /// overlay the M4 CR materializer resolves per-CR, a promotion of the
2173    /// plain `u32` trip count to a richer
2174    /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
2175    /// tuple once Envoy's `outlier_detection` block's peer axes come into
2176    /// scope, a per-Envoy-cluster minimum-request-volume gate before the
2177    /// count arms — would have had to be threaded through every open-
2178    /// coded copy in lockstep or the validate gate and the future M4
2179    /// emit path would silently disagree on which trip threshold a given
2180    /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
2181    /// would satisfy validate while the emit path silently read a drifted
2182    /// other value, or vice versa: a validated typed slot would land at
2183    /// the emit boundary as a no-op breaker whose trip threshold is
2184    /// structurally never reached). Lifting the resolution to a typed
2185    /// method on the substrate primitive means every downstream consumer
2186    /// of the Aplicacao's per-`:politicas :circuit-breaker`
2187    /// trip-threshold surface reaches for exactly one typed dispatch —
2188    /// the resolver's accept-set migrates as a unit on any future axis
2189    /// addition.
2190    ///
2191    /// First sub-struct scalar accessor on the M3 mesh-slot family
2192    /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
2193    /// scalar" projection pattern the sibling `CircuitBreaker::window` /
2194    /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
2195    /// closes the last unlifted per-`:politicas` scalar-value axis after
2196    /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
2197    /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
2198    /// Same "one typed dispatch on the substrate primitive, thin
2199    /// projections at each consumer" discipline the peer
2200    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
2201    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
2202    /// [`Membro::versao_requirement`] (a40b0e3),
2203    /// [`Entrada::destination`] (6db982c) accessors carry on their
2204    /// respective per-mesh-slot-atom scalar-value axes, extended onto the
2205    /// per-sub-struct required-`u32` axis. Named `max_failures()` to
2206    /// match the storage field's name; the accessor's identity maps onto
2207    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2208    /// docstring already carries.
2209    #[must_use]
2210    pub const fn max_failures(&self) -> u32 {
2211        self.max_failures
2212    }
2213
2214    /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
2215    /// Envoy-outlier-detection rolling-observation-interval scalar
2216    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2217    /// breaker rolling-window duration keys off — returns the
2218    /// author-declared `:politicas :circuit-breaker :window` typed
2219    /// `Duration` verbatim, copied out of the typed slot's own
2220    /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
2221    /// by value; no borrow of `&self` past the call). Non-optional (the
2222    /// surrounding `Option<CircuitBreaker>` is the "slot present?"
2223    /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
2224    /// `CircuitBreaker` past pattern-match is definitionally present,
2225    /// and its `:window` field carries the rolling-observation interval
2226    /// as a required-axis scalar).
2227    ///
2228    /// The `:politicas :circuit-breaker :window` axis carries the
2229    /// "consecutive-transient-failure rolling-observation interval"
2230    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2231    /// `Duration` accept-set (zero-floor rejected through
2232    /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
2233    /// residue rejected through
2234    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
2235    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
2236    /// Envoy `outlier_detection.interval` per-cluster
2237    /// ejection-observation-interval scalar (equivalently the future
2238    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2239    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2240    /// consumer that reads the rolling-observation interval keys off
2241    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2242    /// integer-millisecond canonical-form + cap bracket at
2243    /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
2244    /// [`crate::render::require_positive_canonical_bounded_duration`]
2245    /// helper, the future M4 per-Aplicacao Envoy config reconciler
2246    /// materialization pass, the future per-`:contratos`-edge
2247    /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
2248    /// acknowledges).
2249    ///
2250    /// Prior to this lift the `.window` field was accessed inline at
2251    /// one production site — [`AplicacaoSpec::validate_politicas`]'s
2252    /// `require_positive_canonical_bounded_duration(cb.window, …)`
2253    /// call — one open-coded field-access that expressed no compile-
2254    /// time link back to the typed sub-struct axis. A future extension
2255    /// of the `:window` axis to a richer author surface — a
2256    /// per-`:contratos`-edge window override the operator pins through
2257    /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
2258    /// #3 roadmap acknowledges, a per-cluster window-default overlay
2259    /// the M4 CR materializer resolves per-CR, a promotion of the plain
2260    /// `Duration` observation interval to a richer
2261    /// `{interval, base_ejection_time, max_ejection_percent}` tuple
2262    /// once Envoy's `outlier_detection` block's peer axes come into
2263    /// scope, a per-Envoy-cluster minimum-request-volume gate before
2264    /// the window arms — would have had to be threaded through every
2265    /// open-coded copy in lockstep or the validate gate and the future
2266    /// M4 emit path would silently disagree on which observation
2267    /// interval a given [`CircuitBreaker`] resolves to (an author's
2268    /// `:window "60s"` would satisfy validate while the emit path
2269    /// silently read a drifted other value, or vice versa: a validated
2270    /// typed slot would land at the emit boundary as a breaker whose
2271    /// observation window is structurally so wide that no realistic
2272    /// failure-rate shape can trip it). Lifting the resolution to a
2273    /// typed method on the substrate primitive means every downstream
2274    /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
2275    /// observation-window surface reaches for exactly one typed
2276    /// dispatch — the resolver's accept-set migrates as a unit on any
2277    /// future axis addition.
2278    ///
2279    /// Second sub-struct scalar accessor on the M3 mesh-slot family —
2280    /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
2281    /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
2282    /// required-axis, extended onto the per-sub-struct required-`Duration`
2283    /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
2284    /// axis. Same "one typed dispatch on the substrate primitive, thin
2285    /// projections at each consumer" discipline the peer
2286    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
2287    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
2288    /// [`Membro::versao_requirement`] (a40b0e3),
2289    /// [`Entrada::destination`] (6db982c) accessors carry on their
2290    /// respective per-mesh-slot-atom scalar-value axes, extended onto
2291    /// the per-sub-struct required-`Duration` axis. Named `window()` to
2292    /// match the storage field's name; the accessor's identity maps onto
2293    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2294    /// docstring already carries.
2295    #[must_use]
2296    pub const fn window(&self) -> Duration {
2297        self.window
2298    }
2299}
2300
2301#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2302pub struct RateLimit {
2303    /// Requests per window.
2304    pub rate: u32,
2305    /// Window duration.
2306    pub window: Duration,
2307}
2308
2309impl RateLimit {
2310    /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
2311    /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
2312    /// every consumer of the Aplicacao's per-`:contratos`-edge
2313    /// rate-limit-bucket capacity keys off — returns the author-declared
2314    /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
2315    /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
2316    /// returns by value; no borrow of `&self` past the call). Non-optional
2317    /// (the surrounding `Option<RateLimit>` is the "slot present?"
2318    /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
2319    /// `RateLimit` past pattern-match is definitionally present, and its
2320    /// `:rate` field carries the token-bucket capacity as a required-axis
2321    /// scalar).
2322    ///
2323    /// The `:politicas :rate-limit` `:rate` axis carries the
2324    /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
2325    /// the typed slot's `u32` accept-set (zero-floor rejected through
2326    /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
2327    /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
2328    /// `local_rate_limit.token_bucket.max_tokens` per-cluster
2329    /// token-bucket-capacity scalar (equivalently the future
2330    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2331    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2332    /// consumer that reads the token-bucket capacity keys off this
2333    /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2334    /// cap bracket that gates on the canonical
2335    /// [`crate::render::require_positive_bounded_u32`] helper, the
2336    /// [`rate_limit_codec::render`] `Duration → unit` projection that
2337    /// emits the `<n>/<s|m|h>` author surface, the future M4
2338    /// per-Aplicacao Envoy config reconciler materialization pass, the
2339    /// future per-`:contratos`-edge rate-limit-override overlay the
2340    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2341    ///
2342    /// Prior to this lift the `.rate` field was accessed inline at three
2343    /// production sites — [`AplicacaoSpec::validate_politicas`]'s
2344    /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
2345    /// [`rate_limit_codec::render`] format-arm arms (canonical-window
2346    /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
2347    /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
2348    /// field-accesses that expressed no compile-time link back to the
2349    /// typed sub-struct axis. A future extension of the `:rate` axis
2350    /// to a richer author surface — a per-`:contratos`-edge rate
2351    /// override the operator pins through a future `:contratos :rate`
2352    /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
2353    /// per-cluster rate-default overlay the M4 CR materializer resolves
2354    /// per-CR, a promotion of the plain `u32` token capacity to a
2355    /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
2356    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
2357    /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
2358    /// before the token arms — would have had to be threaded through
2359    /// every open-coded copy in lockstep or the validate gate, the
2360    /// codec's render path, and the future M4 emit path would silently
2361    /// disagree on which token capacity a given [`RateLimit`] resolves
2362    /// to (an author's `:rate-limit "100/s"` would satisfy validate
2363    /// while the render / emit paths silently read a drifted other
2364    /// value, or vice versa: a validated typed slot would land at the
2365    /// emit boundary as a no-op limiter whose token capacity is
2366    /// structurally so high that no realistic per-edge traffic shape
2367    /// can drain it). Lifting the resolution to a typed method on the
2368    /// substrate primitive means every downstream consumer of the
2369    /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
2370    /// reaches for exactly one typed dispatch — the resolver's
2371    /// accept-set migrates as a unit on any future axis addition.
2372    ///
2373    /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
2374    /// in shape to the peer per-`CircuitBreaker`
2375    /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
2376    /// on the peer per-sub-struct required-axis, extended onto the
2377    /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
2378    /// required-axis scalar" projection pattern the sibling
2379    /// [`RateLimit::window`] future lift folds on. Same "one typed
2380    /// dispatch on the substrate primitive, thin projections at each
2381    /// consumer" discipline the peer [`WitContract::source`] /
2382    /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
2383    /// (0804823), [`Membro::nome`] (4a32abf),
2384    /// [`Membro::versao_requirement`] (a40b0e3),
2385    /// [`Entrada::destination`] (6db982c),
2386    /// [`CircuitBreaker::max_failures`] (3a74062),
2387    /// [`CircuitBreaker::window`] (373957f) accessors carry on their
2388    /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
2389    /// to match the storage field's name; the accessor's identity maps
2390    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2391    /// docstring already carries.
2392    #[must_use]
2393    pub const fn rate(&self) -> u32 {
2394        self.rate
2395    }
2396
2397    /// Substrate-canonical per-`:politicas :rate-limit` `:window`
2398    /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
2399    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2400    /// rate-limit-bucket refill period keys off — returns the
2401    /// author-declared `:politicas :rate-limit` typed `Duration`
2402    /// verbatim, copied out of the typed slot's own `Duration` storage
2403    /// (`Duration` is `Copy`, so the accessor returns by value; no
2404    /// borrow of `&self` past the call). Non-optional (the surrounding
2405    /// `Option<RateLimit>` is the "slot present?" projection at the
2406    /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
2407    /// pattern-match is definitionally present, and its `:window`
2408    /// field carries the token-bucket refill period as a required-axis
2409    /// scalar).
2410    ///
2411    /// The `:politicas :rate-limit` `:window` axis carries the
2412    /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
2413    /// — the typed slot's `Duration` accept-set (constrained to the
2414    /// three canonical windows `{1s, 60s, 3600s}` the
2415    /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
2416    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
2417    /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
2418    /// per-cluster token-bucket-refill-period scalar (equivalently the
2419    /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2420    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2421    /// consumer that reads the token-bucket refill period keys off
2422    /// this scalar (the [`AplicacaoSpec::validate_politicas`]
2423    /// canonical-window gate that keys off
2424    /// [`is_canonical_rate_limit_window`], the
2425    /// [`rate_limit_codec::render`] `Duration → unit` projection that
2426    /// emits the `<n>/<s|m|h>` author surface — canonical arm via
2427    /// [`rate_limit_window_unit`] and non-canonical fallback via
2428    /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
2429    /// reconciler materialization pass, the future per-`:contratos`-
2430    /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
2431    /// roadmap acknowledges).
2432    ///
2433    /// Prior to this lift the `.window` field was accessed inline at
2434    /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
2435    /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
2436    /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
2437    /// error-payload construction on refusal, and the two
2438    /// [`rate_limit_codec::render`] arms
2439    /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
2440    /// and non-canonical-window `rl.window.as_secs()` fallback). Three
2441    /// open-coded field-accesses that expressed no compile-time link
2442    /// back to the typed sub-struct axis. A future extension of the
2443    /// `:window` axis to a richer author surface — a per-`:contratos`-
2444    /// edge window override the operator pins through a future
2445    /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
2446    /// acknowledges, a per-cluster window-default overlay the M4 CR
2447    /// materializer resolves per-CR, a promotion of the plain
2448    /// `Duration` refill period to a richer
2449    /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
2450    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
2451    /// axis comes into scope, an addition of a `"d"` day suffix once
2452    /// Envoy's `rate_limit_action` grows daily-bucket support — would
2453    /// have had to be threaded through every open-coded copy in
2454    /// lockstep or the validate gate, the codec's render path, and
2455    /// the future M4 emit path would silently disagree on which
2456    /// refill period a given [`RateLimit`] resolves to (an author's
2457    /// `:rate-limit "100/s"` would satisfy validate while the render
2458    /// / emit paths silently read a drifted other value, or vice
2459    /// versa: a validated typed slot would land at the emit boundary
2460    /// as a limiter whose refill period is structurally so long that
2461    /// no realistic per-edge traffic shape stays inside the token
2462    /// budget). Lifting the resolution to a typed method on the
2463    /// substrate primitive means every downstream consumer of the
2464    /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
2465    /// reaches for exactly one typed dispatch — the resolver's
2466    /// accept-set migrates as a unit on any future axis addition.
2467    ///
2468    /// Second sub-struct scalar accessor on the `RateLimit` axis —
2469    /// sibling in shape to the just-landed [`RateLimit::rate`]
2470    /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
2471    /// required-axis, extended onto the per-sub-struct
2472    /// required-`Duration` axis; closes the last unlifted
2473    /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
2474    /// per-sub-struct accessor coverage is now complete across both
2475    /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
2476    /// the substrate primitive, thin projections at each consumer"
2477    /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
2478    /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
2479    /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
2480    /// (7f0fd43), [`WitContract::world_ref`] (0804823),
2481    /// [`Membro::nome`] (4a32abf),
2482    /// [`Membro::versao_requirement`] (a40b0e3),
2483    /// [`Entrada::destination`] (6db982c) accessors carry on their
2484    /// respective per-mesh-slot-atom scalar-value axes. Named
2485    /// `window()` to match the storage field's name; the accessor's
2486    /// identity maps onto the canonical MESH-COMPOSITION §III.2
2487    /// vocabulary the slot's docstring already carries.
2488    #[must_use]
2489    pub const fn window(&self) -> Duration {
2490        self.window
2491    }
2492
2493    /// Recognize this rate-limit's `:window` as a canonical
2494    /// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
2495    /// exactly matches one of the three closed-set arm-Durations
2496    /// (`1s` / `60s` / `3600s`), `None` when the window carries a
2497    /// non-canonical magnitude the codec's round-trip would break on
2498    /// (sub-second residue, or a second-magnitude outside the set
2499    /// [`RateLimitUnit::ALL`] enumerates).
2500    ///
2501    /// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
2502    /// returns `Some` here — the validate gate's
2503    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
2504    /// rejects every window this accessor returns `None` on. Downstream
2505    /// consumers past validate (the codec's [`rate_limit_codec::render`]
2506    /// path, the future M4 per-Aplicacao Envoy config reconciler's
2507    /// materialization pass, the future per-`:contratos`-edge rate-limit-
2508    /// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
2509    /// acknowledges) that read the typed unit off a validated slot can
2510    /// pattern-match on the returned `Some` without re-checking
2511    /// canonicality at the consumer layer — the typed enum surface is
2512    /// the load-bearing carrier of the canonicality invariant.
2513    ///
2514    /// Preferred over the free [`is_canonical_rate_limit_window`]
2515    /// module-private helper at any call site that has the typed
2516    /// [`RateLimit`] in hand (the codec's `render` arm at
2517    /// [`rate_limit_codec::render`], the validate gate's canonical-form
2518    /// arm in [`AplicacaoSpec::validate_politicas`], any future
2519    /// per-`:contratos` edge-override overlay resolver): those consumers
2520    /// reach for the typed enum without going through the
2521    /// `.window()` scalar-projection layer, and get the enum value
2522    /// directly (which the codec's render arm can then format via
2523    /// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
2524    /// "typed sub-struct scalar accessor, one dispatch on the substrate
2525    /// primitive" discipline the sibling [`RateLimit::rate`] and
2526    /// [`RateLimit::window`] accessors carry on the peer per-sub-struct
2527    /// scalar-value axes, extended onto the per-`RateLimit` typed-unit
2528    /// projection axis (the third scalar accessor on the [`RateLimit`]
2529    /// axis, first typed-enum-return projection).
2530    #[must_use]
2531    pub fn canonical_unit(&self) -> Option<RateLimitUnit> {
2532        RateLimitUnit::from_window(self.window)
2533    }
2534}
2535
2536/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
2537/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
2538/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
2539///
2540/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
2541/// the `:politicas :rate-limit` unit surface reads from
2542/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
2543/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
2544/// [`is_canonical_rate_limit_window`] predicate the
2545/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
2546/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
2547/// projection) now lives inside this typed enum's `match self` arms — a
2548/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
2549/// `rate_limit_action` grows daily-bucket support) is one new variant
2550/// plus the exhaustiveness arms on the four methods, so every consumer
2551/// picks it up by compile-time construction rather than a runtime
2552/// table-scan miss.
2553///
2554/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
2555/// scanned via `find_map` at every projection call — an untyped runtime
2556/// walk that carried no compile-time link between the parse arm's
2557/// accepted suffixes, the render arm's emitted suffixes, and the
2558/// validate gate's accepted windows. A future rate-limit-unit addition
2559/// that landed one row without threading through the other consumers
2560/// (or a copy-paste flip that collapsed two rows onto one suffix) would
2561/// silently split the accepted-set across the three consumers — the
2562/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
2563/// for a 24h window that parse can't round-trip, the validate gate
2564/// misses one canonical window. Lifting the pairs onto a typed
2565/// closed-set enum with exhaustive `match` arms makes any such
2566/// half-landed extension a caixa-core build error (the compiler enforces
2567/// arm coverage on every method), not a silent per-consumer drift
2568/// surfacing at apply time. Same "closed-set typed-enum discriminator"
2569/// discipline the sibling [`PlacementStrategy`] (cc8f749),
2570/// [`crate::supervisor::RestartStrategy`],
2571/// [`crate::supervisor::RestartPolicy`],
2572/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
2573/// closed-set typed enums carry on their respective closed-set axes —
2574/// extended onto the seventh closed-set typed-enum discriminator axis
2575/// on the caixa typed surface (the `:politicas :rate-limit :window`
2576/// canonical-unit axis).
2577#[derive(
2578    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
2579)]
2580pub enum RateLimitUnit {
2581    /// 1-second window — canonical author-surface suffix `"s"`
2582    /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
2583    /// with a 1s magnitude.
2584    Second,
2585    /// 1-minute window — canonical author-surface suffix `"m"`
2586    /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
2587    /// with a 60s magnitude.
2588    Minute,
2589    /// 1-hour window — canonical author-surface suffix `"h"`
2590    /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
2591    /// with a 3600s magnitude.
2592    Hour,
2593}
2594
2595impl RateLimitUnit {
2596    /// Exhaustive iteration surface for every consumer that reads the
2597    /// full canonical-unit set (the byte-parity witness against the
2598    /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
2599    /// webhook's accepted-suffix listing in its rejection body, any
2600    /// future round-trip fuzz harness). A future variant addition to
2601    /// [`RateLimitUnit`] extends this slice as a single edit and every
2602    /// consumer picks up the new entry by construction — the compiler-
2603    /// checked exhaustiveness on the sibling method `match` arms is the
2604    /// build-time guarantee that no arm forgets to grow.
2605    pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
2606
2607    /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
2608    /// string every `<n>/<unit>` rate-limit shape carries after its
2609    /// `/` separator. The single source of truth the codec's parse and
2610    /// render arms both dispatch on: the parse arm matches an incoming
2611    /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
2612    /// output; the render arm emits the entry's `as_suffix` verbatim
2613    /// after the rate magnitude.
2614    #[must_use]
2615    pub const fn as_suffix(self) -> &'static str {
2616        match self {
2617            Self::Second => "s",
2618            Self::Minute => "m",
2619            Self::Hour => "h",
2620        }
2621    }
2622
2623    /// Canonical `Duration` for this unit — the token-bucket refill
2624    /// period the [`RateLimit::window`] axis carries when the surrounding
2625    /// slot's `:rate-limit` author surface named this unit.
2626    #[must_use]
2627    pub const fn window(self) -> Duration {
2628        Duration::from_secs(match self {
2629            Self::Second => 1,
2630            Self::Minute => 60,
2631            Self::Hour => 3_600,
2632        })
2633    }
2634
2635    /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
2636    /// `None` when `suffix` is outside the closed-set arm-string set
2637    /// [`Self::as_suffix`] emits. The single `str → Self` projection
2638    /// [`rate_limit_codec::parse`] consumes.
2639    #[must_use]
2640    pub fn from_suffix(suffix: &str) -> Option<Self> {
2641        Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
2642    }
2643
2644    /// Recognize a canonical rate-limit `Duration` as one of the three
2645    /// arms, or `None` when `window` carries sub-second residue or a
2646    /// second-magnitude outside the closed-set arm-window set
2647    /// [`Self::window`] emits. The single `Duration → Self` projection
2648    /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
2649    /// both consume.
2650    #[must_use]
2651    pub fn from_window(window: Duration) -> Option<Self> {
2652        if window.subsec_nanos() != 0 {
2653            return None;
2654        }
2655        Self::ALL.iter().copied().find(|u| u.window() == window)
2656    }
2657}
2658
2659/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
2660/// every consumer that formats a canonical rate-limit unit as user-
2661/// facing text (future M4 admission-webhook rejection bodies naming
2662/// the accepted-suffix set, future `feira app graph` per-`:politicas`
2663/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
2664/// codec's parse arm accepts and the render arm emits. Same
2665/// as_str-through-Display convergence discipline the sibling
2666/// [`PlacementStrategy`], [`crate::CaixaKind`],
2667/// [`crate::supervisor::RestartStrategy`], and
2668/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
2669impl std::fmt::Display for RateLimitUnit {
2670    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2671        f.write_str(self.as_suffix())
2672    }
2673}
2674
2675/// Canonical rate-limit `Duration` for a unit suffix, or `None` when
2676/// the suffix isn't a [`RateLimitUnit`] arm's `as_suffix` output. Thin
2677/// delegate over [`RateLimitUnit::from_suffix`] composed with
2678/// [`RateLimitUnit::window`] — the sole consumer on the
2679/// `&'static str → Duration` axis ([`rate_limit_codec::parse`]) reads
2680/// this projection.
2681///
2682/// The peer `Duration → &'static str` axis (previously carried by the
2683/// module-private `rate_limit_window_unit` delegate) folded onto the
2684/// substrate primitive [`RateLimit::canonical_unit`] typed accessor once
2685/// both production consumers ([`rate_limit_codec::render`] and
2686/// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
2687/// migrated: the free helper's `Duration → &str` projection is now the
2688/// two-step composition `rl.canonical_unit().map(RateLimitUnit::as_suffix)`
2689/// every consumer reads through the typed accessor. The
2690/// [`&str → Duration`] axis here has no such accessor peer (the codec's
2691/// parse arm reads `&str` from the wire, not from a validated typed
2692/// slot), so this delegate stays as the single lifted projection every
2693/// wire-side consumer routes through.
2694#[must_use]
2695fn rate_limit_window_from_unit(unit: &str) -> Option<Duration> {
2696    RateLimitUnit::from_suffix(unit).map(RateLimitUnit::window)
2697}
2698
2699/// Upper-bound ceiling on the `:politicas :timeout` axis — every
2700/// validated [`MeshPolicy::timeout`] past
2701/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
2702/// (inclusive on both ends, integer-millisecond magnitudes by the
2703/// canonical-form gate immediately preceding).
2704///
2705/// The typed field is `Option<Duration>` (the zero-floor arm
2706/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
2707/// `Duration::ZERO`, and the canonical-form arm
2708/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
2709/// sub-millisecond residue), so a programmatic struct literal
2710/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
2711/// 24h) and the equivalent author-surface form
2712/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
2713/// integer-hour magnitude) both round-trip cleanly through serde — a
2714/// structurally unbounded `Duration` ceiling. A `:timeout` value far
2715/// above the documented production-playbook band (Envoy default `15s`,
2716/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
2717/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
2718/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
2719/// at `~3600s`) silently degenerates the mesh-policy contract: the
2720/// per-call deadline is structurally so long that no realistic
2721/// synchronous-`:contratos` traversal can reach it, so the typed slot
2722/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
2723/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
2724/// blocking" degenerates to a nominal-only contract on the
2725/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
2726/// the sibling `:politicas :retries` axis and the
2727/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
2728/// `:politicas :circuit-breaker :max-failures` axis — all three close
2729/// the "structurally unbounded ceiling on a typed `:politicas` axis"
2730/// footgun the prior zero-floor-and-canonical-form-only checks left
2731/// open.
2732///
2733/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
2734/// shared duration codec emits (`"<n>h"` for any integer-hour
2735/// magnitude) — every value in the canonical authoring form's
2736/// `<integer><unit>` grammar at or below this cap renders to a clean
2737/// canonical string. The cap sits an order of magnitude above every
2738/// documented production-playbook recommendation band (Envoy default
2739/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
2740/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
2741/// configured maximum (`proxy_read_timeout` typical max `3600s`),
2742/// below the clearly-pathological "effectively no timeout" floor
2743/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
2744/// want for a long-running synchronous workflow, but a hard wall above
2745/// which the mesh-level deadline is structurally a non-deadline.
2746/// Lifted as a typed `pub const` so the bound has exactly one source
2747/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
2748/// materializer's admission webhook and the caixa-mesh-side
2749/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2750/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
2751/// other typed upper bound in this crate carries
2752/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
2753/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2754/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2755/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2756pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
2757
2758/// Upper-bound ceiling on the `:politicas :retries` axis — every
2759/// validated [`MeshPolicy::retries`] past
2760/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
2761///
2762/// The typed slot is `Option<u32>` (`None` = no retries on transient
2763/// failure; `Some(0)` already rejected by the
2764/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
2765/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
2766/// .. }`) and the equivalent author-surface form
2767/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
2768/// serde / the codec — a structurally unbounded `u32` ceiling. The
2769/// runtime substrate that consumes the value (Envoy's
2770/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
2771/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
2772/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
2773/// admission cap is 10) translates a four-billion-retry policy into a
2774/// thundering-herd amplification vector on transient failure — the
2775/// caller's one request fans out to `retries` server-side calls per
2776/// edge per traversal, multiplying load by `(retries+1)^depth` across
2777/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
2778/// invariant "no infinite blocking" pairs with a no-runaway-amplification
2779/// invariant on the retry axis; both belong at the typed-slot layer.
2780///
2781/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
2782/// upstream mesh-policy schema that documents one) and sits above the
2783/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
2784/// every documented production playbook): a value the author can
2785/// plausibly want, but a hard wall above which the policy is
2786/// structurally a footgun. Lifted as a typed `pub const` so the bound
2787/// has exactly one source of truth — a future axis reaching for the
2788/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
2789/// materializer's admission webhook, the caixa-mesh-side
2790/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
2791/// one place. Same shape every other typed upper bound in this crate
2792/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2793/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2794/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
2795/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2796pub const POLICY_RETRIES_MAX: u32 = 10;
2797
2798/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
2799/// axis — every validated [`CircuitBreaker::max_failures`] past
2800/// [`AplicacaoSpec::validate_politicas`] lies in
2801/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
2802///
2803/// The typed field is `u32` (the zero-floor arm
2804/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
2805/// `0` — a breaker that trips on the first call), so a programmatic
2806/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
2807/// and the equivalent author-surface form
2808/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
2809/// cleanly through serde — a structurally unbounded `u32` ceiling. A
2810/// `max_failures` value far above the documented production-playbook
2811/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
2812/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
2813/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
2814/// typical 5–50) silently disables the breaker's protection role:
2815/// the threshold is structurally so high that no realistic
2816/// failures-per-`:window` traffic shape can reach it, so the breaker
2817/// never trips and the typed slot becomes a no-op carried on every
2818/// emitted Envoy / Cilium L7 overlay. Pairs with the
2819/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
2820/// axis — both close the "structurally unbounded `u32` ceiling on a
2821/// typed policy axis" footgun the prior zero-floor-only checks left
2822/// open.
2823///
2824/// The `1000` ceiling sits an order of magnitude above every
2825/// documented upstream production-playbook recommendation band (the
2826/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
2827/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
2828/// the clearly-pathological "effectively no protection"
2829/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
2830/// plausibly want at hyperscale, but a hard wall above which the
2831/// policy is structurally a no-op. Lifted as a typed `pub const` so
2832/// the bound has exactly one source of truth — the future M4
2833/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
2834/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
2835/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
2836/// one place. Same shape every other typed upper bound in this crate
2837/// carries ([`POLICY_RETRIES_MAX`],
2838/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2839/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2840/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2841pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
2842
2843/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
2844/// every validated [`CircuitBreaker::window`] past
2845/// [`AplicacaoSpec::validate_politicas`] lies in
2846/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
2847/// integer-millisecond magnitudes by the canonical-form gate
2848/// immediately preceding).
2849///
2850/// The typed field is `Duration` (the zero-floor arm
2851/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
2852/// `Duration::ZERO`, and the canonical-form arm
2853/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
2854/// sub-millisecond residue), so a programmatic struct literal
2855/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
2856/// and the equivalent author-surface form
2857/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
2858/// integer-hour magnitude) both round-trip cleanly through serde — a
2859/// structurally unbounded `Duration` ceiling. A `:window` value far
2860/// above the documented production-playbook band (Hystrix
2861/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
2862/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
2863/// Istio `outlierDetection.interval` default `10s`, Envoy
2864/// `outlier_detection.interval` default `10s`, AWS App Mesh
2865/// circuit-breaker time-window typical `30s..=300s`) degenerates the
2866/// breaker's role: a rolling-window failure counter whose window is
2867/// hours long is operationally a lifetime counter, the breaker's
2868/// "recent failures" memory is structurally so long that transient
2869/// failures are never forgotten, and the typed slot becomes a no-op
2870/// trigger that trips once and stays tripped for the lifetime of the
2871/// component carried on every emitted Envoy / Cilium L7 overlay.
2872///
2873/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
2874/// shared duration codec emits (`"<n>h"` for any integer-hour
2875/// magnitude) — every value in the canonical authoring form's
2876/// `<integer><unit>` grammar at or below this cap renders to a clean
2877/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
2878/// cap on the first typed-`Duration` `:politicas` axis: the two
2879/// duration-typed `:politicas` axes now share a single uniform top
2880/// edge so the next typed-slot wiring (the future caixa-mesh
2881/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
2882/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
2883/// admission webhook) reaches for either field knowing the value is
2884/// in `1ms..=1h` without re-validating at the renderer layer. The cap
2885/// sits two orders of magnitude above every documented upstream
2886/// production-playbook recommendation band (Hystrix / resilience4j /
2887/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
2888/// and below the clearly-pathological "rolling window degenerates to
2889/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
2890/// author can plausibly want for a very-low-traffic long-tail
2891/// failure-detection window, but a hard wall above which the breaker's
2892/// rolling-window contract is structurally a lifetime-counter contract.
2893/// Lifted as a typed `pub const` so the bound has exactly one source
2894/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
2895/// materializer's admission webhook and the caixa-mesh-side
2896/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2897/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
2898/// other typed upper bound in this crate carries
2899/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
2900/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
2901/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2902/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2903/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2904pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
2905
2906/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
2907/// every validated [`RateLimit::rate`] past
2908/// [`AplicacaoSpec::validate_politicas`] lies in
2909/// `1..=POLICY_RATE_LIMIT_MAX`.
2910///
2911/// The typed field is `u32` (the zero-floor arm
2912/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
2913/// zero-rate limit denies every request, the canonical "I forgot
2914/// that 0 means deny-everything" footgun), so a programmatic struct
2915/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
2916/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
2917/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
2918/// round-trip cleanly through serde — a structurally unbounded `u32`
2919/// ceiling. The runtime substrate consuming the value (Envoy's
2920/// `local_rate_limit.token_bucket.max_tokens`, the future
2921/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2922/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
2923/// rate-limit into a no-op rate-limiter: the bucket capacity is
2924/// structurally so high no realistic per-edge traffic shape can
2925/// drain it, the limiter never trips, and the typed slot becomes a
2926/// "rate-limit declared, no enforcement" footgun — the canonical
2927/// declared-but-inert shape every other `:politicas` cap arm
2928/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
2929/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
2930///
2931/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
2932/// above every documented upstream production-playbook recommendation
2933/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
2934/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
2935/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
2936/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
2937/// `limit_req_zone` typical `1..=1_000` RPS) and below the
2938/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
2939/// `u32::MAX`): a value the author can plausibly want at hyperscale
2940/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
2941/// /h-window arm), but a hard wall above which the policy is
2942/// structurally a no-op carried verbatim on every emitted Envoy /
2943/// Cilium L7 overlay. The cap brackets all three canonical windows
2944/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
2945/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
2946/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
2947/// per-endpoint API band). Lifted as a typed `pub const` so the bound
2948/// has exactly one source of truth — the future M4
2949/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
2950/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
2951/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
2952/// one place. Same shape every other typed upper bound in this crate
2953/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
2954/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
2955/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2956/// [`crate::LIMITS_WALL_CLOCK_MAX`],
2957/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2958/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2959pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
2960
2961// `:entrada :host` total-length and per-label cap axes route through
2962// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
2963// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
2964// pair of aplicacao-private aliases the previous `validate_entrada_host`
2965// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
2966// = 63`) were structurally the same K8s Gateway API v1 Hostname
2967// admission-schema bounds — the total-length cap on the OpenAPI
2968// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
2969// same regex — that the peer axes at the caixa-core::render level pin,
2970// so hoisting both readers onto the shared lifted constants closes the
2971// third-occurrence duplication threshold structurally: the M4
2972// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
2973// label validator, the future per-`Certificate` SAN emitter, and every
2974// other per-Gateway-API-Hostname landing site reach the same one place
2975// as the `:entrada :host` gate does — no per-axis alias drift surface
2976// between them, by construction.
2977
2978/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
2979/// extractor expression — the upper bound `validate_placement_shard_key`
2980/// enforces on every well-shaped shard-key past validate. The realistic
2981/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
2982/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
2983/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
2984/// `:placement :affinity` / `:placement :clusters` identifier-shaped
2985/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
2986/// in `:shard-key`" footgun at validate time rather than at the future
2987/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
2988const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
2989
2990/// Reject `:membros :caixa` values the K8s apiserver would refuse at
2991/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
2992/// that maps the shared parser-shaped reason into the
2993/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
2994/// is self-locating (the offending `caixa:` is named verbatim) and
2995/// the author can grep their caixa.lisp for `:caixa "<name>"` and
2996/// fix it in one edit. Same diagnostic shape as
2997/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
2998/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
2999fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
3000    // Empty is already gated by `MembroCaixaEmpty` at the call site;
3001    // re-checking here keeps the predicate usable from any future
3002    // call site (the M4 CR materializer) without an empty-check
3003    // footgun. The shared
3004    // [`crate::render::require_valid_dns_1123_label`] helper brackets
3005    // the empty-first + shape cascade every peer name axis
3006    // (`:placement :clusters`, `:placement :affinity`, `:contratos
3007    // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
3008    // `:upgrade-from :module`) routes through, so drift between the
3009    // eight axes' accepted DNS-1123-label sets is structurally
3010    // impossible.
3011    crate::render::require_valid_dns_1123_label(
3012        caixa,
3013        || AplicacaoError::MembroCaixaEmpty,
3014        |reason| AplicacaoError::MembroCaixaInvalid {
3015            caixa: caixa.to_string(),
3016            reason,
3017        },
3018    )
3019}
3020
3021/// Reject `:placement :clusters` entries the K8s apiserver would refuse
3022/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3023/// that maps the shared parser-shaped reason into the
3024/// [`AplicacaoError::PlacementClusterInvalid`] variant.
3025///
3026/// Cluster names land in DNS-1123-label territory across every consumer:
3027/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
3028/// the `lareira-fleet-programs` aggregator applies to scope programs to
3029/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
3030/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
3031/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
3032/// cluster identity the M4 CR materializer round-trips. Each apiserver-
3033/// side schema enforces the DNS-1123 label rule on admission; a
3034/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
3035/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
3036/// mistaken-identity slug) silently passes the prior empty-/duplicate-
3037/// only gate and the failure surfaces as a no-match at filter time —
3038/// the workload doesn't land in the named cluster, with no diagnostic
3039/// naming the offending `:clusters` entry. Lifting the gate to caixa-
3040/// build time mirrors the `:membros :caixa` value-shape trajectory
3041/// (3f9d7a0) on the peer name axis.
3042///
3043/// The diagnostic carries the offending `cluster:` verbatim plus a
3044/// parser-shaped `reason:` naming the specific violation, so the
3045/// author can grep their caixa.lisp for `:clusters` and fix it in
3046/// one edit. Same diagnostic shape as
3047/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
3048fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
3049    // Empty is already gated by `PlacementClusterEmpty` at the call
3050    // site; re-checking here keeps the predicate usable from any
3051    // future call site (the M4 CR materializer's per-cluster validator)
3052    // without an empty-check footgun. Routes through the shared
3053    // [`crate::render::require_valid_dns_1123_label`] gate the peer
3054    // name axes each land on.
3055    crate::render::require_valid_dns_1123_label(
3056        cluster,
3057        || AplicacaoError::PlacementClusterEmpty,
3058        |reason| AplicacaoError::PlacementClusterInvalid {
3059            cluster: cluster.to_string(),
3060            reason,
3061        },
3062    )
3063}
3064
3065/// Reject `:placement :affinity` hints whose shape can never legitimately
3066/// land in any downstream selector or label-keyed routing axis. Thin
3067/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
3068/// shared parser-shaped reason into the
3069/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
3070/// diagnostic is self-locating (the offending `:affinity` is named
3071/// verbatim) and the author can grep their caixa.lisp for
3072/// `:affinity "<hint>"` and fix it in one edit.
3073///
3074/// The `:affinity` slot carries a placement-engine hint — canonical
3075/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
3076/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
3077/// compression overlay and the future M4 placement-engine's per-hint
3078/// routing axis. Each downstream consumer (caixa-mesh's
3079/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
3080/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3081/// `spec.placement.affinity` admission rule, the future M4 per-hint
3082/// node-affinity / pod-affinity rule generator keying off the same
3083/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
3084/// selector) requires the value to be a DNS-1123 label — K8s label
3085/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
3086/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
3087/// admission rule the apiserver enforces.
3088///
3089/// Until this gate landed an `:affinity "DataLocality"` (the canonical
3090/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
3091/// Python-module-name leak), `:affinity "data.locality"` (the
3092/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
3093/// `:affinity "data-locality-"` (boundary-hyphen violation),
3094/// `:affinity "data locality"` (paste-from-doc whitespace),
3095/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
3096/// 64-byte over-cap slug silently passed the empty-only check and the
3097/// failure surfaced as a no-match at the M3 Adaptive compression
3098/// overlay's filter time (`placement.affinity` carried a malformed
3099/// value, no node matched, the workload landed on the default
3100/// heuristic) — the canonical "declared-but-inert" footgun mirroring
3101/// the empty-:affinity / empty-shard-key / zero-:politicas /
3102/// empty-:contratos-target gates already close on every other
3103/// declare-but-no-opinion axis. Lifting the rejection to a build-time
3104/// gate closes the fifth typed slot on the Aplicacao surface to land
3105/// on the canonical DNS-1123 label floor (after the four Servico-name
3106/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
3107/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
3108/// b0e8748).
3109///
3110/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
3111/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
3112/// validated values are guaranteed-accepted by the apiserver without
3113/// re-validation at any downstream renderer or admission layer.
3114fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
3115    // Empty is gated separately at the call site for a self-locating
3116    // diagnostic; re-checking here keeps the predicate usable from any
3117    // future call site (the M4 CR materializer's per-affinity
3118    // validator) without an empty-check footgun. Routes through the
3119    // shared [`crate::render::require_valid_dns_1123_label`] gate the
3120    // peer name axes each land on.
3121    crate::render::require_valid_dns_1123_label(
3122        affinity,
3123        || AplicacaoError::PlacementAffinityEmpty,
3124        |reason| AplicacaoError::PlacementAffinityInvalid {
3125            affinity: affinity.to_string(),
3126            reason,
3127        },
3128    )
3129}
3130
3131/// Reject `:placement :shard-key` extractor expressions whose shape can
3132/// never legitimately drive the future M4 Akka-style cluster-sharding
3133/// reconciler's hash-extractor pass. Maps the per-byte / length checks
3134/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
3135/// diagnostic is self-locating (the offending `:shard-key` value is
3136/// named verbatim alongside the parser-shaped reason) and the author can
3137/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
3138/// edit.
3139///
3140/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
3141/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
3142/// expression naming the message property to hash on. The realistic
3143/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
3144/// property name; `$tenantId` — Akka entity-id placeholder;
3145/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
3146/// `${tenant}` — interpolation-style template) all sit in the printable
3147/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
3148/// multi-line blob landing in `:shard-key`, an embedded space from a
3149/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
3150/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
3151/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
3152/// check and the failure surfaces at the future M4 reconciler's hash
3153/// pass as a runtime extractor-evaluation error far from the source
3154/// `caixa.lisp`, with no field naming which member's `:shard-key`
3155/// carried the offending value.
3156///
3157/// The contract — the printable ASCII single-token intersection-floor
3158/// every Akka-style entity-id extractor implementation admits:
3159///
3160///   - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
3161///     peer DNS-1123-label-shaped `:placement :affinity` /
3162///     `:placement :clusters` identifier axes; realistic shard-keys sit
3163///     well under 32 bytes, the cap surfaces paste-from-doc multi-line
3164///     blob footguns at validate time;
3165///   - every byte in the printable ASCII range `0x21..=0x7E` —
3166///     rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
3167///     `"$tenantId\n"` from paste-from-aligned-doc /
3168///     paste-from-shell-heredoc), control characters (`\x00..\x1F`,
3169///     `\x7F` — the canonical "embedded null from a copy-paste-binary
3170///     footgun"), and non-ASCII bytes (`"$tenàntId"` —
3171///     un-Punycode-encoded IDN that round-trips inconsistently across
3172///     NFC/NFD normalization).
3173///
3174/// The accepted set is broader than the DNS-1123 label floor the peer
3175/// `:placement :clusters` / `:placement :affinity` axes use because the
3176/// `:shard-key` value is not a K8s `metadata.name` / label-selector
3177/// landing site; it's an extractor expression the future Akka-style
3178/// reconciler reads as a property reference. The realistic forms
3179/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
3180/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
3181/// but every Akka-style entity-id extractor parses. The
3182/// printable-ASCII-token floor accepts every shape any such extractor
3183/// would accept while rejecting the cross-implementation footguns
3184/// (whitespace breaks token boundaries; non-ASCII round-trips
3185/// inconsistently across YAML emitters and NFC/NFD normalization;
3186/// control characters silently corrupt the next read).
3187///
3188/// Until this gate landed `validate_placement` only refused the
3189/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
3190/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
3191/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
3192/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
3193/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
3194/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
3195/// control character from paste-from-binary, the 64-byte over-cap
3196/// paste-from-doc multi-line slug) silently passed validate. The future
3197/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
3198/// would then surface the malformed value either as a runtime
3199/// extractor-evaluation error (whitespace breaks the extractor's token
3200/// boundary, no match) or as a silently-different shard assignment
3201/// across YAML emitters (non-ASCII normalizes differently between the
3202/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
3203/// parser, the same entity ID maps to two distinct shards on a
3204/// re-render). Lifting the shape gate to caixa-build time makes the
3205/// extractor-floor invariant a structural property of every validated
3206/// `Placement`: every `Sharded` placement past `validate_placement` has
3207/// a `:shard-key` the future M4 reconciler can hash without
3208/// re-validating at the runtime layer.
3209///
3210/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
3211/// [`AplicacaoError::ContratoSubjectInvalid`] /
3212/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
3213/// on the peer `:contratos` payload axes — each lifts the
3214/// runtime-side parser's intersection-floor to a caixa-build-time gate,
3215/// closing the canonical "this passed validate but the runtime parser
3216/// rejected it" surprise.
3217fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
3218    // Empty is gated separately at the call site via the more
3219    // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
3220    // re-checking here keeps the predicate usable from any future call
3221    // site (the M4 CR materializer's per-shard-key validator) without
3222    // an empty-check footgun.
3223    if key.is_empty() {
3224        return Err(AplicacaoError::ShardedKeyEmpty);
3225    }
3226    if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
3227        return Err(AplicacaoError::ShardKeyInvalid {
3228            shard_key: key.to_string(),
3229            reason: format!(
3230                "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
3231                 (got {} bytes; realistic Akka-style entity-id extractor expressions \
3232                 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
3233                 well under 32 bytes, this length suggests a paste-from-doc \
3234                 multi-line blob landed in `:shard-key` instead of a single-token \
3235                 extractor expression)",
3236                key.len()
3237            ),
3238        });
3239    }
3240    for &b in key.as_bytes() {
3241        if (0x21..=0x7E).contains(&b) {
3242            continue;
3243        }
3244        let reason = if b == b' ' {
3245            "contains a space (Akka-style entity-id extractor expressions are \
3246             single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
3247             whitespace breaks the extractor's token boundary at the runtime layer, \
3248             and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
3249             a multi-token blob in one `:shard-key` slot)"
3250                .to_string()
3251        } else if b == b'\t' {
3252            "contains a tab character (paste-from-aligned-doc footgun; the \
3253             Akka-style entity-id extractor reads `:shard-key` as a single-token \
3254             reference, embedded whitespace breaks the token boundary at the \
3255             runtime hash-extractor pass)"
3256                .to_string()
3257        } else if b == b'\n' || b == b'\r' {
3258            format!(
3259                "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
3260                 paste-from-multiline-doc footgun; the Akka-style entity-id \
3261                 extractor reads `:shard-key` as a single-token reference, embedded \
3262                 newlines either truncate the value at the YAML emitter layer or \
3263                 break the token boundary at the runtime hash-extractor pass)"
3264            )
3265        } else if b < 0x20 || b == 0x7F {
3266            format!(
3267                "contains control character 0x{b:02x} (the canonical \
3268                 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
3269                 control characters silently corrupt round-trip serialization \
3270                 across YAML emitters and break the runtime hash-extractor's \
3271                 single-token parser)"
3272            )
3273        } else {
3274            format!(
3275                "contains non-ASCII byte 0x{b:02x} (the canonical \
3276                 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
3277                 inconsistently across NFC/NFD normalization on APFS / ext4 / \
3278                 across YAML emitter implementations — the same entity ID can \
3279                 silently map to two distinct shards on a re-render. Use a \
3280                 printable-ASCII extractor expression like `tenantId`, \
3281                 `$tenantId`, or `metadata.tenantId`)"
3282            )
3283        };
3284        return Err(AplicacaoError::ShardKeyInvalid {
3285            shard_key: key.to_string(),
3286            reason,
3287        });
3288    }
3289    Ok(())
3290}
3291
3292/// Reject `:contratos :de` / `:contratos :para` values whose shape
3293/// can never legitimately match a validated `:membros :caixa`. Thin
3294/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
3295/// shared parser-shaped reason into the
3296/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
3297/// diagnostic is self-locating (which slot — `:de` or `:para` — and
3298/// the offending value verbatim) and the author can grep their
3299/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
3300/// one edit.
3301///
3302/// Until this gate landed an empty or DNS-1123-malformed `:de` /
3303/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
3304/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
3305/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
3306/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
3307/// un-Punycode-encoded IDN) silently passed the per-axis check and
3308/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
3309/// membership lookup — diagnostic-framed as "this caixa is not in
3310/// `:membros`" when the root cause is "this `:de` value is not a
3311/// well-shaped Servico-name identifier and could never legitimately
3312/// match any validated member". Because every `:membros :caixa` is
3313/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
3314/// `names` HashSet structurally never contains an empty / malformed
3315/// string, so the membership lookup arm misframes every empty /
3316/// malformed input. Lifting the shape arm ahead of the lookup
3317/// preserves the legitimate `ContratoMemberMissing` arm (a
3318/// well-shaped `:de` that simply isn't in `:membros` — a phantom
3319/// reference) while routing every structurally-impossible-to-match
3320/// input through the narrower self-locating shape diagnostic.
3321///
3322/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
3323/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
3324/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
3325/// to land on the canonical [`crate::render::is_dns_1123_label`]
3326/// floor. The `slot: &'static str` field carries the kebab-case
3327/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
3328/// per-callback-slot diagnostic shape and the
3329/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
3330/// (85f102c) cross-list-tag pattern.
3331fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
3332    // Routes through the shared
3333    // [`crate::render::require_valid_dns_1123_label`] gate the peer
3334    // name axes each land on. The `slot: &'static str` field flows
3335    // through both error variants so the diagnostic names which
3336    // per-edge axis (`:de` vs `:para`) the offending value came from.
3337    crate::render::require_valid_dns_1123_label(
3338        caixa,
3339        || AplicacaoError::ContratoCaixaEmpty { slot },
3340        |reason| AplicacaoError::ContratoCaixaInvalid {
3341            slot,
3342            caixa: caixa.to_string(),
3343            reason,
3344        },
3345    )
3346}
3347
3348/// Reject `:entrada :para` values whose shape can never legitimately
3349/// match a validated `:membros :caixa`. Thin wrapper around
3350/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
3351/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
3352/// variant, so the diagnostic is self-locating (the offending
3353/// `:entrada :para` value is named verbatim) and the author can grep
3354/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
3355///
3356/// Until this gate landed an empty or DNS-1123-malformed `:entrada
3357/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
3358/// ADR typo, `:para "my_cart"` the Python-module-name leak,
3359/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
3360/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
3361/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
3362/// silently passed the per-axis check and surfaced as
3363/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
3364/// — diagnostic-framed as "this caixa is not in `:membros`" when the
3365/// root cause is "this `:entrada :para` value is not a well-shaped
3366/// Servico-name identifier and could never legitimately match any
3367/// validated member". Because every `:membros :caixa` is shape-
3368/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
3369/// `HashSet` structurally never contains an empty / malformed string,
3370/// so the membership lookup arm misframes every empty / malformed
3371/// input. Lifting the shape arm ahead of the lookup preserves the
3372/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
3373/// simply isn't in `:membros` — a phantom reference) while routing
3374/// every structurally-impossible-to-match input through the narrower
3375/// self-locating shape diagnostic.
3376///
3377/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
3378/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
3379/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
3380/// fourth and last Aplicacao-level Servico-name reference axis to
3381/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
3382/// No `slot: &'static str` field because there is only one axis
3383/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
3384/// the simpler shape mirrors [`validate_membro_caixa`] and
3385/// [`validate_placement_cluster`].
3386fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
3387    // Empty is gated separately at the call site for a self-locating
3388    // diagnostic; re-checking here keeps the predicate usable from any
3389    // future call site (the M4 CR materializer's per-`:entrada`
3390    // validator) without an empty-check footgun. Routes through the
3391    // shared [`crate::render::require_valid_dns_1123_label`] gate the
3392    // peer name axes each land on.
3393    crate::render::require_valid_dns_1123_label(
3394        para,
3395        || AplicacaoError::EntradaParaEmpty,
3396        |reason| AplicacaoError::EntradaParaInvalid {
3397            para: para.to_string(),
3398            reason,
3399        },
3400    )
3401}
3402
3403/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
3404/// would refuse at admission time. The contract — exactly the regex
3405/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
3406/// and `HTTPRoute.spec.hostnames[]`,
3407/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
3408/// (max length 253; per-label max length 63):
3409///
3410///   - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
3411///     uppercase, no underscore, no Unicode/IDN — IDN must be
3412///     pre-encoded as Punycode `xn--…` by the author);
3413///   - exactly one optional leading wildcard label (`*.`); a wildcard
3414///     in any non-leading label position is rejected;
3415///   - each `.`-separated label is 1..=63 bytes, with non-hyphen
3416///     alphanumeric at both boundaries (no `-foo`, no `foo-`);
3417///   - total length 1..=253 bytes;
3418///   - no IPv4 literal (Gateway API forbids IP literals);
3419///   - no scheme (`https://`, `http://`), no port (`:8080`), no
3420///     whitespace, no path (`/`).
3421///
3422/// Lifted as a typed gate (rather than an inline cascade in
3423/// `validate()`) so the contract lives in one place — every future
3424/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3425/// materializer's host validator, the future per-`:entrada` SAN
3426/// emission for cert-manager Certificates, the multi-`:entrada`
3427/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
3428/// for the same predicate, not its own. Same compounding shape as
3429/// `is_canonical_rate_limit_window` (808017c) and
3430/// [`WitTarget::label`] (previously the free `contrato_target_label`
3431/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
3432/// per-variant label match is compiler-checked-exhaustive).
3433///
3434/// The diagnostic carries the offending `host:` verbatim plus a
3435/// parser-shaped `reason:` naming the specific violation, so the
3436/// author can grep their caixa.lisp for `:host "<host>"` and fix it
3437/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
3438/// (9888b13).
3439fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
3440    // Empty is already gated by `EmptyEntradaHost` at the call site;
3441    // re-checking here keeps the predicate usable from any future
3442    // call site (M4 CR materializer) without an empty-check footgun.
3443    if host.is_empty() {
3444        return Err(AplicacaoError::EmptyEntradaHost);
3445    }
3446    if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
3447        return Err(AplicacaoError::EntradaHostInvalid {
3448            host: host.to_string(),
3449            reason: format!(
3450                "exceeds Gateway API v1 Hostname max length of {cap} bytes \
3451                 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
3452                host.len(),
3453                cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
3454            ),
3455        });
3456    }
3457    if host.contains("://") {
3458        return Err(AplicacaoError::EntradaHostInvalid {
3459            host: host.to_string(),
3460            reason: "must not carry a scheme (drop the `https://` or `http://` prefix; \
3461                     Gateway API takes the bare hostname)"
3462                .to_string(),
3463        });
3464    }
3465    if host.contains('/') {
3466        return Err(AplicacaoError::EntradaHostInvalid {
3467            host: host.to_string(),
3468            reason: "must not carry a path (drop the `/…` suffix; Gateway API path \
3469                     matching is in `:entrada :paths`)"
3470                .to_string(),
3471        });
3472    }
3473    // After the `://` scheme-prefix and `/` path arms have ruled out the
3474    // two `:`-bearing shapes the Gateway API actively rejects with
3475    // location-shaped diagnostics, any remaining `:` in the host body is
3476    // either the canonical "I put the port in the `:host` slot"
3477    // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
3478    // slot lives one axis away on the same `:entrada` block) or an
3479    // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
3480    // Hostname forbids identically to the IPv4-literal arm below. Both
3481    // shapes silently fell through the `://` and `/` arms before this
3482    // lift and surfaced as a deep `label "<rest>:<port>" contains
3483    // invalid character ':'` diagnostic from the per-byte loop near the
3484    // bottom of this predicate, which named the offending byte but not
3485    // the canonical authoring fix — for the port case the author has to
3486    // know the `:entrada` block carries a separate `:port u16` slot
3487    // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
3488    // move the value over; for the IPv6 case the author has to know
3489    // Gateway API v1 forbids IP literals across the board. The contract
3490    // doc-comment above already promises "no port (`:8080`)" verbatim
3491    // in the rejected-shape enumeration but the predicate's
3492    // implementation refused the `:` only as a side-effect of the
3493    // per-label `[a-z0-9-]` character-class loop; this arm brings the
3494    // implementation in line with the documented contract by surfacing
3495    // the canonical fix at the top-level shape gate, peer with how the
3496    // `://` arm names the scheme prefix and the `/` arm names the
3497    // `:entrada :paths` axis. Same compounding trajectory the recent
3498    // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
3499    // — the typed slot's rejected set matches the apiserver's rejected
3500    // set, structurally, with a self-locating diagnostic at the
3501    // offending axis instead of a deep parser-shape leak.
3502    if host.contains(':') {
3503        return Err(AplicacaoError::EntradaHostInvalid {
3504            host: host.to_string(),
3505            reason: "must not contain `:` (the port belongs in the `:entrada :port` \
3506                     slot — a separate `u16` axis on the same `:entrada` block, \
3507                     defaulting to 8080 — not in the host body; drop the `:<port>` \
3508                     suffix and author the bare hostname. If you intended an IPv6 \
3509                     literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
3510                     Hostname forbids IP literals identically to the IPv4-literal \
3511                     arm — use a DNS name)"
3512                .to_string(),
3513        });
3514    }
3515    // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
3516    // predicate — the same single source of truth every peer
3517    // ASCII-whitespace scan in caixa-core flows through: the four
3518    // typed-magnitude codec sites (`limits::parse_byte_size` backing
3519    // `:limits :memory`, `limits::parse_duration` backing `:limits
3520    // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
3521    // `aplicacao::rate_limit_codec::parse` backing `:politicas
3522    // :rate-limit`) and the shared duration codec
3523    // (`supervisor::duration_codec::parse`) backing `:supervisor
3524    // :restart-window` / `:politicas :timeout` / `:politicas
3525    // :circuit-breaker :window`. This landing closes the last string-typed
3526    // slot in caixa-core still calling `.bytes().any(|b|
3527    // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
3528    // across every typed slot now shares one predicate, so a future
3529    // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
3530    // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
3531    // deliberately excluded from the peer non-ASCII predicate) can
3532    // extend at this shared site in one edit rather than seven
3533    // independent scans diverging over time. Naming the offending byte
3534    // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
3535    // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
3536    // the offending byte verbatim" discipline every peer codec site
3537    // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
3538    // / `supervisor.rs:823` / `aplicacao.rs:1640`).
3539    if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
3540        return Err(AplicacaoError::EntradaHostInvalid {
3541            host: host.to_string(),
3542            reason: format!(
3543                "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
3544                 Hostname is a single-token DNS name — leading, trailing, \
3545                 or embedded whitespace breaks the K8s apiserver's Hostname \
3546                 regex at admission time; the paste-from-aligned-doc / \
3547                 paste-from-shell-history / paste-from-CSV footgun silently \
3548                 lands a multi-token blob in `:entrada :host`. Strip every \
3549                 whitespace byte and author the bare hostname — space \
3550                 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
3551                 refuse identically)"
3552            ),
3553        });
3554    }
3555    // Peer of the ASCII-whitespace scan above: route the non-ASCII
3556    // subset of Unicode `White_Space` through the shared
3557    // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
3558    // single source of truth every peer non-ASCII-whitespace scan in
3559    // caixa-core flows through: `limits::parse_byte_size` (`:limits
3560    // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
3561    // `limits::parse_millicores` (`:limits :cpu`),
3562    // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
3563    // and `supervisor::duration_codec::parse` (`:supervisor
3564    // :restart-window` / `:politicas :timeout` / `:politicas
3565    // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
3566    // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
3567    // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
3568    // paste-from-web-doc), or an EM-SPACE-split host
3569    // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
3570    // survived this predicate's ASCII byte-scan (none of the UTF-8
3571    // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
3572    // `u8::is_ascii_whitespace`), then landed on the per-label
3573    // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
3574    // predicate with the generic `label "…" must start and end with an
3575    // alphanumeric` diagnostic — a "far from source at build-time"
3576    // leak that names the label-shape violation but not the
3577    // paste-from-typography origin the author actually needs to fix.
3578    // Peer with the four codec sites the 1b75b38 landing pinned: the
3579    // typed slot's diagnostic axis names the offending codepoint
3580    // (`U+XXXX`) verbatim rather than laundering the value through a
3581    // downstream label-shape arm, so the author can grep their
3582    // caixa.lisp for the invisible codepoint at the surfaced position
3583    // rather than eyeball a multi-byte host for embedded NBSP / LINE
3584    // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
3585    // discipline the peer ASCII-whitespace arm (720ac3b) carries:
3586    // drift between any two typed-slot sites' non-ASCII-whitespace
3587    // rejection set becomes a single-edit fix at the shared predicate
3588    // rather than N independent inline scans diverging over time, and
3589    // a future stricter classification (BOM `\u{FEFF}` / ZWSP
3590    // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
3591    // `char::is_whitespace`" class the peer non-ASCII predicate's
3592    // doc-comment names as the follow-up trajectory) extends at the
3593    // shared predicate in one edit rather than seven.
3594    if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
3595        return Err(AplicacaoError::EntradaHostInvalid {
3596            host: host.to_string(),
3597            reason: format!(
3598                "contains non-ASCII Unicode whitespace character {ch:?} \
3599                 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
3600                 single-token DNS name limited to `[a-z0-9-]` labels; \
3601                 the paste-from-typography footgun silently lands an \
3602                 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
3603                 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
3604                 `U+3000`, and every other member of the Unicode \
3605                 `White_Space` property outside the ASCII byte range) \
3606                 in `:entrada :host`, which the K8s apiserver's \
3607                 Hostname regex refuses at admission time far from the \
3608                 caixa.lisp source line. Strip every non-ASCII \
3609                 whitespace character and author the bare hostname \
3610                 with only ASCII bytes (write \"checkout.quero.cloud\" \
3611                 verbatim)",
3612                codepoint = ch as u32,
3613            ),
3614        });
3615    }
3616
3617    // Strip the optional single leading wildcard label *before* the
3618    // trailing-dot check so the bare `"*."` form surfaces the more
3619    // self-locating "wildcard without domain" diagnostic instead of
3620    // the generic "trailing dot" one.
3621    let (had_wildcard, rest) = match host.strip_prefix("*.") {
3622        Some(r) => (true, r),
3623        None => (false, host),
3624    };
3625    if had_wildcard && rest.is_empty() {
3626        return Err(AplicacaoError::EntradaHostInvalid {
3627            host: host.to_string(),
3628            reason: "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)".to_string(),
3629        });
3630    }
3631    if rest.contains('*') {
3632        return Err(AplicacaoError::EntradaHostInvalid {
3633            host: host.to_string(),
3634            reason: "wildcard `*` is allowed only as the first label (`*.example.com`); \
3635                     no inner or trailing `*` labels"
3636                .to_string(),
3637        });
3638    }
3639    if rest.ends_with('.') {
3640        return Err(AplicacaoError::EntradaHostInvalid {
3641            host: host.to_string(),
3642            reason: "must not have a trailing `.` (Gateway API hostnames are not \
3643                     fully-qualified with a root dot; the apiserver regex rejects \
3644                     trailing dots)"
3645                .to_string(),
3646        });
3647    }
3648
3649    // Reject pure IPv4 literals: four dot-separated labels, every
3650    // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
3651    // literals as Hostnames.
3652    let labels: Vec<&str> = rest.split('.').collect();
3653    if labels.len() == 4
3654        && labels
3655            .iter()
3656            .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
3657    {
3658        return Err(AplicacaoError::EntradaHostInvalid {
3659            host: host.to_string(),
3660            reason: "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
3661                     literals; use a DNS name)"
3662                .to_string(),
3663        });
3664    }
3665
3666    // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
3667    // hyphen, with non-hyphen at both boundaries.
3668    for label in &labels {
3669        if label.is_empty() {
3670            return Err(AplicacaoError::EntradaHostInvalid {
3671                host: host.to_string(),
3672                reason: "has an empty label (consecutive `..` or a leading `.`)".to_string(),
3673            });
3674        }
3675        if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
3676            return Err(AplicacaoError::EntradaHostInvalid {
3677                host: host.to_string(),
3678                reason: format!(
3679                    "label {label:?} exceeds DNS-1123 label max length of \
3680                     {cap} bytes (got {} bytes)",
3681                    label.len(),
3682                    cap = crate::render::DNS_1123_LABEL_MAX_LEN,
3683                ),
3684            });
3685        }
3686        let bytes = label.as_bytes();
3687        if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
3688            return Err(AplicacaoError::EntradaHostInvalid {
3689                host: host.to_string(),
3690                reason: format!(
3691                    "label {label:?} must start and end with an alphanumeric \
3692                     (no leading or trailing `-`)"
3693                ),
3694            });
3695        }
3696        for &b in bytes {
3697            let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
3698            if !valid {
3699                let msg = if b.is_ascii_uppercase() {
3700                    format!(
3701                        "label {label:?} contains uppercase character {ch:?} \
3702                         (Gateway API hostnames are lowercase-only; use {lower:?})",
3703                        ch = b as char,
3704                        lower = label.to_ascii_lowercase()
3705                    )
3706                } else if b == b'_' {
3707                    format!(
3708                        "label {label:?} contains `_` (Gateway API hostnames \
3709                         allow only `[a-z0-9-]`; use `-` instead)"
3710                    )
3711                } else {
3712                    format!(
3713                        "label {label:?} contains invalid character {ch:?} \
3714                         (Gateway API hostnames allow only `[a-z0-9-]`)",
3715                        ch = b as char
3716                    )
3717                };
3718                return Err(AplicacaoError::EntradaHostInvalid {
3719                    host: host.to_string(),
3720                    reason: msg,
3721                });
3722            }
3723        }
3724    }
3725    Ok(())
3726}
3727
3728/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
3729/// would refuse at admission time. Thin wrapper around
3730/// [`crate::render::is_gateway_api_http_path`] that maps the shared
3731/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
3732/// variant, preserving the more self-locating
3733/// [`AplicacaoError::EntradaPathEmpty`] /
3734/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
3735/// path fails those narrower invariants first.
3736///
3737/// The contract is the canonical HTTP-path grammar — `1..=
3738/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
3739/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
3740/// whitespace/control/non-ASCII bytes — shared with the
3741/// `:contratos :endpoint` axis through the lifted predicate so drift
3742/// between either landing site and the K8s apiserver-side
3743/// HTTPPathMatch.value OpenAPI schema is a build error visible at
3744/// the predicate, not a per-renderer "this passed validate but failed
3745/// admission" surprise. The diagnostic carries the offending `path:`
3746/// verbatim plus a parser-shaped `reason:` naming the specific
3747/// violation, so the author can grep their caixa.lisp for `:paths`
3748/// and fix it in one edit. Same diagnostic shape as
3749/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
3750/// axis.
3751fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
3752    // Empty and missing-leading-`/` are already gated at the call
3753    // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
3754    // checking here keeps the per-axis narrower diagnostics in force
3755    // when the predicate is reached directly (and `is_gateway_api_http_path`
3756    // itself defends against `bytes[0]`-style indexing on empty
3757    // input).
3758    if path.is_empty() {
3759        return Err(AplicacaoError::EntradaPathEmpty);
3760    }
3761    if !path.starts_with('/') {
3762        return Err(AplicacaoError::EntradaPathNotAbsolute {
3763            path: path.to_string(),
3764        });
3765    }
3766    crate::render::is_gateway_api_http_path(path).map_err(|reason| {
3767        AplicacaoError::EntradaPathInvalid {
3768            path: path.to_string(),
3769            reason,
3770        }
3771    })
3772}
3773
3774mod rate_limit_codec {
3775    // `Duration` is no longer named here — the codec routes through
3776    // the module-scope [`super::rate_limit_window_from_unit`] /
3777    // [`super::rate_limit_window_unit`] projections that carry the
3778    // canonical typed `Duration` unit-table axis on their signatures.
3779    use super::RateLimit;
3780    use serde::{Deserialize, Deserializer, Serializer};
3781
3782    pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
3783        match v {
3784            Some(rl) => s.serialize_str(&render(*rl)),
3785            None => s.serialize_none(),
3786        }
3787    }
3788
3789    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
3790        let opt: Option<String> = Option::deserialize(d)?;
3791        match opt {
3792            None => Ok(None),
3793            Some(s) => parse(&s).map(Some).map_err(serde::de::Error::custom),
3794        }
3795    }
3796
3797    fn parse(s: &str) -> Result<RateLimit, String> {
3798        // Whitespace-rejection arm — peer with the leading-`+`
3799        // (`"+100/s"`) and leading-zero (`"0100/s"`) arms below on the
3800        // same canonical-form render-determinism axis. Until this gate
3801        // landed the parser silently tolerated leading / trailing /
3802        // internal whitespace via the top-level `s.trim()` and the
3803        // per-part `rate_str.trim()` / `unit.trim()` calls, so every
3804        // whitespace-carrying shape (`" 100/s"`, `"100/s "`,
3805        // `"100 /s"`, `"100/ s"`, `"100 / s"`, `"100/s\n"`,
3806        // `"\t100/s"`) parsed to the same `RateLimit { 100, 1s }` and
3807        // serde silently round-tripped to `"100/s"` on the next emit
3808        // (a *different* canonical string) — breaking the THEORY.md
3809        // Part V render-determinism contract on the same
3810        // canonical-form-drift axis the leading-`+` arm below (the
3811        // 4eeae98 predecessor) and the leading-zero arm below (the
3812        // 4f46830 predecessor) already close.
3813        //
3814        // The canonical author shape is `<integer>/<s|m|h>` with no
3815        // whitespace bytes anywhere — every string [`render`] emits
3816        // carries none, so the parser's accepted set must match for
3817        // serialize / deserialize to round-trip losslessly. This gate
3818        // makes the pre-existing `s.trim()` / `rate_str.trim()` /
3819        // `unit.trim()` calls below strict no-ops on the accepted set
3820        // (every byte-position match they would perform is now already
3821        // trimmed away by the accepted set itself), while the arm
3822        // surfaces every rejected whitespace-carrying shape with a
3823        // self-locating diagnostic naming the offending byte and the
3824        // canonical form the author intended, peer with every prior
3825        // canonical-form-drift arm on this codec.
3826        //
3827        // Routed through the lifted
3828        // [`crate::render::find_ascii_whitespace_byte`] predicate — the
3829        // same source of truth the four peer typed-magnitude codec
3830        // sites (`limits::parse_byte_size`, `limits::parse_duration`,
3831        // `limits::parse_millicores`, `supervisor::duration_codec`)
3832        // share. `u8::is_ascii_whitespace()` at the predicate covers
3833        // the five WhatWG-conformant ASCII whitespace bytes (space,
3834        // tab, LF, FF, CR); the "single lifted predicate" discipline
3835        // the peer non-ASCII arm below carries on the strictly-
3836        // complementary Unicode `White_Space` class extends here to
3837        // the ASCII byte set as well.
3838        if let Some(b) = crate::render::find_ascii_whitespace_byte(s) {
3839            return Err(format!(
3840                "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
3841                 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
3842                 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
3843                 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
3844                 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
3845                 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
3846                 on first serialize — breaking the THEORY.md Part V render-determinism \
3847                 contract every typed slot carries. Strip every whitespace byte (write \
3848                 `\"100/s\"` verbatim)"
3849            ));
3850        }
3851        // Non-ASCII Unicode `White_Space` arm — the strictly-
3852        // complementary class the ASCII arm above cannot see.
3853        // `str::trim` at the top of every peer codec uses
3854        // `char::is_whitespace` (Unicode `White_Space`, strictly
3855        // wider than the ASCII byte set), so an NBSP (`\u{00A0}`) /
3856        // LINE SEPARATOR (`\u{2028}`) / EM-SPACE (`\u{2003}`)
3857        // survives the byte-scan (its UTF-8 bytes are not in
3858        // `is_ascii_whitespace`), gets silently stripped by the
3859        // top-level `s.trim()` below, and the value round-trips
3860        // through `render` to a *different* canonical form
3861        // (`\"100/s\"`) on next emit — breaking the THEORY.md Part V
3862        // render-determinism contract every typed slot carries.
3863        // Closed here (`:politicas :rate-limit`) and at the three
3864        // peer codec sites (`limits::parse_byte_size`,
3865        // `limits::parse_duration`, `supervisor::duration_codec`)
3866        // through the shared
3867        // [`crate::render::find_non_ascii_whitespace_char`] predicate
3868        // — the "single lifted predicate across all four codec sites
3869        // in one follow-up run" the 24a8ad4 commit body's `Forward
3870        // compounding` bullet named as the next compounding step.
3871        if let Some(ch) = crate::render::find_non_ascii_whitespace_char(s) {
3872            return Err(format!(
3873                "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
3874                 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
3875                 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
3876                 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
3877                 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
3878                 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
3879                 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
3880                 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
3881                 silently strips it at parse entry, and the value round-trips through \
3882                 `render` to a *different* canonical form (`\"100/s\"`) on first \
3883                 serialize — breaking the THEORY.md Part V render-determinism contract \
3884                 every typed slot carries. Strip every non-ASCII whitespace character \
3885                 (write `\"100/s\"` verbatim with only ASCII bytes)",
3886                cp = ch as u32
3887            ));
3888        }
3889        let s = s.trim();
3890        let (rate_str, unit) = s
3891            .split_once('/')
3892            .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
3893        let rate_trim = rate_str.trim();
3894        // The canonical authoring form for `:politicas :rate-limit` is
3895        // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
3896        // non-negative integer with no decimal point and no leading
3897        // sign, so the parser's accepted set must match for
3898        // serialize/deserialize to round-trip without canonical-form
3899        // drift. Until this gate landed the parser accepted any
3900        // `u32::from_str`-shaped magnitude — and current Rust
3901        // `u32::from_str` permissively accepts a leading `+` (`"+100"`
3902        // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
3903        // serde silently round-tripped to `"100/s"` on the next emit
3904        // (a *different* canonical string) — breaking the THEORY.md
3905        // Part V render-determinism contract on the fifth typed-codec
3906        // surface in caixa-core (peer with the four duration codecs the
3907        // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
3908        // already covered: `supervisor::duration_codec` backing three
3909        // typed-duration slots, `limits::parse_duration` backing
3910        // `:limits :wall-clock`, `limits::parse_byte_size` backing
3911        // `:limits :memory`). The fractional / decimal-shaped sibling
3912        // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
3913        // existing rejection arm, but the diagnostic is value-laundered
3914        // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
3915        // doesn't name the canonical-form remediation or the round-trip
3916        // drift the next emit would produce); this gate lifts the
3917        // fractional arm onto the same canonical-form diagnostic the
3918        // peer codecs carry.
3919        //
3920        // Strict canonical form: every byte of the magnitude is an
3921        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
3922        // inputs the gate distinguishes "non-canonical-but-numeric"
3923        // (parses as f64 or i64 — surfaced with a self-locating
3924        // diagnostic naming the canonical authoring form and the
3925        // round-trip drift the rejected shape would produce on first
3926        // serialize) from "garbage" (parses as neither — surfaced with
3927        // the existing narrower `"not a u32"` wording so its
3928        // diagnostic shape remains stable for the parser-shape footgun
3929        // case).
3930        //
3931        // Routed through the lifted
3932        // [`crate::render::is_digit_only_magnitude`] predicate — the
3933        // same source of truth the four peer typed-magnitude codec
3934        // sites share.
3935        let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
3936        if !digit_only {
3937            let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
3938            if numeric {
3939                return Err(format!(
3940                    "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
3941                     canonical authoring form for `:politicas :rate-limit` is \
3942                     `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
3943                     with no decimal point and no leading `+` / `-` sign. A fractional / \
3944                     signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
3945                     through `render` to a *different* canonical form (`\"1/s\"`, \
3946                     `\"100/s\"`, parser-reject) on first serialize — breaking the \
3947                     THEORY.md Part V render-determinism contract every typed slot \
3948                     carries. Pick an integer rate that fits the desired window \
3949                     (write `\"6000/m\"` instead of `\"1.66/s\"`)"
3950                ));
3951            }
3952            return Err(format!("rate-limit rate {rate_str:?} not a u32"));
3953        }
3954        // Leading-zero arm — peer with the prior `"+100/s"` arm above
3955        // (4eeae98's predecessor) on the same canonical-form
3956        // render-determinism axis. The digit-only gate accepts
3957        // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
3958        // them losslessly (= 100, 0, 7), but `render` emits the
3959        // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
3960        // a *different* canonical string on the next emit, breaking
3961        // the THEORY.md Part V render-determinism contract the same
3962        // way `"+100/s"` did before the leading-`+` arm landed. The
3963        // single-byte magnitude `"0"` itself round-trips losslessly
3964        // through `render` (`render(0)` emits `"0/s"`) — the
3965        // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
3966        // what refuses rate-zero authoring, so `"0/s"` stays in the
3967        // accepted set at this codec layer and the diagnostic
3968        // partitioning between canonical-form drift (this arm) and
3969        // semantic-zero (the downstream gate) remains stable.
3970        // Peer with the future leading-zero arms on the three peer
3971        // typed-magnitude codecs the trajectory acknowledges:
3972        // `supervisor::duration_codec`, `limits::parse_duration`,
3973        // `limits::parse_byte_size` — each carries the same
3974        // canonical-form-drift class today; this gate lands the
3975        // discipline on the fourth typed-magnitude codec in
3976        // caixa-core first because the peer `"+100/s"` arm above is
3977        // the closest predecessor on the trajectory.
3978        //
3979        // Routed through the lifted
3980        // [`crate::render::is_leading_zero_padded_magnitude`]
3981        // predicate — the same source of truth the four peer
3982        // typed-magnitude codec sites share.
3983        if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
3984            return Err(format!(
3985                "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
3986                 canonical authoring form for `:politicas :rate-limit` is \
3987                 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
3988                 with no leading-zero padding on the magnitude. A leading-zero magnitude \
3989                 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
3990                 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
3991                 first serialize — breaking the THEORY.md Part V render-determinism \
3992                 contract every typed slot carries. Strip the leading zeros (write \
3993                 `\"100/s\"` instead of `\"0100/s\"`)"
3994            ));
3995        }
3996        // The digit-only gate guarantees every byte is `[0-9]`, and
3997        // the leading-zero arm above guarantees the magnitude is
3998        // either the single byte `"0"` or starts with `[1-9]`, so
3999        // the only way `u32::from_str` can fail here is overflow
4000        // (the magnitude exceeds `u32::MAX`). Surface that with an
4001        // overflow-shaped wording so the diagnostic names the
4002        // offending magnitude verbatim rather than collapsing onto
4003        // the non-canonical arm. Same shape
4004        // `supervisor::duration_codec` (1c55a2a) carries on the peer
4005        // duration-codec axis.
4006        let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
4007            format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
4008        })?;
4009        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
4010        // module scope as the lifted [`super::RATE_LIMIT_UNIT_TABLE`]
4011        // const; this parse arm now consumes only the `unit → Duration`
4012        // projection [`super::rate_limit_window_from_unit`], so a future
4013        // rate-limit-unit addition (a `"d"` day suffix once Envoy's
4014        // `rate_limit_action` grows daily-bucket support) is one row
4015        // appended to the table — parse, render, and
4016        // `is_canonical_rate_limit_window` all pick it up by construction.
4017        let unit = unit.trim();
4018        let window = super::rate_limit_window_from_unit(unit)
4019            .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
4020        Ok(RateLimit { rate, window })
4021    }
4022
4023    fn render(rl: RateLimit) -> String {
4024        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
4025        // module scope on the closed-set typed enum [`super::RateLimitUnit`];
4026        // this render arm reads the `Duration → RateLimitUnit` projection
4027        // through the substrate primitive [`super::RateLimit::canonical_unit`]
4028        // (returns `None` on every non-canonical window — the sub-second /
4029        // non-`{1, 60, 3600}` shapes the validate gate rejects), then
4030        // formats the returned typed enum through its
4031        // [`std::fmt::Display`] impl (which routes through
4032        // [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
4033        // the substrate primitive instead of one runtime `find_map`
4034        // walk through the free-helper delegate chain
4035        // [`super::rate_limit_window_unit`] (the vestigial free helper's
4036        // sole production consumer was this arm; every other consumer of
4037        // the `Duration → unit` axis — the validate gate below and the
4038        // future M4 per-Aplicacao Envoy config reconciler — now reads
4039        // the same typed method).
4040        //
4041        // A future rate-limit-unit addition (a `"d"` day suffix once
4042        // Envoy's `rate_limit_action` grows daily-bucket support) is
4043        // one variant + one arm per method on the closed-set enum, and
4044        // the compiler enforces exhaustiveness on every consumer's
4045        // `match self` arms — the codec's `parse` accepted-suffix set,
4046        // this render arm's emitted-suffix set, the validate gate's
4047        // canonical-window set, and every future per-`:contratos`-edge
4048        // rate-limit-override overlay all pick it up by construction.
4049        if let Some(unit) = rl.canonical_unit() {
4050            format!("{}/{unit}", rl.rate())
4051        } else {
4052            // Defensive fallback for non-canonical windows. Note:
4053            // [`AplicacaoSpec::validate_politicas`] rejects any
4054            // non-canonical `:rate-limit :window` via
4055            // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
4056            // a validated `RateLimit` never reaches this branch. The
4057            // emitted `<n>/<k>s` form is *not* round-trippable through
4058            // [`parse`] (which accepts only the closed-set
4059            // [`super::RateLimitUnit`] suffixes, not `<k>s` with an
4060            // explicit count) — the validate gate is what makes the
4061            // round-trip a structural property; this branch exists only
4062            // so a programmatic non-validated serialize doesn't panic.
4063            format!("{}/{}s", rl.rate(), rl.window().as_secs())
4064        }
4065    }
4066}
4067
4068// ── placement strategy ───────────────────────────────────────────────
4069
4070/// How the Aplicacao distributes across clusters. Three options:
4071///
4072/// - `SingleNode` — one cluster runs the app at a time; takeover on
4073///   death (Erlang/OTP distributed-app semantics).
4074/// - `Replicated` — every named cluster runs an instance (active-active).
4075/// - `Sharded` — entities distribute by hash key across clusters
4076///   (Akka cluster sharding).
4077#[derive(
4078    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
4079)]
4080pub enum PlacementStrategy {
4081    SingleNode,
4082    Replicated,
4083    Sharded,
4084}
4085
4086impl Default for PlacementStrategy {
4087    fn default() -> Self {
4088        Self::Replicated
4089    }
4090}
4091
4092impl PlacementStrategy {
4093    /// Canonical camelCase-schema discriminator scalar this variant
4094    /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
4095    /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
4096    /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4097    /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
4098    /// every substrate consumer that dispatches on the strategy (the
4099    /// `lareira-fleet-programs` aggregator, the future `app-operator`
4100    /// reconciler, the M3 Adaptive compression pass) reads the same
4101    /// byte-string the `Serialize` derive emits — the pin test in
4102    /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
4103    /// asserts the two paths agree.
4104    #[must_use]
4105    pub const fn as_str(self) -> &'static str {
4106        match self {
4107            Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
4108            Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
4109            Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
4110        }
4111    }
4112}
4113
4114/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
4115/// the pretty-printed byte-string every consumer that formats the strategy
4116/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
4117/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
4118/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
4119/// per-Aplicacao strategy line, the future M4 CR materializer's per-
4120/// admission-webhook rejection body) reaches for the same lifted
4121/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
4122/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4123/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
4124/// `Serialize` derive already emits under
4125/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
4126/// [`PlacementStrategy::as_str`] helper already returns.
4127///
4128/// Until this lift landed the sibling OTP-shape typed enums —
4129/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
4130/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
4131/// so [`std::fmt::Display`] routes through the same discriminant string
4132/// the wire format emits) — carried a stable [`std::fmt::Display`]
4133/// surface but [`PlacementStrategy`] did not; every consumer reaching
4134/// for a strategy byte-string past the wire format had to pick between
4135/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
4136/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
4137/// derive), any two of which a future variant rename or
4138/// `#[serde(rename_all = "kebab-case")]` attribute would silently
4139/// desynchronize — with the failure surfacing as a downstream renderer /
4140/// operator's per-strategy dispatch reading one spelling while the wire
4141/// format emitted another, far from the source rebrand commit and with
4142/// no field naming the drift. Routing `Display` through
4143/// [`PlacementStrategy::as_str`] makes the three paths
4144/// (`Debug` for structural inspection, `Display` for user-facing text,
4145/// `Serialize` for the wire format) converge on the same lifted
4146/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
4147/// the diagnostic byte-string, and the pretty-printed byte-string move
4148/// as a single unit through one canonical declaration each, by
4149/// construction. Same trajectory as [`PlacementStrategy::as_str`]
4150/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
4151/// closes the third path.
4152///
4153/// Pin tests
4154/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
4155/// and
4156/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
4157/// assert the three paths agree byte-for-byte on every variant, so a
4158/// future variant rename or per-arm serde attribute drift is a build
4159/// error visible at caixa-core test time, not a silent per-consumer
4160/// dispatch miss at apply / reconcile time.
4161impl std::fmt::Display for PlacementStrategy {
4162    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4163        f.write_str(self.as_str())
4164    }
4165}
4166
4167/// Where the Aplicacao runs.
4168#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
4169#[serde(rename_all = "camelCase")]
4170pub struct Placement {
4171    /// Distribution strategy.
4172    #[serde(default)]
4173    pub estrategia: PlacementStrategy,
4174
4175    /// Named clusters that host this Aplicacao. Required for
4176    /// `Replicated` and `SingleNode`; for `Sharded` declares the
4177    /// shard pool.
4178    #[serde(default)]
4179    pub clusters: Vec<String>,
4180
4181    /// Optional hint to the placement engine: `"data-locality"`,
4182    /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
4183    #[serde(default, skip_serializing_if = "Option::is_none")]
4184    pub affinity: Option<String>,
4185
4186    /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
4187    #[serde(default, skip_serializing_if = "Option::is_none")]
4188    pub shard_key: Option<String>,
4189}
4190
4191impl Placement {
4192    /// Substrate-canonical per-`:placement` Akka-cluster-sharding
4193    /// `:shard-key` extractor-expression scalar accessor every consumer
4194    /// of the Aplicacao's hash-keyed distribution routing keys off —
4195    /// returns the author-declared `:placement :shard-key` byte-string
4196    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
4197    /// own `Option<String>` storage; `None` when the slot is absent
4198    /// (the canonical shape under `:estrategia Replicated` /
4199    /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
4200    /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
4201    /// partition — `validate` refuses any `Placement` past this call
4202    /// that lands `Some` on a non-`Sharded` strategy or `None` on
4203    /// `Sharded`).
4204    ///
4205    /// The `:placement :shard-key` slot carries the Akka-style
4206    /// cluster-sharding entity-id extractor expression
4207    /// (MESH-COMPOSITION §II.4) — validated by
4208    /// [`validate_placement_shard_key`] to be a non-empty printable-
4209    /// ASCII single-token reference (`tenantId`, `$tenantId`,
4210    /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
4211    /// future M4 Akka-style cluster-sharding reconciler hashes without
4212    /// re-validating at the runtime layer), and every downstream
4213    /// consumer that reads the key keys off this scalar (the
4214    /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
4215    /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
4216    /// declared-but-inert refusal diagnostic, the caixa-mesh
4217    /// per-Aplicacao `placement.shardKey` emit path the substrate
4218    /// operator's per-entity hash-routing reader consumes, the future
4219    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4220    /// per-shard-key resolver).
4221    ///
4222    /// Prior to this lift the `.shard_key` field was accessed inline at
4223    /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
4224    /// `Sharded` arm's `match &self.placement.shard_key { None => …,
4225    /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
4226    /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
4227    /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
4228    /// — two open-coded field-accesses that expressed no compile-time
4229    /// link back to the typed slot. A future extension of the
4230    /// `:placement :shard-key` axis to a richer author surface — a
4231    /// per-cluster override the operator pins through a future
4232    /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
4233    /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
4234    /// alias table the M4 CR materializer resolves per-CR, a
4235    /// per-Aplicacao dynamic `:shard-key` derivation the future
4236    /// adaptive placement engine computes from `:affinity` weights —
4237    /// would have had to be threaded through both open-coded copies in
4238    /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
4239    /// arm refusal would silently disagree on which extractor
4240    /// expression a given Placement resolves to. Lifting the resolution
4241    /// rule to a typed method on the substrate primitive means every
4242    /// downstream consumer of the Aplicacao's per-`:placement`
4243    /// hash-key surface reaches for exactly one typed dispatch — the
4244    /// resolver's accept-set migrates as a unit on any future axis
4245    /// addition.
4246    ///
4247    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
4248    /// [`WitContract::destination`] / [`WitContract::world_ref`]
4249    /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
4250    /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
4251    /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
4252    /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
4253    /// typed dispatch on the substrate primitive, thin projections at
4254    /// each consumer" discipline extended onto the per-`:placement`
4255    /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
4256    /// First `Option<&str>`-return accessor on the M3 mesh-slot family
4257    /// — opens the "optional per-slot scalar" projection pattern the
4258    /// sibling per-`:placement` `:affinity`, per-`:politicas`
4259    /// `:rate-limit` future lifts fold on. Named `shard_key()` to
4260    /// match the storage field's name; the accessor's identity name
4261    /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
4262    /// slot's docstring already carries.
4263    #[must_use]
4264    pub fn shard_key(&self) -> Option<&str> {
4265        self.shard_key.as_deref()
4266    }
4267
4268    /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
4269    /// compression-hint scalar accessor every weighting-consumer of the
4270    /// Aplicacao's per-hint routing surface keys off — returns the
4271    /// author-declared `:placement :affinity` byte-string verbatim as
4272    /// an `Option<&str>`, borrowed from the typed slot's own
4273    /// `Option<String>` storage; `None` when the slot is absent (the
4274    /// canonical shape of an Aplicacao that leaves the compression
4275    /// weighting up to the placement engine's cluster-default arm — no
4276    /// author-authored `data-locality` / `low-latency` / etc. hint
4277    /// biases the routing).
4278    ///
4279    /// The `:placement :affinity` slot carries the M3 Adaptive-
4280    /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
4281    /// by [`validate_placement_affinity`] to be a DNS-1123 label
4282    /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
4283    /// K8s-conformant label-selector shape every apiserver-side pod-
4284    /// affinity / node-affinity materializer already gates on
4285    /// admission), and every downstream consumer that reads the hint
4286    /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
4287    /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
4288    /// `placement.affinity` overlay emit path the substrate operator's
4289    /// per-hint weighting-consumer reads, the future M4
4290    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
4291    /// pod-affinity / node-affinity selector resolver).
4292    ///
4293    /// Prior to this lift the `.affinity` field was accessed inline at
4294    /// the sole caixa-core site — the
4295    /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
4296    /// `if let Some(a) = &self.placement.affinity { …
4297    /// validate_placement_affinity(a)? … }` cascade — one open-coded
4298    /// field-access that expressed no compile-time link back to the
4299    /// typed slot. A future extension of the `:placement :affinity`
4300    /// axis to a richer author surface — a per-cluster override the
4301    /// operator pins through a future `:placement :affinity-overrides`
4302    /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
4303    /// tenant hint alias table the M4 CR materializer resolves per-CR,
4304    /// a per-Aplicacao dynamic `:affinity` derivation the future
4305    /// adaptive placement engine computes from `:clusters` topology —
4306    /// would have had to be threaded through the open-coded copy in
4307    /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
4308    /// materializer reader that landed on the axis, or the per-hint
4309    /// value-shape gate and its downstream weighting consumers would
4310    /// silently disagree on which hint a given Placement resolves to.
4311    /// Lifting the resolution rule to a typed method on the substrate
4312    /// primitive means every downstream consumer of the Aplicacao's
4313    /// per-`:placement` compression-hint surface reaches for exactly
4314    /// one typed dispatch — the resolver's accept-set migrates as a
4315    /// unit on any future axis addition.
4316    ///
4317    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
4318    /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
4319    /// optional-scalar axis — same "one typed dispatch on the substrate
4320    /// primitive, thin projections at each consumer" discipline extended
4321    /// onto the per-`:placement` M3-Adaptive-compression-hint
4322    /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
4323    /// return accessor on the M3 mesh-slot family; closes the last
4324    /// un-lifted per-`:placement` `Option<String>` axis. Named
4325    /// `affinity()` to match the storage field's name; the accessor's
4326    /// identity name maps onto the canonical MESH-COMPOSITION §II.4
4327    /// vocabulary the slot's docstring already carries.
4328    #[must_use]
4329    pub fn affinity(&self) -> Option<&str> {
4330        self.affinity.as_deref()
4331    }
4332
4333    /// Substrate-canonical per-`:placement` `:estrategia` distribution-
4334    /// strategy scalar accessor every consumer that dispatches on the
4335    /// Aplicacao's per-cluster distribution shape keys off — returns the
4336    /// author-declared `:placement :estrategia` variant verbatim as a
4337    /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
4338    /// `PlacementStrategy` storage.
4339    ///
4340    /// The `:placement :estrategia` slot carries the closed-set
4341    /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
4342    /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
4343    /// `Replicated` — active-active across every named cluster; `Sharded`
4344    /// — Akka-style hash-keyed entity distribution across the cluster pool
4345    /// per §II.4) that every downstream consumer of the Aplicacao's
4346    /// per-cluster fan-out shape keys off. Validated by
4347    /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
4348    /// the sibling `:shard-key` axis (`shard_key.is_some() ==
4349    /// matches!(estrategia, Sharded)` — the cross-slot partition the
4350    /// [`Placement::shard_key`] accessor's docstring pins), and every
4351    /// downstream consumer that reads the strategy keys off this scalar
4352    /// (the [`AplicacaoSpec::validate_placement`]
4353    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
4354    /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
4355    /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
4356    /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
4357    /// declared-but-inert refusal's
4358    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
4359    /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
4360    /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
4361    /// emit path the substrate operator's per-strategy fan-out reader
4362    /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4363    /// materializer's per-strategy admission-webhook resolver).
4364    ///
4365    /// Prior to this lift the `.estrategia` field was accessed inline at
4366    /// four sites — the [`AplicacaoSpec::validate_placement`]
4367    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
4368    /// `estrategia: self.placement.estrategia`, the same method's
4369    /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
4370    /// partition dispatch, the non-`Sharded`-arm
4371    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
4372    /// `estrategia: self.placement.estrategia`, and the `feira app graph`
4373    /// per-Aplicacao strategy print line at
4374    /// `println!("… {} …", spec.placement.estrategia, …)`
4375    /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
4376    /// expressed no compile-time link back to the typed slot. A future
4377    /// extension of the `:placement :estrategia` axis to a richer author
4378    /// surface (a per-cluster override the operator pins through a future
4379    /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
4380    /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
4381    /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
4382    /// derivation the future adaptive placement engine computes from
4383    /// `:affinity` + `:clusters` topology) would have had to be threaded
4384    /// through every open-coded copy in lockstep — one consumer reading
4385    /// the raw variant while a peer read the operator-resolved variant
4386    /// would silently split the `PlacementWithoutClusters` /
4387    /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
4388    /// partition-dispatch input, a two-consumer split at the validator
4389    /// far from the source `caixa.lisp` with no field naming the
4390    /// strategy-drift root cause. Lifting the resolution rule to a typed
4391    /// method on the substrate primitive means every downstream consumer
4392    /// of the Aplicacao's per-`:placement` distribution-strategy surface
4393    /// reaches for exactly one typed dispatch — the resolver's accept-set
4394    /// migrates as a unit on any future axis addition.
4395    ///
4396    /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
4397    /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
4398    /// same "one typed dispatch on the substrate primitive, thin
4399    /// projections at each consumer" discipline extended onto the
4400    /// per-`:placement` distribution-strategy `Copy`-composite-enum
4401    /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
4402    /// family; first `Copy`-return accessor on the M3 mesh-slot
4403    /// `Placement` type — companion to the sibling per-`:placement`
4404    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
4405    /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
4406    /// optional-scalar axes, closing the last unlifted per-`:placement`
4407    /// scalar-value axis (the closed-set `PlacementStrategy`
4408    /// distribution-strategy discriminator) so every downstream
4409    /// per-`:placement` reader now routes through a typed dispatch on
4410    /// the substrate primitive. Named `estrategia()` to match the storage
4411    /// field's name; the accessor's identity name maps onto the
4412    /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
4413    /// already carries.
4414    #[must_use]
4415    pub fn estrategia(&self) -> PlacementStrategy {
4416        self.estrategia
4417    }
4418
4419    /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
4420    /// per-cluster distribution-target slice accessor every consumer that
4421    /// walks the Aplicacao's declared cluster-pool keys off — returns the
4422    /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
4423    /// `&[String]` slice-view, borrowed from the typed slot's own
4424    /// `Vec<String>` storage (a zero-copy slice-view over the same
4425    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
4426    /// through). Non-optional: the empty slice is the load-bearing
4427    /// pre-validation sentinel every downstream consumer of the paired
4428    /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
4429    /// off — every strategy in the closed
4430    /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
4431    /// requires a non-empty list (`SingleNode` / `Replicated` use the
4432    /// list as hosting / takeover candidates per Erlang/OTP distributed-
4433    /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
4434    /// shard pool per Akka cluster-sharding convention, §II.4), so the
4435    /// `.is_empty()` probe is the shared pre-condition every
4436    /// [`AplicacaoSpec::validate_placement`] arm heads on.
4437    ///
4438    /// The `:placement :clusters` slot carries the K8s-conformant DNS-
4439    /// 1123-label per-cluster distribution-target list — the same
4440    /// set-not-multiset shape the sibling `:membros :caixa` /
4441    /// `:children :caixa` axes carry (`validate_placement`'s per-entry
4442    /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
4443    /// pins the shape). Every downstream consumer that fans on the list
4444    /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
4445    /// pre-flight `.is_empty()` probe that trips
4446    /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
4447    /// per-cluster value-shape + duplicate-detection fan-out loop, the
4448    /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
4449    /// that materializes the list verbatim onto every
4450    /// programs.yaml entry the substrate operator's per-cluster
4451    /// `placement.clusters | contains .Values.cluster` filter reads,
4452    /// the `feira app graph` per-Aplicacao cluster print line, the
4453    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4454    /// per-cluster admission-webhook fan-out, the future M5 adaptive-
4455    /// placement engine's cluster-topology reader).
4456    ///
4457    /// Prior to this lift the `.clusters` `Vec<String>` was accessed
4458    /// inline at three production sites — the
4459    /// [`AplicacaoSpec::validate_placement`] pre-flight
4460    /// `self.placement.clusters.is_empty()` refusal probe, the same
4461    /// method's per-cluster validate loop's
4462    /// `for c in &self.placement.clusters` traversal head, and the
4463    /// `feira app graph` per-Aplicacao print line's
4464    /// `spec.placement.clusters` `{:?}` formatter argument
4465    /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
4466    /// that expressed no compile-time link back to the typed slot. A
4467    /// future extension of the `:placement :clusters` axis to a richer
4468    /// author surface (a per-tenant cluster-pool overlay the operator
4469    /// pins through a future `:placement :clusters-overrides` slot the
4470    /// MESH-COMPOSITION §V cross-cluster-federation roadmap
4471    /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
4472    /// the future M5 adaptive-placement engine computes from
4473    /// `:affinity` weights + live cluster-topology probes, a promotion
4474    /// of the plain `Vec<String>` to a richer `{static, dynamic}`
4475    /// partition once the substrate operator's cluster-membership
4476    /// reconciler comes into typed scope) would have had to be threaded
4477    /// through all three open-coded copies in lockstep or one consumer
4478    /// would silently disagree with the peers on which cluster-pool a
4479    /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
4480    /// reading the raw slot while the peer per-cluster validate loop
4481    /// read an operator-resolved slot would silently split the paired
4482    /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
4483    /// `PlacementClusterDuplicate` refusal cascade's actual traversal
4484    /// input from the pre-flight input, a three-consumer split at the
4485    /// validator and formatter far from the source `caixa.lisp` with
4486    /// no field naming the cluster-pool-drift root cause. Lifting the
4487    /// resolution rule to a typed method on the substrate primitive
4488    /// means every downstream consumer of the Aplicacao's
4489    /// per-`:placement` cluster-pool surface reaches for exactly one
4490    /// typed dispatch — the resolver's accept-set migrates as a unit
4491    /// on any future axis addition.
4492    ///
4493    /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
4494    /// slot — sibling to the seed M2
4495    /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
4496    /// slice-return accessor on the peer per-`:supervisor` static-
4497    /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
4498    /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
4499    /// primitive, thin projections at each consumer" discipline. The
4500    /// three peer `Vec`-carry axes still unlifted at the time of this
4501    /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
4502    /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
4503    /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
4504    /// [`crate::UpgradeFromEntry::instructions`]
4505    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
4506    /// — inherit this accessor's discipline as future compounding runs
4507    /// migrate their consumers onto the shared slice-return shape.
4508    /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
4509    /// type, sibling to the two `Option<&str>`-return
4510    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
4511    /// (74ec2d3) accessors and the `Copy`-return
4512    /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
4513    /// unlifted per-`:placement` field axis (the `Vec<String>`
4514    /// distribution-target-list carrier) so every downstream
4515    /// per-`:placement` reader now routes through a typed dispatch on
4516    /// the substrate primitive. Named `clusters()` to match the storage
4517    /// field's name verbatim and the tatara-lisp author-surface term
4518    /// (`:clusters`) the field's own docstring already carries; the
4519    /// accessor's identity maps onto the canonical MESH-COMPOSITION
4520    /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
4521    /// for. Returns `&[String]` (not `&Vec<String>`) because every
4522    /// downstream consumer of the cluster list treats it as a read-only
4523    /// sequence — the slice-view is the narrowest borrow that supports
4524    /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
4525    /// `.len()`) without leaking the backing `Vec`'s
4526    /// grow/push/reserve surface that no consumer of the typed view
4527    /// reaches for (the storage-side `Vec` remains reachable through
4528    /// the `pub clusters` field for the mutation-carrying serde
4529    /// round-trip and per-test fixture-mutation paths).
4530    #[must_use]
4531    pub fn clusters(&self) -> &[String] {
4532        self.clusters.as_slice()
4533    }
4534}
4535
4536impl Default for Placement {
4537    fn default() -> Self {
4538        Self {
4539            estrategia: PlacementStrategy::default(),
4540            clusters: Vec::new(),
4541            affinity: None,
4542            shard_key: None,
4543        }
4544    }
4545}
4546
4547// ── external entry point ─────────────────────────────────────────────
4548
4549/// External entry point — what an outside caller sees. Renders to a
4550/// Gateway / Ingress + a route to the named member Servico.
4551#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
4552#[serde(rename_all = "camelCase")]
4553pub struct Entrada {
4554    /// Public hostname (e.g. `"checkout.quero.cloud"`).
4555    pub host: String,
4556
4557    /// Member Servico the gateway routes to. Must be in `:membros`.
4558    pub para: String,
4559
4560    /// Optional path filter — if set, only matching paths route to
4561    /// this Aplicacao (the rest fall through to other route rules).
4562    #[serde(default)]
4563    pub paths: Vec<String>,
4564
4565    /// Default port on the destination Servico (the trigger.service.port).
4566    #[serde(default = "default_port")]
4567    pub port: u16,
4568}
4569
4570impl Entrada {
4571    /// Substrate-canonical per-`:entrada` URL-path fallback resolver
4572    /// every HTTPRoute-aware renderer keys off — returns the author-
4573    /// declared `:entrada :paths` list verbatim when non-empty, and the
4574    /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
4575    /// all fallback otherwise (so an Aplicacao author who declares an
4576    /// external `:entrada` block but no per-path rule surface still
4577    /// gets a route whose sole `HTTPPathMatch` matches every incoming
4578    /// request under the paired
4579    /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
4580    ///
4581    /// Prior to this lift the "if `:entrada :paths` is empty use the
4582    /// substrate catch-all; else return each declared path verbatim"
4583    /// cascade lived inline at
4584    /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
4585    /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
4586    /// per-Aplicacao HTTPRoute per-rule path-list emit site the
4587    /// substrate ships today, with no typed method on the substrate
4588    /// primitive that named the rule. A future path-resolution axis
4589    /// addition — a per-cluster `:entrada :default-path` override the
4590    /// operator pins through a future `:placement`-scoped slot, an
4591    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
4592    /// admission-webhook floor that materializes the catch-all before
4593    /// the CR lands, a future per-`:entrada :paths` overlay from a
4594    /// per-cluster policy the future `feira app deploy` pipeline
4595    /// consumes — would have to be threaded through every renderer's
4596    /// inline copy of the cascade in lockstep or one consumer would
4597    /// silently disagree with the peers on which path list a given
4598    /// `:entrada` block resolves to. Lifting the rule to a typed
4599    /// method on the substrate primitive means every downstream
4600    /// HTTPRoute-aware consumer (the M4 CR materializer, the future
4601    /// per-cluster overlay resolver, every future per-Aplicacao
4602    /// snapshot renderer) reaches for exactly one typed dispatch —
4603    /// the resolver's accept-set moves as a unit on any future axis
4604    /// addition.
4605    ///
4606    /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
4607    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
4608    /// per-`:entrada` scalar-value axes — extends the "one typed
4609    /// dispatch on the substrate primitive, thin projections at each
4610    /// consumer" discipline onto the per-`:entrada` path-list
4611    /// resolution axis every HTTPRoute-aware renderer consumes. Same
4612    /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
4613    /// sibling `:politicas` primitive — one typed method on the
4614    /// substrate primitive that names the cascade every renderer
4615    /// otherwise re-inlines.
4616    #[must_use]
4617    pub fn resolved_paths(&self) -> Vec<&str> {
4618        // Route the internal cascade-head + per-entry projection reads
4619        // through the lifted [`Self::paths`] slice accessor rather than
4620        // the raw `self.paths` field access — the substrate-primitive
4621        // per-`:entrada` path-list resolver's two internal reads now
4622        // key off the canonical raw-slot surface every downstream
4623        // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
4624        // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
4625        // entrada summary line's `{:?}` Debug print) routes through, so
4626        // any future rebrand on the typed slot's raw-slot reader lands
4627        // at exactly one place. Same two-consumer coherence discipline
4628        // the sibling `Placement::clusters` (a6e18d7) accessor pins on
4629        // the peer M3 mesh-slot `Vec<String>`-carry axis.
4630        if self.paths().is_empty() {
4631            vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
4632        } else {
4633            self.paths().iter().map(String::as_str).collect()
4634        }
4635    }
4636
4637    /// Substrate-canonical per-`:entrada` DNS-hostname singular
4638    /// accessor every Gateway-API `Listener.hostname` reader keys off
4639    /// — returns the author-declared `:entrada :host` byte-string
4640    /// verbatim as a `&str`, borrowed from the typed slot's own
4641    /// [`String`] storage.
4642    ///
4643    /// Named the "singular" half of the DNS-hostname resolver pair on
4644    /// the substrate primitive: the parent-Gateway per-listener
4645    /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
4646    /// (`Listener.hostname: Option<PreciseHostname>` — at most one
4647    /// hostname per listener), and this accessor is the typed dispatch
4648    /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
4649    /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
4650    /// the per-HTTPRoute `spec.hostnames[]` list axis the same
4651    /// per-Aplicacao ingress-hostname surface projects onto.
4652    ///
4653    /// Prior to this lift the `entrada.host.clone()` byte-string was
4654    /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
4655    /// per-listener singular `hostname:` axis
4656    /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
4657    /// per-HTTPRoute plural `spec.hostnames[]` axis
4658    /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
4659    /// consumers read the same `entrada.host` field but the two-site
4660    /// duplication expressed no compile-time contract that the singular
4661    /// Gateway-listener filter and the plural `HTTPRoute` filter list
4662    /// stay in lockstep on future extensions of the `:entrada` slot to
4663    /// a multi-hostname author surface (an `:entrada :alt-hosts` list
4664    /// overlay, a per-cluster SNI fan-out the operator pins through a
4665    /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
4666    /// Aplicacao` CR materializer's per-listener virtual-host filter
4667    /// admission-webhook overlay). Any such extension would have to be
4668    /// threaded through every renderer's inline copy of the resolution
4669    /// in lockstep or the Gateway listener's `hostname:` filter would
4670    /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
4671    /// — a Gateway-API-conformance divergence whose apply-time symptom
4672    /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
4673    /// `NoMatchingParent` — the API server rejects the route because
4674    /// its `hostnames[]` filter doesn't intersect the parent listener's
4675    /// `hostname` filter) is far from the source `caixa.lisp` and never
4676    /// surfaces in the emitted YAML. Lifting the singular and plural
4677    /// resolvers to typed methods on the substrate primitive means
4678    /// every consumer of the Aplicacao's ingress-hostname surface
4679    /// reaches for exactly one typed dispatch, and the pair-invariant
4680    /// `hostnames() == vec![hostname()]` pinned by the sibling
4681    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
4682    /// keeps the two axes in lockstep by construction.
4683    ///
4684    /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
4685    /// (1449891) path-list resolver on the per-HTTPRoute per-rule
4686    /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
4687    /// the substrate primitive, thin projections at each consumer"
4688    /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
4689    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
4690    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
4691    /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
4692    /// `:entrada` scalar-value + list-value axes.
4693    #[must_use]
4694    pub fn hostname(&self) -> &str {
4695        self.host.as_str()
4696    }
4697
4698    /// Substrate-canonical per-`:entrada` DNS-hostname plural
4699    /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
4700    /// keys off — returns the singleton `[hostname()]` list under
4701    /// today's single-hostname-per-Aplicacao author surface, and the
4702    /// authoritative multi-hostname list under a future
4703    /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
4704    ///
4705    /// Plural half of the DNS-hostname resolver pair — see the
4706    /// companion [`Entrada::hostname`] docstring for the two-consumer
4707    /// lift + pair-invariant discipline (`hostnames() ==
4708    /// vec![hostname()]`, pinned load-bearing by the sibling
4709    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
4710    /// test).
4711    ///
4712    /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
4713    /// per-`:entrada` plural-list resolver on the per-HTTPRoute
4714    /// per-rule path-list axis — same `Vec<&str>` shape, same
4715    /// substrate-primitive-owns-the-resolver discipline extended to
4716    /// the per-HTTPRoute virtual-host filter-list axis.
4717    #[must_use]
4718    pub fn hostnames(&self) -> Vec<&str> {
4719        vec![self.hostname()]
4720    }
4721
4722    /// Substrate-canonical per-`:entrada` destination-Servico scalar
4723    /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
4724    /// the author-declared `:entrada :para` byte-string verbatim as a
4725    /// `&str`, borrowed from the typed slot's own [`String`] storage.
4726    ///
4727    /// The `:entrada :para` slot names the single member Servico the
4728    /// external Gateway routes to (validated by
4729    /// [`AplicacaoSpec::validate`] to be a
4730    /// [`Membro::caixa`] the Aplicacao declares — a stray
4731    /// `:para` that doesn't name a member is
4732    /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
4733    /// backend-attachment miss at cluster-apply time). Under today's
4734    /// single-destination author surface `:entrada :para` is the ingress
4735    /// apex Servico's canonical identity; under a hypothetical
4736    /// future multi-backend author surface (a `:entrada
4737    /// :split :backends` weighted-fan-out overlay for canary /
4738    /// blue-green traffic-split rollouts, per-path override for
4739    /// path-based per-Servico routing beyond the single-apex model,
4740    /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4741    /// per-CR admission-webhook that promotes the scalar to a
4742    /// weighted list) this accessor is the substrate primitive's typed
4743    /// dispatch every downstream `HTTPRoute`-aware consumer routes
4744    /// through, so the resolution shape migrates as a unit on one
4745    /// caixa-core edit rather than a coordinated rewrite across every
4746    /// renderer's inline field-access.
4747    ///
4748    /// Prior to this lift the `entrada.para` byte-string was accessed
4749    /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
4750    /// `metadata.name` composer's per-destination discriminator arg
4751    /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
4752    /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
4753    /// per-HTTPRoute per-rule `backendRefs[0].name` axis
4754    /// (`entrada.para.clone()`,
4755    /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
4756    /// consumers read the same `entrada.para` field but the two-site
4757    /// duplication expressed no compile-time contract that the HTTPRoute
4758    /// name-discriminator and the per-rule backend name stay in
4759    /// lockstep on future extensions of the `:entrada` slot to a
4760    /// multi-destination author surface. Any such extension would have
4761    /// to be threaded through every renderer's inline copy of the
4762    /// destination projection in lockstep or the HTTPRoute
4763    /// `metadata.name` would silently reference a different destination
4764    /// than its own `backendRefs[]` — an operator-side
4765    /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
4766    /// grep-by-name lookup would land on a route whose `backendRefs[]`
4767    /// silently point at a peer Servico, dropping every external
4768    /// `:entrada` flow at the gateway with the destination-drift root
4769    /// cause invisible in the emitted YAML.
4770    ///
4771    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
4772    /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
4773    /// the per-listener singular / per-HTTPRoute plural filter axes and
4774    /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
4775    /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
4776    /// typed dispatch on the substrate primitive, thin projections at
4777    /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
4778    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
4779    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
4780    /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
4781    /// sibling per-`:entrada` scalar-value + list-value axes — this
4782    /// accessor closes the last unlifted per-`:entrada` scalar axis
4783    /// (the destination-Servico byte-string) so every downstream
4784    /// per-`:entrada` reader now routes through a typed dispatch on
4785    /// the substrate primitive.
4786    #[must_use]
4787    pub fn destination(&self) -> &str {
4788        self.para.as_str()
4789    }
4790
4791    /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
4792    /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
4793    /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
4794    /// reader keys off — returns the author-declared `:entrada :port`
4795    /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
4796    /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
4797    /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
4798    /// [`AplicacaoError::EntradaPortZero`], not a silent
4799    /// admission-webhook rejection at cluster-apply time).
4800    ///
4801    /// The `:entrada :port` slot carries the destination Servico's
4802    /// canonical in-cluster L4 listener port (`trigger.service.port` on
4803    /// the `pleme-computeunit` library chart), and every downstream
4804    /// consumer that reads the port keys off this scalar (the
4805    /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
4806    /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
4807    /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
4808    /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
4809    /// CR materializer's per-Aplicacao gateway port resolver).
4810    ///
4811    /// Prior to this lift the `.port` field was accessed inline at two
4812    /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
4813    /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
4814    /// the [`AplicacaoSpec::port_for_destination`] resolver's
4815    /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
4816    /// open-coded field-accesses that expressed no compile-time link
4817    /// back to the typed slot. A future extension of the `:entrada :port`
4818    /// axis to a richer author surface — a per-cluster override the
4819    /// operator pins through a future `:placement :default-port` slot the
4820    /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
4821    /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
4822    /// heterogeneous listener ports, an M4
4823    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
4824    /// admission-webhook floor that promotes the scalar to a
4825    /// per-destination map — would have had to be threaded through both
4826    /// open-coded copies in lockstep or the structural-floor validator
4827    /// and the [`AplicacaoSpec::port_for_destination`] resolver would
4828    /// silently disagree on which port a given [`Entrada`] resolves to.
4829    /// Lifting the resolution rule to a typed method on the substrate
4830    /// primitive means every downstream consumer of the Aplicacao's
4831    /// per-`:entrada` L4-port surface reaches for exactly one typed
4832    /// dispatch — the resolver's accept-set migrates as a unit on any
4833    /// future axis addition.
4834    ///
4835    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
4836    /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
4837    /// accessors on the per-`:entrada` scalar-value axis — same "one
4838    /// typed dispatch on the substrate primitive, thin projections at
4839    /// each consumer" discipline extended onto the per-`:entrada`
4840    /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
4841    /// the M3 mesh-slot `Entrada` type — closes the last unlifted
4842    /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
4843    /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
4844    /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
4845    /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
4846    /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
4847    /// storage field's name; the accessor's identity name maps onto the
4848    /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
4849    /// already carries.
4850    #[must_use]
4851    pub fn port(&self) -> u16 {
4852        self.port
4853    }
4854
4855    /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
4856    /// slice accessor every HTTPRoute-aware renderer keys off when it
4857    /// wants the raw author-declared path-list (not the fallback-
4858    /// applied projection [`Self::resolved_paths`] returns) — returns
4859    /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
4860    /// borrowed from the typed slot's own [`Vec<String>`] storage.
4861    ///
4862    /// Named the "raw slot" half of the per-`:entrada` path-list resolver
4863    /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
4864    /// (1449891) closes the fallback-applying arm every per-Aplicacao
4865    /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
4866    /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
4867    /// catch-all; non-empty slot → per-entry verbatim projection); this
4868    /// accessor closes the raw-slot arm every consumer that must see the
4869    /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
4870    /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
4871    /// not `Err(EntradaPathEmpty)`, so it cannot route through the
4872    /// fallback-applying sibling; the `feira app graph` per-Aplicacao
4873    /// external-gateway summary line's `{:?}` Debug print — which must
4874    /// name the author's declaration, not the substrate's fallback, so
4875    /// an author reading their graph output can grep their caixa.lisp
4876    /// for the exact list they authored) routes through.
4877    ///
4878    /// Prior to this lift the `.paths` field was accessed inline at four
4879    /// production sites: the two internal reads in [`Self::resolved_paths`]
4880    /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
4881    /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
4882    /// value-shape gate's `for p in &e.paths` traversal head, and the
4883    /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
4884    /// Debug print — four open-coded field-accesses that expressed no
4885    /// compile-time link back to the typed slot. A future extension of
4886    /// the `:entrada :paths` axis to a richer author surface — a
4887    /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
4888    /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
4889    /// spec supports through `matches[].method`), a per-path per-header
4890    /// filter overlay (`matches[].headers[]`), a per-cluster override
4891    /// the operator pins through a future `:placement :path-overlay`
4892    /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4893    /// per-CR admission-webhook that normalized the list at admission
4894    /// time — would have had to be threaded through every open-coded
4895    /// copy in lockstep or the validator's per-entry gate would silently
4896    /// disagree with the renderer's per-entry emit on which list a given
4897    /// `:entrada` block resolves to. Lifting the resolution to a typed
4898    /// method on the substrate primitive means every downstream consumer
4899    /// of the Aplicacao's per-`:entrada` path-list surface reaches for
4900    /// exactly one typed dispatch — the resolver's accept-set migrates
4901    /// as a unit on any future axis addition.
4902    ///
4903    /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
4904    /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
4905    /// carry axis — same "one typed dispatch on the substrate primitive,
4906    /// thin projections at each consumer" discipline extended onto the
4907    /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
4908    /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
4909    /// carrier) so every downstream per-`:entrada` reader now routes
4910    /// through a typed dispatch on the substrate primitive. Returns
4911    /// `&[String]` (not `&Vec<String>`) because every downstream consumer
4912    /// treats the list as a read-only sequence — the slice-view is the
4913    /// narrowest borrow that supports every present + roadmapped consumer
4914    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
4915    /// `Vec`'s grow/push/reserve surface that no consumer of the typed
4916    /// view reaches for (the storage-side `Vec` remains reachable through
4917    /// the `pub paths` field for the mutation-carrying serde round-trip
4918    /// and per-test fixture-mutation paths).
4919    #[must_use]
4920    pub fn paths(&self) -> &[String] {
4921        self.paths.as_slice()
4922    }
4923}
4924
4925/// Canonical default L4 port every typed Servico exposes on its
4926/// in-cluster K8s Service (the `trigger.service.port` axis the
4927/// `pleme-computeunit` library chart emits, the `:entrada :port` author
4928/// surface defaults to when the author omits the slot, and the
4929/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
4930/// `:entrada` block matches the per-`:contratos` destination Servico).
4931/// The single source of truth all three typed-port consumers reach for:
4932///
4933///   - [`Entrada::port`]'s serde default (via the
4934///     [`default_port`] helper this constant feeds); the author surface
4935///     `(:entrada (:host … :para …))` without an explicit `:port` slot
4936///     reads back as a typed [`Entrada`] carrying this exact value;
4937///   - the
4938///     [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
4939///     emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
4940///     fallback, fired when the typed `:entrada` block doesn't name
4941///     the per-`:contratos` destination Servico — the typed
4942///     `:contratos` graph carries no per-destination port axis (the
4943///     destination port is the destination Servico's
4944///     `lareira-<nome>` chart's `trigger.service.port`, which the
4945///     Aplicacao-level renderer has no visibility into without a
4946///     resolver round-trip), so the renderer falls back to the
4947///     substrate's canonical Servico-port assumption — by
4948///     construction the same value the destination's own
4949///     `pleme-computeunit` chart emits, the same value the
4950///     destination's own typed `:entrada :port` slot defaults to;
4951///   - every future per-Servico renderer the absorption-roadmap
4952///     acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
4953///     CR materializer's per-edge port resolver, the future
4954///     per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
4955///     emitter's per-route bucket key, the future caixa-otel
4956///     collector-pipeline emitter's per-Servico scrape port).
4957///
4958/// Until this lift landed the value `8080` lived at two production-code
4959/// call-sites: the [`default_port`] helper at
4960/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
4961/// and the `.unwrap_or(8080)` literal at
4962/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
4963/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
4964/// resolver). A future Servico-port rebrand — the substrate moving the
4965/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
4966/// gateway grows direct `:80` listeners, to `8443` once the substrate
4967/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
4968/// override the operator pins through a future
4969/// `:placement :default-port` slot — without a coordinated edit on
4970/// both sides would silently emit Servicos listening on one port and
4971/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
4972/// The CNP's apply-time symptom (the policy is admitted but every L4
4973/// flow on the destination Servico's actual port silently drops because
4974/// it doesn't match the whitelisted port) is far from the rebrand
4975/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
4976/// in hubble traces, not in `kubectl describe`. Lifting the literal to
4977/// a shared constant closes the drift footgun structurally — both
4978/// consumers read from the same `u16`, so any rebrand reaches both
4979/// sites by construction.
4980///
4981/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
4982/// per-renderer canonical-K8s-axis constant — the namespace string
4983/// and the canonical Servico port both lived as duplicated literals
4984/// across caixa-core / caixa-mesh / caixa-flux before their respective
4985/// lifts. Same "the typed constant lives in one place" discipline the
4986/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
4987/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
4988/// shared-string axes.
4989///
4990/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
4991pub const DEFAULT_SERVICO_PORT: u16 = 8080;
4992
4993/// Structural floor for the typed `:entrada :port` axis — every
4994/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
4995/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
4996///
4997/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
4998/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
4999/// interprets as "let the kernel pick a free port at bind time", not a
5000/// well-defined destination the substrate's per-`:entrada` Gateway API
5001/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
5002/// carrying `port: 0` degenerates to a nominal-only routing target: the
5003/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
5004/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
5005/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
5006/// at build time rather than at `kubectl apply` time), and the
5007/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
5008/// (caixa-mesh/src/lib.rs:2657 through
5009/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
5010/// [`Entrada::port`] typed value — silently emits a policy whose
5011/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
5012/// actual listener, dropping every L4 flow at the eBPF data plane far
5013/// from the source caixa.lisp with no field naming the port-zero-drift
5014/// root cause.
5015///
5016/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
5017/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
5018/// on the top edge (unlike the peer capped-`u32` `:politicas` /
5019/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
5020/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
5021/// well below `u32::MAX` and therefore need explicit typed caps).
5022///
5023/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
5024/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
5025/// scalar every `(:entrada (:host … :para …))` slot without an explicit
5026/// `:port` inherits through the serde default hook; this constant names
5027/// the accept-set floor every declared port must satisfy. The pair is
5028/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
5029/// substrate's default must satisfy its own accept-set floor by
5030/// construction) — a future rebrand that accidentally moved
5031/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
5032/// negative-cast typo, a per-cluster override the operator pins through
5033/// a future `:placement :default-port` slot that lands out-of-range)
5034/// would silently invalidate the serde-default emission at every
5035/// author-side `(:entrada (:host … :para …))` slot — the compile-time
5036/// invariant pin
5037/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
5038/// closes the drift footgun at caixa-core build time.
5039///
5040/// Lifted as a typed `pub const` (rather than an inline `0` literal at
5041/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
5042/// has exactly one source of truth — the future M4
5043/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
5044/// gateway resolver, the future per-Servico
5045/// `computeunit.trigger.service.port` renderer's per-CR port-value
5046/// validator, and every downstream test-fixture navigator asserting
5047/// the accept-set floor all read from one place. Same shape every
5048/// other typed bracket-floor / bracket-ceiling in this crate carries
5049/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
5050/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
5051/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
5052/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
5053/// [`POLICY_RATE_LIMIT_MAX`]).
5054pub const SERVICO_PORT_MIN: u16 = 1;
5055
5056const fn default_port() -> u16 {
5057    DEFAULT_SERVICO_PORT
5058}
5059
5060// ── the typed view ───────────────────────────────────────────────────
5061
5062/// Typed composition view of the flat Aplicacao slots on
5063/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
5064/// validation + downstream renderer consumption.
5065#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5066#[serde(rename_all = "camelCase")]
5067pub struct AplicacaoSpec {
5068    pub membros: Vec<Membro>,
5069    pub contratos: Vec<WitContract>,
5070    pub politicas: MeshPolicy,
5071    pub placement: Placement,
5072    pub entrada: Option<Entrada>,
5073}
5074
5075impl AplicacaoSpec {
5076    /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
5077    /// per-Aplicacao member-list slice-return accessor every
5078    /// per-Aplicacao member-list reader keys off — returns the author-
5079    /// declared `:membros` list verbatim as a `&[Membro]` slice-view
5080    /// over the same backing buffer the raw `self.membros.as_slice()`
5081    /// field access borrows from.
5082    ///
5083    /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
5084    /// member list — the load-bearing identity of the application graph
5085    /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
5086    /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
5087    /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
5088    /// accessor) with a `:versao` semver-requirement string (through
5089    /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
5090    /// and every downstream consumer that fans on the member-set keys
5091    /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
5092    /// membership-lookup `HashSet<&str>` seed's collect input, the
5093    /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
5094    /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
5095    /// per-member DNS-1123 / semver-requirement / duplicate-detection
5096    /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
5097    /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
5098    /// programs.yaml per-`:membros` fan-out emitter's per-entry
5099    /// mapping-composition loop, the `feira app graph` per-Aplicacao
5100    /// member-count print line and per-member tree traversal,
5101    /// every future wasm-operator (M4) per-Aplicacao CR materializer's
5102    /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
5103    /// placement engine's per-member weight-topology reader).
5104    ///
5105    /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
5106    /// inline at six production sites — the [`AplicacaoSpec::validate`]
5107    /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
5108    /// [`AplicacaoSpec::validate_membros`]'s pre-flight
5109    /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
5110    /// probe, the same method's per-member `for m in &self.membros`
5111    /// validate-loop traversal head, the
5112    /// [`AplicacaoSpec::detect_sync_cycles`]'s
5113    /// `for m in &self.membros` adjacency-list seed, the
5114    /// [`caixa_mesh::programs_for_aplicacao`] emitter's
5115    /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
5116    /// paired with the peer `for m in &spec.membros` per-entry fan-out
5117    /// loop, and the `feira app graph` per-Aplicacao print line's
5118    /// `spec.membros.len()` count formatter argument paired with the
5119    /// peer `for m in &spec.membros` per-member tree traversal — six
5120    /// open-coded field-accesses that expressed no compile-time link
5121    /// back to the typed slot. A future extension of the `:membros`
5122    /// axis to a richer author surface (a per-cluster member-set
5123    /// overlay the operator pins through a future
5124    /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
5125    /// roadmap acknowledges, a per-tenant member-alias table the M4
5126    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
5127    /// CR at admission time, a per-Aplicacao dynamic member-set
5128    /// derivation the future adaptive-placement engine computes from
5129    /// weighted membership topology, a promotion of the plain
5130    /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
5131    /// Orleans-style virtual-actor dynamic-membership comes into typed
5132    /// scope) would have had to be threaded through all six open-coded
5133    /// copies in lockstep or one consumer would silently disagree with
5134    /// the peers on which member-set a given Aplicacao resolves to —
5135    /// the `HashSet<&str>` name-set seed reading the raw slot while
5136    /// the peer `.is_empty()` refusal probe read an operator-resolved
5137    /// slot would silently split the `:contratos` membership-lookup
5138    /// input from the pre-flight-refusal input, a six-consumer split
5139    /// at the validator + programs.yaml emitter + graph printer far
5140    /// from the source `caixa.lisp` with no field naming the member-
5141    /// set-drift root cause. Lifting the resolution rule to a typed
5142    /// method on the substrate primitive means every downstream
5143    /// consumer of the Aplicacao's per-`:membros` member-list surface
5144    /// reaches for exactly one typed dispatch — the resolver's accept-
5145    /// set migrates as a unit on any future axis addition.
5146    ///
5147    /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
5148    /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
5149    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
5150    /// static-child-list `Vec`-carry axis, and to the M3
5151    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
5152    /// on the peer per-`:placement` distribution-target-list `Vec`-
5153    /// carry axis. Same "one typed dispatch on the substrate primitive,
5154    /// thin projections at each consumer" discipline. The two peer
5155    /// `Vec`-carry axes still unlifted at the time of this lift —
5156    /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
5157    /// WIT-typed edge list) and
5158    /// [`crate::UpgradeFromEntry::instructions`]
5159    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
5160    /// — inherit this accessor's discipline as future compounding runs
5161    /// migrate their consumers onto the shared slice-return shape.
5162    /// First `&[T]`-return accessor on the top-level M3 mesh-slot
5163    /// `AplicacaoSpec` type itself, extending the discipline beyond
5164    /// the inner per-slot types ([`crate::Placement`],
5165    /// [`crate::SupervisorSpec`]) onto the outermost typed composition
5166    /// view every renderer consumes. Named `membros()` to match the
5167    /// storage field's name verbatim and the tatara-lisp author-
5168    /// surface term (`:membros`) the field's own docstring already
5169    /// carries; the accessor's identity maps onto the canonical
5170    /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
5171    /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
5172    /// every downstream consumer of the member list treats it as a
5173    /// read-only sequence — the slice-view is the narrowest borrow
5174    /// that supports every present + roadmapped consumer
5175    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
5176    /// backing `Vec`'s grow/push/reserve surface that no consumer of
5177    /// the typed view reaches for (the storage-side `Vec` remains
5178    /// reachable through the `pub membros` field for the mutation-
5179    /// carrying serde round-trip and per-test fixture-mutation paths).
5180    #[must_use]
5181    pub fn membros(&self) -> &[Membro] {
5182        self.membros.as_slice()
5183    }
5184
5185    /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
5186    /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
5187    /// accessor every per-Aplicacao contract-list reader keys off —
5188    /// returns the author-declared `:contratos` list verbatim as a
5189    /// `&[WitContract]` slice-view over the same backing buffer the raw
5190    /// `self.contratos.as_slice()` field access borrows from.
5191    ///
5192    /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
5193    /// WIT-typed edge list — the load-bearing set of directed edges
5194    /// on the application graph whose nodes are the `:membros` entries
5195    /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
5196    /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
5197    /// six-tuple is the edge identity every downstream duplicate gate
5198    /// keys off). Every per-`:contratos` entry pairs a `:de` source-
5199    /// Servico caller name + a `:para` destination-Servico callee name
5200    /// (through the lifted [`WitContract::source`] +
5201    /// [`WitContract::destination`] (7f0fd43) accessor pair on the
5202    /// caller/callee-Servico axis) with a `:wit` world-reference
5203    /// (through the lifted [`WitContract::world_ref`] (0804823)
5204    /// accessor) and the target-shape-appropriate payload-carrier
5205    /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
5206    /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
5207    /// (ed22b66) accessor on the per-target-shape payload-carrier
5208    /// axis). Every downstream consumer that fans on the edge-set
5209    /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
5210    /// name-set / self-edge / target-shape / dedup fan-out loop, the
5211    /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
5212    /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
5213    /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
5214    /// grouping loop, the `feira app graph` per-Aplicacao contract-
5215    /// count print line and per-contract tree traversal, every future
5216    /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
5217    /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
5218    /// mesh-policy overlay resolver's per-contract typed-edge weight
5219    /// reader).
5220    ///
5221    /// Prior to this lift the `.contratos` `Vec<WitContract>` was
5222    /// accessed inline at four production sites — the
5223    /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
5224    /// per-edge validate-loop traversal head (which drives every
5225    /// per-edge name-set membership lookup, self-edge check,
5226    /// target-shape dispatch, and dedup `HashSet` insert), the
5227    /// [`AplicacaoSpec::detect_sync_cycles`]'s
5228    /// `for c in &self.contratos` adjacency-list seed head (which
5229    /// drives every per-edge sync-vs-pub-sub partition and per-edge
5230    /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
5231    /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
5232    /// `BTreeMap` grouping loop head (which drives every per-CNP
5233    /// fan-out emit), and the `feira app graph` per-Aplicacao print
5234    /// line's `spec.contratos.len()` count formatter argument paired
5235    /// with the peer `for c in &spec.contratos` per-contract tree
5236    /// traversal — four open-coded field-accesses that expressed no
5237    /// compile-time link back to the typed slot. A future extension
5238    /// of the `:contratos` axis to a richer author surface (a
5239    /// per-cluster contract overlay the operator pins through a
5240    /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
5241    /// federation roadmap acknowledges, a per-tenant edge-policy
5242    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5243    /// materializer resolves per-CR at admission time, a per-edge
5244    /// weight scalar the future adaptive-placement engine reads to
5245    /// bias sync-subgraph routing, a promotion of the plain
5246    /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
5247    /// once virtual-actor-style dynamic-edge composition comes into
5248    /// typed scope) would have had to be threaded through all four
5249    /// open-coded copies in lockstep or one consumer would silently
5250    /// disagree with the peers on which edge-set a given Aplicacao
5251    /// resolves to — the validator's per-edge dedup `HashSet` seed
5252    /// reading the raw slot while the peer sync-cycle adjacency-list
5253    /// seed read an operator-resolved slot would silently split the
5254    /// build-time edge-set gate from the runtime deadlock-detection
5255    /// gate, a four-consumer split at the validator, the cycle
5256    /// detector, the CNP emitter, and the graph printer far from
5257    /// the source `caixa.lisp` with no field naming the edge-set-
5258    /// drift root cause. Lifting the resolution rule to a typed method on the
5259    /// substrate primitive means every downstream consumer of the
5260    /// Aplicacao's per-`:contratos` edge-list surface reaches for
5261    /// exactly one typed dispatch — the resolver's accept-set
5262    /// migrates as a unit on any future axis addition.
5263    ///
5264    /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
5265    /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
5266    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
5267    /// static-child-list `Vec`-carry axis, to the M3
5268    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
5269    /// on the peer per-`:placement` distribution-target-list `Vec`-
5270    /// carry axis, and to the immediately-adjacent sibling M3
5271    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
5272    /// the peer per-`:membros` node-list `Vec`-carry axis — the
5273    /// per-`:contratos` edge-list accessor is the natural pair of
5274    /// the per-`:membros` node-list accessor (graph edges over graph
5275    /// nodes; every graph-shaped consumer reads both). Same "one
5276    /// typed dispatch on the substrate primitive, thin projections
5277    /// at each consumer" discipline. The last remaining `Vec`-carry
5278    /// axis still unlifted at the time of this lift —
5279    /// [`crate::UpgradeFromEntry::instructions`]
5280    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
5281    /// list) — inherits this accessor's discipline as future
5282    /// compounding runs migrate its consumers onto the shared slice-
5283    /// return shape. Second `&[T]`-return accessor on the top-level
5284    /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
5285    /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
5286    /// `:contratos` are the two `Vec` fields on the outer typed
5287    /// composition view — `:politicas`, `:placement`, `:entrada` are
5288    /// scalar/option-shaped and already route through their per-slot
5289    /// accessor families). Named `contratos()` to match the storage
5290    /// field's name verbatim and the tatara-lisp author-surface term
5291    /// (`:contratos`) the field's own docstring already carries; the
5292    /// accessor's identity maps onto the canonical MESH-COMPOSITION
5293    /// §III.1 vocabulary the slot's docstring already reaches for.
5294    /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
5295    /// every downstream consumer of the contract list treats it as a
5296    /// read-only sequence — the slice-view is the narrowest borrow
5297    /// that supports every present + roadmapped consumer
5298    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
5299    /// backing `Vec`'s grow/push/reserve surface that no consumer of
5300    /// the typed view reaches for (the storage-side `Vec` remains
5301    /// reachable through the `pub contratos` field for the mutation-
5302    /// carrying serde round-trip and per-test fixture-mutation paths).
5303    #[must_use]
5304    pub fn contratos(&self) -> &[WitContract] {
5305        self.contratos.as_slice()
5306    }
5307
5308    /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
5309    /// per-Aplicacao mesh-policy composite-reference accessor every
5310    /// per-Aplicacao policy-block reader keys off — returns the author-
5311    /// declared `:politicas` composite verbatim as a `&MeshPolicy`
5312    /// reference over the same backing storage the raw `&self.politicas`
5313    /// field access borrows from.
5314    ///
5315    /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
5316    /// mesh-policy composite — the load-bearing container of every
5317    /// mesh-level operational-policy axis every downstream mesh-artifact
5318    /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
5319    /// mesh-policy overlay is the single typed surface a
5320    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
5321    /// from). Every per-`:politicas` axis threads through a lifted
5322    /// per-slot accessor on the [`MeshPolicy`] type: the
5323    /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
5324    /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
5325    /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
5326    /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
5327    /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
5328    /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
5329    /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
5330    /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
5331    /// accessor. Every downstream consumer that reaches for a policy
5332    /// axis first passes through this outer accessor onto the composite
5333    /// and then dispatches onto the per-axis accessor — the two-level
5334    /// dispatch means every per-`:politicas` reader now routes through
5335    /// a typed dispatch on the substrate primitive at both altitudes.
5336    ///
5337    /// Prior to this lift the `.politicas` `MeshPolicy` composite was
5338    /// accessed inline at four production sites — the
5339    /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
5340    /// &self.politicas;` traversal seed (which drives every per-axis
5341    /// zero-floor + upper-cap + canonical-form bracket dispatch through
5342    /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
5343    /// `p.rate_limit()` on the axis-level lifted accessors), the
5344    /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
5345    /// emitter's `spec.politicas.mtls_required()` field-then-accessor
5346    /// chain (which drives every per-`(:de, :para)` CNP
5347    /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
5348    /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
5349    /// timeout + retry overlay emitter's paired
5350    /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
5351    /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
5352    /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
5353    /// open-coded outer-field accesses that expressed no compile-time
5354    /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
5355    /// future extension of the `:politicas` outer axis to a richer
5356    /// author surface (a per-cluster policy overlay the operator pins
5357    /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
5358    /// §V federation roadmap acknowledges, a per-tenant policy-alias
5359    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
5360    /// resolves per-CR at admission time, a per-Aplicacao dynamic
5361    /// policy-composite derivation the future adaptive-placement engine
5362    /// computes from a per-cluster load-topology reader, a promotion of
5363    /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
5364    /// partition once virtual-actor-style dynamic-mesh-policy
5365    /// composition comes into typed scope) would have had to be threaded
5366    /// through all four open-coded copies in lockstep or one consumer
5367    /// would silently disagree with the peers on which mesh-policy
5368    /// composite a given Aplicacao resolves to — the validator's
5369    /// per-axis bracket-dispatch seed reading the raw slot while the
5370    /// peer CNP mTLS-overlay emitter read an operator-resolved slot
5371    /// would silently split the build-time policy-shape gate from the
5372    /// runtime CNP-emission gate, a four-consumer split at the
5373    /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
5374    /// the source `caixa.lisp` with no field naming the policy-drift
5375    /// root cause. Lifting the resolution rule to a typed method on the
5376    /// substrate primitive means every downstream consumer of the
5377    /// Aplicacao's per-`:politicas` mesh-policy composite surface
5378    /// reaches for exactly one typed dispatch — the resolver's accept-
5379    /// set migrates as a unit on any future axis addition.
5380    ///
5381    /// First `&Composite`-return accessor on the top-level M3 mesh-slot
5382    /// `AplicacaoSpec` type itself — sibling to the seed slice-return
5383    /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
5384    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
5385    /// close the two `Vec`-carry axes on the outer typed composition
5386    /// view; the outer `:politicas` composite-reference axis is the
5387    /// natural pair to the paired outer `Vec`-carry accessors on the
5388    /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
5389    /// emitter reads all four axes as one unit (graph nodes + graph
5390    /// edges + mesh policy + placement pool). Peer to the same
5391    /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
5392    /// slot: every M2 `SupervisorSpec`-scoped composite reader
5393    /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
5394    /// `restart_window`, `children`) already routes through the M2
5395    /// `SupervisorSpec` accessor family — this lift extends the same
5396    /// "one typed dispatch on the substrate primitive at the outer
5397    /// composition altitude" discipline to the M3 mesh-slot
5398    /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
5399    /// remaining peer outer-composite axes still unlifted at the time
5400    /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
5401    /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
5402    /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
5403    /// inherit this accessor's discipline as future compounding runs
5404    /// migrate their consumers onto the shared reference-return shape.
5405    /// Named `politicas()` to match the storage field's name verbatim
5406    /// and the tatara-lisp author-surface term (`:politicas`) the
5407    /// field's own docstring already carries; the accessor's identity
5408    /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
5409    /// slot's docstring already reaches for. Returns `&MeshPolicy`
5410    /// (not the owning composite by copy or clone) because every
5411    /// downstream consumer of the mesh-policy composite treats it as a
5412    /// read-only per-axis dispatch source — the reference-view is the
5413    /// narrowest borrow that supports every present + roadmapped
5414    /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
5415    /// emptiness probe) without cloning the composite through every
5416    /// consumer's fast path.
5417    #[must_use]
5418    pub fn politicas(&self) -> &MeshPolicy {
5419        &self.politicas
5420    }
5421
5422    /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
5423    /// per-Aplicacao distribution-composite composite-reference accessor
5424    /// every per-Aplicacao placement-block reader keys off — returns the
5425    /// author-declared `:placement` composite verbatim as a `&Placement`
5426    /// reference over the same backing storage the raw `&self.placement`
5427    /// field access borrows from.
5428    ///
5429    /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
5430    /// distribution composite — the load-bearing container of every
5431    /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
5432    /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
5433    /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
5434    /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
5435    /// hosting-pool identity, §V for the `M3-Adaptive`-compression
5436    /// `:affinity` hint). Every per-`:placement` axis threads through a
5437    /// lifted per-slot accessor on the [`Placement`] type: the
5438    /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
5439    /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
5440    /// per-cluster distribution-target slice-return accessor, the
5441    /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
5442    /// optional-scalar accessor, and the [`Placement::shard_key`]
5443    /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
5444    /// downstream consumer that reaches for a placement axis first passes
5445    /// through this outer accessor onto the composite and then dispatches
5446    /// onto the per-axis accessor — the two-level dispatch means every
5447    /// per-`:placement` reader now routes through a typed dispatch on the
5448    /// substrate primitive at both altitudes.
5449    ///
5450    /// Prior to this lift the `.placement` `Placement` composite was
5451    /// accessed inline at three production sites — the
5452    /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
5453    /// seed (six `self.placement.<axis>()` field-then-inner-accessor
5454    /// chains: the pre-flight `.clusters().is_empty()` refusal probe
5455    /// paired with the `.estrategia()` diagnostic-carry copy, the per-
5456    /// cluster `.clusters()` validate-loop traversal head, the per-
5457    /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
5458    /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
5459    /// paired with the shape-gate cascade's `.shard_key()` /
5460    /// `.estrategia()` diagnostic-carry pair), the
5461    /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
5462    /// per-entry placement-block emitter's outer
5463    /// `serde_yaml::to_value(&spec.placement)` composite-serialization
5464    /// seed (which fans onto every per-cluster `programs[]` entry as a
5465    /// self-describing distribution overlay the aggregator filters by),
5466    /// and the `feira app graph` per-Aplicacao print line's paired
5467    /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
5468    /// then-inner-accessor chains (which drive the human-readable
5469    /// distribution summary of the typed Aplicacao view) — three open-
5470    /// coded outer-field accesses that expressed no compile-time link
5471    /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
5472    /// extension of the `:placement` outer axis to a richer author surface
5473    /// (a per-cluster placement overlay the operator pins through a
5474    /// future `:placement-overrides` slot the MESH-COMPOSITION §V
5475    /// federation roadmap acknowledges, a per-tenant placement-alias
5476    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
5477    /// resolves per-CR at admission time, a per-Aplicacao dynamic
5478    /// placement-composite derivation the future M5 adaptive-placement
5479    /// engine computes from a per-cluster load-topology reader, a
5480    /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
5481    /// partition once Orleans-style virtual-actor dynamic-placement comes
5482    /// into typed scope) would have had to be threaded through all three
5483    /// open-coded copies in lockstep or one consumer would silently
5484    /// disagree with the peers on which placement composite a given
5485    /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
5486    /// seed reading the raw slot while the peer
5487    /// `programs_for_aplicacao` emitter read an operator-resolved slot
5488    /// would silently split the build-time distribution-shape gate from
5489    /// the runtime programs.yaml distribution-annotation gate, a three-
5490    /// consumer split at the validator, the programs.yaml emitter, and
5491    /// the `feira app graph` printer far from the source `caixa.lisp`
5492    /// with no field naming the placement-drift root cause. Lifting the
5493    /// resolution rule to a typed method on the substrate primitive
5494    /// means every downstream consumer of the Aplicacao's per-
5495    /// `:placement` distribution composite surface reaches for exactly
5496    /// one typed dispatch — the resolver's accept-set migrates as a unit
5497    /// on any future axis addition.
5498    ///
5499    /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
5500    /// `AplicacaoSpec` type itself — sibling to the seed
5501    /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
5502    /// composite-reference accessor on the peer per-`:politicas` outer-
5503    /// composite axis, and to the paired slice-return accessors
5504    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
5505    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
5506    /// the two `Vec`-carry axes on the outer typed composition view; the
5507    /// outer `:placement` composite-reference axis is the natural pair
5508    /// to the peer `:politicas` composite-reference axis on the two
5509    /// operationally-symmetric M3 mesh slots (`:politicas` carries the
5510    /// how-to-run policy overlay, `:placement` carries the where-to-run
5511    /// distribution composite — every whole-Aplicacao mesh-artifact
5512    /// emitter reads both as one unit). Same "one typed dispatch on the
5513    /// substrate primitive, thin projections at each consumer"
5514    /// discipline the peer per-`:politicas` composite-reference axis
5515    /// already routes through. The one remaining outer-composite axis
5516    /// still unlifted at the time of this lift —
5517    /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
5518    /// external-gateway composite) — inherits this accessor's discipline
5519    /// as the next compounding run migrates its consumers onto the shared
5520    /// reference-return shape, closing the outer-composite altitude on
5521    /// every M3 mesh-slot axis. Named `placement()` to match the storage
5522    /// field's name verbatim and the tatara-lisp author-surface term
5523    /// (`:placement`) the field's own docstring already carries; the
5524    /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
5525    /// vocabulary the slot's docstring already reaches for. Returns
5526    /// `&Placement` (not the owning composite by copy or clone) because
5527    /// every downstream consumer of the placement composite treats it as
5528    /// a read-only per-axis dispatch source — the reference-view is the
5529    /// narrowest borrow that supports every present + roadmapped consumer
5530    /// (per-axis accessor dispatch, serde composite-serialization) without
5531    /// cloning the composite through every consumer's fast path.
5532    #[must_use]
5533    pub fn placement(&self) -> &Placement {
5534        &self.placement
5535    }
5536
5537    /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
5538    /// per-Aplicacao external-gateway composite optional-composite-
5539    /// reference accessor every per-Aplicacao gateway-block reader
5540    /// keys off — returns the author-declared `:entrada` composite
5541    /// verbatim as an `Option<&Entrada>` reference over the same
5542    /// backing storage the raw `self.entrada.as_ref()` field access
5543    /// borrows from, with `None` naming the internal-only mesh shape
5544    /// (the author-omitted `:entrada` slot the K8s Gateway API v1
5545    /// gateway_routes emitter treats as "emit nothing" and the peer
5546    /// `feira app graph` printer treats as "internal-only mesh").
5547    ///
5548    /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
5549    /// external-gateway composite — the load-bearing container of
5550    /// every does-this-Aplicacao-expose-a-public-endpoint axis every
5551    /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
5552    /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
5553    /// hostname axis, §III.4 for the `:para` destination-Servico
5554    /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
5555    /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
5556    /// axis threads through a lifted per-slot accessor on the
5557    /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
5558    /// Gateway-API `Listener.hostname` scalar accessor, the paired
5559    /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
5560    /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
5561    /// backendRefs destination-Servico scalar accessor, the
5562    /// [`Entrada::resolved_paths`] path-fallback resolver, and the
5563    /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
5564    /// scalar accessor. Every downstream consumer that reaches for
5565    /// an entrada axis first passes through this outer accessor onto
5566    /// the composite and then dispatches onto the per-axis accessor
5567    /// — the two-level dispatch means every per-`:entrada` reader
5568    /// now routes through a typed dispatch on the substrate primitive
5569    /// at both altitudes.
5570    ///
5571    /// Prior to this lift the `.entrada` `Option<Entrada>` composite
5572    /// was accessed inline at four production sites — the
5573    /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
5574    /// gate's `if let Some(e) = &self.entrada { … }` traversal head
5575    /// (which drives every per-axis refusal on the composite: the
5576    /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
5577    /// `EntradaMemberMissing` membership lookup against the
5578    /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
5579    /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
5580    /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
5581    /// per-path shape gate on each entry of `e.paths`), the
5582    /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
5583    /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
5584    /// composite-projection seed (which drives the destination-
5585    /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
5586    /// backendRefs port emitter fans on), the
5587    /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
5588    /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
5589    /// early-return seed (which drives the "no `:entrada` ⇒ no
5590    /// external artifacts" partition on the whole-Aplicacao Gateway-
5591    /// API emitter's fan-out), and the `feira app graph` per-
5592    /// Aplicacao print line's `if let Some(e) = &spec.entrada`
5593    /// external-gateway summary emitter (which drives the human-
5594    /// readable `entrada: host → para (paths=…, port=…)` /
5595    /// `entrada: (internal-only mesh)` partition on the typed
5596    /// Aplicacao view) — four open-coded outer-field accesses that
5597    /// expressed no compile-time link back to the typed slot at the
5598    /// [`AplicacaoSpec`] altitude. A future extension of the
5599    /// `:entrada` outer axis to a richer author surface (a
5600    /// multi-`:entrada` list the M4 CR materializer resolves per-CR
5601    /// at admission time so an Aplicacao can expose a public-web +
5602    /// admin-web pair, a per-cluster `:entrada-overrides` slot the
5603    /// MESH-COMPOSITION §V federation roadmap acknowledges so an
5604    /// operator can pin a per-cluster hostname override without
5605    /// re-authoring the `caixa.lisp`, a promotion of the plain
5606    /// `Option<Entrada>` to a richer `{single, multi}` partition once
5607    /// the multi-`:entrada` roadmap lands) would have had to be
5608    /// threaded through all four open-coded copies in lockstep or one
5609    /// consumer would silently disagree with the peers on which
5610    /// entrada composite a given Aplicacao resolves to — the
5611    /// validator's per-axis bracket-dispatch seed reading the raw
5612    /// slot while the peer `gateway_routes` emitter read an
5613    /// operator-resolved slot would silently split the build-time
5614    /// gateway-shape gate from the runtime Gateway + HTTPRoute
5615    /// emission gate, a four-consumer split at the validator, the
5616    /// `port_for_destination` L4-port resolver, the `gateway_routes`
5617    /// emitter, and the `feira app graph` printer far from the
5618    /// source `caixa.lisp` with no field naming the entrada-drift
5619    /// root cause. Lifting the resolution rule to a typed method on
5620    /// the substrate primitive means every downstream consumer of
5621    /// the Aplicacao's per-`:entrada` external-gateway composite
5622    /// surface reaches for exactly one typed dispatch — the
5623    /// resolver's accept-set migrates as a unit on any future axis
5624    /// addition.
5625    ///
5626    /// Third and final `&Composite`-return accessor on the top-level
5627    /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
5628    /// unlifted outer-composite axis on the outer typed composition
5629    /// view, sibling to the seed [`AplicacaoSpec::politicas`]
5630    /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
5631    /// accessor on the per-`:politicas` outer-composite axis and to
5632    /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
5633    /// distribution-composite composite-reference accessor on the
5634    /// per-`:placement` outer-composite axis; extends the outer-
5635    /// composite reference-return discipline the two peers already
5636    /// route through onto the last unlifted per-`AplicacaoSpec`
5637    /// outer-composite axis. The `:entrada` outer-composite axis is
5638    /// the natural pair to the two peer outer-composite axes on the
5639    /// three operationally-symmetric M3 mesh-slot outer composites
5640    /// (`:politicas` carries the how-to-run policy overlay,
5641    /// `:placement` carries the where-to-run distribution composite,
5642    /// `:entrada` carries the who-can-reach-it external-gateway
5643    /// composite — every whole-Aplicacao mesh-artifact emitter reads
5644    /// all three as one unit). Same "one typed dispatch on the
5645    /// substrate primitive, thin projections at each consumer"
5646    /// discipline the peer outer-composite axes already route through.
5647    /// Named `entrada()` to match the storage field's name verbatim
5648    /// and the tatara-lisp author-surface term (`:entrada`) the
5649    /// field's own docstring already carries; the accessor's
5650    /// identity maps onto the canonical MESH-COMPOSITION §III.4
5651    /// vocabulary the slot's docstring already reaches for. Returns
5652    /// `Option<&Entrada>` (not the owning composite by copy or
5653    /// clone) because every downstream consumer of the entrada
5654    /// composite treats it as a read-only per-axis dispatch source
5655    /// — the reference-view is the narrowest borrow that supports
5656    /// every present + roadmapped consumer (per-axis accessor
5657    /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
5658    /// port-fallback projection, early-return partition on the
5659    /// `None` arm) without cloning the composite through every
5660    /// consumer's fast path. The `Option` half of the return-type
5661    /// preserves the load-bearing "author-omitted `:entrada` ⇒
5662    /// internal-only mesh" partition (not a default composite the
5663    /// downstream must reject on emptiness) — the accessor projects
5664    /// the raw `Option<Entrada>` slot's presence bit through the
5665    /// reference-return unchanged.
5666    #[must_use]
5667    pub fn entrada(&self) -> Option<&Entrada> {
5668        self.entrada.as_ref()
5669    }
5670
5671    /// Validate the typed shape:
5672    ///   - `:membros` is non-empty; every entry has a non-empty `:caixa`
5673    ///     and a non-empty `:versao`; no two entries share the same
5674    ///     `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
5675    ///     not a multiset)
5676    ///   - every `:contratos` :de + :para must be in `:membros`
5677    ///   - no `:contratos` edge is a self-edge (`:de == :para`) — a
5678    ///     contract is an inter-Servico edge, so a Servico contracting
5679    ///     with itself is a build error under every WIT shape
5680    ///     (MESH-COMPOSITION §III.1)
5681    ///   - no two `:contratos` entries agree on
5682    ///     `(de, para, wit, endpoint, subject, slot)` — the typed-graph
5683    ///     edges are a set, not a multiset (peer of the `:membros` /
5684    ///     `:placement :clusters` / `:entrada :paths` duplicate gates)
5685    ///   - `:entrada :para` must be in `:membros`
5686    ///   - `:placement Sharded` must declare `:shard-key` (non-empty);
5687    ///     `:placement Replicated`/`SingleNode` must NOT declare
5688    ///     `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
5689    ///     consumes it (MESH-COMPOSITION §II.4), and the typed partition
5690    ///     between strategy and shard-key is symmetric: every validated
5691    ///     `Placement` has `shard_key.is_some()` iff `estrategia ==
5692    ///     Sharded`
5693    ///   - every `:placement` strategy must declare ≥1 `:clusters` entry —
5694    ///     `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
5695    ///     the shard pool (MESH-COMPOSITION §III.1)
5696    ///   - every `:clusters` entry is non-empty and unique
5697    ///   - `:placement :affinity`, when set, is non-empty
5698    ///   - the synchronous-`:contratos` subgraph is acyclic
5699    ///     (MESH-COMPOSITION §III.3)
5700    ///   - every declared `:politicas` value is operationally meaningful
5701    ///     (zero timeout, zero retries, zero breaker thresholds, zero rate
5702    ///     limit are all build errors — MESH-COMPOSITION §V CSE invariants;
5703    ///     omit the field instead to express "no policy on this axis")
5704    pub fn validate(&self) -> Result<(), AplicacaoError> {
5705        self.validate_membros()?;
5706        let names: std::collections::HashSet<&str> =
5707            self.membros().iter().map(Membro::nome).collect();
5708
5709        // Identity key for the typed-edge duplicate gate below: every
5710        // field that distinguishes one contract from another. Two
5711        // entries that agree on all six are *the same edge declared
5712        // twice*, the typed-graph analogue of duplicate `:membros` /
5713        // `:placement :clusters` / `:entrada :paths` entries (which
5714        // are already build errors at this layer). Rejecting it at the
5715        // validate gate closes a renderer-side footgun: caixa-mesh's
5716        // `cilium_network_policies` keys each emitted policy by
5717        // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
5718        // (de, para) and identical payload would land as two K8s
5719        // objects with colliding `metadata.name`, rejected at apply
5720        // time far from the source caixa.lisp.
5721        let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
5722            std::collections::HashSet::new();
5723        for c in self.contratos() {
5724            // Per-axis value-shape gate on every `:contratos` name
5725            // reference, before any graph-membership lookup. Empty +
5726            // DNS-1123-malformed `:de`/`:para` values silently fell
5727            // through to `ContratoMemberMissing` at the lookup arm
5728            // because every `:membros :caixa` is shape-validated
5729            // (3f9d7a0), so the `names` set structurally cannot contain
5730            // an empty / malformed string and the membership-lookup
5731            // diagnostic always misframed the root cause as
5732            // "this caixa is not in `:membros`". The shape gate runs
5733            // ahead of the lookup so structurally-impossible-to-match
5734            // inputs route through the narrower self-locating
5735            // diagnostic, preserving the legitimate "well-shaped
5736            // phantom reference" arm. `:de` runs before `:para` per
5737            // the canonical edge-direction order the existing
5738            // membership lookup, self-edge check, target dispatch,
5739            // and diagnostic strings already use.
5740            // Route the per-`:contratos` per-arm DNS-1123 shape-gate arg
5741            // + the paired [`AplicacaoError::ContratoMemberMissing`]
5742            // diagnostic's `caixa:` carrier through the lifted
5743            // [`WitContract::source`] / [`WitContract::destination`]
5744            // scalar accessors rather than the raw `&c.de` / `&c.para`
5745            // `&String`-borrow arg site + the raw `c.de.clone()` /
5746            // `c.para.clone()` field-access `String`-carry sites — the
5747            // last unlifted per-`:contratos` raw-field-access sites in
5748            // the M3 mesh-slot validator's per-edge per-arm shape-gate
5749            // arg + phantom-name diagnostic wrap-envelope emit surface.
5750            // `c.source()` is byte-identical to `&c.de` (pinned by the
5751            // sibling `wit_contract_source_returns_de_byte_equal_across_permutations`
5752            // + `wit_contract_source_borrows_from_de_storage` accessor
5753            // tests) and `c.destination()` is byte-identical to `&c.para`
5754            // (pinned by the sibling
5755            // `wit_contract_destination_returns_para_byte_equal_across_permutations`
5756            // + `wit_contract_destination_borrows_from_para_storage`
5757            // accessor tests) — so a future rebrand of either underlying
5758            // storage flows through the accessor's one body without a
5759            // coordinated per-consumer rewrite across the M3 mesh
5760            // validator's per-edge shape-gate + phantom-name refusal
5761            // arms. Peer of the sibling per-`:contratos` self-loop
5762            // arm's `.source().to_string()` / `.world_ref().to_string()`
5763            // `String`-carry sites the earlier convergence lifted onto
5764            // the same accessor pair.
5765            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
5766            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
5767            if !names.contains(c.source()) {
5768                return Err(AplicacaoError::ContratoMemberMissing {
5769                    caixa: c.source().to_string(),
5770                });
5771            }
5772            if !names.contains(c.destination()) {
5773                return Err(AplicacaoError::ContratoMemberMissing {
5774                    caixa: c.destination().to_string(),
5775                });
5776            }
5777            // A `:contratos` entry is an *inter*-Servico contract
5778            // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
5779            // typed edge between two distinct graph nodes. An edge whose
5780            // `:de` equals its `:para` is a Servico contracting with
5781            // itself — a degenerate edge under every WIT shape. The
5782            // synchronous shapes were caught only incidentally, and with
5783            // a misleading diagnostic: `detect_sync_cycles` reported
5784            // `cart → cart` as a `ContratoCycle` whose path is
5785            // `["cart", "cart"]` — framing a self-edge as a multi-node
5786            // deadlock. The pub-sub shape slipped through entirely
5787            // (`detect_sync_cycles` excludes `WitTarget::PubSub`, so a
5788            // `nats:pub-sub` edge from a member to itself silently
5789            // validated, then rendered a `CiliumNetworkPolicy` whose
5790            // endpointSelector and fromEndpoints both name the same
5791            // program — a self-allow rule that is a no-op, since
5792            // intra-pod traffic never traverses the mesh). A self-edge's
5793            // runtime meaning is an in-process call, which doesn't go
5794            // through the mesh at all, so no `:contratos` edge can carry
5795            // it. Firing the gate before the `:wit`/`target()` shape
5796            // checks means the structural "this edge can't exist" error
5797            // precedes the narrower payload-shape diagnostics, and shape-
5798            // agnostically covers all four `WitTarget` arms (HTTP / Store
5799            // / Capability / PubSub) at one point — closing the pub-sub
5800            // hole and replacing the misleading cycle diagnostic in one
5801            // gate. Peer of the duplicate-`:contratos` / duplicate-
5802            // `:membros` set gates: both reject a structurally
5803            // ill-formed graph at the typed surface, before the renderer
5804            // emits a K8s object that fails or no-ops far from the source
5805            // caixa.lisp.
5806            // Route the per-`:contratos` structural self-edge probe
5807            // through the lifted [`WitContract::is_self_loop`] typed
5808            // predicate rather than the raw `c.de == c.para` field-
5809            // equality check — the one production consumer of the per-
5810            // `:contratos` caller-equals-callee endpoint-equality axis
5811            // now keys off exactly one typed dispatch on the substrate
5812            // primitive, so any future rebrand of the axis (an M4-typed-
5813            // caller enum whose identity comparison rule the predicate
5814            // could route through, a per-cluster caller/callee-alias
5815            // table the M4 CR materializer resolves per-CR before the
5816            // equality probe) migrates as a single caixa-core edit
5817            // rather than a coordinated rewrite of the gate + every
5818            // downstream self-edge consumer. Peer of the sibling
5819            // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
5820            // [`WitContract::is_store`] shape-predicate routing on the
5821            // `:wit` world-ref axis, extended onto the per-edge
5822            // endpoint-equality axis.
5823            //
5824            // Route the paired [`AplicacaoError::ContratoSelfLoop`]
5825            // diagnostic's `caixa:` / `wit:` carriers through the
5826            // lifted [`WitContract::source`] / [`WitContract::world_ref`]
5827            // scalar accessors rather than the raw `c.de.clone()` /
5828            // `c.wit.clone()` field-access `String`-carry sites — the
5829            // last unlifted per-`:contratos` raw-field-access
5830            // `.clone()` sites in the M3 mesh-slot validator's self-
5831            // edge refusal arm. `.source().to_string()` is byte-
5832            // identical to `.de.clone()` (pinned by the sibling
5833            // `source_returns_de_byte_equal_across_permutations` accessor
5834            // test), and `.world_ref().to_string()` is byte-identical
5835            // to `.wit.clone()` (pinned by the sibling
5836            // `world_ref_returns_wit_byte_equal_across_permutations`
5837            // accessor test) — so a future rebrand of either underlying
5838            // storage flows through the accessor's one body without a
5839            // coordinated per-consumer rewrite across the M3 mesh
5840            // validator.
5841            if c.is_self_loop() {
5842                return Err(AplicacaoError::ContratoSelfLoop {
5843                    caixa: c.source().to_string(),
5844                    wit: c.world_ref().to_string(),
5845                });
5846            }
5847            if c.world_ref().is_empty() {
5848                let (de, para) = c.edge_pair();
5849                return Err(AplicacaoError::EmptyWit { de, para });
5850            }
5851            // Shape ↔ target consistency — surfaces "HTTP wit without
5852            // :endpoint", "NATS wit with :endpoint set", etc. as named
5853            // build errors instead of silent renderer drops. Threaded
5854            // through the duplicate-edge diagnostic below (via
5855            // [`WitTarget::label`]) so the "which typed target arm did
5856            // the duplicate carry" question is answered by the typed
5857            // enum's variant discriminator, not by re-probing the raw
5858            // `Option<String>` payload fields.
5859            let target_view = c.target()?;
5860            // Contract identity: (de, para, wit, endpoint, subject, slot).
5861            // Two contracts that match on all six are the same typed edge
5862            // declared twice — author error, not a legitimate variant of
5863            // "same caller-callee pair, different payload" (e.g.
5864            // cart→catalog at /products vs /search), which keeps distinct
5865            // identity keys via the differing endpoint payloads.
5866            //
5867            // Route the six-axis dedup key through the lifted
5868            // [`WitContract::identity`] composite-projection accessor
5869            // rather than the inline six-tuple builder — the two
5870            // substrate primitives on the per-`:contratos` identity axis
5871            // (the [`ContratoIdentity`] type alias's six axes, this
5872            // dedup-key's six tuple arms) now migrate as a unit on any
5873            // future axis addition. Peer of the sibling per-`:contratos`
5874            // composite-projection [`WitContract::edge_pair`] /
5875            // [`WitContract::edge_triple`] accessors on the
5876            // caller-callee / caller-callee-wit prefix axes; extends
5877            // the discipline onto the full-identity axis that carries
5878            // the three payload-shape arms too.
5879            let key = c.identity();
5880            crate::render::insert_first_seen(&mut seen_contracts, key, || {
5881                // Route the per-`:contratos` duplicate-gate diagnostic's
5882                // `(de, para, wit)` triple through the lifted
5883                // [`WitContract::edge_triple`] typed accessor rather
5884                // than pairing `edge_pair()` for the `(de, para)` prefix
5885                // with a raw `c.wit.clone()` for the `wit:` tail — the
5886                // paired-with-raw-field-access shape was the last
5887                // per-`:contratos` diagnostic constructor bypassing the
5888                // substrate-primitive composite projection, sibling to
5889                // the eight [`AplicacaoError::Contrato*`] triple-
5890                // carrying constructors [`WitContract::target`]'s edge
5891                // closure feeds through the same accessor.
5892                let (de, para, wit) = c.edge_triple();
5893                AplicacaoError::ContratoDuplicate {
5894                    de,
5895                    para,
5896                    wit,
5897                    target: target_view.label(),
5898                }
5899            })?;
5900        }
5901
5902        // Cycles in the synchronous-edge subgraph are build errors
5903        // (MESH-COMPOSITION §III.3). Pub-sub edges are excluded — they
5904        // are "acyclic by construction" because the publisher fires
5905        // and forgets, so no caller blocks on a downstream that loops
5906        // back to it.
5907        self.detect_sync_cycles()?;
5908
5909        if let Some(e) = self.entrada() {
5910            // Route the per-`:entrada` composite-reference read
5911            // through the lifted [`AplicacaoSpec::entrada`] accessor
5912            // rather than the raw `&self.entrada` field access — the
5913            // shape-and-membership gate's traversal head is now the
5914            // canonical read-side surface every per-Aplicacao entrada
5915            // consumer routes through, closing the fourth of four
5916            // open-coded outer-field accesses on the per-`:entrada`
5917            // outer-composite axis.
5918            //
5919            // Shape gate on `:entrada :para` runs ahead of the
5920            // membership lookup. Every `:membros :caixa` past
5921            // `validate_membro_caixa` is a valid DNS-1123 label
5922            // (3f9d7a0), so the `names` set structurally cannot
5923            // contain an empty / malformed string and the membership-
5924            // lookup diagnostic always misframed the root cause as
5925            // "this caixa is not in `:membros`". The shape gate
5926            // routes structurally-impossible-to-match inputs through
5927            // the narrower self-locating diagnostic, preserving the
5928            // legitimate "well-shaped phantom reference" arm — the
5929            // same trajectory the peer `:membros :caixa` (3f9d7a0),
5930            // `:placement :clusters` (6c8c00b), and `:contratos :de`
5931            // / `:para` (8d5af6b) axes already follow. This closes
5932            // the fourth and last Aplicacao-level Servico-name
5933            // reference axis on the canonical DNS-1123 floor.
5934            // Route the per-`:entrada :para` byte-string reads through
5935            // the lifted [`Entrada::destination`] accessor rather than
5936            // the raw `e.para` field access — the three
5937            // per-`AplicacaoSpec::validate` `:entrada :para` consumers
5938            // (shape-gate `validate_entrada_para` arg, membership
5939            // lookup, `EntradaMemberMissing` diagnostic carry) now key
5940            // off exactly one typed dispatch on the substrate
5941            // primitive, closing the last unlifted per-`:entrada :para`
5942            // raw-field-access axis on the M3 mesh-slot validator.
5943            // The `.destination().to_string()` at the diagnostic site
5944            // is byte-identical to `.para.clone()` — pinned by the
5945            // sibling `destination_returns_entrada_para_byte_equal` +
5946            // `destination_borrows_from_entrada_para_storage` accessor
5947            // tests — so a future rebrand of the underlying `:para`
5948            // storage (a lift from `String` to a typed
5949            // `ServicoName(String)` newtype, a per-Aplicacao interning
5950            // arena the M4 CR materializer authors, a
5951            // `smol_str::SmolStr` inline-buffer swap) flows through
5952            // the accessor's one body without a coordinated
5953            // per-consumer rewrite across the M3 mesh validator.
5954            validate_entrada_para(e.destination())?;
5955            if !names.contains(e.destination()) {
5956                return Err(AplicacaoError::EntradaMemberMissing {
5957                    para: e.destination().to_string(),
5958                });
5959            }
5960            // Route the per-`:entrada :host` byte-string reads through
5961            // the lifted [`Entrada::hostname`] accessor rather than
5962            // the raw `e.host` field access — the emptiness gate and
5963            // the shape-gate `validate_entrada_host` arg now key off
5964            // exactly one typed dispatch on the substrate primitive,
5965            // closing the last unlifted per-`:entrada :host` raw-
5966            // field-access axis on the M3 mesh-slot validator. Peer
5967            // of the sibling per-`:entrada :para` convergence above
5968            // and pinned by the existing
5969            // `hostname_returns_entrada_host_byte_equal` +
5970            // `hostnames_returns_singleton_of_hostname_accessor`
5971            // accessor tests, so any future
5972            // Gateway-API-shaped host renormalization (a wildcard-
5973            // label lift, a trailing-`.` FQDN substitution, an IDNA
5974            // Punycode round-trip the SNI fan-out overlay authors)
5975            // flows through the accessor's one body without a
5976            // coordinated per-consumer rewrite across the M3 mesh
5977            // validator.
5978            if e.hostname().is_empty() {
5979                return Err(AplicacaoError::EmptyEntradaHost);
5980            }
5981            // The `:host` lands verbatim as a K8s Gateway API v1
5982            // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
5983            // both apiserver-validated against the same restrictive
5984            // pattern: lowercase RFC 1123 DNS subdomain, optional
5985            // single leading wildcard label (`*.`), max length 253,
5986            // per-label max length 63, no IP literals, no scheme,
5987            // no port. Until this gate landed `validate()` only
5988            // refused the empty string (`EmptyEntradaHost`); a
5989            // structurally invalid hostname (`"https://example.com"`,
5990            // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
5991            // `"_underscored.example.com"`, `"FOO.example.com"`,
5992            // `"checkout.quero.cloud."`) silently passed validate
5993            // and the apiserver `field is invalid` error surfaced at
5994            // `kubectl apply` time, far from the source caixa.lisp.
5995            // Lifting the gate to caixa-build time mirrors the
5996            // `:entrada :paths` value-shape trajectory (eb3456d) and
5997            // closes the last unstructured `:entrada` axis.
5998            validate_entrada_host(e.hostname())?;
5999            // Structural-floor gate on `:entrada :port`: every
6000            // validated `Entrada::port` past this gate lies in
6001            // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
6002            // type-inferred ceiling closes the top edge, so no companion
6003            // upper-cap arm is needed here — unlike the peer capped-
6004            // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
6005            // `require_positive_bounded_u32` bracket covers both edges).
6006            // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
6007            // accept-set-floor const rather than the prior inline
6008            // `if e.port == 0` byte-check so a future rebrand of the
6009            // accept-set floor (a hypothetical unprivileged-only
6010            // migration lifting the floor to `1024`, a per-cluster
6011            // scoping the operator pins through a future
6012            // `:placement :port-floor` slot as the M4 typed-slot
6013            // trajectory adds it, the future
6014            // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6015            // per-Aplicacao gateway resolver reaching for the same
6016            // floor) is a one-line edit on the canonical
6017            // [`SERVICO_PORT_MIN`] declaration, not a coordinated
6018            // rewrite across the emit site + the pin test + every
6019            // future per-target renderer the substrate adds.
6020            if e.port() < SERVICO_PORT_MIN {
6021                return Err(AplicacaoError::EntradaPortZero);
6022            }
6023            // Each `:entrada :paths` entry becomes a K8s Gateway API
6024            // HTTPRoute `matches[].path.value`. The Gateway API rejects
6025            // values that don't start with `/` for `type: PathPrefix`,
6026            // and an empty value is meaningless. Surface those as build
6027            // errors (MESH-COMPOSITION §III.3) rather than apply-time
6028            // failures. Empty `:paths` itself is fine — caixa-mesh
6029            // falls back to a single `/` catch-all.
6030            let mut seen = std::collections::HashSet::new();
6031            // Route the per-entry value-shape gate's traversal head
6032            // through the lifted [`Entrada::paths`] slice accessor
6033            // rather than the raw `&e.paths` field access — the
6034            // per-Aplicacao `:entrada :paths` validate loop now keys
6035            // off the canonical raw-slot surface every downstream
6036            // per-`:entrada` path-list consumer (the sibling
6037            // [`Entrada::resolved_paths`] fallback-applying resolver
6038            // internal reads, `feira app graph`'s per-Aplicacao entrada
6039            // summary line's `{:?}` Debug print) routes through, so any
6040            // future rebrand on the typed slot's raw-slot reader lands
6041            // at exactly one place. Same convergence discipline as the
6042            // sibling [`Placement::clusters`] (a6e18d7) reader-site
6043            // convergences on the peer M3 mesh-slot `Vec<String>`-carry
6044            // axis.
6045            for p in e.paths() {
6046                if p.is_empty() {
6047                    return Err(AplicacaoError::EntradaPathEmpty);
6048                }
6049                if !p.starts_with('/') {
6050                    return Err(AplicacaoError::EntradaPathNotAbsolute { path: p.clone() });
6051                }
6052                // Per-entry value-shape gate: the path lands verbatim
6053                // as a K8s Gateway API HTTPRoute `matches[].path.value`
6054                // (caixa-mesh/src/lib.rs:498), apiserver-validated
6055                // against `maxLength: 1024` + the Gateway API webhook's
6056                // path-grammar rules (no `//`, no `/./`, no `/../`, no
6057                // query/fragment separators, no whitespace, no control
6058                // characters, no non-ASCII bytes). Until this gate
6059                // landed `validate` only refused the empty string and
6060                // missing-leading-slash (eb3456d); a structurally
6061                // invalid path (`"/api?q=1"`, `"/api#frag"`,
6062                // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
6063                // 1025-byte URL-shaped slug) silently passed validate
6064                // and the failure surfaced at `kubectl apply` time as
6065                // a Gateway API webhook rejection, far from the source
6066                // caixa.lisp, with no field naming the offending
6067                // `:paths` entry. Lifting the gate to caixa-build time
6068                // mirrors the `:entrada :host` value-shape trajectory
6069                // (c7d05ec) on the sibling axis — every author surface
6070                // that emits a Gateway API field now matches the
6071                // apiserver's accepted set at validate time.
6072                validate_entrada_path(p)?;
6073                crate::render::insert_first_seen(&mut seen, p.as_str(), || {
6074                    AplicacaoError::EntradaPathDuplicate { path: p.clone() }
6075                })?;
6076            }
6077        }
6078
6079        self.validate_placement()?;
6080
6081        self.validate_politicas()?;
6082
6083        Ok(())
6084    }
6085
6086    /// Reject `:membros` values that are operationally meaningless. The
6087    /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
6088    /// every entry names a Servico that participates in the Aplicacao,
6089    /// and the rendered programs.yaml fan-out emits one entry per
6090    /// `:membros`. Three authoring footguns are closed here:
6091    ///
6092    ///   - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
6093    ///     a `programs:` entry whose `name:` is the empty string, which
6094    ///     downstream `lareira-fleet-programs` rejects at template time
6095    ///     with a non-localized error;
6096    ///   - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
6097    ///     an empty semver constraint, so the failure surfaces far from
6098    ///     the source caixa.lisp;
6099    ///   - duplicate `:caixa` names — two entries with the same name
6100    ///     produce duplicate programs.yaml entries (one silently
6101    ///     overwrites the other in the cluster's HelmRelease values), and
6102    ///     contract membership lookups against `:contratos` collapse the
6103    ///     two onto one node, masking authoring mistakes.
6104    ///
6105    /// Same value-shape discipline as `:placement :clusters` (where empty
6106    /// + duplicate cluster names are rejected) and `:entrada :paths`
6107    /// (where empty + duplicate path entries are rejected). Lifting these
6108    /// invariants to the typed surface mirrors the MESH-COMPOSITION
6109    /// §III.3 promise that the `:membros` set — the load-bearing identity
6110    /// of the application graph — is well-formed by construction.
6111    fn validate_membros(&self) -> Result<(), AplicacaoError> {
6112        if self.membros().is_empty() {
6113            return Err(AplicacaoError::NoMembros);
6114        }
6115        let mut seen = std::collections::HashSet::new();
6116        for m in self.membros() {
6117            // Route the `MembroCaixaEmpty` refusal-arm's per-member
6118            // empty-`:caixa` shape-gate through the typed
6119            // [`Membro::nome`] accessor rather than the raw `.caixa`
6120            // field access — the last un-lifted `.caixa` production-
6121            // code read site on the per-`:membros` member-caixa `:nome`
6122            // axis, sibling to the six caixa-core validator read sites
6123            // (member-set collector, per-member value-shape gate,
6124            // duplicate dedup key, cycle-detector adjacency-map seed,
6125            // self-loop gate) the 4a32abf lift already routed through
6126            // the accessor and the peer 54bf2f3 caixa-mesh emit-side
6127            // per-`programs[]` entry-`name:` `String`-carry converge.
6128            // Prior to this converge the `MembroCaixaEmpty` refusal
6129            // arm was the solitary consumer bypassing the typed
6130            // dispatch — the same-loop iteration's very next call
6131            // `validate_membro_caixa(m.nome())` already routed through
6132            // the accessor, so an author landing an empty-`:caixa`
6133            // entry hit the accessor on the shape-gate line but
6134            // bypassed it on the emptiness line one line above. A
6135            // future extension of the `:membros :caixa` axis to a
6136            // richer author surface (a per-cluster alias table pinned
6137            // through a future `:placement`-scoped slot, a namespace-
6138            // qualified rewrite the M4 CR materializer applies per-CR,
6139            // a per-member overlay from the future `:membros
6140            // :nome-suffix` slot MESH-COMPOSITION §III.2 acknowledges)
6141            // that lands on the accessor would silently disagree
6142            // between the emptiness gate and every peer consumer —
6143            // an author-declared `:caixa "checkout"` value the
6144            // accessor rewrote to `""` under a future alias arm would
6145            // pass the raw `.is_empty()` gate here while the peer
6146            // `validate_membro_caixa(m.nome())` call one line below
6147            // (and every downstream emit-side consumer routing through
6148            // the accessor) tripped on the empty-value shape far from
6149            // this diagnostic. Pinned by the drift-detection test
6150            // [`validate_membros_empty_gate_routes_through_nome_accessor`]
6151            // below.
6152            if m.nome().is_empty() {
6153                return Err(AplicacaoError::MembroCaixaEmpty);
6154            }
6155            // Every emitted cluster artifact's `metadata.name` derives
6156            // from a `:membros :caixa` value verbatim — the rendered
6157            // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
6158            // the [`crate::LABEL_PROGRAM`] label value on every CNP
6159            // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
6160            // 272), the composed `CiliumNetworkPolicy` `metadata.name`
6161            // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
6162            // `metadata.name` when the member is the `:entrada :para`
6163            // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
6164            // schema enforces the DNS-1123 label rule on admission;
6165            // a structurally invalid member name (`"Cart"`, `"my_cart"`,
6166            // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
6167            // mistaken-identity slug) silently passes the prior empty-/
6168            // duplicate-only gate and the failure surfaces at `kubectl
6169            // apply` time as a `metadata.name: Invalid value` rejection,
6170            // far from the source caixa.lisp, with no field naming the
6171            // offending `:membros` entry. Lifting the gate to caixa-build
6172            // time mirrors the `:entrada :host` value-shape trajectory
6173            // (c7d05ec) on the peer axis — every author surface that
6174            // emits a K8s name now matches the apiserver's accepted set
6175            // at validate time.
6176            validate_membro_caixa(m.nome())?;
6177            // The author surface for `:versao` is the same Cargo-shaped
6178            // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
6179            // `"*"`) every `:deps` entry carries — and the lacre pipeline
6180            // resolves both axes through the same
6181            // [`crate::version::parse_requirement`] entry-point. The
6182            // shared [`crate::render::require_valid_versao_requirement`]
6183            // helper brackets the empty-first + parse cascade both peer
6184            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
6185            // [`crate::SupervisorSpec::validate`] on `:children :versao`)
6186            // route through, so drift between the three axes' accepted
6187            // requirement sets is structurally impossible and the parse-
6188            // side no-op the empty-first arm closes (semver's empty
6189            // parse yields an implicit `*`) lives in exactly one
6190            // predicate.
6191            crate::render::require_valid_versao_requirement(
6192                m.versao_requirement(),
6193                || AplicacaoError::MembroVersaoEmpty {
6194                    caixa: m.nome().to_string(),
6195                },
6196                |reason| AplicacaoError::MembroVersaoInvalid {
6197                    caixa: m.nome().to_string(),
6198                    versao: m.versao_requirement().to_string(),
6199                    reason,
6200                },
6201            )?;
6202            crate::render::insert_first_seen(&mut seen, m.nome(), || {
6203                AplicacaoError::MembroDuplicate {
6204                    caixa: m.nome().to_string(),
6205                }
6206            })?;
6207        }
6208        Ok(())
6209    }
6210
6211    /// Reject `:placement` values that are operationally meaningless or
6212    /// internally contradictory. Each strategy variant has the same
6213    /// invariants on `:clusters` (non-empty list, non-empty unique
6214    /// entries) — the §III.1 author surface is uniform on this axis,
6215    /// even though the *meaning* of the list differs by strategy
6216    /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
6217    /// shard pool).
6218    ///
6219    /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
6220    /// are the same authoring footgun closed for `:politicas` zero
6221    /// values and `:entrada` empty paths: the field is *declared* but
6222    /// carries no meaning, so downstream renderers either skip it
6223    /// silently (cluster-fanout drops the empty entry, no diagnostic)
6224    /// or apply it literally and fail at admission time. Lifting both
6225    /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
6226    /// violation is a build error" promise.
6227    ///
6228    /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
6229    /// is required exactly when `:estrategia Sharded` (hash-keyed
6230    /// distribution, Akka cluster-sharding convention, §II.4) and
6231    /// refused on `:estrategia Replicated`/`SingleNode` (where no
6232    /// hash-keyed routing axis consumes it). The partition closes the
6233    /// "I think I configured sharding" footgun where an author writes
6234    /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
6235    /// the typed slot's value silently vanishes at the renderer layer
6236    /// — every validated `Placement` past this call satisfies
6237    /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
6238    fn validate_placement(&self) -> Result<(), AplicacaoError> {
6239        // Every strategy needs at least one named cluster: `Replicated`
6240        // and `SingleNode` use the list as hosting/takeover candidates
6241        // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
6242        // §II.1), while `Sharded` uses it as the shard pool
6243        // (Akka cluster-sharding convention — §II.4). An empty list is
6244        // meaningless under any of the three.
6245        //
6246        // Route the paired pre-flight `.is_empty()` refusal probe and
6247        // the per-cluster validate loop's traversal head through the
6248        // lifted [`Placement::clusters`] slice-return accessor rather
6249        // than the raw `self.placement.clusters` field access — the
6250        // two production consumers of the per-`:placement` cluster-
6251        // pool `Vec`-carry now key off exactly one typed dispatch on
6252        // the substrate primitive, so any future rebrand on the axis
6253        // (a per-tenant cluster-pool overlay the operator pins through
6254        // a future `:placement :clusters-overrides` slot, a per-
6255        // Aplicacao dynamic cluster-pool derivation the future M5
6256        // adaptive-placement engine computes from `:affinity` weights)
6257        // migrates as a single caixa-core edit rather than a
6258        // coordinated rewrite of the paired arms — sibling of the
6259        // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
6260        // arm migration on the per-`:supervisor` static-child-list
6261        // `Vec`-carry axis.
6262        //
6263        // Route the per-`:placement` outer-composite reference read
6264        // through the lifted [`AplicacaoSpec::placement`] outer accessor
6265        // rather than the raw `&self.placement` field access — the
6266        // per-axis bracket-dispatch fan-out below (`p.clusters()`,
6267        // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
6268        // axis-level lifted accessor family) now routes through the
6269        // substrate-primitive typed dispatch at the outer composition
6270        // altitude, the same shape the peer caixa-mesh
6271        // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
6272        // and the sibling `feira app graph` per-Aplicacao print line
6273        // now key off after this accessor lift.
6274        let p = self.placement();
6275        if p.clusters().is_empty() {
6276            return Err(AplicacaoError::PlacementWithoutClusters {
6277                estrategia: p.estrategia(),
6278            });
6279        }
6280        let mut seen = std::collections::HashSet::new();
6281        for c in p.clusters() {
6282            // Per-entry value-shape gate: the cluster name lands in
6283            // every K8s context / `lareira-fleet-programs` aggregator
6284            // filter / future M4 CR materializer's per-cluster axis
6285            // a validated `:clusters` entry passes through, each
6286            // enforcing the DNS-1123 label rule on admission. Same
6287            // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
6288            // on the peer name axis — both axes' validated values
6289            // are guaranteed-accepted by the apiserver without
6290            // re-validation at any downstream renderer or admission
6291            // layer.
6292            validate_placement_cluster(c)?;
6293            crate::render::insert_first_seen(&mut seen, c.as_str(), || {
6294                AplicacaoError::PlacementClusterDuplicate { cluster: c.clone() }
6295            })?;
6296        }
6297        // Route the per-`:placement :affinity` per-hint value-shape
6298        // gate through the typed [`Placement::affinity`] accessor rather
6299        // than the raw `&self.placement.affinity` field access — the
6300        // sole open-coded field-access site on the per-`:placement`
6301        // M3-Adaptive-compression-hint axis the accessor lift now owns.
6302        // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
6303        // the accessor's `Option<&str>` return type;
6304        // [`validate_placement_affinity`]'s `&str` parameter accepts
6305        // the narrower borrow without a re-allocation, so the routing
6306        // change is byte-for-byte in the pass arm and remains
6307        // byte-for-byte in every failure diagnostic
6308        // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
6309        // String` field is populated inside
6310        // [`validate_placement_affinity`] via the peer `.to_string()`
6311        // path on the same borrowed slice). Peer of the sibling
6312        // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
6313        // routing through [`Placement::shard_key`] at the caixa-core
6314        // site above — extends the "read `:placement` optional-scalars
6315        // through the typed accessor" discipline to the second
6316        // `Option<String>`-shape slot on the M3 mesh-slot family.
6317        //
6318        // Per-hint value-shape gate: the `:affinity` value lands
6319        // verbatim in the M3 Adaptive compression overlay
6320        // (caixa-mesh's `placement.affinity` emission) and every
6321        // future M4 placement-engine routing axis keying off the
6322        // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
6323        // selector — each enforces the DNS-1123 label rule on
6324        // admission. Same typed-shape trajectory as `:placement
6325        // :clusters` (6c8c00b) on the sibling slot and the four
6326        // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
6327        // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
6328        // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
6329        // on the Aplicacao surface to land on the canonical
6330        // [`crate::render::is_dns_1123_label`] floor.
6331        if let Some(a) = p.affinity() {
6332            validate_placement_affinity(a)?;
6333        }
6334        match p.estrategia() {
6335            // Route the `Sharded`-arm shape-gate cascade through the
6336            // typed [`Placement::shard_key`] accessor rather than the
6337            // raw `&self.placement.shard_key` field access — one of the
6338            // two open-coded field-access sites on the per-`:placement`
6339            // Akka-cluster-sharding-key axis the accessor lift now
6340            // owns. The `Some(k)`-bound `k` narrows from `&String` to
6341            // `&str` under the accessor's `Option<&str>` return type;
6342            // `str::is_empty` and [`validate_placement_shard_key`]'s
6343            // `&str` parameter both accept the narrower borrow without
6344            // a re-allocation.
6345            PlacementStrategy::Sharded => match p.shard_key() {
6346                None => return Err(AplicacaoError::ShardedWithoutKey),
6347                Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
6348                // Per-axis value-shape gate on the Akka-cluster-sharding
6349                // `:shard-key` extractor expression. The shape gate runs
6350                // after the more self-locating `ShardedKeyEmpty` arm so
6351                // a `:shard-key ""` surfaces the narrower empty
6352                // diagnostic first; every non-empty `:shard-key` past
6353                // this call is guaranteed to be a printable-ASCII
6354                // single-token reference the future M4 Akka-style
6355                // cluster-sharding reconciler can hash without
6356                // re-validating at the runtime layer. Mirrors the
6357                // payload-axis shape gates on the peer `:contratos`
6358                // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
6359                // 63e18a0 / c4213a4) — each lifts the runtime parser's
6360                // intersection-floor to a caixa-build-time gate.
6361                Some(k) => validate_placement_shard_key(k)?,
6362            },
6363            // `:shard-key` is the Akka-cluster-sharding axis
6364            // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
6365            // across the cluster pool. `Replicated` (active-active across
6366            // every named cluster) and `SingleNode` (Erlang/OTP
6367            // distributed-app takeover/failover, §II.1) have no hash-keyed
6368            // routing axis to consume the slot; downstream renderers
6369            // (caixa-mesh's `placement.shardKey` overlay at
6370            // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
6371            // sharding reconciler) ignore `:shard-key` outside the
6372            // `Sharded` arm by construction. Until this gate landed an
6373            // author who wrote `:placement (:estrategia Replicated
6374            // :shard-key "tenantId")` (an off-by-one strategy typo, a
6375            // copy-paste from a Sharded sibling caixa, the "I think I
6376            // configured sharding" footgun) silently passed validate and
6377            // the typed slot's value vanished at the renderer layer with
6378            // no diagnostic — the canonical "declared-but-inert" footgun
6379            // the empty-:affinity / empty-shard-key / zero-:politicas /
6380            // empty-:contratos-target gates already close on every other
6381            // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
6382            // Lifting the rejection to a build-time gate closes the
6383            // Sharded ↔ non-Sharded partition over the typed
6384            // `:placement` slot: every validated `Placement` past this
6385            // call has `shard_key.is_some()` iff `estrategia ==
6386            // Sharded`, structurally — the future Akka reconciler can
6387            // reach for `placement.shard_key` knowing it's `Some` exactly
6388            // when the strategy consumes it, without re-deriving the
6389            // partition from inline strategy probes.
6390            PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
6391                // Route the non-`Sharded`-arm declared-but-inert refusal
6392                // through the typed [`Placement::shard_key`] accessor —
6393                // the second of the two open-coded field-access sites the
6394                // accessor lift now owns. The `Some(k)`-bound `k` narrows
6395                // from `&String` to `&str`; the `AplicacaoError::
6396                // ShardKeyOnNonSharded { shard_key: String }` diagnostic
6397                // materializes the owned `String` via `k.to_string()`
6398                // (peer to the sibling per-Membro `String`-carry sites
6399                // 4127bb6 routed through `m.nome().to_string()` /
6400                // `m.versao_requirement().to_string()`), so the whole
6401                // `Sharded` ↔ non-`Sharded` partition on the
6402                // `:shard-key` axis now flows through the same typed
6403                // dispatch as the sibling `Sharded`-arm shape gate.
6404                if let Some(k) = p.shard_key() {
6405                    return Err(AplicacaoError::ShardKeyOnNonSharded {
6406                        estrategia: p.estrategia(),
6407                        shard_key: k.to_string(),
6408                    });
6409                }
6410            }
6411        }
6412        Ok(())
6413    }
6414
6415    /// Reject `:politicas` values that are operationally meaningless.
6416    /// Each axis is optional — omitting it expresses "no policy on this
6417    /// axis". Carrying a *zero* value for a declared axis is the bug
6418    /// this function rejects: zero is either
6419    ///
6420    ///   - re-interpreted as "infinite" by downstream proxies (Envoy's
6421    ///     `RouteAction.timeout = 0s` disables the timeout entirely),
6422    ///     directly contradicting MESH-COMPOSITION §V CSE invariant
6423    ///     "every Aplicacao declares :politicas :timeout (no infinite
6424    ///     blocking)", or
6425    ///   - a renderer footgun (a 0-failure circuit breaker trips on the
6426    ///     first call; a 0-rate rate-limit denies every request).
6427    ///
6428    /// Lifting these "0 means the opposite of what you think" idioms to
6429    /// the typed Aplicacao surface as build errors mirrors the §III.3
6430    /// promise that contract drift, capability leaks, and cycles are all
6431    /// build errors — not runtime surprises.
6432    fn validate_politicas(&self) -> Result<(), AplicacaoError> {
6433        // Route the per-`:politicas` composite-reference read through
6434        // the lifted [`AplicacaoSpec::politicas`] outer accessor rather
6435        // than the raw `&self.politicas` field access — the per-axis
6436        // bracket-dispatch fan-out below (`p.timeout()`, `p.retries()`,
6437        // `p.circuit_breaker()`, `p.rate_limit()`) now routes through
6438        // the substrate-primitive typed dispatch at the outer
6439        // composition altitude AND at every per-axis altitude, matching
6440        // the peer caixa-mesh CNP mTLS-overlay + HTTPRoute
6441        // timeout/retry-overlay emitters that already key off the same
6442        // per-axis accessor family. The four-axis fan-out is now
6443        // uniformly `p.<axis>()` — the last two raw `p.timeout` /
6444        // `p.retries` field-access sites (co-resident with the peer
6445        // `p.circuit_breaker()` / `p.rate_limit()` accessor sites that
6446        // b0e741a / 21a6c3b already lifted) now route through
6447        // [`MeshPolicy::timeout`] / [`MeshPolicy::retries`], closing
6448        // the per-`:politicas` bracket-dispatch fan-out's raw-field-
6449        // access axis on the M3 mesh-slot family.
6450        let p = self.politicas();
6451        if let Some(t) = p.timeout() {
6452            // Zero-floor + integer-millisecond canonical-form +
6453            // upper-cap bracket on the typed `:timeout` axis. See
6454            // [`crate::render::require_positive_canonical_bounded_duration`]
6455            // for the full three-arm ordering discipline (zero-floor
6456            // strictly precedes the canonical-form arm so
6457            // `Duration::ZERO` surfaces the self-locating
6458            // `PolicyTimeoutZero` diagnostic naming the omit-axis
6459            // remediation; canonical-form strictly precedes the cap
6460            // arm so a sub-millisecond above-cap `Duration` surfaces
6461            // the more fundamental round-trip-shape diagnostic first)
6462            // and the four peer typed-`Duration` sites that now share
6463            // this canonical bracket. Every validated value lies in
6464            // `1ms..=POLICY_TIMEOUT_MAX` (1ms..=1h), integer-millisecond
6465            // granularity — the same top-and-bottom-edge discipline
6466            // [`POLICY_RETRIES_MAX`] and
6467            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] apply on the sibling
6468            // capped-`u32` `:politicas` axes.
6469            crate::render::require_positive_canonical_bounded_duration(
6470                t,
6471                POLICY_TIMEOUT_MAX,
6472                || AplicacaoError::PolicyTimeoutZero,
6473                |timeout| AplicacaoError::PolicyTimeoutNotCanonical { timeout },
6474                |timeout| AplicacaoError::PolicyTimeoutExceedsCap { timeout },
6475            )?;
6476        }
6477        if let Some(r) = p.retries() {
6478            // Zero-floor + upper-cap bracket on the typed `:retries`
6479            // axis. See [`crate::render::require_positive_bounded_u32`]
6480            // for the ordering discipline (zero-floor arm strictly
6481            // precedes cap arm so `Some(0)` surfaces the self-locating
6482            // `PolicyRetriesZero` diagnostic with its omit-axis
6483            // remediation directly named, not the misleading
6484            // `0 > POLICY_RETRIES_MAX == false` cap-arm miss). Until
6485            // this bracket landed the top edge ran all the way to
6486            // `u32::MAX` and a struct-literal `MeshPolicy { retries:
6487            // Some(100_000), .. }` (or the equivalent author-surface
6488            // `(:retries 100000)` / `(:retries 4294967295)` typo
6489            // landing in the slot) silently passed validate. The
6490            // runtime substrate consuming the value (Envoy's
6491            // `retry_policy.num_retries`, the future
6492            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
6493            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
6494            // policy into a thundering-herd amplification vector —
6495            // the caller's one request fans out to `retries`
6496            // server-side calls per edge per traversal, multiplying
6497            // load by `(retries+1)^depth` across the
6498            // synchronous-`:contratos` subgraph at the precise moment
6499            // the substrate is already failing (transient failure is
6500            // the trigger), exactly the failure mode AWS App Mesh's
6501            // explicit `maxRetries ≤ 10` schema cap exists to prevent.
6502            // The bracket set is `1..=POLICY_RETRIES_MAX`. Peer with
6503            // the sibling capped-`u32` `:politicas` axes
6504            // (`max_failures`, `rate_limit.rate`) and the peer capped-
6505            // `u32` axes in `:supervisor :max-restarts` +
6506            // `:limits :cpu`; all five now route through the same
6507            // canonical bracket helper.
6508            crate::render::require_positive_bounded_u32(
6509                r,
6510                POLICY_RETRIES_MAX,
6511                || AplicacaoError::PolicyRetriesZero,
6512                |retries| AplicacaoError::PolicyRetriesExceedsCap { retries },
6513            )?;
6514        }
6515        if let Some(cb) = p.circuit_breaker() {
6516            // Zero-floor + upper-cap bracket on the typed
6517            // `:max-failures` axis. See
6518            // [`crate::render::require_positive_bounded_u32`] for the
6519            // ordering discipline (zero-floor arm strictly precedes
6520            // cap arm so `max_failures == 0` surfaces the
6521            // self-locating `PolicyBreakerZeroFailures` diagnostic
6522            // with its omit-axis remediation directly named, not the
6523            // misleading `0 > POLICY_BREAKER_MAX_FAILURES_MAX ==
6524            // false` cap-arm miss). Until this bracket landed the top
6525            // edge ran all the way to `u32::MAX` and a struct-literal
6526            // `CircuitBreaker { max_failures: 100_000, .. }` (or the
6527            // equivalent author-surface `(:max-failures 100000)` /
6528            // `(:max-failures 4294967295)` typo landing in the slot)
6529            // silently passed validate. The runtime substrate
6530            // consuming the value (Envoy's
6531            // `outlier_detection.consecutive_5xx`, the future
6532            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
6533            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
6534            // breaker policy into a no-op — the trip threshold is
6535            // structurally so high that no realistic
6536            // failures-per-`:window` traffic shape can reach it, the
6537            // breaker never trips, and every typed-slot consumer
6538            // emits an Envoy / Cilium L7 overlay carrying a
6539            // protection that is structurally never enforced. The
6540            // bracket set is `1..=POLICY_BREAKER_MAX_FAILURES_MAX`;
6541            // peer with `retries` and `rate_limit.rate` on the same
6542            // helper.
6543            crate::render::require_positive_bounded_u32(
6544                cb.max_failures(),
6545                POLICY_BREAKER_MAX_FAILURES_MAX,
6546                || AplicacaoError::PolicyBreakerZeroFailures,
6547                |max_failures| AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
6548            )?;
6549            // Zero-floor + integer-millisecond canonical-form +
6550            // upper-cap bracket on the typed `:window` axis. See
6551            // [`crate::render::require_positive_canonical_bounded_duration`]
6552            // for the full three-arm ordering discipline (peer to the
6553            // `:timeout` site immediately above); every validated
6554            // value lies in `1ms..=POLICY_BREAKER_WINDOW_MAX`
6555            // (1ms..=1h), integer-millisecond granularity — the same
6556            // top-and-bottom-edge discipline
6557            // [`POLICY_TIMEOUT_MAX`] applies on the sibling
6558            // duration-typed `:politicas :timeout` axis.
6559            crate::render::require_positive_canonical_bounded_duration(
6560                cb.window(),
6561                POLICY_BREAKER_WINDOW_MAX,
6562                || AplicacaoError::PolicyBreakerZeroWindow,
6563                |window| AplicacaoError::PolicyBreakerWindowNotCanonical { window },
6564                |window| AplicacaoError::PolicyBreakerWindowExceedsCap { window },
6565            )?;
6566        }
6567        if let Some(rl) = p.rate_limit() {
6568            // Zero-floor + upper-cap bracket on the typed
6569            // `:rate-limit` rate axis. See
6570            // [`crate::render::require_positive_bounded_u32`] for the
6571            // ordering discipline (zero-floor arm strictly precedes
6572            // cap arm so `rl.rate == 0` surfaces the self-locating
6573            // `PolicyRateLimitZero` diagnostic with its omit-axis
6574            // remediation directly named, not the misleading
6575            // `0 > POLICY_RATE_LIMIT_MAX == false` cap-arm miss).
6576            // Until this bracket landed the top edge ran all the way
6577            // to `u32::MAX` and a struct-literal
6578            // `RateLimit { rate: u32::MAX, .. }` (or the equivalent
6579            // author-surface `(:rate-limit "4294967295/s")` /
6580            // `(:rate-limit "100000000/m")` typo landing in the slot)
6581            // silently passed validate. The runtime substrate
6582            // consuming the value (Envoy's
6583            // `local_rate_limit.token_bucket.max_tokens`, the future
6584            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
6585            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
6586            // rate-limit policy into a no-op limiter: the bucket
6587            // capacity is structurally so high that no realistic
6588            // per-edge traffic shape can drain it, the limiter never
6589            // trips, and every typed-slot consumer emits a "rate
6590            // declared" L7 overlay carrying enforcement that is
6591            // structurally never reached — the canonical
6592            // declared-but-inert footgun the sibling
6593            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap arm closes on
6594            // the peer no-op-breaker shape. The bracket set is
6595            // `1..=POLICY_RATE_LIMIT_MAX`; peer with `retries` and
6596            // `max_failures` on the same helper. The rate bracket
6597            // strictly precedes the window-canonical gate so a
6598            // structurally absurd rate magnitude surfaces the more
6599            // fundamental amplification-shape diagnostic before the
6600            // narrower codec-round-trip-shape diagnostic on `:window`.
6601            crate::render::require_positive_bounded_u32(
6602                rl.rate(),
6603                POLICY_RATE_LIMIT_MAX,
6604                || AplicacaoError::PolicyRateLimitZero,
6605                |rate| AplicacaoError::PolicyRateLimitExceedsCap { rate },
6606            )?;
6607            // The `:rate-limit` author surface is the canonical
6608            // `"<n>/<s|m|h>"` form, and the [`rate_limit_codec`] parser
6609            // accepts exactly the three-unit set (1s/60s/3600s) the
6610            // [`rate_limit_codec::render`] formatter emits the canonical
6611            // unit suffix for. A `RateLimit` whose `:window` is anything
6612            // else (zero, 30s, 45s, 120s, 86400s, …) is constructible
6613            // programmatically (struct literals in Rust + the typed
6614            // `Duration` field) but renders to a `<n>/<k>s` fragment
6615            // (the codec's fall-through) the parser then rejects on
6616            // round-trip — silently breaking the THEORY.md §V.2.7
6617            // render-determinism contract for any consumer that
6618            // serializes-then-deserializes the typed slot. Lifting the
6619            // canonical-window invariant to a build-time gate at
6620            // `validate_politicas` makes the codec's round-trip property
6621            // a structural property of the validated typed value:
6622            // every `RateLimit` past `AplicacaoSpec::validate` has a
6623            // window the codec round-trips losslessly, so the next
6624            // typed-slot wiring (the future `CiliumClusterwideEnvoyConfig`
6625            // emitter for `:politicas :rate-limit`, MESH-COMPOSITION
6626            // §III.2 #3) reaches for `rate_limit.window` knowing the
6627            // value is in the codec's accepted set without re-validating
6628            // at the renderer layer. Same trajectory as c4213a4 (typed
6629            // WitContract endpoint/subject/slot value-shape gates) and
6630            // the b0c8389 :behavior + :upgrade-from script-path lifts:
6631            // the typed slot's valid set matches its codec's accepted
6632            // set, structurally.
6633            // Route the canonical-window shape-gate through the substrate
6634            // primitive [`RateLimit::canonical_unit`] rather than the free
6635            // module-private [`is_canonical_rate_limit_window`] predicate:
6636            // both projections resolve `Duration → Option<RateLimitUnit>`
6637            // through [`RateLimitUnit::from_window`] (the sole `Duration → Self`
6638            // arm on the closed-set typed enum), but the accessor is the
6639            // typed method every downstream consumer of the validated slot
6640            // ([`rate_limit_codec::render`]'s canonical arm above, the
6641            // future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6642            // per-`:politicas :rate-limit` admission webhook, the future
6643            // per-`:contratos`-edge rate-limit-override overlay
6644            // MESH-COMPOSITION §III.2 #3 acknowledges) already reads. Two
6645            // production consumers of the canonical-unit axis (the codec
6646            // render and this validate gate) now key off exactly one typed
6647            // dispatch on the substrate primitive, so any future extension
6648            // to `canonical_unit` (a per-cluster canonical-window overlay
6649            // the operator pins through a future `:contratos :rate-limit
6650            // -unit-overrides` slot, a per-tenant unit-alias table the M4
6651            // CR materializer resolves per-CR) reaches both consumers by
6652            // construction rather than a coordinated rewrite of every
6653            // free-helper call site.
6654            if rl.canonical_unit().is_none() {
6655                return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical {
6656                    window: rl.window(),
6657                });
6658            }
6659        }
6660        Ok(())
6661    }
6662
6663    /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
6664    /// A synchronous edge is any contract whose typed [`WitTarget`] is
6665    /// `Http`, `Store`, or `Capability` — the caller blocks on the
6666    /// callee, so a cycle would deadlock at runtime. Pub-sub edges
6667    /// (`WitTarget::PubSub`) are skipped: an event publisher does not
6668    /// block on its subscribers, so they can never close a sync loop.
6669    ///
6670    /// Iterative DFS with three-coloring; the reported cycle is the
6671    /// path of caixa names traversed from the back-edge target around
6672    /// to itself, in declaration order. Adjacency lists and DFS roots
6673    /// are visited in `BTreeMap` key order so the diagnostic is
6674    /// deterministic across runs.
6675    fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
6676        use std::collections::{BTreeMap, BTreeSet};
6677
6678        #[derive(Clone, Copy, PartialEq, Eq)]
6679        enum Mark {
6680            White,
6681            Gray,
6682            Black,
6683        }
6684
6685        let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
6686        for m in self.membros() {
6687            adj.entry(m.nome()).or_default();
6688        }
6689        for c in self.contratos() {
6690            // target() was already called by validate(); re-running here
6691            // keeps detect_sync_cycles self-contained for callers that
6692            // reuse it (M4 per-edge policy resolver) without revalidating.
6693            //
6694            // The pub-sub-arm check routes through the lifted
6695            // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
6696            // arm-discriminator predicate rather than a raw `matches!(…,
6697            // WitTarget::PubSub { .. })` on the variant so a future
6698            // rebrand on the axis (an M4 per-edge WIT registry split of
6699            // [`WitTarget::PubSub`] into shape-specific peers, a
6700            // per-consumer rename that the accept-set already carries)
6701            // reaches this call site through the derive rather than a
6702            // scattered per-arm `matches!` rewrite — same
6703            // `IsVariant`-derived-arm-discriminator discipline the
6704            // peer closed-set typed enums ([`crate::CaixaKind`] via
6705            // f5bba80, [`PlacementStrategy`] via 766ec63,
6706            // [`crate::supervisor::RestartStrategy`] +
6707            // [`crate::supervisor::RestartPolicy`],
6708            // [`crate::upgrade::UpgradeInstruction`] via 915a934)
6709            // already route through on the substrate's other typed-enum
6710            // arm-discriminator axes.
6711            if c.target()?.is_pubsub() {
6712                continue;
6713            }
6714            adj.entry(c.source()).or_default().insert(c.destination());
6715        }
6716
6717        let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
6718        let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
6719
6720        // Stable DFS root order — BTreeMap iteration is sorted by key.
6721        let roots: Vec<&str> = adj.keys().copied().collect();
6722
6723        // Frame: (node, sorted-neighbours snapshot, next-edge index).
6724        for root in roots {
6725            if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
6726                continue;
6727            }
6728            let root_neighbors: Vec<&str> = adj
6729                .get(root)
6730                .map(|s| s.iter().copied().collect())
6731                .unwrap_or_default();
6732            let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
6733            color.insert(root, Mark::Gray);
6734
6735            loop {
6736                // Read+advance the top frame in one borrow scope so we
6737                // can later mutate the stack (push/pop) without holding
6738                // a borrow across.
6739                let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
6740                    let node = top.0;
6741                    if top.2 >= top.1.len() {
6742                        (node, None)
6743                    } else {
6744                        let nxt = top.1[top.2];
6745                        top.2 += 1;
6746                        (node, Some(nxt))
6747                    }
6748                });
6749                let Some((node, nxt_opt)) = step else { break };
6750                let Some(nxt) = nxt_opt else {
6751                    color.insert(node, Mark::Black);
6752                    stack.pop();
6753                    continue;
6754                };
6755                let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
6756                match nxt_color {
6757                    Mark::Gray => {
6758                        // Reconstruct the cycle from `node` back through
6759                        // the parent chain to `nxt`, then close.
6760                        let mut cycle = Vec::new();
6761                        let mut cur = node;
6762                        cycle.push(cur.to_string());
6763                        while cur != nxt {
6764                            match parent.get(cur).copied() {
6765                                Some(p) => {
6766                                    cur = p;
6767                                    cycle.push(cur.to_string());
6768                                }
6769                                None => break,
6770                            }
6771                        }
6772                        cycle.reverse();
6773                        cycle.push(nxt.to_string());
6774                        return Err(AplicacaoError::ContratoCycle { cycle });
6775                    }
6776                    Mark::White => {
6777                        parent.insert(nxt, node);
6778                        color.insert(nxt, Mark::Gray);
6779                        let nxt_neighbors: Vec<&str> = adj
6780                            .get(nxt)
6781                            .map(|s| s.iter().copied().collect())
6782                            .unwrap_or_default();
6783                        stack.push((nxt, nxt_neighbors, 0));
6784                    }
6785                    Mark::Black => {}
6786                }
6787            }
6788        }
6789        Ok(())
6790    }
6791
6792    /// Substrate-canonical destination-facing TCP port every emitted
6793    /// per-Aplicacao artifact must key `destination`-shaped port axes
6794    /// off. Returns the typed `:entrada :port` scalar when this
6795    /// Aplicacao's `:entrada` block names `destination` under its
6796    /// `:para` axis (the destination Servico *is* the ingress apex, so
6797    /// the substrate honors the author-declared listener port
6798    /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
6799    /// fallback otherwise (every non-apex destination — the internal
6800    /// mesh Servicos `:contratos` reach across, the future per-edge
6801    /// policy resolver's per-destination probe targets, the
6802    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
6803    /// L4 port resolver — reads the same substrate-canonical port floor
6804    /// by construction).
6805    ///
6806    /// Prior to this lift the "if :entrada matches this destination use
6807    /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
6808    /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
6809    /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
6810    /// prior to this lift), with no typed method on the substrate primitive
6811    /// that named the rule. A future per-destination port axis addition
6812    /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
6813    /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
6814    /// per-Servico listener ports land, a per-cluster override the operator
6815    /// pins through a future `:placement :default-port` slot — would have
6816    /// to be threaded through every renderer's inline cascade in lockstep
6817    /// or one consumer would silently disagree on which port a given
6818    /// destination Servico's ingress lands at. Lifting the rule to a
6819    /// typed method on the substrate primitive means the M4 CR
6820    /// materializer, the future per-edge policy resolver, and every
6821    /// downstream test-fixture navigator reach for exactly one typed
6822    /// dispatch — the resolver's accept-set moves as a unit on any
6823    /// future axis addition.
6824    ///
6825    /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
6826    /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
6827    /// the typed primitive, thin projections at each consumer"
6828    /// discipline lifts on the sibling `:contratos` payload / `:politicas
6829    /// :rate-limit` unit-suffix axes; extends the discipline onto the
6830    /// destination-facing port-resolution axis every per-Aplicacao
6831    /// L4-fallback renderer consumes.
6832    #[must_use]
6833    pub fn port_for_destination(&self, destination: &str) -> u16 {
6834        // Route the per-`:entrada` composite-reference read through
6835        // the lifted [`AplicacaoSpec::entrada`] accessor rather than
6836        // the raw `self.entrada.as_ref()` field access — the
6837        // per-destination L4-port fallback resolver's composite-
6838        // projection seed is now the canonical read-side surface
6839        // every per-Aplicacao entrada consumer routes through, peer
6840        // of the sibling `validate` per-`:entrada` shape-and-
6841        // membership gate migration on the same outer-composite
6842        // axis.
6843        // Route the per-`:entrada` apex-destination membership probe
6844        // through the lifted [`Entrada::destination`] accessor rather
6845        // than the raw `e.para == destination` field access — the last
6846        // un-lifted `.para` production-code read site on the per-
6847        // `:entrada` `:para` axis, sibling to the four caixa-core
6848        // consumer sites the peer 15ddd8c converge already routed
6849        // through the accessor (the three
6850        // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
6851        // membership gate sites: the `validate_entrada_para` DNS-1123
6852        // shape gate, the per-`:membros` membership lookup, and the
6853        // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
6854        // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
6855        // `entrada.para`-projection converge at
6856        // caixa-core/src/render.rs (the `gateway_api_http_route_name`
6857        // route-name projection site). Prior to this converge the
6858        // `port_for_destination` resolver was the solitary consumer
6859        // bypassing the typed dispatch on the `.para` axis — the two
6860        // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
6861        // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
6862        // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
6863        // reach through the same accessor family compose with this
6864        // resolver at the emit boundary via the apex-identity
6865        // invariant `spec.port_for_destination(entrada.destination())
6866        // == entrada.port` the sibling
6867        // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
6868        // pin pins across four permutations. A future extension of the
6869        // `:entrada :para` axis to a richer author surface (a per-
6870        // cluster alias overlay the operator pins through a future
6871        // `:placement`-scoped slot, a namespace-qualified rewrite the
6872        // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
6873        // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
6874        // §III.2 acknowledges) that lands on the accessor would silently
6875        // disagree between this resolver and the two `caixa-mesh` emit
6876        // sites — an author-declared `:para "cart"` value the accessor
6877        // rewrote to `"cart-v2"` under a future canary arm would leave
6878        // the resolver's membership arm falling through to
6879        // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
6880        // `.para`) while the peer emit-site consumers landed on the
6881        // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
6882        // silently disagreed on which destination port a given typed
6883        // `:entrada` resolves to at cluster-apply time. Pinned by the
6884        // drift-detection test
6885        // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
6886        // below.
6887        self.entrada()
6888            .filter(|e| e.destination() == destination)
6889            .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
6890    }
6891}
6892
6893/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
6894/// entry may name the Aplicacao's own `:nome`.
6895///
6896/// An Aplicacao that lists itself as a member is a degenerate self-edge in
6897/// the typed graph — the application graph is a DAG rooted at the Aplicacao
6898/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
6899/// Servicos that compose the app; an Aplicacao is never its own constituent),
6900/// and the lacre pipeline's closure-resolution would otherwise be handed a
6901/// node that is its own parent: a one-node cycle it either rejects far from
6902/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
6903/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
6904/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
6905/// label + lacre closure root), a member whose `:caixa` equals the
6906/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
6907/// peer.
6908///
6909/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
6910/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
6911/// gate `validate_upgrade_from_against_versao` and the supervision-tree
6912/// self-parent gate `crate::supervisor::validate_no_self_supervision`
6913/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
6914/// not a tree/mesh edge" discipline, here on the second typed-graph axis
6915/// (the Aplicacao :membros set; the supervision-tree :children list was the
6916/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
6917/// every validated Supervisor's children are distinct from its `:nome`,
6918/// every validated Aplicacao's membros are distinct from its `:nome`. The
6919/// transitive consequence is that `:entrada :para` and `:contratos`
6920/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
6921/// name the Aplicacao itself, without re-deriving the partition.
6922pub fn validate_no_self_membership(
6923    membros: &[Membro],
6924    parent_nome: &str,
6925) -> Result<(), AplicacaoError> {
6926    for m in membros {
6927        if m.nome() == parent_nome {
6928            return Err(AplicacaoError::MembroIsSelfAplicacao {
6929                caixa: parent_nome.to_string(),
6930            });
6931        }
6932    }
6933    Ok(())
6934}
6935
6936#[derive(Debug, Error, PartialEq, Eq)]
6937pub enum AplicacaoError {
6938    #[error("Aplicacao must declare at least one :membros entry")]
6939    NoMembros,
6940    #[error(
6941        ":membros entry has empty :caixa (every member must name a Servico; \
6942         omit the entry instead of carrying an empty name)"
6943    )]
6944    MembroCaixaEmpty,
6945    #[error(
6946        ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
6947         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
6948         name / label value the member name lands in; use a lowercase \
6949         alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
6950    )]
6951    MembroCaixaInvalid { caixa: String, reason: String },
6952    #[error(
6953        ":membros entry {caixa:?} has empty :versao (every member must pin a \
6954         semver constraint that resolves through the lacre pipeline)"
6955    )]
6956    MembroVersaoEmpty { caixa: String },
6957    #[error(
6958        ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
6959         requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
6960         `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
6961         carries; the lacre pipeline resolves both through the same parser)"
6962    )]
6963    MembroVersaoInvalid {
6964        caixa: String,
6965        versao: String,
6966        reason: String,
6967    },
6968    #[error(
6969        ":membros entry {caixa:?} appears more than once (the graph node set \
6970         is a set, not a multiset; duplicate members produce duplicate \
6971         programs.yaml entries and ambiguous :contratos membership lookups)"
6972    )]
6973    MembroDuplicate { caixa: String },
6974    #[error(
6975        "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
6976         never its own constituent Servico (the application graph is a DAG rooted \
6977         at the Aplicacao; :membros names the *other* caixas that compose the \
6978         app, not the app itself). Since every :nome is a globally-unique \
6979         substrate identity, a member naming the Aplicacao's own :nome is a \
6980         one-node lacre-closure recursion, not a coincidentally-named peer; \
6981         drop the self-referential :membros entry or rename it to the actual \
6982         constituent caixa."
6983    )]
6984    MembroIsSelfAplicacao { caixa: String },
6985    #[error(
6986        "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
6987         caixa declared in :membros; omit the contract or fill the {slot} field with a \
6988         member name)"
6989    )]
6990    ContratoCaixaEmpty { slot: &'static str },
6991    #[error(
6992        "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
6993         :contratos {slot} value names a member of :membros, which is itself a \
6994         DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
6995         object the member name lands in — Service, Pod, identity-based Cilium \
6996         selector; use a lowercase alphanumeric + hyphen identifier like \
6997         `\"checkout\"` or `\"cart-v2\"`)"
6998    )]
6999    ContratoCaixaInvalid {
7000        slot: &'static str,
7001        caixa: String,
7002        reason: String,
7003    },
7004    #[error("contrato references caixa {caixa:?} not declared in :membros")]
7005    ContratoMemberMissing { caixa: String },
7006    #[error(
7007        "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
7008         entry is an inter-Servico contract whose :de and :para must name distinct \
7009         :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
7010         the contract, or point :para at the member it actually calls)"
7011    )]
7012    ContratoSelfLoop { caixa: String, wit: String },
7013    #[error("contrato {de:?} → {para:?} has empty :wit")]
7014    EmptyWit { de: String, para: String },
7015    #[error(
7016        "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
7017         {reason} (the substrate dispatches `:wit` values on the canonical \
7018         lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
7019         `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
7020         demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
7021         kebab-case identifier per segment)"
7022    )]
7023    ContratoWitInvalid {
7024        de: String,
7025        para: String,
7026        wit: String,
7027        reason: String,
7028    },
7029    #[error(
7030        ":entrada :para is empty (every :entrada must route to a caixa declared in \
7031         :membros; fill the :para field with a member name)"
7032    )]
7033    EntradaParaEmpty,
7034    #[error(
7035        ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
7036         :entrada :para value names a member of :membros, which is itself a DNS-1123 \
7037         label per the K8s apiserver's `metadata.name` rule on every object the \
7038         member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
7039         Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
7040         `\"checkout\"` or `\"cart-v2\"`)"
7041    )]
7042    EntradaParaInvalid { para: String, reason: String },
7043    #[error(":entrada routes to caixa {para:?} not declared in :membros")]
7044    EntradaMemberMissing { para: String },
7045    #[error(":entrada must declare a non-empty :host")]
7046    EmptyEntradaHost,
7047    #[error(
7048        ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
7049         (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
7050         `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
7051         like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
7052    )]
7053    EntradaHostInvalid { host: String, reason: String },
7054    #[error(":entrada :port must be in 1..=65535, got 0")]
7055    EntradaPortZero,
7056    #[error(":entrada :paths entry is empty (use the empty list to match all)")]
7057    EntradaPathEmpty,
7058    #[error(
7059        ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
7060    )]
7061    EntradaPathNotAbsolute { path: String },
7062    #[error(
7063        ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
7064         value: {reason} (the K8s apiserver enforces the same shape on \
7065         `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
7066         single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
7067         requires percent-encoding `%XX` for non-ASCII and whitespace)"
7068    )]
7069    EntradaPathInvalid { path: String, reason: String },
7070    #[error(":entrada :paths entry {path:?} appears more than once")]
7071    EntradaPathDuplicate { path: String },
7072    #[error(
7073        ":placement {estrategia} requires at least one :clusters entry \
7074         (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
7075    )]
7076    PlacementWithoutClusters { estrategia: PlacementStrategy },
7077    #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
7078    PlacementClusterEmpty,
7079    #[error(
7080        ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
7081         (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
7082         in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
7083         future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
7084         — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
7085         identifier like `\"rio\"` or `\"mar-east\"`)"
7086    )]
7087    PlacementClusterInvalid { cluster: String, reason: String },
7088    #[error(":placement :clusters entry {cluster:?} appears more than once")]
7089    PlacementClusterDuplicate { cluster: String },
7090    #[error(
7091        ":placement :affinity must be non-empty when set (omit :affinity to express \
7092         `no placement hint`)"
7093    )]
7094    PlacementAffinityEmpty,
7095    #[error(
7096        ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
7097         (placement hints land verbatim in the M3 Adaptive compression overlay's \
7098         `placement.affinity` field and in every future M4 placement-engine routing \
7099         axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
7100         selector — both enforce the DNS-1123 label rule on admission; use a \
7101         lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
7102         `\"low-latency\"`, or `\"anti-affinity\"`)"
7103    )]
7104    PlacementAffinityInvalid { affinity: String, reason: String },
7105    #[error(":placement Sharded requires :shard-key")]
7106    ShardedWithoutKey,
7107    #[error(
7108        ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
7109         hashes every entity onto the same shard, defeating sharding entirely)"
7110    )]
7111    ShardedKeyEmpty,
7112    #[error(
7113        ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
7114         entity-id extractor expression: {reason} (the future M4 Akka-style \
7115         cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
7116         as a single-token property reference and hashes the extracted entity ID \
7117         to compute shard placement; use a printable-ASCII extractor expression \
7118         like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
7119         `\"${{tenant}}\"`)"
7120    )]
7121    ShardKeyInvalid { shard_key: String, reason: String },
7122    #[error(
7123        ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
7124         Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
7125         convention); :estrategia Replicated runs every cluster active-active and \
7126         :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
7127         distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
7128         to :estrategia Sharded if hash-keyed routing is the intent"
7129    )]
7130    ShardKeyOnNonSharded {
7131        estrategia: PlacementStrategy,
7132        shard_key: String,
7133    },
7134    #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
7135    ContratoMissingTarget {
7136        de: String,
7137        para: String,
7138        wit: String,
7139        expected: &'static str,
7140    },
7141    #[error(
7142        "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
7143         expected `:{expected}` only"
7144    )]
7145    ContratoWrongTarget {
7146        de: String,
7147        para: String,
7148        wit: String,
7149        expected: &'static str,
7150    },
7151    #[error(
7152        "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
7153         like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
7154         that matches no traffic and silently drops every request)"
7155    )]
7156    ContratoEndpointEmpty { de: String, para: String },
7157    #[error(
7158        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
7159         (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
7160         :entrada :paths)"
7161    )]
7162    ContratoEndpointNotAbsolute {
7163        de: String,
7164        para: String,
7165        endpoint: String,
7166    },
7167    #[error(
7168        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
7169         Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
7170         emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
7171         caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
7172         shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
7173         like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
7174         and whitespace)"
7175    )]
7176    ContratoEndpointInvalid {
7177        de: String,
7178        para: String,
7179        endpoint: String,
7180        reason: String,
7181    },
7182    #[error(
7183        "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
7184         subject is a no-op subscribe; omit :subject only if the WIT world is not \
7185         pub-sub-shaped)"
7186    )]
7187    ContratoSubjectEmpty { de: String, para: String },
7188    #[error(
7189        "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
7190         NATS subject: {reason} (the NATS server's subject parser enforces the \
7191         same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
7192         single-token and `>` multi-token wildcards — at publish/subscribe time; \
7193         use a token-by-token form like `\"checkout.events.charge.failed\"` or \
7194         `\"orders.*.completed\"` — a malformed subject silently drops every \
7195         message at runtime far from the source caixa.lisp)"
7196    )]
7197    ContratoSubjectInvalid {
7198        de: String,
7199        para: String,
7200        subject: String,
7201        reason: String,
7202    },
7203    #[error(
7204        "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
7205         addresses the bucket root, defeating the per-key isolation the slot exists \
7206         for; omit :slot only if the WIT world is not store-shaped)"
7207    )]
7208    ContratoSlotEmpty { de: String, para: String },
7209    #[error(
7210        "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
7211         WASI keyvalue store slot template: {reason} (the substrate enforces \
7212         the printable-ASCII intersection-floor every kv backend admits — \
7213         use a single-token path / template expression like `\"checkout/$orderId\"`, \
7214         `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
7215         percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
7216         slot either gets rejected on write by strict backends or silently \
7217         corrupts the next read on permissive ones, far from the source caixa.lisp)"
7218    )]
7219    ContratoSlotInvalid {
7220        de: String,
7221        para: String,
7222        slot: String,
7223        reason: String,
7224    },
7225    #[error(
7226        "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
7227         or an event-sourced indirection (MESH-COMPOSITION §III.3)",
7228        cycle.join(" → ")
7229    )]
7230    ContratoCycle { cycle: Vec<String> },
7231    #[error(
7232        ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
7233         than once (the typed graph edges are a set, not a multiset; duplicate \
7234         contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
7235         values that K8s admission rejects far from the source caixa.lisp)"
7236    )]
7237    ContratoDuplicate {
7238        de: String,
7239        para: String,
7240        wit: String,
7241        target: String,
7242    },
7243    #[error(
7244        ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
7245         contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
7246         express `no per-call deadline on this axis`"
7247    )]
7248    PolicyTimeoutZero,
7249    #[error(
7250        ":politicas :retries must be > 0 when set; omit :retries to express \
7251         `no retries on transient failure`"
7252    )]
7253    PolicyRetriesZero,
7254    #[error(
7255        ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
7256         (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
7257         retry policy into a thundering-herd amplification vector on transient \
7258         failure (one caller request fans out to `(retries+1)^depth` server-side \
7259         calls across the synchronous-:contratos subgraph), exactly the failure \
7260         mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
7261         Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
7262         or omit :retries to disable retries entirely"
7263    )]
7264    PolicyRetriesExceedsCap { retries: u32 },
7265    #[error(
7266        ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
7267         breaker trips on the first call); omit :circuit-breaker to disable it"
7268    )]
7269    PolicyBreakerZeroFailures,
7270    #[error(
7271        ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
7272         mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
7273         above this cap turns the typed breaker policy into a no-op: the trip \
7274         threshold is structurally so high that no realistic failures-per-:window \
7275         traffic shape can reach it, so the breaker never trips and every typed-slot \
7276         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
7277         Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
7278         structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
7279         Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
7280         omit :circuit-breaker to disable the breaker entirely"
7281    )]
7282    PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
7283    #[error(
7284        ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
7285         tracks no failures); omit :circuit-breaker to disable it"
7286    )]
7287    PolicyBreakerZeroWindow,
7288    #[error(
7289        ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
7290         request); omit :rate-limit to disable rate limiting"
7291    )]
7292    PolicyRateLimitZero,
7293    #[error(
7294        ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
7295         (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
7296         rate-limit policy into a no-op limiter: the token-bucket capacity is \
7297         structurally so high that no realistic per-edge traffic shape can drain it, \
7298         so the limiter never trips and every typed-slot consumer (the future \
7299         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
7300         local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
7301         that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
7302         Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
7303         Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
7304         Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
7305         to disable rate limiting entirely"
7306    )]
7307    PolicyRateLimitExceedsCap { rate: u32 },
7308    #[error(
7309        ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
7310         the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
7311         rate-limit codec round-trips losslessly; got {window:?} which renders to a \
7312         non-round-trippable form (omit :rate-limit to disable, or pick one of the \
7313         three canonical windows)"
7314    )]
7315    PolicyRateLimitWindowNotCanonical { window: Duration },
7316    #[error(
7317        ":politicas :timeout must be an integer number of milliseconds — the canonical \
7318         authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
7319         duration codec round-trips losslessly; got {timeout:?} which carries a \
7320         sub-millisecond residue that either truncates to a different `Duration` on \
7321         re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
7322         to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
7323         zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
7324         (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
7325    )]
7326    PolicyTimeoutNotCanonical { timeout: Duration },
7327    #[error(
7328        ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
7329         (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
7330         per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
7331         overlays carry a deadline so long no realistic synchronous-:contratos \
7332         traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
7333         CSE invariant degenerates to enforcement only at the per-Servico \
7334         `:limits :wall-clock` layer — far above the per-edge granularity the typed \
7335         `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
7336         (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
7337         ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
7338         maxes out at the same `3600s` ceiling) or omit :timeout to express \
7339         `no per-call deadline on this axis` (the synchronous-call deadline then \
7340         relies entirely on the per-Servico `:limits :wall-clock` axis)"
7341    )]
7342    PolicyTimeoutExceedsCap { timeout: Duration },
7343    #[error(
7344        ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
7345         the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
7346         the shared duration codec round-trips losslessly; got {window:?} which carries a \
7347         sub-millisecond residue that either truncates to a different `Duration` on \
7348         re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
7349         Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
7350    )]
7351    PolicyBreakerWindowNotCanonical { window: Duration },
7352    #[error(
7353        ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
7354         (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
7355         rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
7356         is structurally so long that transient failures are never forgotten, the breaker \
7357         trips once and stays tripped for the lifetime of the component, and every typed-slot \
7358         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
7359         outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
7360         Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
7361         default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
7362         the breaker entirely"
7363    )]
7364    PolicyBreakerWindowExceedsCap { window: Duration },
7365}
7366
7367#[cfg(test)]
7368mod tests {
7369    use super::*;
7370
7371    fn membro(name: &str, ver: &str) -> Membro {
7372        Membro {
7373            caixa: name.into(),
7374            versao: ver.into(),
7375        }
7376    }
7377
7378    fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
7379        WitContract {
7380            de: de.into(),
7381            para: para.into(),
7382            wit: "wasi:http/proxy".into(),
7383            endpoint: Some(ep.into()),
7384            subject: None,
7385            slot: None,
7386        }
7387    }
7388
7389    fn three_member_spec() -> AplicacaoSpec {
7390        AplicacaoSpec {
7391            membros: vec![
7392                membro("catalog", "^0.1"),
7393                membro("cart", "^0.1"),
7394                membro("payment", "^0.2"),
7395            ],
7396            contratos: vec![
7397                contract_http("cart", "catalog", "/products/:id"),
7398                contract_http("cart", "payment", "/charge"),
7399            ],
7400            politicas: MeshPolicy {
7401                timeout: Some(Duration::from_secs(30)),
7402                retries: Some(3),
7403                mtls_required: Some(true),
7404                ..Default::default()
7405            },
7406            placement: Placement {
7407                estrategia: PlacementStrategy::Replicated,
7408                clusters: vec!["rio".into(), "mar".into()],
7409                affinity: Some("data-locality".into()),
7410                shard_key: None,
7411            },
7412            entrada: Some(Entrada {
7413                host: "checkout.quero.cloud".into(),
7414                para: "cart".into(),
7415                paths: vec!["/api/cart".into(), "/api/products".into()],
7416                port: 8080,
7417            }),
7418        }
7419    }
7420
7421    #[test]
7422    fn happy_path_validates() {
7423        three_member_spec().validate().unwrap();
7424    }
7425
7426    #[test]
7427    fn rejects_empty_membros() {
7428        let mut s = three_member_spec();
7429        s.membros = vec![];
7430        assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
7431    }
7432
7433    #[test]
7434    fn rejects_empty_membro_caixa() {
7435        // A `:caixa ""` entry has no name to render into programs.yaml
7436        // and no caixa.lisp to resolve at lacre time.
7437        let mut s = three_member_spec();
7438        s.membros[1].caixa = String::new();
7439        assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
7440    }
7441
7442    #[test]
7443    fn rejects_empty_membro_versao() {
7444        // A `:versao ""` entry can't pin a semver constraint, so the
7445        // lacre pipeline fails far from the source.
7446        let mut s = three_member_spec();
7447        s.membros[2].versao = String::new();
7448        let err = s.validate().unwrap_err();
7449        assert!(
7450            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
7451            "got {err:?}"
7452        );
7453    }
7454
7455    #[test]
7456    fn rejects_duplicate_membro_caixa() {
7457        // Two `:membros` entries with the same `:caixa` collapse to one
7458        // node in the membership HashSet, which masks `:contratos`
7459        // membership errors and produces duplicate programs.yaml entries.
7460        let mut s = three_member_spec();
7461        s.membros.push(membro("cart", "^0.2"));
7462        let err = s.validate().unwrap_err();
7463        assert!(
7464            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
7465            "got {err:?}"
7466        );
7467    }
7468
7469    #[test]
7470    fn rejects_invalid_membro_versao_requirement() {
7471        // The fail-before-pass-after pin: a non-empty but malformed
7472        // semver requirement (`"^bad-version"`) silently passed
7473        // `validate()` on every pre-gate codebase because the prior
7474        // shape only refused the empty string. The parse failure
7475        // surfaced far downstream at lacre-resolve time with a
7476        // `semver::Error` that didn't name which `:membros` entry
7477        // carried the typo. The new gate moves the check to caixa-build
7478        // time at the source caixa.lisp.
7479        let mut s = three_member_spec();
7480        s.membros[2].versao = "^bad-version".into();
7481        let err = s.validate().unwrap_err();
7482        assert!(
7483            matches!(
7484                err,
7485                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
7486                    if caixa == "payment" && versao == "^bad-version"
7487            ),
7488            "got {err:?}"
7489        );
7490    }
7491
7492    #[test]
7493    fn rejects_membro_versao_with_double_caret_typo() {
7494        // `"^^0.1"` is the canonical doubled-caret typo — looks like a
7495        // Cargo-shaped requirement on first glance but fails the parser
7496        // because semver doesn't accept stacked operators. Pin this
7497        // adjacent-shape footgun explicitly so a future relaxation that
7498        // accepts "looks-canonical-but-isn't" forms surfaces here.
7499        let mut s = three_member_spec();
7500        s.membros[0].versao = "^^0.1".into();
7501        let err = s.validate().unwrap_err();
7502        assert!(
7503            matches!(
7504                err,
7505                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
7506                    if caixa == "catalog" && versao == "^^0.1"
7507            ),
7508            "got {err:?}"
7509        );
7510    }
7511
7512    #[test]
7513    fn rejects_membro_versao_with_v_prefixed_tag() {
7514        // `"v0.1"` is the canonical "git-tag-shape leaking into the
7515        // semver requirement slot" typo — an author copies the
7516        // publish-side git-tag string verbatim into `:versao`, but
7517        // Cargo's semver parser rejects the leading `v` (only digits +
7518        // canonical operators are valid in the major-version
7519        // position). The gate's diagnostic names which member entry
7520        // carried the v-prefix so the fix is one edit, not a grep
7521        // through every member's `:versao`. (Note: bare `x`-glob
7522        // shorthands like `^0.1.x` are *accepted* by the semver crate
7523        // as an `*` wildcard on the patch axis — they're a Cargo-side
7524        // valid shape, not a typo, so the gate intentionally lets them
7525        // through.)
7526        let mut s = three_member_spec();
7527        s.membros[1].versao = "v0.1".into();
7528        let err = s.validate().unwrap_err();
7529        assert!(
7530            matches!(
7531                err,
7532                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
7533                    if caixa == "cart" && versao == "v0.1"
7534            ),
7535            "got {err:?}"
7536        );
7537    }
7538
7539    #[test]
7540    fn accepts_canonical_membro_versao_forms() {
7541        // The four Cargo-shaped requirement forms `:deps :versao`
7542        // already accepts via `crate::parse_requirement` must pass the
7543        // membros gate without re-validating at the resolver layer.
7544        // Pin every leg so a future tightening of the canonical set
7545        // surfaces here as a test failure.
7546        for form in [
7547            "^0.1",      // caret — minor-range pin (the most common shape)
7548            "~0.1.2",    // tilde — patch-range pin
7549            "0.1.0",     // exact — single-version pin
7550            "*",         // wildcard — explicitly any-version (semver::VersionReq::STAR)
7551            ">=0.1, <2", // multi-range — comma-separated comparators
7552        ] {
7553            let mut s = three_member_spec();
7554            for m in &mut s.membros {
7555                m.versao = form.into();
7556            }
7557            s.validate()
7558                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
7559        }
7560    }
7561
7562    #[test]
7563    fn membro_versao_empty_takes_precedence_over_invalid() {
7564        // Order pin: the existing `MembroVersaoEmpty` diagnostic
7565        // (which doesn't try to parse) fires before the new
7566        // `MembroVersaoInvalid` parse-side diagnostic, so an empty
7567        // `:versao` keeps its narrower error message — `parse_requirement`
7568        // would also reject `""`, but the empty-string arm is the more
7569        // self-locating diagnostic for the author.
7570        let mut s = three_member_spec();
7571        s.membros[1].versao = String::new();
7572        let err = s.validate().unwrap_err();
7573        assert!(
7574            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
7575            "got {err:?}"
7576        );
7577    }
7578
7579    #[test]
7580    fn membro_versao_invalid_fires_before_duplicate_check() {
7581        // Order pin: a malformed requirement on a non-duplicate entry
7582        // surfaces *its own* diagnostic (which names the offending
7583        // `:versao` string), even when a later entry would otherwise
7584        // collapse onto an earlier name. The per-entry shape gate runs
7585        // inline before the duplicate-key insert, parallel to
7586        // `membros_validation_runs_before_contratos_membership_check`
7587        // and `duplicate_contrato_gate_runs_after_target_shape_check`.
7588        let mut s = three_member_spec();
7589        s.membros[0].versao = "^bad".into();
7590        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
7591        let err = s.validate().unwrap_err();
7592        assert!(
7593            matches!(
7594                err,
7595                AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
7596            ),
7597            "got {err:?}"
7598        );
7599    }
7600
7601    #[test]
7602    fn membro_versao_invalid_diagnostic_carries_offending_versao() {
7603        // The diagnostic-shape pin: the error names the offending
7604        // `:versao` value verbatim so the author can grep their
7605        // caixa.lisp without re-running the build, and carries a
7606        // non-empty `reason` from `semver::VersionReq::parse` so the
7607        // parser's own wording flows through to the diagnostic.
7608        let mut s = three_member_spec();
7609        s.membros[2].versao = "not-a-req".into();
7610        let err = s.validate().unwrap_err();
7611        let AplicacaoError::MembroVersaoInvalid {
7612            caixa,
7613            versao,
7614            reason,
7615        } = err
7616        else {
7617            panic!("expected MembroVersaoInvalid, got other variant");
7618        };
7619        assert_eq!(caixa, "payment");
7620        assert_eq!(versao, "not-a-req");
7621        assert!(
7622            !reason.is_empty(),
7623            "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
7624        );
7625    }
7626
7627    #[test]
7628    fn membro_versao_invalid_runs_before_contratos_check() {
7629        // A malformed `:versao` on any member must surface its own
7630        // diagnostic (which names *which* member to fix) before any
7631        // `:contratos` membership lookup raises `ContratoMemberMissing`.
7632        // The `:contratos` gate runs after `validate_membros`, so this
7633        // is structurally guaranteed — pin it explicitly so a future
7634        // refactor that reorders the gates surfaces here.
7635        let mut s = three_member_spec();
7636        s.membros[1].versao = "^^0.1".into();
7637        // Add a contrato whose `:para` doesn't exist — would normally
7638        // raise ContratoMemberMissing at the membership lookup, but
7639        // the membros gate must fire first.
7640        s.contratos
7641            .push(contract_http("cart", "phantom", "/never-reached"));
7642        let err = s.validate().unwrap_err();
7643        assert!(
7644            matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
7645            "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
7646        );
7647    }
7648
7649    #[test]
7650    fn membros_validation_runs_before_contratos_membership_check() {
7651        // If `:membros` carries a duplicate, the membership-collapse
7652        // would silently accept a `:contratos :para "phantom"` so long
7653        // as some entry hashes to "phantom". Pinning order: the
7654        // duplicate-membros error fires first, regardless of whether
7655        // contratos reference real members.
7656        let mut s = three_member_spec();
7657        s.membros = vec![
7658            membro("cart", "^0.1"),
7659            membro("cart", "^0.2"),
7660            membro("catalog", "^0.1"),
7661            membro("payment", "^0.1"),
7662        ];
7663        let err = s.validate().unwrap_err();
7664        assert!(
7665            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
7666            "got {err:?}"
7667        );
7668    }
7669
7670    #[test]
7671    fn distinct_membros_validate() {
7672        // Pin the happy-path: every `:membros` entry has a non-empty
7673        // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
7674        // The fixture already satisfies this; this test makes the
7675        // invariant explicit so a future refactor of the fixture can't
7676        // silently break the guarantee.
7677        three_member_spec().validate().unwrap();
7678    }
7679
7680    // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
7681
7682    #[test]
7683    fn rejects_membro_caixa_with_uppercase() {
7684        // The canonical "I copied the Servico's display name verbatim"
7685        // typo — caixa names are lowercase per K8s DNS-1123 label rule,
7686        // but author tools often round-trip a TitleCase or CamelCase
7687        // identifier from an ADR or a sketch. Pin the diagnostic names
7688        // the offending name and suggests the lower-cased fix in one
7689        // edit, mirroring the `rejects_entrada_host_with_uppercase`
7690        // gate's shape (c7d05ec).
7691        let mut s = three_member_spec();
7692        s.membros[1].caixa = "Cart".into();
7693        let err = s.validate().unwrap_err();
7694        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
7695            panic!("expected MembroCaixaInvalid, got other variant");
7696        };
7697        assert_eq!(caixa, "Cart");
7698        assert!(
7699            reason.contains("uppercase"),
7700            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
7701        );
7702        assert!(
7703            reason.contains("\"cart\""),
7704            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
7705        );
7706    }
7707
7708    #[test]
7709    fn rejects_membro_caixa_with_underscore() {
7710        // The canonical "I'm thinking of a Python module / Postgres
7711        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
7712        // label schema. K8s rejects `metadata.name: my_cart` at admission
7713        // time with an opaque `field is invalid` (no source-citing
7714        // diagnostic). The gate moves it to caixa-build time.
7715        let mut s = three_member_spec();
7716        s.membros[0].caixa = "my_cart".into();
7717        let err = s.validate().unwrap_err();
7718        assert!(
7719            matches!(
7720                err,
7721                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
7722                    if caixa == "my_cart" && reason.contains('_')
7723            ),
7724            "got {err:?}"
7725        );
7726    }
7727
7728    #[test]
7729    fn rejects_membro_caixa_with_dot() {
7730        // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
7731        // subdomain — even though K8s `metadata.name` itself accepts
7732        // dots (DNS-1123 subdomain rule), this string also lands as a
7733        // K8s Service name (DNS-1035 label — no dots) and as a label
7734        // value on identity-based Cilium selectors. The strictest floor
7735        // among the use sites wins. The "I want to namespace my member
7736        // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
7737        let mut s = three_member_spec();
7738        s.membros[2].caixa = "team.cart".into();
7739        let err = s.validate().unwrap_err();
7740        assert!(
7741            matches!(
7742                err,
7743                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
7744                    if caixa == "team.cart" && reason.contains('.')
7745            ),
7746            "got {err:?}"
7747        );
7748    }
7749
7750    #[test]
7751    fn rejects_membro_caixa_with_leading_hyphen() {
7752        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
7753        // with an alphanumeric. The K8s apiserver rejects `-cart`
7754        // outright; the renderer would emit a `metadata.name: "-cart"`
7755        // that fails admission far from the source caixa.lisp.
7756        let mut s = three_member_spec();
7757        s.membros[0].caixa = "-cart".into();
7758        let err = s.validate().unwrap_err();
7759        assert!(
7760            matches!(
7761                err,
7762                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
7763                    if caixa == "-cart" && reason.contains("start and end")
7764            ),
7765            "got {err:?}"
7766        );
7767    }
7768
7769    #[test]
7770    fn rejects_membro_caixa_with_trailing_hyphen() {
7771        // The symmetric arm of the boundary rule. Pin separately so
7772        // both ends of the label are covered against a future relaxation
7773        // that only checks one boundary.
7774        let mut s = three_member_spec();
7775        s.membros[1].caixa = "cart-".into();
7776        let err = s.validate().unwrap_err();
7777        assert!(
7778            matches!(
7779                err,
7780                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
7781                    if caixa == "cart-"
7782            ),
7783            "got {err:?}"
7784        );
7785    }
7786
7787    #[test]
7788    fn rejects_membro_caixa_with_unicode() {
7789        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
7790        // (`xn--…`) by the author before it reaches K8s. The byte-by-
7791        // byte ASCII validity check rejects multi-byte UTF-8 sequences
7792        // by the first byte that fails the `[a-z0-9-]` predicate.
7793        let mut s = three_member_spec();
7794        s.membros[2].caixa = "café".into();
7795        let err = s.validate().unwrap_err();
7796        assert!(
7797            matches!(
7798                err,
7799                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
7800                    if caixa == "café"
7801            ),
7802            "got {err:?}"
7803        );
7804    }
7805
7806    #[test]
7807    fn rejects_membro_caixa_with_whitespace() {
7808        // Whitespace is the canonical "I pasted from a sketch / doc"
7809        // footgun. The apiserver rejects every `metadata.name` value
7810        // carrying whitespace; pin the gate fires at the right boundary.
7811        let mut s = three_member_spec();
7812        s.membros[0].caixa = "my cart".into();
7813        let err = s.validate().unwrap_err();
7814        assert!(
7815            matches!(
7816                err,
7817                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
7818                    if caixa == "my cart"
7819            ),
7820            "got {err:?}"
7821        );
7822    }
7823
7824    #[test]
7825    fn rejects_membro_caixa_too_long() {
7826        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
7827        // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
7828        // exactly. The gate's reason names both the cap and the actual
7829        // length so the author can shorten in one edit.
7830        let mut s = three_member_spec();
7831        let too_long = "a".repeat(64);
7832        s.membros[1].caixa = too_long.clone();
7833        let err = s.validate().unwrap_err();
7834        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
7835            panic!("expected MembroCaixaInvalid");
7836        };
7837        assert_eq!(caixa, too_long);
7838        assert!(
7839            reason.contains("63") && reason.contains("64"),
7840            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
7841        );
7842    }
7843
7844    #[test]
7845    fn membro_caixa_max_length_validates() {
7846        // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
7847        // so a future tightening (e.g. dropping to 62) surfaces here as
7848        // a regression, mirroring `entrada_host_max_length_validates`
7849        // (c7d05ec).
7850        let mut s = three_member_spec();
7851        s.membros[2].caixa = "a".repeat(63);
7852        s.entrada.as_mut().unwrap().para = "a".repeat(63);
7853        // remove contratos referencing the renamed member; they'd
7854        // raise ContratoMemberMissing otherwise
7855        s.contratos
7856            .retain(|c| c.de != "payment" && c.para != "payment");
7857        s.validate().unwrap();
7858    }
7859
7860    #[test]
7861    fn accepts_canonical_membro_caixa_forms() {
7862        // The DNS-1123 label shapes a caixa author is realistically
7863        // going to write: single-word lowercase, hyphen-joined, ending
7864        // in a digit-suffixed version (`cart-v2`), starting with a
7865        // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
7866        // DNS-1035 which requires a letter at position 0), single-
7867        // character (`a` — boundary). Pin every leg so a future
7868        // tightening that bans (e.g.) digit-start identifiers surfaces
7869        // here.
7870        for form in [
7871            "checkout",
7872            "cart",
7873            "cart-v2",
7874            "a",
7875            "c0",
7876            "3rd-party-shim",
7877            "x-1-2-3-4",
7878        ] {
7879            let mut s = three_member_spec();
7880            // Renaming a member also requires updating downstream refs;
7881            // drop everything else and rebuild a minimal spec around
7882            // just the one renamed member.
7883            s.membros = vec![membro(form, "^0.1")];
7884            s.contratos = vec![];
7885            s.entrada = None;
7886            s.validate()
7887                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
7888        }
7889    }
7890
7891    #[test]
7892    fn membro_caixa_empty_takes_precedence_over_invalid() {
7893        // Order pin: the existing `MembroCaixaEmpty` diagnostic
7894        // (which doesn't try to parse) fires before the new
7895        // `MembroCaixaInvalid` parse-side diagnostic, so an empty
7896        // `:caixa` keeps its narrower error message — the new gate
7897        // would also reject `""`, but the empty-string arm is the more
7898        // self-locating diagnostic for the author. Mirrors the
7899        // `entrada_host_empty_takes_precedence_over_invalid` pin
7900        // (c7d05ec).
7901        let mut s = three_member_spec();
7902        s.membros[1].caixa = String::new();
7903        let err = s.validate().unwrap_err();
7904        assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
7905    }
7906
7907    #[test]
7908    fn membro_caixa_invalid_fires_before_versao_check() {
7909        // Order pin: an invalid-shape `:caixa` surfaces *its own*
7910        // diagnostic (which names the offending caixa name), even when
7911        // the same entry's `:versao` is also empty/invalid. The shape
7912        // gate runs first because the diagnostic is more self-locating —
7913        // an empty/invalid `:versao` on an invalid-shape caixa name is
7914        // a downstream-fix-after-the-caixa-rename concern.
7915        let mut s = three_member_spec();
7916        s.membros[1].caixa = "Cart".into();
7917        s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
7918        let err = s.validate().unwrap_err();
7919        assert!(
7920            matches!(
7921                err,
7922                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
7923            ),
7924            "got {err:?}"
7925        );
7926    }
7927
7928    #[test]
7929    fn membro_caixa_invalid_fires_before_duplicate_check() {
7930        // Order pin: a malformed-shape `:caixa` on an earlier entry
7931        // surfaces *its own* diagnostic, even when a later entry would
7932        // otherwise collapse onto a duplicate name. The per-entry shape
7933        // gate runs inline before the duplicate-key insert, parallel
7934        // to `membro_versao_invalid_fires_before_duplicate_check`.
7935        let mut s = three_member_spec();
7936        s.membros[0].caixa = "Catalog".into();
7937        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
7938        let err = s.validate().unwrap_err();
7939        assert!(
7940            matches!(
7941                err,
7942                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
7943            ),
7944            "got {err:?}"
7945        );
7946    }
7947
7948    #[test]
7949    fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
7950        // The diagnostic-shape pin: the error names the offending
7951        // `:caixa` value verbatim so the author can grep their
7952        // caixa.lisp without re-running the build, and carries a
7953        // non-empty `reason` naming the specific violation. Same
7954        // shape every typed-shape gate enshrines (c7d05ec's
7955        // `entrada_host_diagnostic_carries_offending_host`,
7956        // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
7957        let mut s = three_member_spec();
7958        s.membros[2].caixa = "BAD_NAME".into();
7959        let err = s.validate().unwrap_err();
7960        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
7961            panic!("expected MembroCaixaInvalid");
7962        };
7963        assert_eq!(caixa, "BAD_NAME");
7964        assert!(
7965            !reason.is_empty(),
7966            "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
7967        );
7968    }
7969
7970    #[test]
7971    fn rejects_contrato_with_unknown_de() {
7972        let mut s = three_member_spec();
7973        s.contratos.push(contract_http("phantom", "catalog", "/x"));
7974        let err = s.validate().unwrap_err();
7975        assert!(
7976            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
7977        );
7978    }
7979
7980    #[test]
7981    fn rejects_contrato_with_unknown_para() {
7982        let mut s = three_member_spec();
7983        s.contratos.push(contract_http("cart", "phantom", "/x"));
7984        let err = s.validate().unwrap_err();
7985        assert!(
7986            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
7987        );
7988    }
7989
7990    #[test]
7991    fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
7992        // The read-path pin: the phantom-`:de` refusal arm's
7993        // `ContratoMemberMissing.caixa` carrier must be observed through
7994        // the lifted [`WitContract::source`] accessor, not the raw
7995        // `.de.clone()` field-access `String`-carry. Peer of the sibling
7996        // per-`:contratos` self-loop arm's `.source().to_string()` /
7997        // `.world_ref().to_string()` `String`-carry sites the earlier
7998        // convergence lifted onto the same accessor pair. A future
7999        // silent detour that reintroduced the raw `.de.clone()` at the
8000        // wrap envelope while the shape-gate and membership lookup
8001        // routed through the accessor would surface here as a byte-equal
8002        // miss between the fired diagnostic's `caixa:` field and the
8003        // offending edge's `.source()` — pinning the accessor as the
8004        // sole read path across the phantom-name refusal arm's arg +
8005        // wrap-envelope emit surface.
8006        let mut s = three_member_spec();
8007        let phantom = contract_http("phantom", "catalog", "/x");
8008        s.contratos.push(phantom.clone());
8009        let err = s.validate().unwrap_err();
8010        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
8011            panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
8012        };
8013        assert_eq!(
8014            caixa,
8015            phantom.source(),
8016            "ContratoMemberMissing.caixa on the phantom-:de arm must \
8017             byte-equal WitContract::source — the wrap envelope must \
8018             route through the lifted accessor rather than the raw \
8019             .de.clone() field-access String-carry"
8020        );
8021    }
8022
8023    #[test]
8024    fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
8025        // The symmetric read-path pin on the `:para` phantom-name
8026        // refusal arm — same shape as the sibling `:de` pin above but
8027        // on the callee-Servico axis. Pins the wrap envelope's
8028        // `caixa:` field is observed through the lifted
8029        // [`WitContract::destination`] accessor, not the raw
8030        // `.para.clone()` field-access `String`-carry.
8031        let mut s = three_member_spec();
8032        let phantom = contract_http("cart", "phantom", "/x");
8033        s.contratos.push(phantom.clone());
8034        let err = s.validate().unwrap_err();
8035        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
8036            panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
8037        };
8038        assert_eq!(
8039            caixa,
8040            phantom.destination(),
8041            "ContratoMemberMissing.caixa on the phantom-:para arm must \
8042             byte-equal WitContract::destination — the wrap envelope \
8043             must route through the lifted accessor rather than the raw \
8044             .para.clone() field-access String-carry"
8045        );
8046    }
8047
8048    #[test]
8049    fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
8050        // The read-path pin on the `:de` DNS-1123-malformed shape-gate
8051        // refusal arm — the `validate_contrato_caixa` arg must be
8052        // observed through the lifted [`WitContract::source`] accessor,
8053        // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
8054        // value routes through the shared
8055        // [`crate::render::require_valid_dns_1123_label`] floor with the
8056        // accessor-projected value; the fired
8057        // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
8058        // the offending edge's `.source()`, pinning that the arg + the
8059        // downstream `caixa: caixa.to_string()` wrap route through the
8060        // same accessor's read path.
8061        let mut s = three_member_spec();
8062        let malformed = contract_http("BAD_NAME", "catalog", "/x");
8063        s.contratos.push(malformed.clone());
8064        let err = s.validate().unwrap_err();
8065        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
8066            panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
8067        };
8068        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
8069        assert_eq!(
8070            caixa,
8071            malformed.source(),
8072            "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
8073             byte-equal WitContract::source — the shape-gate arg + wrap \
8074             envelope must route through the lifted accessor rather \
8075             than the raw &c.de &String-borrow"
8076        );
8077    }
8078
8079    #[test]
8080    fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
8081        // Symmetric arm to the sibling `:de` malformed-shape pin above,
8082        // on the `:para` axis. Pins the shape-gate arg + wrap envelope
8083        // route through the lifted [`WitContract::destination`]
8084        // accessor. `:para` runs after the `:de` shape gate in the
8085        // canonical edge-direction order, so the `:de` value must be
8086        // well-shaped for the `:para` gate to fire — the `cart` :de is
8087        // canonical.
8088        let mut s = three_member_spec();
8089        let malformed = contract_http("cart", "BAD_NAME", "/x");
8090        s.contratos.push(malformed.clone());
8091        let err = s.validate().unwrap_err();
8092        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
8093            panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
8094        };
8095        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
8096        assert_eq!(
8097            caixa,
8098            malformed.destination(),
8099            "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
8100             byte-equal WitContract::destination — the shape-gate arg + \
8101             wrap envelope must route through the lifted accessor \
8102             rather than the raw &c.para &String-borrow"
8103        );
8104    }
8105
8106    // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
8107
8108    #[test]
8109    fn rejects_contrato_de_empty() {
8110        // `:de ""` previously fell through to `ContratoMemberMissing`
8111        // (with `caixa: ""`) because the validated `:membros :caixa`
8112        // set never contains the empty string. The narrower
8113        // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
8114        // the offending slot.
8115        let mut s = three_member_spec();
8116        s.contratos.push(contract_http("", "catalog", "/x"));
8117        let err = s.validate().unwrap_err();
8118        assert_eq!(
8119            err,
8120            AplicacaoError::ContratoCaixaEmpty {
8121                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
8122            },
8123            "got {err:?}"
8124        );
8125    }
8126
8127    #[test]
8128    fn rejects_contrato_para_empty() {
8129        // Symmetric arm to `:de ""` — `:para ""` previously fell
8130        // through to `ContratoMemberMissing { caixa: "" }`.
8131        let mut s = three_member_spec();
8132        s.contratos.push(contract_http("cart", "", "/x"));
8133        let err = s.validate().unwrap_err();
8134        assert_eq!(
8135            err,
8136            AplicacaoError::ContratoCaixaEmpty {
8137                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
8138            },
8139            "got {err:?}"
8140        );
8141    }
8142
8143    #[test]
8144    fn rejects_contrato_de_with_uppercase() {
8145        // The canonical "I copied the Servico's TitleCase display
8146        // name from an ADR" typo. Until this gate landed `:de "Cart"`
8147        // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
8148        // as "this caixa isn't in `:membros`" when the root cause is
8149        // "this `:de` value's shape can never legitimately match a
8150        // validated member (DNS-1123 labels are lowercase)". The
8151        // narrower diagnostic names the offending slot, the value
8152        // verbatim, and the parser-shaped reason.
8153        let mut s = three_member_spec();
8154        s.contratos.push(contract_http("Cart", "catalog", "/x"));
8155        let err = s.validate().unwrap_err();
8156        let AplicacaoError::ContratoCaixaInvalid {
8157            slot,
8158            caixa,
8159            reason,
8160        } = err
8161        else {
8162            panic!("expected ContratoCaixaInvalid, got other variant");
8163        };
8164        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
8165        assert_eq!(caixa, "Cart");
8166        assert!(
8167            reason.contains("uppercase"),
8168            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
8169        );
8170    }
8171
8172    #[test]
8173    fn rejects_contrato_para_with_underscore() {
8174        // The canonical "I'm thinking of a Python module" leak —
8175        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
8176        // Pin the `:para` axis surfaces the same diagnostic shape as
8177        // the `:de` axis on the underscore violation.
8178        let mut s = three_member_spec();
8179        s.contratos.push(contract_http("cart", "my_catalog", "/x"));
8180        let err = s.validate().unwrap_err();
8181        assert!(
8182            matches!(
8183                err,
8184                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
8185                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
8186            ),
8187            "got {err:?}"
8188        );
8189    }
8190
8191    #[test]
8192    fn rejects_contrato_de_with_dot() {
8193        // A `:contratos :de` value is a single DNS-1123 *label*, not
8194        // a subdomain — mirroring the `:membros :caixa` floor. The
8195        // strictest floor among the use sites wins.
8196        let mut s = three_member_spec();
8197        s.contratos
8198            .push(contract_http("team.cart", "catalog", "/x"));
8199        let err = s.validate().unwrap_err();
8200        assert!(
8201            matches!(
8202                err,
8203                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
8204                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
8205            ),
8206            "got {err:?}"
8207        );
8208    }
8209
8210    #[test]
8211    fn rejects_contrato_para_with_unicode() {
8212        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
8213        // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
8214        // validity check rejects multi-byte UTF-8 by the first
8215        // non-`[a-z0-9-]` byte.
8216        let mut s = three_member_spec();
8217        s.contratos.push(contract_http("cart", "café", "/x"));
8218        let err = s.validate().unwrap_err();
8219        assert!(
8220            matches!(
8221                err,
8222                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
8223                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
8224            ),
8225            "got {err:?}"
8226        );
8227    }
8228
8229    #[test]
8230    fn rejects_contrato_de_with_leading_hyphen() {
8231        // DNS-1123 boundary rule: labels must start and end with an
8232        // alphanumeric. K8s rejects `-cart` outright; the narrower
8233        // shape diagnostic now names the violation at caixa-build
8234        // time rather than the misframed membership-lookup arm.
8235        let mut s = three_member_spec();
8236        s.contratos.push(contract_http("-cart", "catalog", "/x"));
8237        let err = s.validate().unwrap_err();
8238        assert!(
8239            matches!(
8240                err,
8241                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
8242                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
8243            ),
8244            "got {err:?}"
8245        );
8246    }
8247
8248    #[test]
8249    fn contrato_de_empty_takes_precedence_over_invalid() {
8250        // Order pin: the `ContratoCaixaEmpty` arm fires before the
8251        // `ContratoCaixaInvalid` parse-side arm — same empty-first
8252        // cascade `validate_membro_caixa` / `validate_placement_cluster`
8253        // / `validate_entrada_host` already establish on their peer
8254        // name axes. The empty string is a structurally distinct
8255        // authoring footgun (the author left the field blank, vs.
8256        // typed a malformed value), so it gets its own diagnostic.
8257        let mut s = three_member_spec();
8258        s.contratos.push(contract_http("", "catalog", "/x"));
8259        let err = s.validate().unwrap_err();
8260        assert_eq!(
8261            err,
8262            AplicacaoError::ContratoCaixaEmpty {
8263                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
8264            }
8265        );
8266    }
8267
8268    #[test]
8269    fn contrato_de_shape_fires_before_para_shape() {
8270        // Per-axis order pin: within one `:contratos` entry, the `:de`
8271        // shape gate fires before the `:para` shape gate — same
8272        // edge-direction order the existing `ContratoMemberMissing` /
8273        // `ContratoSelfLoop` / target-dispatch checks use, so the
8274        // diagnostic for a contract with both `:de` and `:para`
8275        // malformed is stable. Authors fixing the surfaced `:de`
8276        // first will see `:para`'s diagnostic on re-run.
8277        let mut s = three_member_spec();
8278        s.contratos.push(contract_http("Cart", "Catalog", "/x"));
8279        let err = s.validate().unwrap_err();
8280        assert!(
8281            matches!(
8282                err,
8283                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
8284                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
8285            ),
8286            "got {err:?}"
8287        );
8288    }
8289
8290    #[test]
8291    fn contrato_shape_fires_before_membership_lookup() {
8292        // The load-bearing pin: an invalid-shape `:de` surfaces its
8293        // *own* diagnostic, not the misframed `ContratoMemberMissing`.
8294        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
8295        // an invalid-shape `:de` could never legitimately match any
8296        // member — the prior `ContratoMemberMissing` diagnostic was
8297        // a structural impossibility framed as a graph-membership
8298        // failure. The shape gate now routes every such input through
8299        // the narrower self-locating diagnostic.
8300        let mut s = three_member_spec();
8301        s.contratos.push(contract_http("Cart", "catalog", "/x"));
8302        let err = s.validate().unwrap_err();
8303        assert!(
8304            matches!(
8305                err,
8306                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
8307            ),
8308            "got {err:?}"
8309        );
8310        // And the symmetric case: an invalid-shape `:para` surfaces
8311        // its own diagnostic too, even when `:de` is well-shaped.
8312        let mut s = three_member_spec();
8313        s.contratos.push(contract_http("cart", "Catalog", "/x"));
8314        let err = s.validate().unwrap_err();
8315        assert!(
8316            matches!(
8317                err,
8318                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
8319            ),
8320            "got {err:?}"
8321        );
8322    }
8323
8324    #[test]
8325    fn contrato_shape_fires_before_self_edge_check() {
8326        // A `:de "Cart" :para "Cart"` entry is two distinct authoring
8327        // bugs: the shape violation (uppercase) and the self-edge
8328        // violation. The narrower per-axis shape diagnostic surfaces
8329        // first because fixing the shape may reveal that the author
8330        // also meant to point `:para` at a different member — the
8331        // self-edge framing is only useful once both endpoints have
8332        // valid shape.
8333        let mut s = three_member_spec();
8334        s.contratos.push(contract_http("Cart", "Cart", "/x"));
8335        let err = s.validate().unwrap_err();
8336        assert!(
8337            matches!(
8338                err,
8339                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
8340                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
8341            ),
8342            "got {err:?}"
8343        );
8344    }
8345
8346    #[test]
8347    fn contrato_well_shaped_phantom_still_raises_member_missing() {
8348        // Strict-improvement pin: a well-shaped `:de` that simply
8349        // isn't in `:membros` (a phantom reference — author meant
8350        // to add the member but didn't, or renamed and missed an
8351        // update) still surfaces `ContratoMemberMissing`, unchanged.
8352        // The shape gate only intercepts inputs that could never
8353        // legitimately match a validated member; legitimately-shaped
8354        // phantom references remain on the graph-membership axis.
8355        let mut s = three_member_spec();
8356        s.contratos
8357            .push(contract_http("phantom-shim", "catalog", "/x"));
8358        let err = s.validate().unwrap_err();
8359        assert!(
8360            matches!(
8361                err,
8362                AplicacaoError::ContratoMemberMissing { ref caixa }
8363                    if caixa == "phantom-shim"
8364            ),
8365            "got {err:?}"
8366        );
8367    }
8368
8369    #[test]
8370    fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
8371        // The diagnostic-shape pin: the error names the offending
8372        // slot (`:de` or `:para`) verbatim and the offending value
8373        // verbatim plus a non-empty parser-shaped reason, so the
8374        // author can grep their caixa.lisp for `:de "<name>"` /
8375        // `:para "<name>"` and fix it in one edit. Same diagnostic
8376        // shape as `MembroCaixaInvalid` (3f9d7a0) and
8377        // `PlacementClusterInvalid` (6c8c00b).
8378        let mut s = three_member_spec();
8379        s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
8380        let err = s.validate().unwrap_err();
8381        let AplicacaoError::ContratoCaixaInvalid {
8382            slot,
8383            caixa,
8384            reason,
8385        } = err
8386        else {
8387            panic!("expected ContratoCaixaInvalid, got {err:?}");
8388        };
8389        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
8390        assert_eq!(caixa, "BAD_NAME");
8391        assert!(
8392            !reason.is_empty(),
8393            "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
8394        );
8395    }
8396
8397    #[test]
8398    fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
8399        // Scalar-value pin: the two author-facing kebab-case labels the
8400        // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
8401        // admits on the `:contratos` per-entry endpoint-shape axis,
8402        // one arm per typed sub-slot. Mirrors the peer scalar-value
8403        // pin the sibling top-level M2 / M3 / Supervisor
8404        // author-facing-label consts carry
8405        // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
8406        // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
8407        // slot itself), so every altitude of the typed-slot algebra
8408        // shares the same "one canonical byte-string per arm"
8409        // discipline. A future rebrand (`:de` → `:from` matching the
8410        // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
8411        // sibling, `:para` → `:to` matching the same, or
8412        // `:de`/`:para` → `:source`/`:target` matching the WIT
8413        // world's `import`/`export` half-vocabulary) lands as an
8414        // edit to exactly one const, and every consumer that reaches
8415        // for the label picks it up at build time rather than at
8416        // runtime as a downstream `ContratoCaixaEmpty` /
8417        // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
8418        // diagnostic mismatch far from the rename's commit.
8419        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
8420        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
8421    }
8422
8423    #[test]
8424    fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
8425        // Production-through-const pin: the two per-axis labels the
8426        // per-`:contratos` entry endpoint-shape gate at
8427        // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
8428        // argument to [`validate_contrato_caixa`] route through the
8429        // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
8430        // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
8431        // future rebrand that reaches the const but not the gate (or
8432        // vice versa) surfaces here at build time rather than at
8433        // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
8434        // `slot: <stale-kebab-case>` diagnostic far from the rename's
8435        // commit. Mirror of the peer
8436        // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
8437        // pin (882f498) on the sibling M3 top-level slot axis.
8438        let mut s = three_member_spec();
8439        s.contratos.push(contract_http("", "catalog", "/x"));
8440        assert_eq!(
8441            s.validate().unwrap_err(),
8442            AplicacaoError::ContratoCaixaEmpty {
8443                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
8444            }
8445        );
8446        let mut s = three_member_spec();
8447        s.contratos.push(contract_http("cart", "", "/x"));
8448        assert_eq!(
8449            s.validate().unwrap_err(),
8450            AplicacaoError::ContratoCaixaEmpty {
8451                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
8452            }
8453        );
8454    }
8455
8456    #[test]
8457    fn accepts_canonical_contrato_caixa_forms() {
8458        // The DNS-1123 label shapes a caixa author is realistically
8459        // going to write on a `:contratos :de` / `:para`. Pin every
8460        // leg so a future tightening that bans (e.g.) digit-start
8461        // identifiers surfaces here, mirroring
8462        // `accepts_canonical_membro_caixa_forms` on the peer name
8463        // axis.
8464        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
8465            let mut s = three_member_spec();
8466            s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
8467            s.contratos = vec![contract_http("checkout", form, "/x")];
8468            s.entrada = None;
8469            s.validate().unwrap_or_else(|e| {
8470                panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
8471            });
8472
8473            let mut s = three_member_spec();
8474            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
8475            s.contratos = vec![contract_http(form, "catalog", "/x")];
8476            s.entrada = None;
8477            s.validate().unwrap_or_else(|e| {
8478                panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
8479            });
8480        }
8481    }
8482
8483    #[test]
8484    fn rejects_empty_wit() {
8485        let mut s = three_member_spec();
8486        s.contratos.push(WitContract {
8487            de: "cart".into(),
8488            para: "catalog".into(),
8489            wit: "".into(),
8490            endpoint: None,
8491            subject: None,
8492            slot: None,
8493        });
8494        let err = s.validate().unwrap_err();
8495        assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
8496    }
8497
8498    #[test]
8499    fn rejects_entrada_to_unknown_member() {
8500        let mut s = three_member_spec();
8501        s.entrada.as_mut().unwrap().para = "phantom".into();
8502        assert!(matches!(
8503            s.validate().unwrap_err(),
8504            AplicacaoError::EntradaMemberMissing { .. }
8505        ));
8506    }
8507
8508    // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
8509
8510    #[test]
8511    fn rejects_entrada_para_empty() {
8512        // `:para ""` previously fell through to
8513        // `EntradaMemberMissing { para: "" }` because the validated
8514        // `:membros :caixa` set never contains the empty string. The
8515        // narrower `EntradaParaEmpty` diagnostic now names the
8516        // offending slot directly — same empty-first cascade
8517        // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
8518        // `ContratoCaixaEmpty` establish on the peer name axes.
8519        let mut s = three_member_spec();
8520        s.entrada.as_mut().unwrap().para = String::new();
8521        let err = s.validate().unwrap_err();
8522        assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
8523    }
8524
8525    #[test]
8526    fn rejects_entrada_para_with_uppercase() {
8527        // The canonical "I copied the Servico's TitleCase display
8528        // name from an ADR" typo. Until this gate landed `:para "Cart"`
8529        // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
8530        // as "this caixa isn't in `:membros`" when the root cause is
8531        // "this `:para` value's shape can never legitimately match a
8532        // validated member (DNS-1123 labels are lowercase)". The
8533        // narrower diagnostic names the value verbatim plus the
8534        // parser-shaped reason.
8535        let mut s = three_member_spec();
8536        s.entrada.as_mut().unwrap().para = "Cart".into();
8537        let err = s.validate().unwrap_err();
8538        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
8539            panic!("expected EntradaParaInvalid, got other variant");
8540        };
8541        assert_eq!(para, "Cart");
8542        assert!(
8543            reason.contains("uppercase"),
8544            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
8545        );
8546    }
8547
8548    #[test]
8549    fn rejects_entrada_para_with_underscore() {
8550        // The canonical "I'm thinking of a Python module" leak —
8551        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
8552        let mut s = three_member_spec();
8553        s.entrada.as_mut().unwrap().para = "my_cart".into();
8554        let err = s.validate().unwrap_err();
8555        assert!(
8556            matches!(
8557                err,
8558                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8559                    if para == "my_cart" && reason.contains('_')
8560            ),
8561            "got {err:?}"
8562        );
8563    }
8564
8565    #[test]
8566    fn rejects_entrada_para_with_dot() {
8567        // An `:entrada :para` value is a single DNS-1123 *label*, not
8568        // a subdomain — mirroring the `:membros :caixa` floor. The
8569        // strictest floor among the use sites wins.
8570        let mut s = three_member_spec();
8571        s.entrada.as_mut().unwrap().para = "team.cart".into();
8572        let err = s.validate().unwrap_err();
8573        assert!(
8574            matches!(
8575                err,
8576                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8577                    if para == "team.cart" && reason.contains('.')
8578            ),
8579            "got {err:?}"
8580        );
8581    }
8582
8583    #[test]
8584    fn rejects_entrada_para_with_unicode() {
8585        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
8586        // (`xn--…`) before it reaches K8s.
8587        let mut s = three_member_spec();
8588        s.entrada.as_mut().unwrap().para = "café".into();
8589        let err = s.validate().unwrap_err();
8590        assert!(
8591            matches!(
8592                err,
8593                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
8594            ),
8595            "got {err:?}"
8596        );
8597    }
8598
8599    #[test]
8600    fn rejects_entrada_para_with_leading_hyphen() {
8601        // DNS-1123 boundary rule: labels must start and end with an
8602        // alphanumeric. K8s rejects `-cart` outright.
8603        let mut s = three_member_spec();
8604        s.entrada.as_mut().unwrap().para = "-cart".into();
8605        let err = s.validate().unwrap_err();
8606        assert!(
8607            matches!(
8608                err,
8609                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8610                    if para == "-cart" && reason.contains("start and end")
8611            ),
8612            "got {err:?}"
8613        );
8614    }
8615
8616    #[test]
8617    fn rejects_entrada_para_with_trailing_hyphen() {
8618        // Symmetric boundary arm.
8619        let mut s = three_member_spec();
8620        s.entrada.as_mut().unwrap().para = "cart-".into();
8621        let err = s.validate().unwrap_err();
8622        assert!(
8623            matches!(
8624                err,
8625                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8626                    if para == "cart-" && reason.contains("start and end")
8627            ),
8628            "got {err:?}"
8629        );
8630    }
8631
8632    #[test]
8633    fn rejects_entrada_para_too_long() {
8634        // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
8635        // bytes per label. K8s rejects longer names at admission on
8636        // every `metadata.name` axis.
8637        let mut s = three_member_spec();
8638        s.entrada.as_mut().unwrap().para = "a".repeat(64);
8639        let err = s.validate().unwrap_err();
8640        assert!(
8641            matches!(
8642                err,
8643                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8644                    if para.len() == 64 && reason.contains("max length")
8645            ),
8646            "got {err:?}"
8647        );
8648    }
8649
8650    #[test]
8651    fn entrada_para_empty_takes_precedence_over_invalid() {
8652        // Order pin: the `EntradaParaEmpty` arm fires before the
8653        // `EntradaParaInvalid` parse-side arm — same empty-first
8654        // cascade `validate_membro_caixa` / `validate_placement_cluster`
8655        // / `validate_contrato_caixa` already establish.
8656        let mut s = three_member_spec();
8657        s.entrada.as_mut().unwrap().para = String::new();
8658        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
8659    }
8660
8661    #[test]
8662    fn entrada_para_shape_fires_before_membership_lookup() {
8663        // The load-bearing pin: an invalid-shape `:para` surfaces its
8664        // *own* diagnostic, not the misframed `EntradaMemberMissing`.
8665        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
8666        // an invalid-shape `:para` could never legitimately match any
8667        // member — the prior `EntradaMemberMissing` diagnostic framed
8668        // a structural impossibility as a graph-membership failure.
8669        let mut s = three_member_spec();
8670        s.entrada.as_mut().unwrap().para = "Cart".into();
8671        let err = s.validate().unwrap_err();
8672        assert!(
8673            matches!(
8674                err,
8675                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
8676            ),
8677            "got {err:?}"
8678        );
8679    }
8680
8681    #[test]
8682    fn entrada_para_shape_fires_before_host_gate() {
8683        // Per-`:entrada` order pin: the `:para` shape gate fires
8684        // before the `:host` gate, mirroring the existing
8685        // `entrada_host_member_missing_takes_precedence_over_host_invalid`
8686        // ordering where the member-lookup arm preceded the host gate.
8687        // The shape gate slots ahead of that, so a malformed `:para`
8688        // surfaces its own diagnostic even when `:host` is also wrong.
8689        let mut s = three_member_spec();
8690        let e = s.entrada.as_mut().unwrap();
8691        e.para = "Cart".into();
8692        e.host = "BAD HOST".into();
8693        let err = s.validate().unwrap_err();
8694        assert!(
8695            matches!(
8696                err,
8697                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
8698            ),
8699            "got {err:?}"
8700        );
8701    }
8702
8703    #[test]
8704    fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
8705        // Strict-improvement pin: a well-shaped `:para` that simply
8706        // isn't in `:membros` (a phantom reference — author meant to
8707        // add the member but didn't, or renamed and missed an
8708        // update) still surfaces `EntradaMemberMissing`, unchanged.
8709        // The shape gate only intercepts inputs that could never
8710        // legitimately match a validated member.
8711        let mut s = three_member_spec();
8712        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
8713        let err = s.validate().unwrap_err();
8714        assert!(
8715            matches!(
8716                err,
8717                AplicacaoError::EntradaMemberMissing { ref para }
8718                    if para == "phantom-shim"
8719            ),
8720            "got {err:?}"
8721        );
8722    }
8723
8724    #[test]
8725    fn entrada_para_invalid_diagnostic_carries_offending_para() {
8726        // The diagnostic-shape pin: the error names the offending
8727        // `:para` value verbatim plus a non-empty parser-shaped
8728        // reason, so the author can grep their caixa.lisp for
8729        // `:para "<name>"` and fix it in one edit. Same diagnostic
8730        // shape as `MembroCaixaInvalid` (3f9d7a0),
8731        // `PlacementClusterInvalid` (6c8c00b), and
8732        // `ContratoCaixaInvalid` (8d5af6b).
8733        let mut s = three_member_spec();
8734        s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
8735        let err = s.validate().unwrap_err();
8736        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
8737            panic!("expected EntradaParaInvalid, got {err:?}");
8738        };
8739        assert_eq!(para, "BAD_NAME");
8740        assert!(
8741            !reason.is_empty(),
8742            "EntradaParaInvalid `reason` must carry a parser-shaped wording"
8743        );
8744    }
8745
8746    #[test]
8747    fn accepts_canonical_entrada_para_forms() {
8748        // Positive-control sweep covering the DNS-1123 label shapes a
8749        // caixa author is realistically going to write on `:entrada
8750        // :para`. Pin every leg so a future tightening that bans
8751        // (e.g.) digit-start identifiers surfaces here, mirroring
8752        // `accepts_canonical_membro_caixa_forms` and
8753        // `accepts_canonical_contrato_caixa_forms` on the peer name
8754        // axes.
8755        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
8756            let mut s = three_member_spec();
8757            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
8758            s.contratos = vec![contract_http(form, "catalog", "/x")];
8759            s.entrada = Some(Entrada {
8760                host: "checkout.quero.cloud".into(),
8761                para: form.into(),
8762                paths: vec!["/api".into()],
8763                port: 8080,
8764            });
8765            s.validate().unwrap_or_else(|e| {
8766                panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
8767            });
8768        }
8769    }
8770
8771    #[test]
8772    fn rejects_replicated_without_clusters() {
8773        let mut s = three_member_spec();
8774        s.placement.clusters = vec![];
8775        assert!(matches!(
8776            s.validate().unwrap_err(),
8777            AplicacaoError::PlacementWithoutClusters { .. }
8778        ));
8779    }
8780
8781    #[test]
8782    fn rejects_sharded_without_key() {
8783        let mut s = three_member_spec();
8784        s.placement.estrategia = PlacementStrategy::Sharded;
8785        s.placement.shard_key = None;
8786        s.placement.clusters = vec!["rio".into()];
8787        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
8788    }
8789
8790    #[test]
8791    fn sharded_with_key_validates() {
8792        let mut s = three_member_spec();
8793        s.placement.estrategia = PlacementStrategy::Sharded;
8794        s.placement.shard_key = Some("$tenantId".into());
8795        s.validate().unwrap();
8796    }
8797
8798    #[test]
8799    fn round_trip_via_json_preserves_shape() {
8800        let s = three_member_spec();
8801        let json = serde_json::to_string(&s.membros).unwrap();
8802        let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
8803        assert_eq!(back, s.membros);
8804
8805        let json = serde_json::to_string(&s.contratos).unwrap();
8806        let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
8807        assert_eq!(back, s.contratos);
8808
8809        let json = serde_json::to_string(&s.placement).unwrap();
8810        let back: Placement = serde_json::from_str(&json).unwrap();
8811        assert_eq!(back, s.placement);
8812
8813        let json = serde_json::to_string(&s.entrada).unwrap();
8814        let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
8815        assert_eq!(back, s.entrada);
8816    }
8817
8818    #[test]
8819    fn rate_limit_round_trip_seconds() {
8820        let policy = MeshPolicy {
8821            rate_limit: Some(RateLimit {
8822                rate: 100,
8823                window: Duration::from_secs(1),
8824            }),
8825            ..Default::default()
8826        };
8827        let json = serde_json::to_string(&policy).unwrap();
8828        assert!(json.contains("\"100/s\""));
8829        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
8830        assert_eq!(back.rate_limit.unwrap().rate, 100);
8831        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
8832    }
8833
8834    #[test]
8835    fn rate_limit_round_trip_minutes() {
8836        let policy = MeshPolicy {
8837            rate_limit: Some(RateLimit {
8838                rate: 5000,
8839                window: Duration::from_secs(60),
8840            }),
8841            ..Default::default()
8842        };
8843        let json = serde_json::to_string(&policy).unwrap();
8844        assert!(json.contains("\"5000/m\""));
8845    }
8846
8847    #[test]
8848    fn circuit_breaker_round_trip() {
8849        let policy = MeshPolicy {
8850            circuit_breaker: Some(CircuitBreaker {
8851                max_failures: 5,
8852                window: Duration::from_secs(60),
8853            }),
8854            ..Default::default()
8855        };
8856        let json = serde_json::to_string(&policy).unwrap();
8857        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
8858        assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
8859        assert_eq!(
8860            back.circuit_breaker.unwrap().window,
8861            Duration::from_secs(60)
8862        );
8863    }
8864
8865    #[test]
8866    fn rejects_http_contrato_without_endpoint() {
8867        let mut s = three_member_spec();
8868        s.contratos.push(WitContract {
8869            de: "cart".into(),
8870            para: "catalog".into(),
8871            wit: "wasi:http/proxy".into(),
8872            endpoint: None,
8873            subject: None,
8874            slot: None,
8875        });
8876        let err = s.validate().unwrap_err();
8877        assert!(matches!(
8878            err,
8879            AplicacaoError::ContratoMissingTarget {
8880                expected: WitTarget::HTTP_FIELD_NAME,
8881                ..
8882            }
8883        ));
8884    }
8885
8886    #[test]
8887    fn rejects_http_contrato_with_subject() {
8888        let mut s = three_member_spec();
8889        s.contratos.push(WitContract {
8890            de: "cart".into(),
8891            para: "catalog".into(),
8892            wit: "wasi:http/proxy".into(),
8893            endpoint: Some("/x".into()),
8894            subject: Some("not.allowed.here".into()),
8895            slot: None,
8896        });
8897        let err = s.validate().unwrap_err();
8898        assert!(matches!(
8899            err,
8900            AplicacaoError::ContratoWrongTarget {
8901                expected: WitTarget::HTTP_FIELD_NAME,
8902                ..
8903            }
8904        ));
8905    }
8906
8907    #[test]
8908    fn rejects_pubsub_contrato_without_subject() {
8909        let mut s = three_member_spec();
8910        s.contratos.push(WitContract {
8911            de: "cart".into(),
8912            para: "catalog".into(),
8913            wit: "nats:pub-sub".into(),
8914            endpoint: None,
8915            subject: None,
8916            slot: None,
8917        });
8918        let err = s.validate().unwrap_err();
8919        assert!(matches!(
8920            err,
8921            AplicacaoError::ContratoMissingTarget {
8922                expected: WitTarget::PUBSUB_FIELD_NAME,
8923                ..
8924            }
8925        ));
8926    }
8927
8928    #[test]
8929    fn rejects_pubsub_contrato_with_endpoint() {
8930        let mut s = three_member_spec();
8931        s.contratos.push(WitContract {
8932            de: "cart".into(),
8933            para: "catalog".into(),
8934            wit: "kafka:topic".into(),
8935            endpoint: Some("/wrong".into()),
8936            subject: Some("topic.x".into()),
8937            slot: None,
8938        });
8939        let err = s.validate().unwrap_err();
8940        assert!(matches!(
8941            err,
8942            AplicacaoError::ContratoWrongTarget {
8943                expected: WitTarget::PUBSUB_FIELD_NAME,
8944                ..
8945            }
8946        ));
8947    }
8948
8949    #[test]
8950    fn rejects_store_contrato_without_slot() {
8951        let mut s = three_member_spec();
8952        s.contratos.push(WitContract {
8953            de: "cart".into(),
8954            para: "catalog".into(),
8955            wit: "wasi:keyvalue/store".into(),
8956            endpoint: None,
8957            subject: None,
8958            slot: None,
8959        });
8960        let err = s.validate().unwrap_err();
8961        assert!(matches!(
8962            err,
8963            AplicacaoError::ContratoMissingTarget {
8964                expected: WitTarget::STORE_FIELD_NAME,
8965                ..
8966            }
8967        ));
8968    }
8969
8970    // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
8971
8972    #[test]
8973    fn rejects_http_contrato_with_empty_endpoint() {
8974        // `Some("")` for an HTTP endpoint passes the presence check
8975        // (target() previously returned WitTarget::Http { endpoint: "" })
8976        // but renders as a `path: ""` Cilium L7 rule that matches no
8977        // traffic. Same value-shape footgun closed for :entrada :paths
8978        // entries (eb3456d).
8979        let mut s = three_member_spec();
8980        s.contratos.push(WitContract {
8981            de: "cart".into(),
8982            para: "catalog".into(),
8983            wit: "wasi:http/proxy".into(),
8984            endpoint: Some(String::new()),
8985            subject: None,
8986            slot: None,
8987        });
8988        let err = s.validate().unwrap_err();
8989        assert!(
8990            matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
8991                if de == "cart" && para == "catalog"),
8992            "got {err:?}"
8993        );
8994    }
8995
8996    #[test]
8997    fn rejects_http_contrato_with_relative_endpoint() {
8998        // Cilium L7 :path + Gateway API PathPrefix both require a
8999        // leading `/`. Same shape required of :entrada :paths
9000        // (eb3456d). Lifted into target() so every consumer of the
9001        // typed WitTarget view inherits the guarantee.
9002        let mut s = three_member_spec();
9003        s.contratos.push(WitContract {
9004            de: "cart".into(),
9005            para: "catalog".into(),
9006            wit: "wasi:http/proxy".into(),
9007            endpoint: Some("products/:id".into()),
9008            subject: None,
9009            slot: None,
9010        });
9011        let err = s.validate().unwrap_err();
9012        assert!(
9013            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
9014                if endpoint == "products/:id"),
9015            "got {err:?}"
9016        );
9017    }
9018
9019    #[test]
9020    fn rejects_pubsub_contrato_with_empty_subject() {
9021        // NATS / Kafka publish without a subject is a no-op subscribe;
9022        // never the author's intent. Same empty-string rejection as
9023        // :membros :caixa, :placement :clusters entries, :entrada
9024        // :paths entries — every value carried by every typed slot is
9025        // value-shape-checked at validate().
9026        let mut s = three_member_spec();
9027        s.contratos.push(WitContract {
9028            de: "cart".into(),
9029            para: "catalog".into(),
9030            wit: "nats:pub-sub".into(),
9031            endpoint: None,
9032            subject: Some(String::new()),
9033            slot: None,
9034        });
9035        let err = s.validate().unwrap_err();
9036        assert!(
9037            matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
9038                if de == "cart" && para == "catalog"),
9039            "got {err:?}"
9040        );
9041    }
9042
9043    #[test]
9044    fn rejects_store_contrato_with_empty_slot() {
9045        // An empty slot template addresses the bucket root, defeating
9046        // the per-key isolation the slot exists for — a footgun on
9047        // `wasi:keyvalue/store` whose closest analog is the empty
9048        // shard-key rejected on :placement Sharded (c7c7799).
9049        let mut s = three_member_spec();
9050        s.contratos.push(WitContract {
9051            de: "cart".into(),
9052            para: "catalog".into(),
9053            wit: "wasi:keyvalue/store".into(),
9054            endpoint: None,
9055            subject: None,
9056            slot: Some(String::new()),
9057        });
9058        let err = s.validate().unwrap_err();
9059        assert!(
9060            matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
9061                if de == "cart" && para == "catalog"),
9062            "got {err:?}"
9063        );
9064    }
9065
9066    #[test]
9067    fn http_contrato_root_endpoint_validates() {
9068        // Pin the boundary case: a single-`/` endpoint is the catch-all
9069        // form the Gateway HTTPRoute renderer falls back to when
9070        // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
9071        // must remain a valid contrato endpoint too.
9072        let mut s = three_member_spec();
9073        s.contratos.push(contract_http("cart", "catalog", "/"));
9074        s.validate().unwrap();
9075    }
9076
9077    // ── :contratos :endpoint value-shape gate ────────────────────────────
9078    //
9079    // Mirrors the `:entrada :paths` value-shape suite on the peer
9080    // HTTP-path axis. Until this gate landed `WitContract::target()`
9081    // only refused the empty string + the missing-leading-`/` form
9082    // (c4213a4); a structurally invalid endpoint passed validate and
9083    // landed verbatim as a Cilium L7 `path:` rule
9084    // (caixa-mesh/src/lib.rs:311) that either silently dropped all
9085    // traffic or was rejected at apply time by Cilium policy admission.
9086    // Every authoring footgun the K8s Gateway API webhook / Cilium
9087    // policy validator would catch on admission now becomes a caixa-
9088    // build-time `ContratoEndpointInvalid` with the offending
9089    // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
9090    // shape as `EntradaPathInvalid` on the sibling axis; same shared
9091    // predicate (`crate::render::is_gateway_api_http_path`) ensures
9092    // drift between the two axes' rule enforcement is a build error
9093    // at the predicate.
9094
9095    fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
9096        // Fresh spec per call so the would-be-duplicate edge
9097        // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
9098        // `three_member_spec`'s pre-existing
9099        // `(cart, catalog, …, /products/:id)` entry — only the
9100        // endpoint payload differs.
9101        let mut s = three_member_spec();
9102        s.contratos.push(contract_http("cart", "catalog", ep));
9103        s.validate().unwrap_err()
9104    }
9105
9106    #[test]
9107    fn rejects_http_contrato_endpoint_with_query() {
9108        // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
9109        // silently rendered as a Cilium L7 `path: "/charge?token=X"`
9110        // rule the L7 matcher would never satisfy.
9111        let err = contrato_endpoint_err("/charge?token=X");
9112        assert!(
9113            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9114                if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
9115            "got {err:?}"
9116        );
9117    }
9118
9119    #[test]
9120    fn rejects_http_contrato_endpoint_with_fragment() {
9121        let err = contrato_endpoint_err("/charge#frag");
9122        assert!(
9123            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9124                if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
9125            "got {err:?}"
9126        );
9127    }
9128
9129    #[test]
9130    fn rejects_http_contrato_endpoint_with_whitespace() {
9131        let err = contrato_endpoint_err("/foo bar");
9132        assert!(
9133            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9134                if endpoint == "/foo bar" && reason.contains("whitespace")),
9135            "got {err:?}"
9136        );
9137    }
9138
9139    #[test]
9140    fn rejects_http_contrato_endpoint_with_control_char() {
9141        let err = contrato_endpoint_err("/api/\x01bar");
9142        assert!(
9143            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9144                if endpoint == "/api/\x01bar" && reason.contains("control character")),
9145            "got {err:?}"
9146        );
9147    }
9148
9149    #[test]
9150    fn rejects_http_contrato_endpoint_with_non_ascii() {
9151        let err = contrato_endpoint_err("/api/café");
9152        assert!(
9153            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9154                if endpoint == "/api/café" && reason.contains("non-ASCII")),
9155            "got {err:?}"
9156        );
9157    }
9158
9159    #[test]
9160    fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
9161        let err = contrato_endpoint_err("/api//cart");
9162        assert!(
9163            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9164                if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
9165            "got {err:?}"
9166        );
9167    }
9168
9169    #[test]
9170    fn rejects_http_contrato_endpoint_with_dot_segment() {
9171        let err = contrato_endpoint_err("/api/./cart");
9172        assert!(
9173            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9174                if endpoint == "/api/./cart" && reason.contains("`.` segment")),
9175            "got {err:?}"
9176        );
9177    }
9178
9179    #[test]
9180    fn rejects_http_contrato_endpoint_with_parent_segment() {
9181        // Path-traversal in a contrato endpoint is the canonical
9182        // "L7 rule that the workload's HTTP server's path-resolution
9183        // logic interprets differently than the policy enforcer"
9184        // footgun. Rejected outright at validate time.
9185        let err = contrato_endpoint_err("/api/../etc");
9186        assert!(
9187            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9188                if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
9189            "got {err:?}"
9190        );
9191    }
9192
9193    #[test]
9194    fn rejects_http_contrato_endpoint_too_long() {
9195        // 1025-byte endpoint — one over the Gateway API
9196        // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
9197        // path matcher has no inherent length limit but the policy
9198        // CR itself rides through the K8s apiserver, which enforces
9199        // ConfigMap-shaped limits; sharing the Gateway API cap is the
9200        // conservative floor.
9201        let big = format!("/api/{}", "a".repeat(1020));
9202        assert_eq!(big.len(), 1025);
9203        let err = contrato_endpoint_err(&big);
9204        assert!(
9205            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9206                if endpoint == &big && reason.contains("max length of 1024")),
9207            "got {err:?}"
9208        );
9209    }
9210
9211    #[test]
9212    fn http_contrato_endpoint_max_length_validates() {
9213        // 1024-byte endpoint — exactly the cap. Boundary pin: drift
9214        // in the cap surfaces here and at
9215        // `rejects_http_contrato_endpoint_too_long` simultaneously,
9216        // mirroring `entrada_path_max_length_validates` on the peer
9217        // axis.
9218        let big = format!("/api/{}", "a".repeat(1019));
9219        assert_eq!(big.len(), 1024);
9220        let mut s = three_member_spec();
9221        s.contratos.push(contract_http("cart", "catalog", &big));
9222        s.validate().unwrap();
9223    }
9224
9225    #[test]
9226    fn http_contrato_endpoint_accepts_canonical_forms() {
9227        // Positive-set sweep: every canonical HTTP-path shape the
9228        // sibling `:entrada :paths` axis accepts (the bare-root `/`,
9229        // plain paths, hidden-file-style `.config` segments distinct
9230        // from the `.` segment, digit-bearing segments, the canonical
9231        // route-template `:param` form, trailing-slash form,
9232        // percent-encoded segments, the `/foo..bar` interior-`..`-
9233        // substring forms that are NOT `..` segments) must remain a
9234        // valid contrato endpoint too. Drift between this list and
9235        // the entrada path positive sweep surfaces at the shared
9236        // `is_gateway_api_http_path` substrate-side suite — one
9237        // source of truth. Uses a fresh `(payment, catalog)` edge so
9238        // none of the swept endpoints collide with the pre-existing
9239        // `(cart, catalog, /products/:id)` / `(cart, payment,
9240        // /charge)` entries in `three_member_spec`.
9241        for ep in [
9242            "/",
9243            "/charge",
9244            "/v1/charge",
9245            "/api/.config",
9246            "/products/:id",
9247            "/api/cart/",
9248            "/api/caf%C3%A9",
9249            "/foo..bar",
9250            "/...",
9251        ] {
9252            let mut s = three_member_spec();
9253            s.contratos.push(contract_http("payment", "catalog", ep));
9254            s.validate()
9255                .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
9256        }
9257    }
9258
9259    #[test]
9260    fn contrato_endpoint_empty_takes_precedence_over_invalid() {
9261        // Ordering pin: `ContratoEndpointEmpty` is the more self-
9262        // locating diagnostic on `""` and must lead — the value-
9263        // shape gate is only reached after the empty-check fires.
9264        // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
9265        // on the peer axis.
9266        let mut s = three_member_spec();
9267        s.contratos.push(WitContract {
9268            de: "cart".into(),
9269            para: "catalog".into(),
9270            wit: "wasi:http/proxy".into(),
9271            endpoint: Some(String::new()),
9272            subject: None,
9273            slot: None,
9274        });
9275        let err = s.validate().unwrap_err();
9276        assert!(
9277            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
9278            "got {err:?}"
9279        );
9280    }
9281
9282    #[test]
9283    fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
9284        // Ordering pin: an endpoint without a leading `/` surfaces the
9285        // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
9286        // value-shape gate is only consulted on endpoints that already
9287        // satisfy the absolute-prefix invariant. Mirrors
9288        // `entrada_path_not_absolute_takes_precedence_over_invalid`.
9289        let err = contrato_endpoint_err("bad path");
9290        assert!(
9291            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
9292                if endpoint == "bad path"),
9293            "got {err:?}"
9294        );
9295    }
9296
9297    #[test]
9298    fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
9299        // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
9300        // `:para` + a non-empty reason flow through verbatim so the
9301        // author can grep their caixa.lisp for the offending contrato
9302        // block and fix it in one edit. Same shape as
9303        // `entrada_path_diagnostic_carries_offending_path`.
9304        let err = contrato_endpoint_err("/api?q=1");
9305        match err {
9306            AplicacaoError::ContratoEndpointInvalid {
9307                de,
9308                para,
9309                endpoint,
9310                reason,
9311            } => {
9312                assert_eq!(de, "cart");
9313                assert_eq!(para, "catalog");
9314                assert_eq!(endpoint, "/api?q=1");
9315                assert!(!reason.is_empty(), "reason field must be non-empty");
9316            }
9317            other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
9318        }
9319    }
9320
9321    #[test]
9322    fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
9323        // The compounding theorem: every &str inside a WitTarget
9324        // returned by target() is non-empty (and absolute, for Http).
9325        // Renderers downstream of typed_view() can rely on this
9326        // without re-checking — the type system carries the proof.
9327        let http = contract_http("cart", "catalog", "/x");
9328        match http.target().unwrap() {
9329            WitTarget::Http { endpoint } => {
9330                assert!(!endpoint.is_empty());
9331                assert!(endpoint.starts_with('/'));
9332            }
9333            other => panic!("expected Http, got {other:?}"),
9334        }
9335        let nats = WitContract {
9336            de: "a".into(),
9337            para: "b".into(),
9338            wit: "nats:pub-sub".into(),
9339            endpoint: None,
9340            subject: Some("topic.x".into()),
9341            slot: None,
9342        };
9343        match nats.target().unwrap() {
9344            WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
9345            other => panic!("expected PubSub, got {other:?}"),
9346        }
9347        let kv = WitContract {
9348            de: "a".into(),
9349            para: "b".into(),
9350            wit: "wasi:keyvalue/store".into(),
9351            endpoint: None,
9352            subject: None,
9353            slot: Some("checkout/$orderId".into()),
9354        };
9355        match kv.target().unwrap() {
9356            WitTarget::Store { slot } => assert!(!slot.is_empty()),
9357            other => panic!("expected Store, got {other:?}"),
9358        }
9359    }
9360
9361    #[test]
9362    fn target_diagnostic_names_offending_endpoint_value() {
9363        // When the malformed endpoint string is non-trivial, the
9364        // diagnostic carries the actual value back to the author —
9365        // not a generic "endpoint malformed" error.
9366        let bad = WitContract {
9367            de: "src".into(),
9368            para: "dst".into(),
9369            wit: "wasi:http/proxy".into(),
9370            endpoint: Some("api/v1/charge".into()),
9371            subject: None,
9372            slot: None,
9373        };
9374        match bad.target().unwrap_err() {
9375            AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
9376                assert_eq!(de, "src");
9377                assert_eq!(para, "dst");
9378                assert_eq!(endpoint, "api/v1/charge");
9379            }
9380            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
9381        }
9382    }
9383
9384    #[test]
9385    fn rejects_unknown_wit_with_target_set() {
9386        let mut s = three_member_spec();
9387        s.contratos.push(WitContract {
9388            de: "cart".into(),
9389            para: "catalog".into(),
9390            wit: "custom:exchange".into(),
9391            endpoint: Some("/leaked".into()),
9392            subject: None,
9393            slot: None,
9394        });
9395        let err = s.validate().unwrap_err();
9396        assert!(matches!(
9397            err,
9398            AplicacaoError::ContratoWrongTarget {
9399                expected: WitTarget::CAPABILITY_EXPECTED,
9400                ..
9401            }
9402        ));
9403    }
9404
9405    #[test]
9406    fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
9407        // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
9408        // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
9409        // fourth arm of the same "which payload field name goes in the
9410        // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
9411        // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
9412        // consts cover on the peer HTTP / PubSub / Store arms
9413        // (`wit_target_field_name_pins_per_variant`). Until this lift
9414        // landed the byte-string sat twice — once inline in the
9415        // [`WitContract::target`] Capability-arm rejection at the
9416        // production dispatch, once in `rejects_unknown_wit_with_target_set`
9417        // pinning against the same literal — with no compile-time link
9418        // between them. Same "one canonical declaration, next to the
9419        // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
9420        // lift established for the payload-less arm's human-readable
9421        // label axis; this test is the shape peer of
9422        // `wit_target_label_pins_per_variant`'s Capability-arm assertion
9423        // pair (routes-through-const + scalar-value pin) on the
9424        // wrong-target diagnostic-scalar axis.
9425        //
9426        // Fail-before-pass-after was verified locally by mutating the
9427        // const declaration to `"capability"` — the scalar-value pin
9428        // below fires (`"capability" != "none"`) and the routes-through
9429        // assertion below still holds (production and const walk in
9430        // lockstep), which is the correct behavior: a rename on the
9431        // const drifts here first, not at a downstream consumer.
9432        assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
9433
9434        let mut s = three_member_spec();
9435        s.contratos.push(WitContract {
9436            de: "cart".into(),
9437            para: "catalog".into(),
9438            wit: "custom:exchange".into(),
9439            endpoint: Some("/leaked".into()),
9440            subject: None,
9441            slot: None,
9442        });
9443        match s.validate().unwrap_err() {
9444            AplicacaoError::ContratoWrongTarget { expected, .. } => {
9445                assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
9446            }
9447            other => panic!("expected ContratoWrongTarget, got {other:?}"),
9448        }
9449    }
9450
9451    #[test]
9452    fn unknown_wit_capability_only_validates() {
9453        let mut s = three_member_spec();
9454        s.contratos.push(WitContract {
9455            de: "cart".into(),
9456            para: "catalog".into(),
9457            // A WIT world we haven't yet shaped — accept it as a typed
9458            // capability edge so authors aren't blocked while the WIT
9459            // registry catches up. No payload field may be carried.
9460            wit: "custom:exchange".into(),
9461            endpoint: None,
9462            subject: None,
9463            slot: None,
9464        });
9465        s.validate().unwrap();
9466        let added = s.contratos.last().unwrap();
9467        assert_eq!(added.target().unwrap(), WitTarget::Capability);
9468    }
9469
9470    #[test]
9471    fn target_typed_view_round_trips_each_shape() {
9472        let http = contract_http("cart", "catalog", "/products/:id");
9473        assert_eq!(
9474            http.target().unwrap(),
9475            WitTarget::Http {
9476                endpoint: "/products/:id"
9477            }
9478        );
9479        let nats = WitContract {
9480            de: "a".into(),
9481            para: "b".into(),
9482            wit: "nats:pub-sub".into(),
9483            endpoint: None,
9484            subject: Some("topic.x".into()),
9485            slot: None,
9486        };
9487        assert_eq!(
9488            nats.target().unwrap(),
9489            WitTarget::PubSub { subject: "topic.x" }
9490        );
9491        let kv = WitContract {
9492            de: "a".into(),
9493            para: "b".into(),
9494            wit: "wasi:keyvalue/store".into(),
9495            endpoint: None,
9496            subject: None,
9497            slot: Some("checkout/$orderId".into()),
9498        };
9499        assert_eq!(
9500            kv.target().unwrap(),
9501            WitTarget::Store {
9502                slot: "checkout/$orderId"
9503            }
9504        );
9505    }
9506
9507    #[test]
9508    fn wit_contract_kind_predicates() {
9509        let http = contract_http("a", "b", "/x");
9510        assert!(http.is_http());
9511        assert!(!http.is_pubsub());
9512        assert!(!http.is_store());
9513
9514        let nats = WitContract {
9515            de: "a".into(),
9516            para: "b".into(),
9517            wit: "nats:pub-sub".into(),
9518            endpoint: None,
9519            subject: Some("topic.x".into()),
9520            slot: None,
9521        };
9522        assert!(nats.is_pubsub());
9523        assert!(!nats.is_http());
9524
9525        let kv = WitContract {
9526            de: "a".into(),
9527            para: "b".into(),
9528            wit: "wasi:keyvalue/store".into(),
9529            endpoint: None,
9530            subject: None,
9531            slot: Some("checkout/$orderId".into()),
9532        };
9533        assert!(kv.is_store());
9534        assert!(!kv.is_http());
9535    }
9536
9537    // ── :contratos :wit value-shape gate ─────────────────────────────────
9538    //
9539    // Mirrors the `:contratos :endpoint` value-shape suite on the peer
9540    // dispatch-discriminator axis. Until this gate landed
9541    // `WitContract::target()` accepted any non-empty string and
9542    // silently demoted unrecognized shapes to a capability-only L4
9543    // edge — the canonical "I thought I had L7 HTTP routing, got
9544    // L4-only" footgun. Every authoring footgun the WIT registry's
9545    // own grammar rejects (uppercase, hyphen-for-colon typo,
9546    // whitespace, empty package, doubled `@`, …) now becomes a
9547    // caixa-build-time `ContratoWitInvalid` with the offending
9548    // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
9549    // as `ContratoEndpointInvalid` on the sibling axis; same shared
9550    // predicate (`crate::render::is_wit_world_ref`) ensures drift
9551    // between any two axes' rule enforcement is a build error at the
9552    // predicate, not piecemeal across renderers.
9553
9554    fn contrato_wit_err(wit: &str) -> AplicacaoError {
9555        // Fresh spec per call so the new contract doesn't collide on
9556        // identity with `three_member_spec`'s pre-existing entries.
9557        // The new edge uses `(payment, catalog)` — a pair the fixture
9558        // doesn't already declare — with no payload field set, so the
9559        // wit-shape gate fires before any payload-shape arm.
9560        let mut s = three_member_spec();
9561        s.contratos.push(WitContract {
9562            de: "payment".into(),
9563            para: "catalog".into(),
9564            wit: wit.into(),
9565            endpoint: None,
9566            subject: None,
9567            slot: None,
9568        });
9569        s.validate().unwrap_err()
9570    }
9571
9572    #[test]
9573    fn rejects_wit_with_uppercase_namespace() {
9574        // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
9575        // didn't match the lowercase `wasi:http/` prefix is_http() keys
9576        // off, so the dispatch fell through to the capability arm and
9577        // the contract silently rendered as an L4-only Cilium edge.
9578        // The new gate surfaces the uppercase typo at validate time
9579        // with the offending `:wit` named.
9580        let err = contrato_wit_err("WASI:http/proxy");
9581        assert!(
9582            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9583                if wit == "WASI:http/proxy" && reason.contains("lowercase")),
9584            "got {err:?}"
9585        );
9586    }
9587
9588    #[test]
9589    fn rejects_wit_with_hyphen_for_colon_typo() {
9590        // The canonical "I forgot the `:` separator" typo — pre-gate
9591        // this passed as Capability silently, so the renderer emitted
9592        // an L4-only policy where the author expected L7 HTTP rules.
9593        let err = contrato_wit_err("wasi-http/proxy");
9594        assert!(
9595            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9596                if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
9597            "got {err:?}"
9598        );
9599    }
9600
9601    #[test]
9602    fn rejects_wit_with_multiple_colons() {
9603        // Doubled `:` — the namespace/package split has nowhere to
9604        // anchor, so the dispatch silently demotes to Capability.
9605        let err = contrato_wit_err("wasi:http:proxy");
9606        assert!(
9607            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9608                if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
9609            "got {err:?}"
9610        );
9611    }
9612
9613    #[test]
9614    fn rejects_wit_with_empty_package() {
9615        // `wasi:` — namespace alone with no package. Pre-gate this
9616        // failed neither the is_http nor is_pubsub nor is_store
9617        // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
9618        // a bare `wasi:`), so it silently demoted to Capability.
9619        let err = contrato_wit_err("wasi:");
9620        assert!(
9621            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9622                if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
9623            "got {err:?}"
9624        );
9625    }
9626
9627    #[test]
9628    fn rejects_wit_with_underscore() {
9629        // Underscore — WIT identifiers are kebab-case, same rule
9630        // DNS-1123 enforces on its peer axes. The diagnostic carries
9631        // the explicit "use `-` instead" remediation.
9632        let err = contrato_wit_err("wasi:http_proxy");
9633        assert!(
9634            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9635                if wit == "wasi:http_proxy" && reason.contains('_')),
9636            "got {err:?}"
9637        );
9638    }
9639
9640    #[test]
9641    fn rejects_wit_with_whitespace() {
9642        // Whitespace mid-token — the prefix check matches but the
9643        // package-and-onward parse silently demoted to Capability.
9644        let err = contrato_wit_err("wasi:http proxy");
9645        assert!(
9646            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9647                if wit == "wasi:http proxy" && reason.contains("whitespace")),
9648            "got {err:?}"
9649        );
9650    }
9651
9652    #[test]
9653    fn rejects_wit_with_non_ascii() {
9654        // Un-percent-encoded non-ASCII byte — the canonical "I copied
9655        // the package name from a doc with smart quotes / accented
9656        // characters" footgun.
9657        let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
9658        assert!(
9659            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9660                if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
9661            "got {err:?}"
9662        );
9663    }
9664
9665    #[test]
9666    fn rejects_wit_with_consecutive_hyphens() {
9667        // `pub--sub` — WIT identifiers join words with single hyphens.
9668        let err = contrato_wit_err("nats:pub--sub");
9669        assert!(
9670            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9671                if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
9672            "got {err:?}"
9673        );
9674    }
9675
9676    #[test]
9677    fn rejects_wit_with_trailing_at_no_version() {
9678        // `wasi:http/proxy@` — the version-suffix author started to
9679        // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
9680        // parser would reject this; surface it at validate time.
9681        let err = contrato_wit_err("wasi:http/proxy@");
9682        assert!(
9683            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9684                if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
9685            "got {err:?}"
9686        );
9687    }
9688
9689    #[test]
9690    fn rejects_wit_too_long() {
9691        // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
9692        // The legitimate-shape arms all pass (lowercase, single `:`,
9693        // kebab-case identifiers); only the cap arm fires. Surfaces
9694        // the paste-from-binary / accidental-multi-line-blob landing
9695        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
9696        // on the peer axis.
9697        let big = format!("wasi:{}", "a".repeat(124));
9698        assert_eq!(big.len(), 129);
9699        let err = contrato_wit_err(&big);
9700        assert!(
9701            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9702                if wit == &big && reason.contains("max length of 128")),
9703            "got {err:?}"
9704        );
9705    }
9706
9707    #[test]
9708    fn wit_max_length_validates() {
9709        // 128-byte WIT reference — exactly the cap. Boundary pin:
9710        // drift in the cap surfaces here and at `rejects_wit_too_long`
9711        // simultaneously, mirroring
9712        // `http_contrato_endpoint_max_length_validates` on the peer
9713        // axis.
9714        let big = format!("wasi:{}", "a".repeat(123));
9715        assert_eq!(big.len(), 128);
9716        let mut s = three_member_spec();
9717        s.contratos.push(WitContract {
9718            de: "payment".into(),
9719            para: "catalog".into(),
9720            wit: big,
9721            endpoint: None,
9722            subject: None,
9723            slot: None,
9724        });
9725        s.validate().unwrap();
9726    }
9727
9728    #[test]
9729    fn wit_accepts_canonical_forms_at_aplicacao_layer() {
9730        // Positive-set sweep through the AplicacaoSpec::validate
9731        // surface (rather than the substrate-side predicate directly)
9732        // — pins every shape the existing test fixtures + the
9733        // checkout-aplicacao example carry, so the gate's accept-set
9734        // matches the substrate's emit-set. Drift between this list
9735        // and `render::tests::wit_world_ref_accepts_canonical_forms`
9736        // surfaces at the substrate layer's positive sweep — one
9737        // source of truth for the rule.
9738        for wit in [
9739            "wasi:http/proxy",
9740            "wasi:keyvalue/store",
9741            "nats:pub-sub",
9742            "kafka:topic",
9743            "custom:exchange",
9744            "pleme:cap/audit",
9745            "wasi:http/proxy@0.2.0",
9746        ] {
9747            // Payload field paired to the dispatched WIT shape so the
9748            // shape-↔-target arm doesn't fire instead of the wit-shape
9749            // arm we're exercising. Routes off the same
9750            // `wit_shape_is_http` / `wit_shape_is_pubsub` /
9751            // `wit_shape_is_store` free functions the production
9752            // `WitContract::is_http` / `is_pubsub` / `is_store`
9753            // methods delegate to (both consult the lifted
9754            // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
9755            // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
9756            // future prefix addition to the routing accept-set
9757            // reaches this test's payload-dispatch arm by
9758            // construction — no per-test-site drift can hide a
9759            // shape-→-target-slot mismatch that would silently
9760            // demote a canonical `:wit` value to the
9761            // `(None, None, None)` capability-only arm and let the
9762            // `AplicacaoSpec::validate` positive sweep pass on a
9763            // shape it should exercise as HTTP / pub-sub / store.
9764            let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
9765                (Some("/x".into()), None, None)
9766            } else if wit_shape_is_pubsub(wit) {
9767                (None, Some("topic.x".into()), None)
9768            } else if wit_shape_is_store(wit) {
9769                (None, None, Some("bucket/$key".into()))
9770            } else {
9771                (None, None, None)
9772            };
9773            let mut s = three_member_spec();
9774            s.contratos.push(WitContract {
9775                de: "payment".into(),
9776                para: "catalog".into(),
9777                wit: wit.into(),
9778                endpoint,
9779                subject,
9780                slot,
9781            });
9782            s.validate()
9783                .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
9784        }
9785    }
9786
9787    #[test]
9788    fn wit_shape_predicates_accept_canonical_prefix_set() {
9789        // Positive-set sweep pinning every prefix in
9790        // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
9791        // WIT_STORE_SHAPE_PREFIXES against the three free-function
9792        // dispatch predicates. The six prefixes are the load-bearing
9793        // routing keys the substrate's WIT-shape dispatch consults
9794        // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
9795        // key/value-store-slot admission); any drift between the
9796        // free-function accept-set and this list surfaces here
9797        // rather than at apply time as a silent
9798        // shape-→-capability-only demotion.
9799        assert!(wit_shape_is_http("wasi:http/proxy"));
9800        assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
9801        assert!(wit_shape_is_http("http:incoming"));
9802
9803        assert!(wit_shape_is_pubsub("nats:pub-sub"));
9804        assert!(wit_shape_is_pubsub("kafka:topic"));
9805
9806        assert!(wit_shape_is_store("wasi:keyvalue/store"));
9807        assert!(wit_shape_is_store("kv:cache/session"));
9808    }
9809
9810    #[test]
9811    fn wit_shape_predicates_reject_uncanonical_forms() {
9812        // Negative-set pin: the six canonical prefixes are
9813        // lowercase-only (mirrors the `is_wit_world_ref` substrate
9814        // predicate's lowercase invariant — see its docstring on the
9815        // "I thought I had L7 HTTP routing, got L4-only" footgun).
9816        // The empty string, an uppercase-prefixed form, a hyphen-
9817        // instead-of-colon typo, and a bare kebab identifier all miss
9818        // every shape arm — reachable-by-construction only via the
9819        // `is_wit_world_ref` gate that admission-checks the `:wit`
9820        // value first, but pinned here so any future
9821        // free-function change (e.g. a case-insensitive
9822        // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
9823        // this unit level.
9824        for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
9825            assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
9826            assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
9827            assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
9828        }
9829    }
9830
9831    #[test]
9832    fn wit_shape_predicates_partition_canonical_set() {
9833        // Every canonical prefix routes to exactly one shape arm —
9834        // the three prefix sets are pairwise disjoint. Pins the
9835        // routing property [`WitContract::target`] relies on: an
9836        // `is_http()` return of `true` guarantees `is_pubsub()` and
9837        // `is_store()` return `false`, so the shape-→-target-slot
9838        // dispatch (endpoint vs subject vs slot) is unambiguous.
9839        // Drift (e.g. a future `"kv:"` moved into the HTTP set
9840        // without removal from the store set) would silently route
9841        // one prefix to two arms and the first-matching-arm order
9842        // becomes load-bearing — this pin surfaces it as a build
9843        // error instead.
9844        for prefix in WIT_HTTP_SHAPE_PREFIXES {
9845            let sample = format!("{prefix}x");
9846            assert!(wit_shape_is_http(&sample));
9847            assert!(!wit_shape_is_pubsub(&sample));
9848            assert!(!wit_shape_is_store(&sample));
9849        }
9850        for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
9851            let sample = format!("{prefix}x");
9852            assert!(!wit_shape_is_http(&sample));
9853            assert!(wit_shape_is_pubsub(&sample));
9854            assert!(!wit_shape_is_store(&sample));
9855        }
9856        for prefix in WIT_STORE_SHAPE_PREFIXES {
9857            let sample = format!("{prefix}x");
9858            assert!(!wit_shape_is_http(&sample));
9859            assert!(!wit_shape_is_pubsub(&sample));
9860            assert!(wit_shape_is_store(&sample));
9861        }
9862    }
9863
9864    #[test]
9865    fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
9866        // Positive pin: [`wit_shape_matches`] is exactly the
9867        // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
9868        // parameterized on the accept-set. Two-prefix accept-set,
9869        // one-prefix accept-set, and empty accept-set (which must
9870        // reject everything, including the empty string — an empty
9871        // `any()` fold returns `false`) all pinned so a future
9872        // reimplementation that swaps `starts_with` for `contains`,
9873        // `==`, or a case-folded comparator surfaces at unit-test
9874        // time.
9875        let two = &["wasi:http/", "http:"];
9876        assert!(wit_shape_matches("wasi:http/proxy", two));
9877        assert!(wit_shape_matches("http:incoming", two));
9878        assert!(!wit_shape_matches("wasi:keyvalue/store", two));
9879
9880        let one = &["nats:"];
9881        assert!(wit_shape_matches("nats:pub-sub", one));
9882        assert!(!wit_shape_matches("kafka:topic", one));
9883
9884        // Empty accept-set matches nothing — the identity element
9885        // for the disjunctive `any()` fold across the prefix set.
9886        // Reachable via a future `wit_shape_is_<name>` const paired
9887        // to a still-empty prefix table on a nascent shape-arm draft.
9888        let empty: &[&str] = &[];
9889        assert!(!wit_shape_matches("wasi:http/proxy", empty));
9890        assert!(!wit_shape_matches("", empty));
9891
9892        // starts_with, not contains: a prefix embedded mid-string
9893        // never matches. Pins the routing invariant [`WitContract::target`]
9894        // relies on (an authored `:wit "custom:wasi:http/"` string
9895        // does not silently route through the HTTP arm just because
9896        // it happens to contain the canonical HTTP prefix).
9897        assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
9898    }
9899
9900    #[test]
9901    fn wit_shape_predicates_delegate_to_wit_shape_matches() {
9902        // Equivalence pin: each per-shape predicate is exactly
9903        // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
9904        // every canonical prefix + the empty string + one negative
9905        // sample against every peer so a future predicate that grew
9906        // its own inline `iter().any(starts_with)` (rather than
9907        // delegating through the lifted combinator) drifts loudly here
9908        // — the peer-const table's contents must agree with the
9909        // predicate's accept-set by construction.
9910        let samples = [
9911            String::new(),
9912            "wasi:http/proxy".to_string(),
9913            "http:incoming".to_string(),
9914            "nats:pub-sub".to_string(),
9915            "kafka:topic".to_string(),
9916            "wasi:keyvalue/store".to_string(),
9917            "kv:cache/session".to_string(),
9918            "custom-shape".to_string(),
9919            "WASI:HTTP/proxy".to_string(),
9920        ];
9921        for wit in &samples {
9922            assert_eq!(
9923                wit_shape_is_http(wit),
9924                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
9925                "wit_shape_is_http drifted from combinator on {wit:?}",
9926            );
9927            assert_eq!(
9928                wit_shape_is_pubsub(wit),
9929                wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
9930                "wit_shape_is_pubsub drifted from combinator on {wit:?}",
9931            );
9932            assert_eq!(
9933                wit_shape_is_store(wit),
9934                wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
9935                "wit_shape_is_store drifted from combinator on {wit:?}",
9936            );
9937        }
9938    }
9939
9940    #[test]
9941    fn wit_contract_shape_methods_delegate_to_free_functions() {
9942        // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
9943        // `is_store` are `&self` conveniences on top of the free
9944        // functions — for every canonical prefix the method's return
9945        // matches its free-function peer. Sweeps the union of the
9946        // three prefix sets so a future method that grew its own
9947        // inline prefix logic (rather than delegating) drifts loudly
9948        // here on the first prefix the free function accepts and the
9949        // method doesn't.
9950        for shape_set in [
9951            WIT_HTTP_SHAPE_PREFIXES,
9952            WIT_PUBSUB_SHAPE_PREFIXES,
9953            WIT_STORE_SHAPE_PREFIXES,
9954        ] {
9955            for prefix in shape_set {
9956                let c = WitContract {
9957                    de: "cart".into(),
9958                    para: "catalog".into(),
9959                    wit: format!("{prefix}x"),
9960                    endpoint: None,
9961                    subject: None,
9962                    slot: None,
9963                };
9964                assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
9965                assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
9966                assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
9967            }
9968        }
9969    }
9970
9971    #[test]
9972    fn empty_wit_takes_precedence_over_invalid() {
9973        // Ordering pin: `EmptyWit` is the more self-locating
9974        // diagnostic on `""` and must lead — the value-shape gate is
9975        // only reached after the empty-check fires. Mirrors
9976        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
9977        // the peer payload axis.
9978        let mut s = three_member_spec();
9979        s.contratos.push(WitContract {
9980            de: "payment".into(),
9981            para: "catalog".into(),
9982            wit: String::new(),
9983            endpoint: None,
9984            subject: None,
9985            slot: None,
9986        });
9987        let err = s.validate().unwrap_err();
9988        assert!(
9989            matches!(err, AplicacaoError::EmptyWit { .. }),
9990            "got {err:?}"
9991        );
9992    }
9993
9994    #[test]
9995    fn wit_invalid_fires_before_payload_shape_arm() {
9996        // Ordering pin: a malformed `:wit` surfaces *its own*
9997        // diagnostic (which names the offending wit verbatim) before
9998        // any payload-field check — a contrato whose wit is
9999        // structurally invalid AND carries a wrong target field
10000        // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
10001        // because the dispatch on the wit is what decides which
10002        // payload field is "right" in the first place. Without this
10003        // ordering, the author would see "wrong target field" for a
10004        // wit that hasn't even been parsed, which doesn't name the
10005        // root cause.
10006        let mut s = three_member_spec();
10007        s.contratos.push(WitContract {
10008            de: "payment".into(),
10009            para: "catalog".into(),
10010            // Hyphen-for-colon typo + endpoint set: pre-gate this
10011            // raised `ContratoWrongTarget { expected: "none" }` (the
10012            // Capability arm rejecting the endpoint), masking the
10013            // real authoring mistake (the wit isn't `wasi:http/proxy`).
10014            wit: "wasi-http/proxy".into(),
10015            endpoint: Some("/x".into()),
10016            subject: None,
10017            slot: None,
10018        });
10019        let err = s.validate().unwrap_err();
10020        assert!(
10021            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
10022                if wit == "wasi-http/proxy"),
10023            "got {err:?}"
10024        );
10025    }
10026
10027    #[test]
10028    fn wit_invalid_diagnostic_carries_offending_wit() {
10029        // Diagnostic-shape pin — the offending `:wit` + `:de` +
10030        // `:para` + a non-empty reason flow through verbatim so the
10031        // author can grep their caixa.lisp for the offending contrato
10032        // block and fix it in one edit. Same shape as
10033        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
10034        let err = contrato_wit_err("WASI:HTTP/proxy");
10035        match err {
10036            AplicacaoError::ContratoWitInvalid {
10037                de,
10038                para,
10039                wit,
10040                reason,
10041            } => {
10042                assert_eq!(de, "payment");
10043                assert_eq!(para, "catalog");
10044                assert_eq!(wit, "WASI:HTTP/proxy");
10045                assert!(!reason.is_empty(), "reason field must be non-empty");
10046            }
10047            other => panic!("expected ContratoWitInvalid, got {other:?}"),
10048        }
10049    }
10050
10051    // ── :contratos :subject value-shape gate ─────────────────────────────
10052    //
10053    // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
10054    // suites on the peer payload axes. Until this gate landed
10055    // `WitContract::target()` only refused the empty string; a
10056    // structurally invalid subject silently passed validate and the
10057    // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
10058    // Subject'` on publish / subscribe, or as a silent message drop,
10059    // far from the source caixa.lisp. Every authoring footgun the
10060    // NATS server's subject parser would catch on admission now
10061    // becomes a caixa-build-time `ContratoSubjectInvalid` with the
10062    // offending `:subject` + `:de` + `:para` named verbatim. Same
10063    // diagnostic shape as `ContratoEndpointInvalid` /
10064    // `ContratoWitInvalid` on the peer payload axes; same shared
10065    // predicate (`crate::render::is_nats_subject`) ensures drift
10066    // between any two axes' rule enforcement is a build error at the
10067    // predicate, not piecemeal across renderers.
10068
10069    fn contrato_subject_err(subject: &str) -> AplicacaoError {
10070        // Fresh spec per call so the new contract doesn't collide on
10071        // identity with `three_member_spec`'s pre-existing entries.
10072        // The new edge uses `(payment, catalog)` — a pair the fixture
10073        // doesn't already declare — with `:wit "nats:pub-sub"` and the
10074        // varying `:subject`, so the subject-shape gate fires cleanly
10075        // after the wit-shape gate (which `"nats:pub-sub"` passes).
10076        let mut s = three_member_spec();
10077        s.contratos.push(WitContract {
10078            de: "payment".into(),
10079            para: "catalog".into(),
10080            wit: "nats:pub-sub".into(),
10081            endpoint: None,
10082            subject: Some(subject.into()),
10083            slot: None,
10084        });
10085        s.validate().unwrap_err()
10086    }
10087
10088    #[test]
10089    fn rejects_pubsub_contrato_subject_with_whitespace() {
10090        // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
10091        // landed at the NATS server as a malformed subject the parser
10092        // rejects with `-ERR 'Invalid Subject'`. Now caught at the
10093        // source caixa.lisp.
10094        let err = contrato_subject_err("foo bar");
10095        assert!(
10096            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10097                if subject == "foo bar" && reason.contains("whitespace")),
10098            "got {err:?}"
10099        );
10100    }
10101
10102    #[test]
10103    fn rejects_pubsub_contrato_subject_with_control_char() {
10104        let err = contrato_subject_err("foo\x01bar");
10105        assert!(
10106            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10107                if subject == "foo\x01bar" && reason.contains("control character")),
10108            "got {err:?}"
10109        );
10110    }
10111
10112    #[test]
10113    fn rejects_pubsub_contrato_subject_with_non_ascii() {
10114        // Un-percent-encoded non-ASCII byte — the canonical "I copied
10115        // the subject from a doc with smart quotes / accented
10116        // characters" footgun.
10117        let err = contrato_subject_err("foo.caf\u{e9}");
10118        assert!(
10119            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10120                if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
10121            "got {err:?}"
10122        );
10123    }
10124
10125    #[test]
10126    fn rejects_pubsub_contrato_subject_with_leading_dot() {
10127        // Empty leading token — NATS rejects.
10128        let err = contrato_subject_err(".foo");
10129        assert!(
10130            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10131                if subject == ".foo" && reason.contains("must not start with `.`")),
10132            "got {err:?}"
10133        );
10134    }
10135
10136    #[test]
10137    fn rejects_pubsub_contrato_subject_with_trailing_dot() {
10138        // Empty trailing token — NATS rejects. The remediation
10139        // (use `>` instead) is in the reason string.
10140        let err = contrato_subject_err("foo.");
10141        assert!(
10142            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10143                if subject == "foo." && reason.contains("must not end with `.`")),
10144            "got {err:?}"
10145        );
10146    }
10147
10148    #[test]
10149    fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
10150        // The canonical "I forgot to fill in the middle segment"
10151        // typo — `"foo..bar"`. NATS rejects empty tokens.
10152        let err = contrato_subject_err("foo..bar");
10153        assert!(
10154            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10155                if subject == "foo..bar" && reason.contains("consecutive `.`")),
10156            "got {err:?}"
10157        );
10158    }
10159
10160    #[test]
10161    fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
10162        // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
10163        // as the final segment. Pre-gate this passed as a typed edge
10164        // and surfaced at runtime as a NATS subscribe rejection.
10165        let err = contrato_subject_err("foo.>.bar");
10166        assert!(
10167            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10168                if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
10169            "got {err:?}"
10170        );
10171    }
10172
10173    #[test]
10174    fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
10175        // `foo*.bar` — NATS wildcards are standalone tokens. The
10176        // remediation is in the reason string.
10177        let err = contrato_subject_err("foo*.bar");
10178        assert!(
10179            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10180                if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
10181            "got {err:?}"
10182        );
10183    }
10184
10185    #[test]
10186    fn rejects_pubsub_contrato_subject_with_invalid_char() {
10187        // `foo,bar` — comma is not a valid NATS subject character.
10188        // Pinned separately from the wildcard arms so the invalid-
10189        // character diagnostic is in force.
10190        let err = contrato_subject_err("foo,bar");
10191        assert!(
10192            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10193                if subject == "foo,bar" && reason.contains("invalid character")),
10194            "got {err:?}"
10195        );
10196    }
10197
10198    #[test]
10199    fn rejects_pubsub_contrato_subject_too_long() {
10200        // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
10201        // The legitimate-shape arms all pass (one all-`a` token, no
10202        // `.`, no wildcards); only the cap arm fires. Surfaces the
10203        // paste-from-binary / accidental-multi-line-blob landing
10204        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
10205        // on the peer axis.
10206        let big = "a".repeat(257);
10207        assert_eq!(big.len(), 257);
10208        let err = contrato_subject_err(&big);
10209        assert!(
10210            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10211                if subject == &big && reason.contains("max length of 256")),
10212            "got {err:?}"
10213        );
10214    }
10215
10216    #[test]
10217    fn pubsub_contrato_subject_max_length_validates() {
10218        // 256-byte subject — exactly the cap. Boundary pin: drift in
10219        // the cap surfaces here and at
10220        // `rejects_pubsub_contrato_subject_too_long` simultaneously,
10221        // mirroring `http_contrato_endpoint_max_length_validates` and
10222        // `wit_max_length_validates` on the peer axes.
10223        let big = "a".repeat(256);
10224        assert_eq!(big.len(), 256);
10225        let mut s = three_member_spec();
10226        s.contratos.push(WitContract {
10227            de: "payment".into(),
10228            para: "catalog".into(),
10229            wit: "nats:pub-sub".into(),
10230            endpoint: None,
10231            subject: Some(big),
10232            slot: None,
10233        });
10234        s.validate().unwrap();
10235    }
10236
10237    #[test]
10238    fn pubsub_contrato_subject_accepts_canonical_forms() {
10239        // Positive-set sweep: every canonical NATS subject shape the
10240        // substrate-side `is_nats_subject` predicate accepts (the
10241        // multi-dot `events.order.charged`, the snake_case / kebab-
10242        // case / mixed-case tokens, the digit-bearing tokens, the
10243        // single-token wildcard `*` at every segment position, and
10244        // the trailing `>` multi-token wildcard) must remain a valid
10245        // contrato subject too. Drift between this list and the
10246        // substrate-side `nats_subject_accepts_canonical_forms` sweep
10247        // surfaces at the shared predicate — one source of truth.
10248        // Uses a fresh `(payment, catalog)` edge so none of the swept
10249        // subjects collide with the pre-existing entries in
10250        // `three_member_spec`.
10251        for subject in [
10252            "checkout.events.charge.failed",
10253            "rio.events.order.charged",
10254            "orders",
10255            "orders.123",
10256            "snake_case.token",
10257            "kebab-case.token",
10258            "MixedCase.Token",
10259            "orders.*.charged",
10260            "*.events.*",
10261            "orders.>",
10262        ] {
10263            let mut s = three_member_spec();
10264            s.contratos.push(WitContract {
10265                de: "payment".into(),
10266                para: "catalog".into(),
10267                wit: "nats:pub-sub".into(),
10268                endpoint: None,
10269                subject: Some(subject.into()),
10270                slot: None,
10271            });
10272            s.validate()
10273                .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
10274        }
10275    }
10276
10277    #[test]
10278    fn contrato_subject_empty_takes_precedence_over_invalid() {
10279        // Ordering pin: `ContratoSubjectEmpty` is the more self-
10280        // locating diagnostic on `""` and must lead — the value-shape
10281        // gate is only reached after the empty-check fires. Mirrors
10282        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
10283        // the peer payload axis.
10284        let mut s = three_member_spec();
10285        s.contratos.push(WitContract {
10286            de: "payment".into(),
10287            para: "catalog".into(),
10288            wit: "nats:pub-sub".into(),
10289            endpoint: None,
10290            subject: Some(String::new()),
10291            slot: None,
10292        });
10293        let err = s.validate().unwrap_err();
10294        assert!(
10295            matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
10296            "got {err:?}"
10297        );
10298    }
10299
10300    #[test]
10301    fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
10302        // Diagnostic-shape pin — the offending `:subject` + `:de` +
10303        // `:para` + a non-empty reason flow through verbatim so the
10304        // author can grep their caixa.lisp for the offending contrato
10305        // block and fix it in one edit. Same shape as
10306        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
10307        // and `wit_invalid_diagnostic_carries_offending_wit`.
10308        let err = contrato_subject_err("foo..bar");
10309        match err {
10310            AplicacaoError::ContratoSubjectInvalid {
10311                de,
10312                para,
10313                subject,
10314                reason,
10315            } => {
10316                assert_eq!(de, "payment");
10317                assert_eq!(para, "catalog");
10318                assert_eq!(subject, "foo..bar");
10319                assert!(!reason.is_empty(), "reason field must be non-empty");
10320            }
10321            other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
10322        }
10323    }
10324
10325    #[test]
10326    fn target_view_pubsub_subject_passes_through_to_typed_view() {
10327        // The compounding theorem on the pub-sub axis: every
10328        // `WitTarget::PubSub { subject }` returned by `target()` carries
10329        // a NATS-server-accepted subject. Renderers downstream of
10330        // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
10331        // NATS Stream/Consumer CR emitter, the future `feira app graph`
10332        // view's subject labeller) can rely on this without re-checking
10333        // — the type system carries the proof. Mirrors
10334        // `target_view_payload_is_guaranteed_nonempty_after_target_call`
10335        // on the peer axes.
10336        let nats = WitContract {
10337            de: "a".into(),
10338            para: "b".into(),
10339            wit: "nats:pub-sub".into(),
10340            endpoint: None,
10341            subject: Some("orders.events.*.charged".into()),
10342            slot: None,
10343        };
10344        match nats.target().unwrap() {
10345            WitTarget::PubSub { subject } => {
10346                assert_eq!(subject, "orders.events.*.charged");
10347            }
10348            other => panic!("expected PubSub, got {other:?}"),
10349        }
10350    }
10351
10352    // ── :contratos :slot value-shape gate ────────────────────────────────
10353    //
10354    // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
10355    // (63e18a0) value-shape suites on the peer payload axes. Until this
10356    // gate landed `WitContract::target()` only refused the empty string
10357    // for the Store arm; a structurally invalid slot (raw whitespace,
10358    // control character, non-ASCII byte, paste-from-binary multi-line
10359    // blob) silently passed validate and surfaced at runtime as a
10360    // per-backend kv write rejection or a silent next-read corruption,
10361    // far from the source caixa.lisp with no field naming which
10362    // `:contratos` edge carried the typo. Every authoring footgun the
10363    // kv backend intersection-floor would catch on write now becomes a
10364    // caixa-build-time `ContratoSlotInvalid` with the offending
10365    // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
10366    // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
10367    // peer payload axes; same shared predicate
10368    // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
10369    // any two axes' rule enforcement is a build error at the
10370    // predicate, not piecemeal across renderers. Closes the typed
10371    // payload-axis value-shape trajectory across all three legs of the
10372    // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
10373
10374    fn contrato_slot_err(slot: &str) -> AplicacaoError {
10375        // Fresh spec per call so the new contract doesn't collide on
10376        // identity with `three_member_spec`'s pre-existing entries
10377        // and doesn't close a synchronous cycle the cycle detector
10378        // would reject before the slot-shape gate fires. The new edge
10379        // uses `(payment, catalog)` — a pair the fixture doesn't
10380        // already declare in either direction (the fixture carries
10381        // `cart -> catalog` and `cart -> payment`, so `payment ->
10382        // catalog` doesn't form a cycle on the sync subgraph) — with
10383        // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
10384        // slot-shape gate fires cleanly after the wit-shape gate
10385        // (which `"wasi:keyvalue/store"` passes). Same edge pair the
10386        // peer `contrato_subject_err` helper uses (63e18a0).
10387        let mut s = three_member_spec();
10388        s.contratos.push(WitContract {
10389            de: "payment".into(),
10390            para: "catalog".into(),
10391            wit: "wasi:keyvalue/store".into(),
10392            endpoint: None,
10393            subject: None,
10394            slot: Some(slot.into()),
10395        });
10396        s.validate().unwrap_err()
10397    }
10398
10399    #[test]
10400    fn rejects_store_contrato_slot_with_whitespace() {
10401        // Fail-before-pass-after pin — pre-gate `"check out/$order"`
10402        // silently landed at the kv backend with whitespace whose
10403        // runtime behavior varies unpredictably across backends (etcd
10404        // accepts, Redis accepts then breaks on next CLI op, DynamoDB
10405        // rejects on write). Now caught at the source caixa.lisp.
10406        let err = contrato_slot_err("check out/$order");
10407        assert!(
10408            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10409                if slot == "check out/$order" && reason.contains("whitespace")),
10410            "got {err:?}"
10411        );
10412    }
10413
10414    #[test]
10415    fn rejects_store_contrato_slot_with_tab() {
10416        // Tab byte arm-pinned separately from the space arm so a
10417        // future relaxation that admits one but not the other surfaces
10418        // here.
10419        let err = contrato_slot_err("check\tout");
10420        assert!(
10421            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10422                if slot == "check\tout" && reason.contains("whitespace")),
10423            "got {err:?}"
10424        );
10425    }
10426
10427    #[test]
10428    fn rejects_store_contrato_slot_with_control_char() {
10429        // SOH (0x01) — distinct from the whitespace arm. Redis admits
10430        // and corrupts on RESP protocol framing; DynamoDB rejects on
10431        // write.
10432        let err = contrato_slot_err("checkout/\x01order");
10433        assert!(
10434            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10435                if slot == "checkout/\x01order" && reason.contains("control character")),
10436            "got {err:?}"
10437        );
10438    }
10439
10440    #[test]
10441    fn rejects_store_contrato_slot_with_newline() {
10442        // Embedded newline — the canonical "the paste-from-binary slug
10443        // spans multiple lines" footgun. Distinct from the whitespace
10444        // arm because `\n` is a control character (0x0A).
10445        let err = contrato_slot_err("checkout\norder");
10446        assert!(
10447            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10448                if slot == "checkout\norder" && reason.contains("control character")),
10449            "got {err:?}"
10450        );
10451    }
10452
10453    #[test]
10454    fn rejects_store_contrato_slot_with_non_ascii() {
10455        // Un-percent-encoded non-ASCII byte — the canonical "I copied
10456        // the slot from a doc with accented characters" footgun. Each
10457        // kv backend re-encodes non-ASCII differently (etcd preserves
10458        // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
10459        // rejects), so the typed slot's value set is the intersection-
10460        // floor every backend admits identically (printable ASCII).
10461        let err = contrato_slot_err("ch\u{e9}ckout/$order");
10462        assert!(
10463            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10464                if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
10465            "got {err:?}"
10466        );
10467    }
10468
10469    #[test]
10470    fn rejects_store_contrato_slot_too_long() {
10471        // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
10472        // legitimate-shape arms all pass (a single all-`a` token, no
10473        // separators); only the cap arm fires. Surfaces the paste-
10474        // from-binary / accidental-multi-line-blob landing footgun.
10475        // Mirrors `rejects_pubsub_contrato_subject_too_long` and
10476        // `rejects_http_contrato_endpoint_too_long` on the peer
10477        // payload axes.
10478        let big = "a".repeat(513);
10479        assert_eq!(big.len(), 513);
10480        let err = contrato_slot_err(&big);
10481        assert!(
10482            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10483                if slot == &big && reason.contains("max length of 512")),
10484            "got {err:?}"
10485        );
10486    }
10487
10488    #[test]
10489    fn store_contrato_slot_max_length_validates() {
10490        // 512-byte slot — exactly the cap. Boundary pin: drift in the
10491        // cap surfaces here and at `rejects_store_contrato_slot_too_long`
10492        // simultaneously, mirroring
10493        // `pubsub_contrato_subject_max_length_validates` and
10494        // `http_contrato_endpoint_max_length_validates` on the peer
10495        // payload axes.
10496        let big = "a".repeat(512);
10497        assert_eq!(big.len(), 512);
10498        let mut s = three_member_spec();
10499        s.contratos.push(WitContract {
10500            de: "payment".into(),
10501            para: "catalog".into(),
10502            wit: "wasi:keyvalue/store".into(),
10503            endpoint: None,
10504            subject: None,
10505            slot: Some(big),
10506        });
10507        s.validate().unwrap();
10508    }
10509
10510    #[test]
10511    fn store_contrato_slot_accepts_canonical_forms() {
10512        // Positive-set sweep: every canonical kv slot template the
10513        // substrate-side `is_wasi_keyvalue_slot` predicate accepts
10514        // (single-token identifiers, path-namespaced `$`-templates,
10515        // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
10516        // snake_case / kebab-case / MixedCase tokens, digit-bearing
10517        // tokens, percent-encoded fragments) must remain valid
10518        // contrato slots too. Drift between this list and the
10519        // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
10520        // surfaces at the shared predicate — one source of truth.
10521        // Uses a fresh `(payment, catalog)` edge so none of the swept
10522        // slots collide with the pre-existing entries in
10523        // `three_member_spec`.
10524        for slot in [
10525            "checkout",
10526            "checkout/$orderId",
10527            "users:{tenant}/{id}",
10528            "session.<sid>",
10529            "session.tokens.<sid>",
10530            "snake_case_key",
10531            "kebab-case-key",
10532            "MixedCase",
10533            "shard0",
10534            "v2/key",
10535            "users/caf%C3%A9",
10536        ] {
10537            let mut s = three_member_spec();
10538            s.contratos.push(WitContract {
10539                de: "payment".into(),
10540                para: "catalog".into(),
10541                wit: "wasi:keyvalue/store".into(),
10542                endpoint: None,
10543                subject: None,
10544                slot: Some(slot.into()),
10545            });
10546            s.validate()
10547                .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
10548        }
10549    }
10550
10551    #[test]
10552    fn contrato_slot_empty_takes_precedence_over_invalid() {
10553        // Ordering pin: `ContratoSlotEmpty` is the more self-locating
10554        // diagnostic on `""` and must lead — the value-shape gate is
10555        // only reached after the empty-check fires. Mirrors
10556        // `contrato_subject_empty_takes_precedence_over_invalid` and
10557        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
10558        // the peer payload axes.
10559        let mut s = three_member_spec();
10560        s.contratos.push(WitContract {
10561            de: "payment".into(),
10562            para: "catalog".into(),
10563            wit: "wasi:keyvalue/store".into(),
10564            endpoint: None,
10565            subject: None,
10566            slot: Some(String::new()),
10567        });
10568        let err = s.validate().unwrap_err();
10569        assert!(
10570            matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
10571            "got {err:?}"
10572        );
10573    }
10574
10575    #[test]
10576    fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
10577        // Diagnostic-shape pin — the offending `:slot` + `:de` +
10578        // `:para` + a non-empty reason flow through verbatim so the
10579        // author can grep their caixa.lisp for the offending contrato
10580        // block and fix it in one edit. Same shape as
10581        // `contrato_subject_invalid_diagnostic_carries_offending_subject`
10582        // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
10583        // on the peer payload axes.
10584        let err = contrato_slot_err("check out/$order");
10585        match err {
10586            AplicacaoError::ContratoSlotInvalid {
10587                de,
10588                para,
10589                slot,
10590                reason,
10591            } => {
10592                assert_eq!(de, "payment");
10593                assert_eq!(para, "catalog");
10594                assert_eq!(slot, "check out/$order");
10595                assert!(!reason.is_empty(), "reason field must be non-empty");
10596            }
10597            other => panic!("expected ContratoSlotInvalid, got {other:?}"),
10598        }
10599    }
10600
10601    #[test]
10602    fn target_view_store_slot_passes_through_to_typed_view() {
10603        // The compounding theorem on the store axis: every
10604        // `WitTarget::Store { slot }` returned by `target()` carries a
10605        // kv-backend-accepted slot template. Renderers downstream of
10606        // `typed_view()` (the future per-Servico `:capabilities
10607        // wasi:keyvalue/store` axis emitter, the future `feira app
10608        // graph` view's slot labeller, the future kv-provider CR
10609        // materializer) can rely on this without re-checking — the
10610        // type system carries the proof. Mirrors
10611        // `target_view_pubsub_subject_passes_through_to_typed_view` on
10612        // the peer payload axis.
10613        let store = WitContract {
10614            de: "a".into(),
10615            para: "b".into(),
10616            wit: "wasi:keyvalue/store".into(),
10617            endpoint: None,
10618            subject: None,
10619            slot: Some("checkout/$orderId".into()),
10620        };
10621        match store.target().unwrap() {
10622            WitTarget::Store { slot } => {
10623                assert_eq!(slot, "checkout/$orderId");
10624            }
10625            other => panic!("expected Store, got {other:?}"),
10626        }
10627    }
10628
10629    #[test]
10630    fn rejects_self_loop_in_synchronous_contratos() {
10631        // A synchronous self-edge (`cart → cart` over HTTP) is now
10632        // rejected by the dedicated `ContratoSelfLoop` gate — a precise
10633        // "this edge is degenerate" diagnostic — rather than incidentally
10634        // by the cycle detector framing it as a `["cart", "cart"]`
10635        // multi-node deadlock.
10636        let mut s = three_member_spec();
10637        s.contratos.push(contract_http("cart", "cart", "/loop"));
10638        let err = s.validate().unwrap_err();
10639        match err {
10640            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
10641                assert_eq!(caixa, "cart");
10642                assert_eq!(wit, "wasi:http/proxy");
10643            }
10644            other => panic!("expected ContratoSelfLoop, got {other:?}"),
10645        }
10646    }
10647
10648    #[test]
10649    fn rejects_self_loop_in_pubsub_contratos() {
10650        // The cycle detector excludes pub-sub edges (acyclic by
10651        // construction), so before the explicit gate a `nats:pub-sub`
10652        // self-edge silently validated and rendered a self-allow CNP.
10653        // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
10654        let mut s = three_member_spec();
10655        s.contratos.push(WitContract {
10656            de: "payment".into(),
10657            para: "payment".into(),
10658            wit: "nats:pub-sub".into(),
10659            endpoint: None,
10660            subject: Some("rio.events.payment".into()),
10661            slot: None,
10662        });
10663        let err = s.validate().unwrap_err();
10664        match err {
10665            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
10666                assert_eq!(caixa, "payment");
10667                assert_eq!(wit, "nats:pub-sub");
10668            }
10669            other => panic!("expected ContratoSelfLoop, got {other:?}"),
10670        }
10671    }
10672
10673    #[test]
10674    fn self_loop_fires_before_payload_shape_check() {
10675        // The structural "this edge can't exist" error precedes the
10676        // narrower payload-shape diagnostics: a self-edge carrying an
10677        // otherwise-malformed endpoint still reports ContratoSelfLoop,
10678        // not ContratoEndpointInvalid.
10679        let mut s = three_member_spec();
10680        s.contratos.push(WitContract {
10681            de: "cart".into(),
10682            para: "cart".into(),
10683            wit: "wasi:http/proxy".into(),
10684            endpoint: Some("not-absolute".into()),
10685            subject: None,
10686            slot: None,
10687        });
10688        match s.validate().unwrap_err() {
10689            AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
10690            other => panic!("expected ContratoSelfLoop, got {other:?}"),
10691        }
10692    }
10693
10694    #[test]
10695    fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
10696        // A self-edge naming a non-member reports the more fundamental
10697        // ContratoMemberMissing first (the member doesn't exist), so the
10698        // self-loop gate is reached only once both endpoints resolve.
10699        let mut s = three_member_spec();
10700        s.contratos.push(contract_http("ghost", "ghost", "/loop"));
10701        match s.validate().unwrap_err() {
10702            AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
10703            other => panic!("expected ContratoMemberMissing, got {other:?}"),
10704        }
10705    }
10706
10707    #[test]
10708    fn rejects_two_node_synchronous_cycle() {
10709        let mut s = three_member_spec();
10710        // existing edges: cart → catalog, cart → payment
10711        // adding catalog → cart closes a 2-cycle on the HTTP subgraph
10712        s.contratos
10713            .push(contract_http("catalog", "cart", "/refresh"));
10714        let err = s.validate().unwrap_err();
10715        match err {
10716            AplicacaoError::ContratoCycle { cycle } => {
10717                // Cycle traversal should mention both endpoints, with
10718                // the back-edge target appearing as both first and last
10719                // element to close the loop.
10720                assert!(cycle.len() >= 3);
10721                assert_eq!(cycle.first(), cycle.last());
10722                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
10723                assert!(body.contains("cart"));
10724                assert!(body.contains("catalog"));
10725            }
10726            other => panic!("expected ContratoCycle, got {other:?}"),
10727        }
10728    }
10729
10730    #[test]
10731    fn rejects_three_node_synchronous_cycle() {
10732        let mut s = three_member_spec();
10733        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
10734        s.contratos = vec![
10735            contract_http("catalog", "cart", "/x"),
10736            contract_http("cart", "payment", "/y"),
10737            contract_http("payment", "catalog", "/z"),
10738        ];
10739        let err = s.validate().unwrap_err();
10740        match err {
10741            AplicacaoError::ContratoCycle { cycle } => {
10742                assert_eq!(cycle.first(), cycle.last());
10743                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
10744                assert_eq!(body.len(), 3);
10745                assert!(body.contains("cart"));
10746                assert!(body.contains("catalog"));
10747                assert!(body.contains("payment"));
10748            }
10749            other => panic!("expected ContratoCycle, got {other:?}"),
10750        }
10751    }
10752
10753    #[test]
10754    fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
10755        // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
10756        // "acyclic by construction" — so a cycle whose closing edge
10757        // is pub-sub should NOT raise ContratoCycle.
10758        let mut s = three_member_spec();
10759        s.contratos = vec![
10760            contract_http("catalog", "cart", "/x"),
10761            contract_http("cart", "payment", "/y"),
10762            // Closing edge is pub-sub — async; not a sync deadlock.
10763            WitContract {
10764                de: "payment".into(),
10765                para: "catalog".into(),
10766                wit: "nats:pub-sub".into(),
10767                endpoint: None,
10768                subject: Some("checkout.events.charge.completed".into()),
10769                slot: None,
10770            },
10771        ];
10772        s.validate().expect("pub-sub edge breaks the sync cycle");
10773    }
10774
10775    #[test]
10776    fn store_edge_counts_as_synchronous_for_cycle_detection() {
10777        // wasi:keyvalue/store is request/response; a cycle through one
10778        // *is* a sync deadlock, just like HTTP.
10779        let mut s = three_member_spec();
10780        s.contratos = vec![
10781            contract_http("catalog", "cart", "/x"),
10782            WitContract {
10783                de: "cart".into(),
10784                para: "catalog".into(),
10785                wit: "wasi:keyvalue/store".into(),
10786                endpoint: None,
10787                subject: None,
10788                slot: Some("session/$id".into()),
10789            },
10790        ];
10791        let err = s.validate().unwrap_err();
10792        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
10793    }
10794
10795    #[test]
10796    fn capability_edge_counts_as_synchronous_for_cycle_detection() {
10797        // Capability-only edges (unknown WIT shape, no payload) default
10798        // to synchronous — safer; authors with truly async capability
10799        // semantics can model them as pub-sub explicitly.
10800        let mut s = three_member_spec();
10801        s.contratos = vec![
10802            contract_http("catalog", "cart", "/x"),
10803            WitContract {
10804                de: "cart".into(),
10805                para: "catalog".into(),
10806                wit: "custom:exchange".into(),
10807                endpoint: None,
10808                subject: None,
10809                slot: None,
10810            },
10811        ];
10812        let err = s.validate().unwrap_err();
10813        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
10814    }
10815
10816    #[test]
10817    fn long_acyclic_chain_validates() {
10818        // A long sync chain (no back-edges) must validate even when
10819        // every node is reachable from the first.
10820        let mut s = three_member_spec();
10821        s.membros = vec![
10822            membro("a", "^0.1"),
10823            membro("b", "^0.1"),
10824            membro("c", "^0.1"),
10825            membro("d", "^0.1"),
10826            membro("e", "^0.1"),
10827        ];
10828        s.contratos = vec![
10829            contract_http("a", "b", "/1"),
10830            contract_http("b", "c", "/2"),
10831            contract_http("c", "d", "/3"),
10832            contract_http("d", "e", "/4"),
10833        ];
10834        s.entrada.as_mut().unwrap().para = "a".into();
10835        s.validate().unwrap();
10836    }
10837
10838    #[test]
10839    fn diamond_acyclic_validates() {
10840        // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
10841        let mut s = three_member_spec();
10842        s.membros = vec![
10843            membro("a", "^0.1"),
10844            membro("b", "^0.1"),
10845            membro("c", "^0.1"),
10846            membro("d", "^0.1"),
10847        ];
10848        s.contratos = vec![
10849            contract_http("a", "b", "/1"),
10850            contract_http("a", "c", "/2"),
10851            contract_http("b", "d", "/3"),
10852            contract_http("c", "d", "/4"),
10853        ];
10854        s.entrada.as_mut().unwrap().para = "a".into();
10855        s.validate().unwrap();
10856    }
10857
10858    // ── duplicate-`:contratos` build-error gate ──────────────────────────
10859
10860    #[test]
10861    fn rejects_duplicate_http_contrato() {
10862        // Fail-before-pass-after pin: the fixture's `cart → catalog`
10863        // HTTP edge appears once. Push an identical entry — same
10864        // (de, para, wit, endpoint) — and validate() must reject it.
10865        // Until this gate landed the typed surface accepted the
10866        // duplicate silently and caixa-mesh's `cilium_network_policies`
10867        // emitted two ``CiliumNetworkPolicy`` objects with identical
10868        // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
10869        // admission rejects on `kubectl apply` far from the source.
10870        let mut s = three_member_spec();
10871        s.contratos
10872            .push(contract_http("cart", "catalog", "/products/:id"));
10873        let err = s.validate().unwrap_err();
10874        assert!(
10875            matches!(
10876                err,
10877                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
10878                    if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
10879            ),
10880            "got {err:?}"
10881        );
10882    }
10883
10884    #[test]
10885    fn rejects_duplicate_pubsub_contrato() {
10886        // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
10887        // edges with identical (de, para, subject) are degenerate;
10888        // pin that the typed surface refuses both at validate time.
10889        let mut s = three_member_spec();
10890        let pubsub = WitContract {
10891            de: "payment".into(),
10892            para: "cart".into(),
10893            wit: "nats:pub-sub".into(),
10894            endpoint: None,
10895            subject: Some("checkout.events.charge.failed".into()),
10896            slot: None,
10897        };
10898        s.contratos.push(pubsub.clone());
10899        s.contratos.push(pubsub);
10900        let err = s.validate().unwrap_err();
10901        assert!(
10902            matches!(
10903                err,
10904                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
10905                    if de == "payment" && para == "cart" && wit == "nats:pub-sub"
10906            ),
10907            "got {err:?}"
10908        );
10909    }
10910
10911    #[test]
10912    fn rejects_duplicate_store_contrato() {
10913        // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
10914        // edges with identical (de, para, slot) collapse to one mesh-
10915        // policy edge; pin the build error.
10916        let mut s = three_member_spec();
10917        let store = WitContract {
10918            de: "cart".into(),
10919            para: "payment".into(),
10920            wit: "wasi:keyvalue/store".into(),
10921            endpoint: None,
10922            subject: None,
10923            slot: Some("checkout/$orderId".into()),
10924        };
10925        // Drop the conflicting HTTP `cart → payment` edge from the
10926        // fixture so the duplicate-store pair is the only one
10927        // distinguishable on this pair.
10928        s.contratos
10929            .retain(|c| !(c.de == "cart" && c.para == "payment"));
10930        s.contratos.push(store.clone());
10931        s.contratos.push(store);
10932        let err = s.validate().unwrap_err();
10933        assert!(
10934            matches!(
10935                err,
10936                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
10937                    if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
10938            ),
10939            "got {err:?}"
10940        );
10941    }
10942
10943    #[test]
10944    fn rejects_duplicate_capability_contrato() {
10945        // Same gate on the pure-capability axis (no payload selector).
10946        // Two contracts with identical (de, para, wit) and no
10947        // endpoint/subject/slot are duplicate edges; pin so a future
10948        // `target_label` change can't accidentally collapse the
10949        // capability arm into a None-shaped key that compares equal
10950        // to a populated one.
10951        let mut s = three_member_spec();
10952        let capability = WitContract {
10953            de: "cart".into(),
10954            para: "catalog".into(),
10955            wit: "pleme:cap/audit".into(),
10956            endpoint: None,
10957            subject: None,
10958            slot: None,
10959        };
10960        s.contratos.push(capability.clone());
10961        s.contratos.push(capability);
10962        let err = s.validate().unwrap_err();
10963        match err {
10964            AplicacaoError::ContratoDuplicate {
10965                de,
10966                para,
10967                wit,
10968                target,
10969            } => {
10970                assert_eq!(de, "cart");
10971                assert_eq!(para, "catalog");
10972                assert_eq!(wit, "pleme:cap/audit");
10973                assert!(
10974                    target.contains("capability"),
10975                    "capability-edge duplicate diagnostic must surface the \
10976                     no-payload shape (got target = {target:?})"
10977                );
10978            }
10979            other => panic!("expected ContratoDuplicate, got {other:?}"),
10980        }
10981    }
10982
10983    #[test]
10984    fn accepts_distinct_http_paths_between_same_pair() {
10985        // Negative pin: two HTTP contracts cart → catalog at distinct
10986        // endpoints (`/products/:id` and `/search`) are *not*
10987        // duplicates — they're distinct typed edges differing on the
10988        // payload axis. The duplicate-gate must not over-match here,
10989        // since the cart-calls-catalog-on-multiple-paths shape is the
10990        // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
10991        // example: cart calls catalog at /products/:id, payment at
10992        // /charge — same shape extends to two paths on one para).
10993        let mut s = three_member_spec();
10994        s.contratos
10995            .push(contract_http("cart", "catalog", "/search"));
10996        s.validate()
10997            .expect("distinct endpoints between same (de, para) must validate");
10998    }
10999
11000    #[test]
11001    fn accepts_same_endpoint_on_different_pairs() {
11002        // Negative pin: the same `/charge` endpoint reused on two
11003        // different (de, para) pairs is two distinct edges, not a
11004        // duplicate. Pinning this shape so the gate's identity key
11005        // includes both `de` and `para` (not just `(wit, endpoint)`).
11006        let mut s = three_member_spec();
11007        s.contratos
11008            .push(contract_http("payment", "catalog", "/charge"));
11009        s.validate()
11010            .expect("same endpoint reused on distinct (de, para) must validate");
11011    }
11012
11013    #[test]
11014    fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
11015        // Pin the diagnostic shape: the duplicate-edge error names
11016        // *which* target field carried the conflict, so the author
11017        // doesn't have to re-grep the source caixa.lisp to find it.
11018        // Same self-locating diagnostic discipline as
11019        // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
11020        let mut s = three_member_spec();
11021        s.contratos
11022            .push(contract_http("cart", "catalog", "/products/:id"));
11023        let err = s.validate().unwrap_err();
11024        let msg = format!("{err}");
11025        assert!(
11026            msg.contains("\"/products/:id\""),
11027            "duplicate-contrato diagnostic must name the offending \
11028             :endpoint payload (got: {msg:?})"
11029        );
11030        assert!(
11031            msg.contains("cart") && msg.contains("catalog"),
11032            "diagnostic must name both endpoints of the duplicate edge \
11033             (got: {msg:?})"
11034        );
11035    }
11036
11037    #[test]
11038    fn duplicate_contrato_gate_runs_after_membership_check() {
11039        // Order pin: a duplicate contract whose `:de` is *also* not in
11040        // `:membros` surfaces the membership error first — the
11041        // missing-member diagnostic is more locating than the
11042        // duplicate-edge one (the author has to fix the membership
11043        // before the duplicate is meaningful). Same ordering
11044        // discipline as `membros_validation_runs_before_contratos_membership_check`.
11045        let mut s = three_member_spec();
11046        s.contratos.push(contract_http("phantom", "catalog", "/x"));
11047        s.contratos.push(contract_http("phantom", "catalog", "/x"));
11048        let err = s.validate().unwrap_err();
11049        assert!(
11050            matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
11051            "membership-missing must fire before duplicate-edge (got {err:?})"
11052        );
11053    }
11054
11055    #[test]
11056    fn duplicate_contrato_gate_runs_after_target_shape_check() {
11057        // Order pin: a contract with a malformed target (e.g. an HTTP
11058        // wit world with an empty :endpoint) surfaces the target-shape
11059        // error first, not the duplicate one. Even when two such
11060        // malformed entries are identical, the per-contract `target()`
11061        // check fires inside the loop *before* the duplicate-key
11062        // insert, so the diagnostic remains the most-locating one.
11063        let mut s = three_member_spec();
11064        let malformed = WitContract {
11065            de: "cart".into(),
11066            para: "catalog".into(),
11067            wit: "wasi:http/proxy".into(),
11068            endpoint: Some(String::new()),
11069            subject: None,
11070            slot: None,
11071        };
11072        s.contratos.push(malformed.clone());
11073        s.contratos.push(malformed);
11074        let err = s.validate().unwrap_err();
11075        assert!(
11076            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
11077            "endpoint-empty must fire before duplicate-edge (got {err:?})"
11078        );
11079    }
11080
11081    #[test]
11082    fn wit_target_label_pins_per_variant_format() {
11083        // Label format is the single source of truth every duplicate-
11084        // `:contratos` diagnostic + every future `feira app graph`
11085        // consumer routes through. Pin the shape per variant so a
11086        // future edit to `WitTarget::label` (e.g. a JSON emitter that
11087        // strips the leading `:`, or a rename from `endpoint` →
11088        // `path`) surfaces as a red-red test rather than as a silent
11089        // downstream diagnostic drift. Together with the exhaustive
11090        // `match` on `WitTarget` inside `label()`, adding a future
11091        // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
11092        // peer, per-edge WIT registry variants) is a compile error at
11093        // the label site — not a fall-through into the `Capability`
11094        // "no payload" default the prior raw-field-probe helper
11095        // silently landed on.
11096        assert_eq!(
11097            WitTarget::Http {
11098                endpoint: "/charge",
11099            }
11100            .label(),
11101            "\
11102:endpoint \"/charge\""
11103        );
11104        assert_eq!(
11105            WitTarget::PubSub {
11106                subject: "events.checkout.paid",
11107            }
11108            .label(),
11109            "\
11110:subject \"events.checkout.paid\""
11111        );
11112        assert_eq!(
11113            WitTarget::Store {
11114                slot: "checkout/$order",
11115            }
11116            .label(),
11117            "\
11118:slot \"checkout/$order\""
11119        );
11120        assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
11121        // Capability-arm label routes through the lifted
11122        // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
11123        // declaration per arm, next to the variant" discipline the
11124        // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
11125        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
11126        // consts already carry extends to the payload-less arm; the
11127        // byte-string equality pin below plus this label-routes-
11128        // through-the-const pin make a future rebrand on either the
11129        // const declaration or the `label()` template a build error
11130        // here rather than a downstream consumer surprise.
11131        assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
11132        assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
11133    }
11134
11135    #[test]
11136    fn wit_target_display_routes_through_label_helper() {
11137        // Fail-before-pass-after pin on the fourth (and only remaining)
11138        // typed-shape-discriminator axis to converge onto the
11139        // three-path-convergence discipline the sibling M3
11140        // [`PlacementStrategy`] (0a2f653) and M2
11141        // [`crate::supervisor::RestartStrategy`] /
11142        // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
11143        // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
11144        // through [`WitTarget::label`], so every consumer reaching for
11145        // `format!("{v}")` on a typed payload target lands on the same
11146        // stable author-facing byte-string [`WitTarget::label`] returns
11147        // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
11148        // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
11149        // `:contratos` gate seeds via [`WitTarget::label`] at
11150        // aplicacao.rs:5491 already threads through.
11151        //
11152        // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
11153        // through to the `Debug` derive's structural output
11154        // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
11155        // rather than the [`WitTarget::label`] helper's stable byte-
11156        // string (`:endpoint "/charge"` — the author-facing `:contratos`
11157        // keyword form). Every future consumer that reaches for
11158        // `format!("{target}")` — the canonical shape every user-facing
11159        // pretty-print site on the sibling typed-enum axes
11160        // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
11161        // [`crate::supervisor::RestartPolicy`]) already uses — would
11162        // silently land under a different byte-string than the
11163        // [`WitTarget::label`] callers that the duplicate-`:contratos`
11164        // diagnostic already threads through, with the mismatch
11165        // surfacing as a downstream diagnostic / graph / audit line
11166        // reading one spelling while the substrate's own gate emitted
11167        // another.
11168        //
11169        // Pin the routing here so a future
11170        // `impl std::fmt::Display for WitTarget<'_>` reimplementation
11171        // that hand-rolls the per-arm formatting instead of delegating
11172        // to [`WitTarget::label`] fails at caixa-core build time.
11173        for variant in [
11174            WitTarget::Http {
11175                endpoint: "/charge",
11176            },
11177            WitTarget::PubSub {
11178                subject: "events.checkout.paid",
11179            },
11180            WitTarget::Store {
11181                slot: "checkout/$order",
11182            },
11183            WitTarget::Capability,
11184        ] {
11185            assert_eq!(
11186                variant.to_string(),
11187                variant.label(),
11188                "WitTarget::{variant:?} Display must route through \
11189                 WitTarget::label (single source of truth: the lifted \
11190                 payload_pair 4-arm dispatch the label helper already \
11191                 threads through)"
11192            );
11193        }
11194    }
11195
11196    #[test]
11197    fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
11198        // Consumer-side pin on the three-path convergence:
11199        // [`std::fmt::Display`] agrees byte-for-byte with the
11200        // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
11201        // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
11202        // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
11203        // Pre-lift the two paths were structurally independent — the
11204        // substrate-side gate reached for `target_view.label()` while a
11205        // future downstream diagnostic / graph / audit line reaching
11206        // for `format!("{target}")` would silently land on the `Debug`
11207        // derive's structural output. Pin the two paths byte-for-byte
11208        // here so any future variant addition (M4 `Rest`/`Grpc` split
11209        // of [`WitTarget::Http`], `Queue`-shaped peer of
11210        // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
11211        // match error at [`WitTarget::payload_pair`] rather than a
11212        // silent per-consumer dispatch miss.
11213        for variant in [
11214            WitTarget::Http {
11215                endpoint: "/charge",
11216            },
11217            WitTarget::PubSub {
11218                subject: "events.checkout.paid",
11219            },
11220            WitTarget::Store {
11221                slot: "checkout/$order",
11222            },
11223            WitTarget::Capability,
11224        ] {
11225            assert_eq!(
11226                format!("{variant}"),
11227                variant.label(),
11228                "WitTarget::{variant:?} Display byte-string must match \
11229                 the AplicacaoError::ContratoDuplicate `target:` carrier \
11230                 the AplicacaoSpec::validate duplicate-`:contratos` gate \
11231                 seeds via WitTarget::label — three-path convergence: \
11232                 Display + label + payload_pair all resolve to the same \
11233                 per-arm byte-string"
11234            );
11235        }
11236    }
11237
11238    #[test]
11239    fn wit_target_payload_pair_pins_per_variant() {
11240        // Pin the per-arm `(field-name, payload)` pair single-sourced
11241        // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
11242        // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
11243        // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
11244        // and [`WitTarget::field_name`] (returns the first component)
11245        // route through. Until this lift landed [`WitTarget::label`]
11246        // dispatched on the same three arms with a per-arm
11247        // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
11248        // paired [`WitTarget::HTTP_FIELD_NAME`] /
11249        // [`WitTarget::PUBSUB_FIELD_NAME`] /
11250        // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
11251        // canonical "same shape, written N times" duplication
11252        // THEORY.md §I.3.5 promotes to a build-time concern. A future
11253        // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
11254        // [`WitTarget::Http`], `Queue`-shaped peer of
11255        // [`WitTarget::Store`]) is one match-arm edit at
11256        // [`WitTarget::payload_pair`], visible here as a compile-time
11257        // exhaustiveness error on both this pin and the label-format
11258        // pin above.
11259        assert_eq!(
11260            WitTarget::Http {
11261                endpoint: "/charge"
11262            }
11263            .payload_pair(),
11264            Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
11265        );
11266        assert_eq!(
11267            WitTarget::PubSub {
11268                subject: "events.x",
11269            }
11270            .payload_pair(),
11271            Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
11272        );
11273        assert_eq!(
11274            WitTarget::Store {
11275                slot: "checkout/$order",
11276            }
11277            .payload_pair(),
11278            Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
11279        );
11280        assert_eq!(WitTarget::Capability.payload_pair(), None);
11281    }
11282
11283    #[test]
11284    fn wit_target_field_name_pins_per_variant() {
11285        // Pin the per-arm author-facing `:contratos` payload field
11286        // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
11287        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
11288        // + returned by [`WitTarget::field_name`]. Every downstream
11289        // consumer (the [`WitContract::target`] gate's `expected:`
11290        // scalar, the [`WitTarget::label`] template's keyword prefix,
11291        // the `feira app graph` verb's `endpoint=…` prefix) routes
11292        // through the same three peer consts, so a rename on the
11293        // author-surface `(defcaixa … :contratos ((:de … :para …
11294        // :wit … :endpoint …)))` field lands in exactly one place.
11295        assert_eq!(
11296            WitTarget::Http {
11297                endpoint: "/charge"
11298            }
11299            .field_name(),
11300            Some(WitTarget::HTTP_FIELD_NAME),
11301        );
11302        assert_eq!(
11303            WitTarget::PubSub {
11304                subject: "events.x",
11305            }
11306            .field_name(),
11307            Some(WitTarget::PUBSUB_FIELD_NAME),
11308        );
11309        assert_eq!(
11310            WitTarget::Store {
11311                slot: "checkout/$order",
11312            }
11313            .field_name(),
11314            Some(WitTarget::STORE_FIELD_NAME),
11315        );
11316        // Capability arm carries no payload field — the diagnostic
11317        // never reports `expected: "capability"` because the gate's
11318        // Capability arm accepts no payload at all (it fires the
11319        // "expected: none" WrongTarget error instead), so the field-
11320        // name method returns None here rather than a placeholder.
11321        assert_eq!(WitTarget::Capability.field_name(), None);
11322
11323        // Peer const scalar values pinned so a rename on either side
11324        // (author-surface field name in the `(defcaixa …)` DSL, or
11325        // the diagnostic's `expected:` scalar) can't drift without
11326        // failing here first.
11327        assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
11328        assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
11329        assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
11330    }
11331
11332    #[test]
11333    fn wit_target_field_names_are_pairwise_distinct() {
11334        // Distinctness pin: if any two of the three payload-field-name
11335        // scalars ever collapse (e.g. an accidental `endpoint` copy-
11336        // paste over the `subject` const), the [`WitContract::target`]
11337        // gate's diagnostic would point authors at the wrong field —
11338        // an "expected `:endpoint`" error on a pub-sub edge would
11339        // silently misroute the fix. Same cross-axis-distinctness
11340        // discipline as the peer M3 `:placement :estrategia` variant-
11341        // discriminator scalar-value pins (cc8f749) applied to the
11342        // payload-field-name axis.
11343        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
11344        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
11345        assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
11346    }
11347
11348    #[test]
11349    fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
11350        // 4-way distinctness pin extending the sibling
11351        // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
11352        // (which covers only the HTTP / PubSub / Store payload arms)
11353        // onto the fourth scalar the shared
11354        // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
11355        // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
11356        // (`"none"`), the payload-less Capability-arm rejection scalar.
11357        //
11358        // All four [`WitTarget::HTTP_FIELD_NAME`] /
11359        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
11360        // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
11361        // dispatch surface [`WitContract::target`] writes onto the
11362        // `ContratoWrongTarget::expected` field — the same `&'static
11363        // str` axis authors read as "this WIT world's shape admits
11364        // (only|not) `:<field>`". Pairwise-distinctness is the invariant
11365        // downstream consumers rely on: an `expected: "endpoint"`
11366        // diagnostic on a Capability-shaped edge tells the author to
11367        // add a `:endpoint "…"` slot to a WIT world that admits none,
11368        // silently misrouting the fix. Until this pin landed the three
11369        // payload-arm consts were distinctness-guarded by the sibling
11370        // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
11371        // scalar (d4f54f2) sat unguarded — a rebrand collision (the
11372        // author-facing vocabulary shift from `"none"` to `"endpoint"`
11373        // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
11374        // into per-shape peers) would have silently landed one
11375        // Capability-arm rejection on a payload-arm's `expected:` byte-
11376        // string and desynchronized the diagnostic from the author's
11377        // typed shape.
11378        //
11379        // Same 4-way pairwise-distinctness pin discipline as the peer
11380        // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
11381        // (cc8f749) applies on the sibling M3 closed-set typed-enum
11382        // scalar-value dispatch axis; extends the pin trajectory the
11383        // sibling `wit_target_field_names_are_pairwise_distinct`
11384        // 3-way pin opened to cover the last unguarded corner on the
11385        // `ContratoWrongTarget::expected` scalar-value axis.
11386        //
11387        // Fail-before-pass-after locally verified by mutating
11388        // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
11389        // — this pin fires as expected; restoring passes.
11390        let all = [
11391            WitTarget::HTTP_FIELD_NAME,
11392            WitTarget::PUBSUB_FIELD_NAME,
11393            WitTarget::STORE_FIELD_NAME,
11394            WitTarget::CAPABILITY_EXPECTED,
11395        ];
11396        for (i, a) in all.iter().enumerate() {
11397            for (j, b) in all.iter().enumerate() {
11398                if i != j {
11399                    assert_ne!(
11400                        a, b,
11401                        "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
11402                         STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
11403                         pairwise distinct — got duplicate {a:?} at indices \
11404                         {i} and {j}; all four scalars thread through the \
11405                         shared `AplicacaoError::ContratoWrongTarget::expected` \
11406                         &'static str axis, so a collapse silently misdirects \
11407                         the diagnostic on which typed shape the WIT world admits",
11408                    );
11409                }
11410            }
11411        }
11412    }
11413
11414    #[test]
11415    fn wit_target_is_variant_predicates_partition_the_arm_set() {
11416        // Fail-before-pass-after pin on the
11417        // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
11418        // each of the four variants exactly one of the generated
11419        // `is_http` / `is_pubsub` / `is_store` / `is_capability`
11420        // predicates returns `true` and the other three return
11421        // `false`. Prior to this derive the only production
11422        // arm-discriminator on [`WitTarget`] — the sync-cycle
11423        // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
11424        // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
11425        // the variant that expressed no compile-time link back to
11426        // the closed-set typed dispatch a future fifth
11427        // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
11428        // split of [`WitTarget::PubSub`] into shape-specific peers,
11429        // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
11430        // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
11431        // to thread through in lockstep or the DFS exclusion would
11432        // silently disagree with the peer diagnostic templates on
11433        // which arms carry sync-versus-async semantics. Peer of the
11434        // sibling [`crate::CaixaKind`] (f5bba80),
11435        // [`PlacementStrategy`] (766ec63),
11436        // [`crate::supervisor::RestartStrategy`],
11437        // [`crate::supervisor::RestartPolicy`], and
11438        // [`crate::upgrade::UpgradeInstruction`] (915a934)
11439        // `IsVariant` derives on the sibling closed-set typed-enum
11440        // discriminator axes — extends the same one-typed-dispatch-
11441        // per-variant discipline onto the last unlifted closed-set
11442        // typed-enum discriminator on the caixa surface (the M3
11443        // mesh-slot per-`:contratos` target-arm axis), closing the
11444        // arm-discriminator convergence trajectory across every
11445        // closed-set typed enum in caixa-core.
11446        let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
11447            (
11448                WitTarget::Http { endpoint: "/x" },
11449                [true, false, false, false],
11450            ),
11451            (
11452                WitTarget::PubSub {
11453                    subject: "events.x",
11454                },
11455                [false, true, false, false],
11456            ),
11457            (
11458                WitTarget::Store { slot: "kv/x" },
11459                [false, false, true, false],
11460            ),
11461            (WitTarget::Capability, [false, false, false, true]),
11462        ];
11463        for (variant, expected) in rows {
11464            let observed = [
11465                variant.is_http(),
11466                variant.is_pubsub(),
11467                variant.is_store(),
11468                variant.is_capability(),
11469            ];
11470            assert_eq!(
11471                observed, expected,
11472                "WitTarget::{variant:?} is_* predicates must partition \
11473                 the arm set (http, pubsub, store, capability); got {observed:?}"
11474            );
11475        }
11476    }
11477
11478    #[test]
11479    fn wit_target_is_variant_predicates_are_const_fn() {
11480        // The [`gen_platform::IsVariant`] derive emits `const fn`
11481        // predicates on the peer [`crate::CaixaKind`] +
11482        // [`crate::upgrade::UpgradeInstruction`] +
11483        // [`crate::supervisor::RestartStrategy`] +
11484        // [`crate::supervisor::RestartPolicy`] +
11485        // [`PlacementStrategy`] closed-set typed enums — pin the
11486        // same posture on [`WitTarget`] so a future accidental
11487        // downgrade to non-`const` (an added runtime helper reachable
11488        // only from a non-`const` context, a manual hand-rolled
11489        // `impl` that shadows the derive-generated method) trips at
11490        // caixa-core build time rather than surfacing as a downstream
11491        // `const`-context regression far from the derive declaration.
11492        //
11493        // Unlike the peer unit-variant enums (`CaixaKind` /
11494        // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
11495        // whose `const` constructors need no arguments, the three
11496        // payload-carrying [`WitTarget`] arms are const-constructed
11497        // through `&'static str` payloads — the same `'static`
11498        // lifetime the closed-set typed enum's four-arm partition
11499        // pin above already threads through.
11500        const HTTP: WitTarget<'static> = WitTarget::Http { endpoint: "/x" };
11501        const PUBSUB: WitTarget<'static> = WitTarget::PubSub { subject: "e" };
11502        const STORE: WitTarget<'static> = WitTarget::Store { slot: "kv/x" };
11503        const CAPABILITY: WitTarget<'static> = WitTarget::Capability;
11504        const IS_HTTP: bool = HTTP.is_http();
11505        const IS_PUBSUB: bool = PUBSUB.is_pubsub();
11506        const IS_STORE: bool = STORE.is_store();
11507        const IS_CAPABILITY: bool = CAPABILITY.is_capability();
11508        assert!(IS_HTTP);
11509        assert!(IS_PUBSUB);
11510        assert!(IS_STORE);
11511        assert!(IS_CAPABILITY);
11512    }
11513
11514    #[test]
11515    fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
11516        // Consumer-side pin on the sole production converge site:
11517        // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
11518        // edges from the synchronous-subgraph DFS via the lifted
11519        // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
11520        // predicate (rebound from the prior raw
11521        // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
11522        // variant). Byte-equivalent today (`is_pubsub` is the
11523        // derive-generated `matches!(self, Self::PubSub { .. })` by
11524        // construction, the `#[is_variant(name = "pubsub")]` override
11525        // aliasing the auto-derived `is_pub_sub` back to the sibling
11526        // [`WitContract::is_pubsub`] name); pin the behavior so a
11527        // future accidental drift (a rebind onto a peer arm
11528        // predicate, a manual hand-rolled `impl` that shadows the
11529        // derive-generated method with different semantics, a peer
11530        // arm rename that shifts which variant carries sync-versus-
11531        // async semantics) trips at caixa-core test time rather than
11532        // at some downstream operator's runtime dispatch far from the
11533        // rebind commit.
11534        //
11535        // The fixture constructs a two-Servico Aplicacao with one
11536        // pub-sub edge that would close a sync-cycle if the DFS did
11537        // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
11538        // pub-sub exclusion means the DFS sees only the `b → a` HTTP
11539        // edge, which is not a cycle. A regression in the converge
11540        // (a rebind that reads the pub-sub arm as sync) would report
11541        // `AplicacaoError::ContratoCycle`.
11542        let s = AplicacaoSpec {
11543            membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
11544            contratos: vec![
11545                // Pub-sub edge: DFS must skip via is_pubsub().
11546                WitContract {
11547                    de: "a".into(),
11548                    para: "b".into(),
11549                    wit: "nats:pub-sub".into(),
11550                    endpoint: None,
11551                    subject: Some("events.x".into()),
11552                    slot: None,
11553                },
11554                // HTTP edge: DFS must include.
11555                WitContract {
11556                    de: "b".into(),
11557                    para: "a".into(),
11558                    wit: "wasi:http/proxy".into(),
11559                    endpoint: Some("/x".into()),
11560                    subject: None,
11561                    slot: None,
11562                },
11563            ],
11564            politicas: MeshPolicy::default(),
11565            placement: Placement {
11566                estrategia: PlacementStrategy::Replicated,
11567                clusters: vec!["rio".into()],
11568                affinity: None,
11569                shard_key: None,
11570            },
11571            entrada: None,
11572        };
11573        s.validate()
11574            .expect("pub-sub edge must be excluded from sync-cycle DFS");
11575    }
11576
11577    #[test]
11578    fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
11579        // Consumer-side pin: the same three peer consts thread through
11580        // both the [`WitTarget::label`] template (leading-`:` keyword
11581        // prefix in the duplicate-`:contratos` diagnostic) and the
11582        // [`WitContract::target`] gate's [`AplicacaoError::
11583        // ContratoMissingTarget`] `expected:` scalar (the field the
11584        // author needs to add). Pin both routes at once so a future
11585        // refactor can't accidentally split them onto separate string
11586        // literals — the "one place, everywhere reaches for it"
11587        // invariant the peer const set carries.
11588        let http_label = WitTarget::Http { endpoint: "/x" }.label();
11589        assert!(
11590            http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
11591            "label must lead with :{} keyword (got {http_label:?})",
11592            WitTarget::HTTP_FIELD_NAME,
11593        );
11594
11595        let mut s = three_member_spec();
11596        s.contratos.push(WitContract {
11597            de: "cart".into(),
11598            para: "catalog".into(),
11599            wit: "kafka:topic".into(),
11600            endpoint: None,
11601            subject: None,
11602            slot: None,
11603        });
11604        match s.validate().unwrap_err() {
11605            AplicacaoError::ContratoMissingTarget { expected, .. } => {
11606                assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
11607            }
11608            other => panic!("expected ContratoMissingTarget, got {other:?}"),
11609        }
11610    }
11611
11612    #[test]
11613    fn duplicate_pubsub_diagnostic_names_offending_subject() {
11614        // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
11615        // on the pub-sub target axis: the duplicate-edge diagnostic
11616        // must name the `:subject` payload verbatim (not just the
11617        // `(de, para, wit)` triple). Prior to lifting the label onto
11618        // [`WitTarget::label`] the diagnostic derived the label from
11619        // raw [`WitContract`] `Option<String>` probes — a future
11620        // `WitTarget` variant addition (M4 per-edge WIT registry)
11621        // would silently fall through to the `Capability` "no
11622        // payload" default without a compiler warning. Pinning the
11623        // pub-sub arm's format closes the second of three
11624        // payload-carrying `WitTarget` arms this diagnostic threads
11625        // through.
11626        let mut s = three_member_spec();
11627        let pubsub = WitContract {
11628            de: "payment".into(),
11629            para: "cart".into(),
11630            wit: "nats:pub-sub".into(),
11631            endpoint: None,
11632            subject: Some("events.checkout.paid".into()),
11633            slot: None,
11634        };
11635        s.contratos.push(pubsub.clone());
11636        s.contratos.push(pubsub);
11637        let err = s.validate().unwrap_err();
11638        let msg = format!("{err}");
11639        assert!(
11640            msg.contains(":subject \"events.checkout.paid\""),
11641            "duplicate-pubsub diagnostic must name the offending \
11642             :subject payload (got: {msg:?})"
11643        );
11644    }
11645
11646    #[test]
11647    fn duplicate_store_diagnostic_names_offending_slot() {
11648        // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
11649        // key-value target axis: the diagnostic must name the `:slot`
11650        // payload verbatim. Third of three payload-carrying
11651        // `WitTarget` arms this diagnostic threads through, closing
11652        // the per-arm label pin trilogy (`Http` — 6841,
11653        // `PubSub` + `Store` — this test + peer above).
11654        let mut s = three_member_spec();
11655        let store = WitContract {
11656            de: "cart".into(),
11657            para: "payment".into(),
11658            wit: "wasi:keyvalue/store".into(),
11659            endpoint: None,
11660            subject: None,
11661            slot: Some("checkout/$orderId".into()),
11662        };
11663        s.contratos
11664            .retain(|c| !(c.de == "cart" && c.para == "payment"));
11665        s.contratos.push(store.clone());
11666        s.contratos.push(store);
11667        let err = s.validate().unwrap_err();
11668        let msg = format!("{err}");
11669        assert!(
11670            msg.contains(":slot \"checkout/$orderId\""),
11671            "duplicate-store diagnostic must name the offending :slot \
11672             payload (got: {msg:?})"
11673        );
11674    }
11675
11676    #[test]
11677    fn rejects_entrada_path_without_leading_slash() {
11678        let mut s = three_member_spec();
11679        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
11680        let err = s.validate().unwrap_err();
11681        assert!(
11682            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
11683            "got {err:?}"
11684        );
11685    }
11686
11687    #[test]
11688    fn rejects_empty_entrada_path() {
11689        let mut s = three_member_spec();
11690        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "".into()];
11691        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
11692    }
11693
11694    #[test]
11695    fn rejects_duplicate_entrada_paths() {
11696        let mut s = three_member_spec();
11697        s.entrada.as_mut().unwrap().paths = vec![
11698            "/api/cart".into(),
11699            "/api/products".into(),
11700            "/api/cart".into(),
11701        ];
11702        let err = s.validate().unwrap_err();
11703        assert!(
11704            matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
11705            "got {err:?}"
11706        );
11707    }
11708
11709    #[test]
11710    fn rejects_zero_entrada_port() {
11711        let mut s = three_member_spec();
11712        s.entrada.as_mut().unwrap().port = 0;
11713        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
11714    }
11715
11716    // ── :entrada :paths value-shape gate ─────────────────────────────
11717    //
11718    // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
11719    // sibling `:paths` axis. Every authoring footgun the K8s Gateway
11720    // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
11721    // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
11722    // time now becomes a caixa-build-time `EntradaPathInvalid` with
11723    // the offending `:paths` entry named verbatim.
11724
11725    #[test]
11726    fn rejects_entrada_path_with_query() {
11727        // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
11728        // silently passed validate and the Gateway API webhook
11729        // rejected it at apply time with no source citation.
11730        let mut s = three_member_spec();
11731        s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
11732        let err = s.validate().unwrap_err();
11733        assert!(
11734            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11735                if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
11736            "got {err:?}"
11737        );
11738    }
11739
11740    #[test]
11741    fn rejects_entrada_path_with_fragment() {
11742        let mut s = three_member_spec();
11743        s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
11744        let err = s.validate().unwrap_err();
11745        assert!(
11746            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11747                if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
11748            "got {err:?}"
11749        );
11750    }
11751
11752    #[test]
11753    fn rejects_entrada_path_with_space() {
11754        let mut s = three_member_spec();
11755        s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
11756        let err = s.validate().unwrap_err();
11757        assert!(
11758            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11759                if path == "/api/my cart" && reason.contains("whitespace")),
11760            "got {err:?}"
11761        );
11762    }
11763
11764    #[test]
11765    fn rejects_entrada_path_with_tab() {
11766        let mut s = three_member_spec();
11767        s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
11768        let err = s.validate().unwrap_err();
11769        assert!(
11770            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11771                if path == "/api/\tcart" && reason.contains("whitespace")),
11772            "got {err:?}"
11773        );
11774    }
11775
11776    #[test]
11777    fn rejects_entrada_path_with_control_char() {
11778        // 0x01 (SOH) — a non-whitespace control char surfaces the
11779        // distinct "control character" reason arm, separate from
11780        // the whitespace arm. Pinned so a future refactor that
11781        // collapses the two arms can't accidentally drop the more
11782        // self-locating diagnostic.
11783        let mut s = three_member_spec();
11784        s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
11785        let err = s.validate().unwrap_err();
11786        assert!(
11787            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11788                if path == "/api/\x01cart" && reason.contains("control character")),
11789            "got {err:?}"
11790        );
11791    }
11792
11793    #[test]
11794    fn rejects_entrada_path_with_non_ascii() {
11795        // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
11796        // unreserved-set rule rejects. The Gateway API webhook
11797        // rejects literal non-ASCII bytes; percent-encoding is the
11798        // only way to author non-ASCII in a path.
11799        let mut s = three_member_spec();
11800        s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
11801        let err = s.validate().unwrap_err();
11802        assert!(
11803            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11804                if path == "/api/café" && reason.contains("non-ASCII")),
11805            "got {err:?}"
11806        );
11807    }
11808
11809    #[test]
11810    fn rejects_entrada_path_with_consecutive_slashes() {
11811        let mut s = three_member_spec();
11812        s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
11813        let err = s.validate().unwrap_err();
11814        assert!(
11815            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11816                if path == "/api//cart" && reason.contains("consecutive `/`")),
11817            "got {err:?}"
11818        );
11819    }
11820
11821    #[test]
11822    fn rejects_entrada_path_with_dot_segment() {
11823        let mut s = three_member_spec();
11824        s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
11825        let err = s.validate().unwrap_err();
11826        assert!(
11827            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11828                if path == "/api/./cart" && reason.contains("`.` segment")),
11829            "got {err:?}"
11830        );
11831    }
11832
11833    #[test]
11834    fn rejects_entrada_path_with_trailing_dot_segment() {
11835        // The bare `/.` and the trailing `/foo/.` are both rejected
11836        // by the Gateway API webhook; pinned separately so a future
11837        // narrowing that catches only the inner form surfaces here.
11838        let mut s = three_member_spec();
11839        s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
11840        let err = s.validate().unwrap_err();
11841        assert!(
11842            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11843                if path == "/api/." && reason.contains("`.` segment")),
11844            "got {err:?}"
11845        );
11846    }
11847
11848    #[test]
11849    fn rejects_entrada_path_with_parent_segment() {
11850        let mut s = three_member_spec();
11851        s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
11852        let err = s.validate().unwrap_err();
11853        assert!(
11854            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11855                if path == "/api/../etc" && reason.contains("`..` parent-segment")),
11856            "got {err:?}"
11857        );
11858    }
11859
11860    #[test]
11861    fn rejects_entrada_path_with_trailing_parent_segment() {
11862        // Trailing `/..` — symmetric arm of the parent-segment rule,
11863        // pinned separately so a future relaxation that only checks
11864        // the inner form (`/../`) surfaces here.
11865        let mut s = three_member_spec();
11866        s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
11867        let err = s.validate().unwrap_err();
11868        assert!(
11869            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11870                if path == "/api/.." && reason.contains("`..` parent-segment")),
11871            "got {err:?}"
11872        );
11873    }
11874
11875    #[test]
11876    fn rejects_entrada_path_too_long() {
11877        // 1025-byte path — one over the Gateway API HTTPPathMatch.value
11878        // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
11879        // ASCII-alphanumeric body so only the length rule fires.
11880        let mut s = three_member_spec();
11881        let big = format!("/api/{}", "a".repeat(1020));
11882        assert_eq!(big.len(), 1025);
11883        s.entrada.as_mut().unwrap().paths = vec![big.clone()];
11884        let err = s.validate().unwrap_err();
11885        assert!(
11886            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11887                if path == &big && reason.contains("max length of 1024")),
11888            "got {err:?}"
11889        );
11890    }
11891
11892    #[test]
11893    fn entrada_path_max_length_validates() {
11894        // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
11895        // maxLength cap. Boundary pin: drift in the cap surfaces here
11896        // and at `rejects_entrada_path_too_long` simultaneously.
11897        let mut s = three_member_spec();
11898        let big = format!("/api/{}", "a".repeat(1019));
11899        assert_eq!(big.len(), 1024);
11900        s.entrada.as_mut().unwrap().paths = vec![big];
11901        s.validate().unwrap();
11902    }
11903
11904    #[test]
11905    fn entrada_accepts_canonical_paths() {
11906        // Positive-control sweep — every form the Gateway API
11907        // apiserver accepts must round-trip through validate. Covers
11908        // the root catch-all, plain paths, dot-prefixed segments
11909        // (hidden-file-style, distinct from `.` and `..` segments
11910        // which are rejected), digit-bearing segments, the canonical
11911        // route-template `:param` form (`:` is RFC 3986 reserved-set
11912        // valid in paths), trailing-slash form, percent-encoded
11913        // segments, and an interior `..` *substring* (`/foo..bar` is
11914        // not the `..` segment and is allowed).
11915        for path in [
11916            "/",
11917            "/api/cart",
11918            "/healthz",
11919            "/api/.config",
11920            "/v1/products",
11921            "/products/:id",
11922            "/api/cart/",
11923            "/api/caf%C3%A9",
11924            "/foo..bar",
11925            "/...",
11926        ] {
11927            let mut s = three_member_spec();
11928            s.entrada.as_mut().unwrap().paths = vec![path.into()];
11929            s.validate()
11930                .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
11931        }
11932    }
11933
11934    #[test]
11935    fn entrada_path_empty_takes_precedence_over_invalid() {
11936        // Ordering pin: `EntradaPathEmpty` is the more self-locating
11937        // diagnostic on `""` and must lead — `validate_entrada_path`
11938        // is only reached after the empty-check fires at the call
11939        // site. (The predicate itself defends against direct
11940        // invocation by returning the same error on `""`.)
11941        let mut s = three_member_spec();
11942        s.entrada.as_mut().unwrap().paths = vec!["".into()];
11943        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
11944    }
11945
11946    #[test]
11947    fn entrada_path_not_absolute_takes_precedence_over_invalid() {
11948        // Ordering pin: a path without a leading `/` surfaces the
11949        // narrower `EntradaPathNotAbsolute` diagnostic first; the
11950        // value-shape gate is only consulted on paths that already
11951        // satisfy the absolute-prefix invariant.
11952        let mut s = three_member_spec();
11953        // `bad path` would fire the whitespace rule under the
11954        // value-shape gate, but missing-leading-`/` is the more
11955        // self-locating diagnostic.
11956        s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
11957        let err = s.validate().unwrap_err();
11958        assert!(
11959            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
11960            "got {err:?}"
11961        );
11962    }
11963
11964    #[test]
11965    fn entrada_path_invalid_fires_before_duplicate_check() {
11966        // Ordering pin: a malformed path on the *first* entry of a
11967        // would-be duplicate pair fires the value-shape gate before
11968        // the duplicate gate, mirroring the
11969        // `placement_cluster_invalid_fires_before_duplicate_check`
11970        // (6cbb900) pattern on the peer axis.
11971        let mut s = three_member_spec();
11972        s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
11973        let err = s.validate().unwrap_err();
11974        assert!(
11975            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
11976            "got {err:?}"
11977        );
11978    }
11979
11980    #[test]
11981    fn entrada_path_diagnostic_carries_offending_path() {
11982        // Diagnostic-shape pin — the offending path + a non-empty
11983        // reason flow through verbatim so the author can grep their
11984        // caixa.lisp for `:paths` and fix it in one edit. Same shape
11985        // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
11986        let mut s = three_member_spec();
11987        s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
11988        let err = s.validate().unwrap_err();
11989        match err {
11990            AplicacaoError::EntradaPathInvalid { path, reason } => {
11991                assert_eq!(path, "/api?q=1");
11992                assert!(!reason.is_empty(), "reason field must be non-empty");
11993            }
11994            other => panic!("expected EntradaPathInvalid, got {other:?}"),
11995        }
11996    }
11997
11998    #[test]
11999    fn rejects_entrada_path_with_curly_brace_template_form() {
12000        // Per-axis pin on the shared `is_gateway_api_http_path`
12001        // reserved-byte arm: the canonical "I wrote an OpenAPI
12002        // path-template `{id}` instead of the Gateway API `:id` form"
12003        // footgun the K8s apiserver would otherwise catch at admission
12004        // time on every `HTTPRoute.spec.rules[].matches[].path.value`
12005        // landing site, far from the caixa.lisp. Surfaces as
12006        // `EntradaPathInvalid` carrying the offending path verbatim
12007        // plus the canonical `%7B`/`%7D` percent-encoding remediation
12008        // — the substrate-side `gateway_api_http_path_rejects_every_
12009        // reserved_printable_ascii_byte` predicate-level sweep pins the
12010        // full eleven-byte set; this per-axis pin confirms the
12011        // diagnostic flows through to the `EntradaPathInvalid` variant.
12012        let mut s = three_member_spec();
12013        s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
12014        let err = s.validate().unwrap_err();
12015        assert!(
12016            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12017                if path == "/api/cart/{id}"
12018                    && reason.contains("reserved character")
12019                    && reason.contains("'{'")
12020                    && reason.contains("%7B")),
12021            "got {err:?}"
12022        );
12023    }
12024
12025    #[test]
12026    fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
12027        // Per-axis peer of `rejects_entrada_path_with_curly_brace_
12028        // template_form` on the sibling `:contratos :endpoint` axis.
12029        // Same shared `is_gateway_api_http_path` reserved-byte arm
12030        // fires through `ContratoEndpointInvalid`, with the offending
12031        // endpoint + `:de` + `:para` + reason flowing through verbatim.
12032        // Pins that the lifted predicate's tightening lands on both
12033        // caller axes simultaneously — one source of truth for the
12034        // Gateway API HTTPPathMatch.value accepted set.
12035        let err = contrato_endpoint_err("/api/cart/{id}");
12036        assert!(
12037            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12038                if endpoint == "/api/cart/{id}"
12039                    && reason.contains("reserved character")
12040                    && reason.contains("'{'")
12041                    && reason.contains("%7B")),
12042            "got {err:?}"
12043        );
12044    }
12045
12046    // ── :entrada :host value-shape gate ──────────────────────────────
12047    //
12048    // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
12049    // the sibling `:host` axis. Every authoring footgun the K8s
12050    // Gateway API v1 apiserver would catch at admission time becomes
12051    // a caixa-build-time `EntradaHostInvalid` with the offending
12052    // `:host` named verbatim. Same diagnostic shape as
12053    // `MembroVersaoInvalid` (9888b13).
12054
12055    #[test]
12056    fn rejects_entrada_host_with_scheme() {
12057        // Fail-before-pass-after pin — pre-gate codebases silently
12058        // accepted `https://…` and the apiserver rejected it at apply
12059        // time with no source citation.
12060        let mut s = three_member_spec();
12061        s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
12062        let err = s.validate().unwrap_err();
12063        assert!(
12064            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
12065                if host == "https://checkout.quero.cloud"),
12066            "got {err:?}"
12067        );
12068    }
12069
12070    #[test]
12071    fn rejects_entrada_host_with_port() {
12072        // The `:8080` port suffix is the canonical "I forgot the port
12073        // belongs in `:entrada :port`" footgun. The top-level `:` arm
12074        // (introduced after the per-label loop-only impl silently
12075        // surfaced a deep "label \"cloud:8080\" contains invalid
12076        // character ':'" leak) names the canonical fix verbatim — the
12077        // `:entrada :port` slot.
12078        let mut s = three_member_spec();
12079        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
12080        let err = s.validate().unwrap_err();
12081        assert!(
12082            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
12083                if host == "checkout.quero.cloud:8080"
12084                && reason.contains(":entrada :port")),
12085            "got {err:?}"
12086        );
12087    }
12088
12089    #[test]
12090    fn rejects_entrada_host_with_trailing_colon() {
12091        // Trailing `:` (e.g. an in-progress `:host "example.com:"`
12092        // edit) — the per-label loop would land it as a deep
12093        // "label \"com:\" must start and end with an alphanumeric"
12094        // / "contains invalid character ':'" leak. The top-level
12095        // `:` arm pre-empts with the canonical `:port` slot
12096        // diagnostic.
12097        let mut s = three_member_spec();
12098        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
12099        let err = s.validate().unwrap_err();
12100        assert!(
12101            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
12102                if host == "checkout.quero.cloud:"
12103                && reason.contains(":entrada :port")),
12104            "got {err:?}"
12105        );
12106    }
12107
12108    #[test]
12109    fn rejects_entrada_host_unbracketed_ipv6_literal() {
12110        // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
12111        // literals across the board (peer with `rejects_entrada_host_
12112        // ipv4_literal` above for the four-label-all-digit IPv4 arm).
12113        // Before this top-level `:` arm landed the per-label loop
12114        // surfaced a single-label byte-class diagnostic that named the
12115        // `:` byte but not the IP-literal prohibition. The top-level
12116        // `:` arm names both the `:port` slot and the IP-literal
12117        // prohibition verbatim, so an author whose `:host "2001:..."`
12118        // value lands here gets a self-locating fix either way.
12119        let mut s = three_member_spec();
12120        s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
12121        let err = s.validate().unwrap_err();
12122        assert!(
12123            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
12124                if host == "2001:db8::1"
12125                && reason.contains("IPv6")),
12126            "got {err:?}"
12127        );
12128    }
12129
12130    #[test]
12131    fn rejects_entrada_host_wildcard_with_port() {
12132        // Wildcard host with port suffix — the `*.` strip and the
12133        // per-label loop on `["foo", "quero", "cloud:8080"]` would
12134        // surface the deep byte-class leak. The top-level `:` arm sits
12135        // upstream of the `*.` strip, so it names the canonical `:port`
12136        // fix verbatim regardless of whether the host is wildcard-led.
12137        let mut s = three_member_spec();
12138        s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
12139        let err = s.validate().unwrap_err();
12140        assert!(
12141            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
12142                if host == "*.quero.cloud:8080"
12143                && reason.contains(":entrada :port")),
12144            "got {err:?}"
12145        );
12146    }
12147
12148    #[test]
12149    fn rejects_entrada_host_with_path() {
12150        let mut s = three_member_spec();
12151        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
12152        let err = s.validate().unwrap_err();
12153        assert!(
12154            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
12155                if host == "checkout.quero.cloud/api"),
12156            "got {err:?}"
12157        );
12158    }
12159
12160    #[test]
12161    fn rejects_entrada_host_with_uppercase() {
12162        // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
12163        // rejected, not silently lower-cased.
12164        let mut s = three_member_spec();
12165        s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
12166        let err = s.validate().unwrap_err();
12167        assert!(
12168            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12169                if reason.contains("uppercase")),
12170            "got {err:?}"
12171        );
12172    }
12173
12174    #[test]
12175    fn rejects_entrada_host_with_underscore() {
12176        // RFC 1123 allows `[a-z0-9-]` only; underscore is the
12177        // canonical "I'm thinking of HTTP cookies / SRV records" leak.
12178        let mut s = three_member_spec();
12179        s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
12180        let err = s.validate().unwrap_err();
12181        assert!(
12182            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12183                if reason.contains('_')),
12184            "got {err:?}"
12185        );
12186    }
12187
12188    #[test]
12189    fn rejects_entrada_host_ipv4_literal() {
12190        // Gateway API v1 explicitly forbids IP literals as Hostnames.
12191        let mut s = three_member_spec();
12192        s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
12193        let err = s.validate().unwrap_err();
12194        assert!(
12195            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12196                if reason.contains("IPv4")),
12197            "got {err:?}"
12198        );
12199    }
12200
12201    #[test]
12202    fn rejects_entrada_host_with_trailing_dot() {
12203        // The Gateway API regex anchors at end-of-string with no
12204        // trailing `.` allowance — the FQDN root-dot form is rejected.
12205        let mut s = three_member_spec();
12206        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
12207        let err = s.validate().unwrap_err();
12208        assert!(
12209            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
12210                if host == "checkout.quero.cloud."),
12211            "got {err:?}"
12212        );
12213    }
12214
12215    #[test]
12216    fn rejects_entrada_host_with_leading_dot() {
12217        let mut s = three_member_spec();
12218        s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
12219        let err = s.validate().unwrap_err();
12220        assert!(
12221            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12222                if reason.contains("empty label")),
12223            "got {err:?}"
12224        );
12225    }
12226
12227    #[test]
12228    fn rejects_entrada_host_with_consecutive_dots() {
12229        let mut s = three_member_spec();
12230        s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
12231        let err = s.validate().unwrap_err();
12232        assert!(
12233            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12234                if reason.contains("empty label")),
12235            "got {err:?}"
12236        );
12237    }
12238
12239    #[test]
12240    fn rejects_entrada_host_with_leading_hyphen_label() {
12241        let mut s = three_member_spec();
12242        s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
12243        let err = s.validate().unwrap_err();
12244        assert!(
12245            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12246                if reason.contains("alphanumeric")),
12247            "got {err:?}"
12248        );
12249    }
12250
12251    #[test]
12252    fn rejects_entrada_host_with_trailing_hyphen_label() {
12253        let mut s = three_member_spec();
12254        s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
12255        let err = s.validate().unwrap_err();
12256        assert!(
12257            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12258                if reason.contains("alphanumeric")),
12259            "got {err:?}"
12260        );
12261    }
12262
12263    #[test]
12264    fn rejects_entrada_host_with_inner_wildcard() {
12265        // Gateway API allows `*` only as the first label (`*.foo`);
12266        // any inner or trailing `*` is rejected.
12267        let mut s = three_member_spec();
12268        s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
12269        let err = s.validate().unwrap_err();
12270        assert!(
12271            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12272                if reason.contains("wildcard")),
12273            "got {err:?}"
12274        );
12275    }
12276
12277    #[test]
12278    fn rejects_entrada_host_bare_wildcard() {
12279        // `*.` with no domain is meaningless; Gateway API rejects it.
12280        let mut s = three_member_spec();
12281        s.entrada.as_mut().unwrap().host = "*.".into();
12282        let err = s.validate().unwrap_err();
12283        assert!(
12284            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12285                if reason.contains("wildcard")),
12286            "got {err:?}"
12287        );
12288    }
12289
12290    #[test]
12291    fn rejects_entrada_host_with_whitespace() {
12292        let mut s = three_member_spec();
12293        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
12294        let err = s.validate().unwrap_err();
12295        assert!(
12296            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12297                if reason.contains("whitespace")),
12298            "got {err:?}"
12299        );
12300    }
12301
12302    #[test]
12303    fn rejects_entrada_host_space_names_offending_byte() {
12304        // Embedded space in the `:entrada :host` axis surfaces the
12305        // byte-naming diagnostic through the lifted
12306        // `find_ascii_whitespace_byte` predicate. Peer with the
12307        // sibling `parse_rejects_leading_whitespace` pins on
12308        // `supervisor::duration_codec` (a7ae622) — same "the
12309        // diagnostic carries the offending byte's `0x{b:02x}` shape"
12310        // discipline extended from the shared duration codec to the
12311        // Gateway API v1 Hostname axis.
12312        let mut s = three_member_spec();
12313        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
12314        let err = s.validate().unwrap_err();
12315        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12316            panic!("expected EntradaHostInvalid, got {err:?}");
12317        };
12318        assert!(
12319            reason.contains("ASCII whitespace byte"),
12320            "expected byte-naming diagnostic, got {reason:?}"
12321        );
12322        assert!(
12323            reason.contains("0x20"),
12324            "expected offending space byte 0x20, got {reason:?}"
12325        );
12326    }
12327
12328    #[test]
12329    fn rejects_entrada_host_tab_names_offending_byte() {
12330        // Embedded tab byte in the `:entrada :host` axis — the
12331        // canonical paste-from-YAML-block-scalar / paste-from-
12332        // indented-doc footgun. Pins that the lifted predicate covers
12333        // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
12334        // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
12335        // not just the leading-space case the pre-lift `.bytes().any`
12336        // arm's opaque "must not contain whitespace" reason already
12337        // covered. Peer with `parse_rejects_tab_byte` on
12338        // `supervisor::duration_codec` (a7ae622).
12339        let mut s = three_member_spec();
12340        s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
12341        let err = s.validate().unwrap_err();
12342        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12343            panic!("expected EntradaHostInvalid, got {err:?}");
12344        };
12345        assert!(
12346            reason.contains("ASCII whitespace byte"),
12347            "expected byte-naming diagnostic, got {reason:?}"
12348        );
12349        assert!(
12350            reason.contains("0x09"),
12351            "expected offending tab byte 0x09, got {reason:?}"
12352        );
12353    }
12354
12355    #[test]
12356    fn rejects_entrada_host_lf_names_offending_byte() {
12357        // Embedded LF byte in the `:entrada :host` axis — the
12358        // canonical paste-from-shell-heredoc / paste-from-multiline-
12359        // doc footgun the caixa-mesh YAML emitter would silently
12360        // reinterpret at the Gateway API v1 HTTPRoute admission
12361        // layer (an embedded LF byte in a YAML plain scalar either
12362        // truncates the value at the emitter or crashes the parser
12363        // on the k8s-apiserver side). Pins the third representative
12364        // of the full ASCII-whitespace set through the shared
12365        // predicate.
12366        let mut s = three_member_spec();
12367        s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
12368        let err = s.validate().unwrap_err();
12369        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12370            panic!("expected EntradaHostInvalid, got {err:?}");
12371        };
12372        assert!(
12373            reason.contains("ASCII whitespace byte"),
12374            "expected byte-naming diagnostic, got {reason:?}"
12375        );
12376        assert!(
12377            reason.contains("0x0a"),
12378            "expected offending LF byte 0x0a, got {reason:?}"
12379        );
12380    }
12381
12382    #[test]
12383    fn rejects_entrada_host_nbsp_names_offending_codepoint() {
12384        // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
12385        // axis — the canonical paste-from-typography /
12386        // paste-from-word-processor footgun. Before the non-ASCII
12387        // Unicode `White_Space` scan lifted through the shared
12388        // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
12389        // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
12390        // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
12391        // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
12392        // with the far-from-source `label "…" must start and end
12393        // with an alphanumeric` diagnostic — burying the
12394        // paste-from-typography origin under a label-shape leak.
12395        // Peer with the sibling non-ASCII-whitespace pins at
12396        // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
12397        // — 1b75b38), `limits::parse_duration`,
12398        // `limits::parse_millicores`, and the shared duration codec
12399        // — same "the diagnostic carries the offending Unicode
12400        // codepoint's `U+XXXX` shape" discipline extended from every
12401        // typed-magnitude codec to the Gateway API v1 Hostname axis.
12402        let mut s = three_member_spec();
12403        s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
12404        let err = s.validate().unwrap_err();
12405        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12406            panic!("expected EntradaHostInvalid, got {err:?}");
12407        };
12408        assert!(
12409            reason.contains("non-ASCII Unicode whitespace character"),
12410            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
12411        );
12412        assert!(
12413            reason.contains("U+00A0"),
12414            "expected offending NBSP codepoint U+00A0, got {reason:?}"
12415        );
12416    }
12417
12418    #[test]
12419    fn rejects_entrada_host_line_separator_names_offending_codepoint() {
12420        // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
12421        // `:entrada :host` axis — the canonical paste-from-web-doc /
12422        // paste-from-published-HTML footgun. `char::is_whitespace`
12423        // returns true for `U+2028` per the Unicode `White_Space`
12424        // property, so `str::trim` at any downstream site would
12425        // silently strip it — same drift class as NBSP but on a
12426        // different codepoint region. Pins the second representative
12427        // (non-Latin-1 `char::is_whitespace` member) through the
12428        // shared predicate. Peer with
12429        // `parse_byte_size_rejects_internal_line_separator` on
12430        // `limits::parse_byte_size` (1b75b38).
12431        let mut s = three_member_spec();
12432        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
12433        let err = s.validate().unwrap_err();
12434        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12435            panic!("expected EntradaHostInvalid, got {err:?}");
12436        };
12437        assert!(
12438            reason.contains("non-ASCII Unicode whitespace character"),
12439            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
12440        );
12441        assert!(
12442            reason.contains("U+2028"),
12443            "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
12444        );
12445    }
12446
12447    #[test]
12448    fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
12449        // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
12450        // labels in the `:entrada :host` axis — the canonical
12451        // paste-from-CJK-typography footgun (CJK IMEs default to
12452        // full-width whitespace when the space bar is pressed in
12453        // Japanese / Chinese input modes). Pins the third
12454        // representative of the non-ASCII Unicode `White_Space` set
12455        // through the shared predicate: the CJK block, distinct from
12456        // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
12457        // SEPARATOR `U+2028` — covering the same axis breadth the
12458        // sibling `parse_byte_size_rejects_trailing_ideographic_space`
12459        // (1b75b38) pins on `limits::parse_byte_size`.
12460        let mut s = three_member_spec();
12461        s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
12462        let err = s.validate().unwrap_err();
12463        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12464            panic!("expected EntradaHostInvalid, got {err:?}");
12465        };
12466        assert!(
12467            reason.contains("non-ASCII Unicode whitespace character"),
12468            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
12469        );
12470        assert!(
12471            reason.contains("U+3000"),
12472            "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
12473        );
12474    }
12475
12476    #[test]
12477    fn rejects_entrada_host_too_long() {
12478        // Total length cap = 253; build a 254-byte host out of two
12479        // 63-byte labels + one 62-byte label + dots.
12480        let mut s = three_member_spec();
12481        let big = format!(
12482            "{}.{}.{}.{}",
12483            "a".repeat(63),
12484            "b".repeat(63),
12485            "c".repeat(63),
12486            "d".repeat(254 - 63 * 3 - 3)
12487        );
12488        assert_eq!(big.len(), 254);
12489        s.entrada.as_mut().unwrap().host = big;
12490        let err = s.validate().unwrap_err();
12491        assert!(
12492            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12493                if reason.contains("max length of 253")),
12494            "got {err:?}"
12495        );
12496    }
12497
12498    #[test]
12499    fn rejects_entrada_host_label_too_long() {
12500        let mut s = three_member_spec();
12501        // 64-byte label — one over the per-label cap.
12502        s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
12503        let err = s.validate().unwrap_err();
12504        assert!(
12505            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12506                if reason.contains("label max length of 63")),
12507            "got {err:?}"
12508        );
12509    }
12510
12511    #[test]
12512    fn entrada_host_diagnostic_carries_offending_host() {
12513        // Diagnostic-shape pin — the offending host + a non-empty
12514        // reason flow through verbatim so the author can grep their
12515        // caixa.lisp for `:host "<host>"` and fix it in one edit.
12516        let mut s = three_member_spec();
12517        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
12518        let err = s.validate().unwrap_err();
12519        match err {
12520            AplicacaoError::EntradaHostInvalid { host, reason } => {
12521                assert_eq!(host, "checkout.quero.cloud:8080");
12522                assert!(!reason.is_empty(), "reason field must be non-empty");
12523            }
12524            other => panic!("expected EntradaHostInvalid, got {other:?}"),
12525        }
12526    }
12527
12528    #[test]
12529    fn entrada_host_empty_takes_precedence_over_invalid() {
12530        // Ordering pin: `EmptyEntradaHost` is the more self-locating
12531        // diagnostic on `""` and must lead — `validate_entrada_host`
12532        // is only reached after the empty-check fires at the call
12533        // site. (The predicate itself defends against direct
12534        // invocation by returning the same error on `""`.)
12535        let mut s = three_member_spec();
12536        s.entrada.as_mut().unwrap().host = String::new();
12537        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
12538    }
12539
12540    #[test]
12541    fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
12542        // Ordering pin: a missing :para member is the more
12543        // self-locating diagnostic and fires before the host gate.
12544        let mut s = three_member_spec();
12545        let e = s.entrada.as_mut().unwrap();
12546        e.para = "ghost".into();
12547        e.host = "BAD HOST".into();
12548        let err = s.validate().unwrap_err();
12549        assert!(
12550            matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
12551            "got {err:?}"
12552        );
12553    }
12554
12555    #[test]
12556    fn entrada_host_invalid_fires_before_port_zero() {
12557        // Ordering pin: the host gate fires before the port gate so
12558        // a malformed host is named even when the port is also wrong.
12559        let mut s = three_member_spec();
12560        let e = s.entrada.as_mut().unwrap();
12561        e.host = "Checkout.quero.cloud".into();
12562        e.port = 0;
12563        let err = s.validate().unwrap_err();
12564        assert!(
12565            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
12566                if host == "Checkout.quero.cloud"),
12567            "got {err:?}"
12568        );
12569    }
12570
12571    #[test]
12572    fn entrada_accepts_canonical_hosts() {
12573        // Positive-control sweep — every form the Gateway API
12574        // apiserver accepts must round-trip through validate. Covers
12575        // a plain DNS subdomain, a leading wildcard, a single-label
12576        // host (cluster-internal), a max-length-edge label, a
12577        // hyphen-bearing label, and a Punycode IDN label.
12578        for host in [
12579            "checkout.quero.cloud",
12580            "*.quero.cloud",
12581            "checkout",
12582            // 63-byte label — exactly the per-label cap.
12583            "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
12584            "foo-bar.quero.cloud",
12585            // Punycode IDN — valid because the author pre-encoded.
12586            "xn--bcher-kva.example.com",
12587        ] {
12588            let mut s = three_member_spec();
12589            s.entrada.as_mut().unwrap().host = host.into();
12590            s.validate()
12591                .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
12592        }
12593    }
12594
12595    #[test]
12596    fn entrada_host_max_length_validates() {
12597        // 253-byte host is the cap exactly — must validate. Build a
12598        // 253-byte host out of three 63-byte labels + one 61-byte
12599        // label + 3 dots = 252 bytes, then pad one byte to 253.
12600        let mut s = three_member_spec();
12601        let host = format!(
12602            "{}.{}.{}.{}",
12603            "a".repeat(63),
12604            "b".repeat(63),
12605            "c".repeat(63),
12606            "d".repeat(253 - 63 * 3 - 3)
12607        );
12608        assert_eq!(host.len(), 253);
12609        s.entrada.as_mut().unwrap().host = host;
12610        s.validate().unwrap();
12611    }
12612
12613    #[test]
12614    fn entrada_host_total_length_cap_threads_lifted_render_const() {
12615        // Cross-crate-side pin: the aplicacao-side `:entrada :host`
12616        // total-length gate now reads the K8s Gateway API v1 Hostname
12617        // `maxLength: 253` cap from the lifted
12618        // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
12619        // of truth — the same constant every future Gateway-API-Hostname
12620        // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
12621        // materializer's per-host validator, the future per-`Certificate`
12622        // SAN emitter for cert-manager, the multi-`:entrada`
12623        // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
12624        // from. Before the lift, the aplicacao-side reader consumed a
12625        // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
12626        // 253-byte value as the peer render-side canonical bounds
12627        // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
12628        // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
12629        // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
12630        // module boundary — a future 253-byte drift on either side would
12631        // silently split into two axes' worth of admission-schema mismatch
12632        // without a build-time signal. Pin the cap through a fresh 254-
12633        // byte host that hits the total-length arm, then read the reason
12634        // for the exact byte count the shared constant carries: any future
12635        // regression on the lift (a private alias reintroduced, a hard-
12636        // coded literal at the arm, a mismatch between the aplicacao-side
12637        // and render-side canonicals) surfaces as this pin's diagnostic
12638        // failing to match, not as a per-cluster admission rejection far
12639        // from the caixa.lisp source line.
12640        let mut s = three_member_spec();
12641        let over_cap = format!(
12642            "{}.{}.{}.{}",
12643            "a".repeat(63),
12644            "b".repeat(63),
12645            "c".repeat(63),
12646            "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
12647        );
12648        assert_eq!(
12649            over_cap.len(),
12650            crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
12651        );
12652        s.entrada.as_mut().unwrap().host = over_cap;
12653        let err = s.validate().unwrap_err();
12654        match err {
12655            AplicacaoError::EntradaHostInvalid { reason, .. } => {
12656                let needle = format!(
12657                    "max length of {} bytes",
12658                    crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
12659                );
12660                assert!(
12661                    reason.contains(&needle),
12662                    "diagnostic must name the lifted \
12663                     GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
12664                );
12665            }
12666            other => panic!("expected EntradaHostInvalid, got {other:?}"),
12667        }
12668    }
12669
12670    #[test]
12671    fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
12672        // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
12673        // on the per-label-cap axis. Before the lift, the aplicacao-side
12674        // per-label arm consumed a private const alias
12675        // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
12676        // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
12677        // split from it at the module boundary — every `.`-separated
12678        // label in a Gateway API v1 Hostname is a DNS-1123 label under
12679        // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
12680        // so the private alias's 63 and the canonical const's 63 were
12681        // pinning the same underlying rule twice. Pin the cap through a
12682        // 64-byte label that hits the per-label arm, then read the reason
12683        // for the exact byte count the shared constant carries: any
12684        // future drift on either side (a private alias reintroduced, a
12685        // hard-coded literal at the arm, a mismatch between the two
12686        // 63-byte pins) surfaces at this pin's diagnostic rather than at
12687        // a per-cluster admission rejection whose "field is invalid"
12688        // opacity misframes the root cause.
12689        let mut s = three_member_spec();
12690        let over_cap_label = format!(
12691            "{}.quero.cloud",
12692            "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
12693        );
12694        s.entrada.as_mut().unwrap().host = over_cap_label;
12695        let err = s.validate().unwrap_err();
12696        match err {
12697            AplicacaoError::EntradaHostInvalid { reason, .. } => {
12698                let needle = format!(
12699                    "label max length of {} bytes",
12700                    crate::render::DNS_1123_LABEL_MAX_LEN,
12701                );
12702                assert!(
12703                    reason.contains(&needle),
12704                    "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
12705                     cap verbatim on the per-label arm, got: {reason:?}",
12706                );
12707            }
12708            other => panic!("expected EntradaHostInvalid, got {other:?}"),
12709        }
12710    }
12711
12712    #[test]
12713    fn entrada_with_empty_paths_validates() {
12714        // Empty `:paths` is the documented "match every path" form;
12715        // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
12716        let mut s = three_member_spec();
12717        s.entrada.as_mut().unwrap().paths = vec![];
12718        s.validate().unwrap();
12719    }
12720
12721    #[test]
12722    fn entrada_root_path_validates() {
12723        // The author-supplied bare-root `:entrada :paths` entry is the
12724        // same byte-shape the peer emit-side catch-all constant
12725        // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
12726        // the author's `:paths` list is empty — sweeping the test-side
12727        // probe literal onto the lifted const closes the two-axis pin
12728        // (author-side admit + emit-side canonical fallback) around
12729        // one `&'static str`, so a future rebrand of the catch-all
12730        // reaches both consumers by construction. Peer to
12731        // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
12732        // on the canonical-literal pin surface.
12733        let mut s = three_member_spec();
12734        s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
12735        s.validate().unwrap();
12736    }
12737
12738    #[test]
12739    fn placement_strategy_variants_round_trip() {
12740        for s in [
12741            PlacementStrategy::SingleNode,
12742            PlacementStrategy::Replicated,
12743            PlacementStrategy::Sharded,
12744        ] {
12745            let p = Placement {
12746                estrategia: s,
12747                clusters: vec!["rio".into()],
12748                affinity: None,
12749                shard_key: if s.is_sharded() {
12750                    Some("$key".into())
12751                } else {
12752                    None
12753                },
12754            };
12755            let json = serde_json::to_string(&p).unwrap();
12756            let back: Placement = serde_json::from_str(&json).unwrap();
12757            assert_eq!(back, p);
12758        }
12759    }
12760
12761    #[test]
12762    fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
12763        // The fail-before-pass-after pin: pre-lift there was no
12764        // single-source binding between the [`PlacementStrategy`]
12765        // variant name the `Serialize` derive emits and the byte-
12766        // string every downstream cluster-side dispatcher (the
12767        // `lareira-fleet-programs` aggregator's per-entry strategy
12768        // branch, the future `app-operator` reconciler, the M3
12769        // Adaptive compression pass's per-strategy weighting) probes
12770        // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
12771        // future `#[serde(rename_all = "kebab-case")]` attribute on
12772        // the enum — or a variant rename in the source — would
12773        // silently rebrand the emitted scalar under one spelling
12774        // while every downstream dispatcher still probed the other,
12775        // with the failure surfacing at the aggregator's dispatch
12776        // step or the operator's reconcile posture (workloads coming
12777        // up under the `default()` `Replicated` arm rather than the
12778        // typed slot's declared strategy) far from the source
12779        // rebrand commit and with no field naming the drift. Pinning
12780        // the two paths (the `Serialize` derive's serialized string
12781        // AND the [`PlacementStrategy::as_str`] helper) to the same
12782        // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
12783        // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
12784        // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
12785        // makes any future drift on either endpoint fail here at
12786        // caixa-core build time.
12787        for (variant, expected) in [
12788            (
12789                PlacementStrategy::SingleNode,
12790                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
12791            ),
12792            (
12793                PlacementStrategy::Replicated,
12794                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
12795            ),
12796            (
12797                PlacementStrategy::Sharded,
12798                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
12799            ),
12800        ] {
12801            let json = serde_json::to_string(&variant).unwrap();
12802            assert_eq!(
12803                json,
12804                format!("\"{expected}\""),
12805                "PlacementStrategy::{variant:?} must serialize to {expected:?}"
12806            );
12807            assert_eq!(
12808                variant.as_str(),
12809                expected,
12810                "PlacementStrategy::{variant:?}.as_str() must return the lifted \
12811                 M3_PLACEMENT_ESTRATEGIA_* constant"
12812            );
12813        }
12814    }
12815
12816    #[test]
12817    fn m3_placement_estrategia_consts_are_pairwise_distinct() {
12818        // Cross-arm drift-detection pin on the M3
12819        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
12820        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
12821        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
12822        // scalar-value pentad: a future collapse of two canonical
12823        // variant byte-strings onto the same value (an accidental
12824        // copy-paste flip of
12825        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
12826        // read `"SingleNode"`, a per-arm rebrand that lands one const
12827        // without touching its paired peer) would silently reroute
12828        // every downstream operator's per-strategy dispatch onto the
12829        // sibling arm's reconcile branch and pass every
12830        // propagation-probe test that expected only the stale arm's
12831        // value — a `Replicated`-declared Aplicacao would come up
12832        // under the `SingleNode` primary-and-standby reconcile
12833        // posture, so every-cluster active-active workload would
12834        // silently collapse onto one-cluster-runs-at-a-time takeover
12835        // semantics against its declared strategy, with no field
12836        // naming the strategy-value drift root cause. Peer of the
12837        // sibling
12838        // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
12839        // (09ffb2d) /
12840        // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
12841        // (ccdf955) /
12842        // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
12843        // (d739850) distinctness pins on the sibling OTP-shape /
12844        // caixa-kind closed-set typed-enum discriminator axes — the
12845        // fourth (and structurally the M3 mesh-primitive-defining)
12846        // closed-set typed-enum axis to converge on the same
12847        // "pairwise-distinct-by-construction" discipline.
12848        //
12849        // Fail-before-pass-after locally verified by mutating
12850        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
12851        // also read `"SingleNode"` — this pin fires as expected;
12852        // restoring passes.
12853        let all = [
12854            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
12855            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
12856            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
12857        ];
12858        for (i, a) in all.iter().enumerate() {
12859            for (j, b) in all.iter().enumerate() {
12860                if i != j {
12861                    assert_ne!(
12862                        a, b,
12863                        "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
12864                         distinct — got duplicate {a:?} at indices {i} and {j}",
12865                    );
12866                }
12867            }
12868        }
12869    }
12870
12871    #[test]
12872    fn placement_strategy_display_routes_through_as_str_helper() {
12873        // The fail-before-pass-after pin: pre-lift the sibling
12874        // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
12875        // / [`crate::supervisor::RestartPolicy`] both carried a stable
12876        // [`std::fmt::Display`] surface via their
12877        // `#[discriminant(also_display)]` gen-platform derive, but
12878        // [`PlacementStrategy`] did not — every consumer reaching for
12879        // a strategy byte-string past the wire format had to pick
12880        // between three paths ([`PlacementStrategy::as_str`], the
12881        // `Serialize` derive's serialized string, or `format!("{v:?}")`
12882        // on the `Debug` derive), any two of which a future variant
12883        // rename or `#[serde(rename_all = "kebab-case")]` attribute
12884        // would silently desynchronize. Wiring [`std::fmt::Display`]
12885        // through [`PlacementStrategy::as_str`] closes the third path:
12886        // every `format!("{v}")` call reaches the same lifted
12887        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
12888        // and the [`PlacementStrategy::as_str`] helper already route
12889        // through, so a future variant rename lands at exactly one
12890        // place. Pin the routing here so a future
12891        // `impl std::fmt::Display for PlacementStrategy` reimplementation
12892        // that hand-rolls the arms instead of delegating to
12893        // [`PlacementStrategy::as_str`] fails at caixa-core build time.
12894        for variant in [
12895            PlacementStrategy::SingleNode,
12896            PlacementStrategy::Replicated,
12897            PlacementStrategy::Sharded,
12898        ] {
12899            assert_eq!(
12900                variant.to_string(),
12901                variant.as_str(),
12902                "PlacementStrategy::{variant:?} Display must route through \
12903                 PlacementStrategy::as_str (single source of truth: the lifted \
12904                 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
12905            );
12906        }
12907    }
12908
12909    #[test]
12910    fn placement_strategy_display_matches_serialized_wire_byte_string() {
12911        // The fail-before-pass-after pin on the second half of the
12912        // three-path convergence: `Display` (user-facing text) agrees
12913        // byte-for-byte with the `Serialize` derive's wire format
12914        // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
12915        // scalar) on every variant. Pre-lift the two paths were
12916        // structurally independent — a future
12917        // `#[serde(rename_all = "kebab-case")]` attribute on the enum
12918        // would silently rebrand the emitted wire scalar
12919        // (`single-node`, `replicated`, `sharded`) while every consumer
12920        // that pretty-prints the strategy (the M3 diagnostic templates,
12921        // the future `feira app graph` per-Aplicacao strategy line,
12922        // the future M4 CR materializer's admission-webhook rejection
12923        // body) would still emit the TitleCase form the `as_str` /
12924        // `Display` route returns, with the mismatch surfacing at
12925        // consumer parse time / operator dispatch time far from the
12926        // source rebrand commit. Pin the two paths byte-for-byte here
12927        // so any future serde-attribute or variant-rename drift is a
12928        // caixa-core-build-time test failure at this call, not a
12929        // silent per-consumer dispatch miss.
12930        for variant in [
12931            PlacementStrategy::SingleNode,
12932            PlacementStrategy::Replicated,
12933            PlacementStrategy::Sharded,
12934        ] {
12935            let wire = serde_json::to_string(&variant).unwrap();
12936            // Strip the outer `"…"` the JSON string form carries — the
12937            // wire scalar the K8s / YAML apiserver consumes is the
12938            // enclosed byte-string, not the quote wrapper.
12939            let unquoted = wire
12940                .strip_prefix('"')
12941                .and_then(|s| s.strip_suffix('"'))
12942                .expect("serialized PlacementStrategy is a JSON string");
12943            assert_eq!(
12944                variant.to_string(),
12945                unquoted,
12946                "PlacementStrategy::{variant:?} Display byte-string must match the \
12947                 Serialize derive's wire byte-string (three-path convergence: \
12948                 Display + as_str + Serialize all resolve to the same \
12949                 M3_PLACEMENT_ESTRATEGIA_* const)"
12950            );
12951        }
12952    }
12953
12954    #[test]
12955    fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
12956        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
12957        // derive on [`PlacementStrategy`]: for each of the three variants
12958        // exactly one of the generated `is_single_node` / `is_replicated`
12959        // / `is_sharded` predicates returns `true` and the other two
12960        // return `false`. Prior to this derive the three per-arm
12961        // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
12962        // (the `placement_strategy_variants_round_trip` fixture, the
12963        // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
12964        // fixture, and the
12965        // `validate_placement_reads_through_lifted_estrategia_accessor`
12966        // fixture) each open-coded a per-arm PartialEq compare against
12967        // the enum variant — three sites that expressed no compile-time
12968        // link back to the closed-set typed dispatch a future fourth
12969        // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
12970        // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
12971        // would have to thread through in lockstep or one fixture would
12972        // silently disagree with the others on which arms consume the
12973        // `:shard-key` axis. Peer of the sibling
12974        // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
12975        // / [`crate::supervisor::RestartPolicy`] /
12976        // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
12977        // the sibling closed-set typed-enum discriminator axes — extends
12978        // the same one-typed-dispatch-per-variant discipline onto the
12979        // fifth (and only remaining) closed-set typed-enum discriminator
12980        // on the caixa surface, closing the axis on the M3 mesh-slot
12981        // family.
12982        let rows: [(PlacementStrategy, [bool; 3]); 3] = [
12983            (PlacementStrategy::SingleNode, [true, false, false]),
12984            (PlacementStrategy::Replicated, [false, true, false]),
12985            (PlacementStrategy::Sharded, [false, false, true]),
12986        ];
12987        for (variant, expected) in rows {
12988            let observed = [
12989                variant.is_single_node(),
12990                variant.is_replicated(),
12991                variant.is_sharded(),
12992            ];
12993            assert_eq!(
12994                observed, expected,
12995                "PlacementStrategy::{variant:?} is_* predicates must partition \
12996                 the arm set (single_node, replicated, sharded); got {observed:?}"
12997            );
12998        }
12999    }
13000
13001    #[test]
13002    fn placement_strategy_is_variant_predicates_are_const_fn() {
13003        // The [`gen_platform::IsVariant`] derive emits `const fn`
13004        // predicates on the peer [`crate::CaixaKind`] +
13005        // [`crate::upgrade::UpgradeInstruction`] +
13006        // [`crate::supervisor::RestartStrategy`] +
13007        // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
13008        // pin the same posture on [`PlacementStrategy`] so a future
13009        // accidental downgrade to non-`const` (an added runtime helper
13010        // reachable only from a non-`const` context, a manual hand-rolled
13011        // `impl` that shadows the derive-generated method) trips at
13012        // caixa-core build time rather than surfacing as a downstream
13013        // `const`-context regression far from the derive declaration.
13014        const IS_SINGLE_NODE: bool = PlacementStrategy::SingleNode.is_single_node();
13015        const IS_REPLICATED: bool = PlacementStrategy::Replicated.is_replicated();
13016        const IS_SHARDED: bool = PlacementStrategy::Sharded.is_sharded();
13017        assert!(IS_SINGLE_NODE);
13018        assert!(IS_REPLICATED);
13019        assert!(IS_SHARDED);
13020    }
13021
13022    #[test]
13023    fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
13024        // Pin the M3 diagnostic template routes through the typed
13025        // [`PlacementStrategy`] Display byte-string (rebound from the
13026        // prior `{estrategia:?}` `Debug` route). Pre-lift the two
13027        // routes emitted identical bytes (the `Debug` derive on a
13028        // unit variant emits the variant name verbatim, exactly what
13029        // `as_str` returns), but the two paths were structurally
13030        // independent — a future `#[serde(rename_all = "…")]`
13031        // attribute or variant rename would coordinate the wire /
13032        // `Display` / `as_str` triple through the lifted const but
13033        // leave the `Debug` route on the compiler-derived variant name,
13034        // silently desynchronizing the diagnostic byte-string from the
13035        // wire byte-string. Rebinding the template onto `Display`
13036        // ties the diagnostic to the same lifted
13037        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
13038        // emits — drift becomes structurally impossible. Pin the
13039        // byte-string here so a future edit that reverts the template
13040        // to `{estrategia:?}` is caught at caixa-core test time, not
13041        // at consumer dispatch time.
13042        for (variant, expected_scalar) in [
13043            (
13044                PlacementStrategy::SingleNode,
13045                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
13046            ),
13047            (
13048                PlacementStrategy::Replicated,
13049                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
13050            ),
13051            (
13052                PlacementStrategy::Sharded,
13053                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
13054            ),
13055        ] {
13056            let err = AplicacaoError::PlacementWithoutClusters {
13057                estrategia: variant,
13058            };
13059            let msg = err.to_string();
13060            assert!(
13061                msg.starts_with(&format!(":placement {expected_scalar} requires")),
13062                "PlacementWithoutClusters diagnostic for {variant:?} must open \
13063                 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
13064            );
13065        }
13066    }
13067
13068    #[test]
13069    fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
13070        // Peer of
13071        // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
13072        // on the second M3 diagnostic that carries the typed
13073        // [`PlacementStrategy`] in its `#[error(…)]` template. Both
13074        // diagnostics now route the strategy scalar through the same
13075        // [`std::fmt::Display`] surface, tying the diagnostic
13076        // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
13077        // const set the wire format also emits. The two non-Sharded
13078        // arms are exercised here (the diagnostic exists to flag a
13079        // `:shard-key` slot the current strategy will never consume);
13080        // the peer `Sharded` arm never reaches this diagnostic (the
13081        // `Sharded` strategy consumes `:shard-key` — the
13082        // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
13083        // slot instead).
13084        for (variant, expected_scalar) in [
13085            (
13086                PlacementStrategy::SingleNode,
13087                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
13088            ),
13089            (
13090                PlacementStrategy::Replicated,
13091                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
13092            ),
13093        ] {
13094            let err = AplicacaoError::ShardKeyOnNonSharded {
13095                estrategia: variant,
13096                shard_key: "$tenantId".into(),
13097            };
13098            let msg = err.to_string();
13099            assert!(
13100                msg.starts_with(&format!(":placement {expected_scalar} carries")),
13101                "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
13102                 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
13103            );
13104        }
13105    }
13106
13107    #[test]
13108    fn rejects_zero_policy_timeout() {
13109        let mut s = three_member_spec();
13110        s.politicas.timeout = Some(Duration::ZERO);
13111        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
13112    }
13113
13114    #[test]
13115    fn rejects_zero_policy_retries() {
13116        let mut s = three_member_spec();
13117        s.politicas.retries = Some(0);
13118        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
13119    }
13120
13121    #[test]
13122    fn rejects_policy_retries_above_cap() {
13123        // The fail-before-pass-after pin: `Some(11)` is structurally
13124        // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
13125        // passed validate on every pre-gate codebase because the
13126        // typed slot's only check was the zero-floor arm. The
13127        // thundering-herd amplification vector only surfaced at the
13128        // runtime substrate (Envoy / Cilium L7 retry overlay)
13129        // far from the source caixa.lisp with no field naming the
13130        // offending policy.
13131        let mut s = three_member_spec();
13132        s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
13133        assert_eq!(
13134            s.validate().unwrap_err(),
13135            AplicacaoError::PolicyRetriesExceedsCap {
13136                retries: POLICY_RETRIES_MAX + 1
13137            }
13138        );
13139    }
13140
13141    #[test]
13142    fn rejects_policy_retries_far_above_cap() {
13143        // The `u32::MAX` worst case — the four-billion-retry policy
13144        // a typo (`(:retries 4294967295)`) or struct-literal
13145        // copy-paste lands in the slot. Pin the cap arm's coverage
13146        // explicitly across the full `u32` overflow so a future
13147        // relaxation that drops the upper bound surfaces here.
13148        let mut s = three_member_spec();
13149        s.politicas.retries = Some(u32::MAX);
13150        assert_eq!(
13151            s.validate().unwrap_err(),
13152            AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
13153        );
13154    }
13155
13156    #[test]
13157    fn accepts_policy_retries_at_cap() {
13158        // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
13159        // must validate. The cap is inclusive on the top edge,
13160        // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
13161        // discipline on the sibling [`crate::LimitsSpec::memory`]
13162        // axis. Pin the boundary explicitly so a future off-by-one
13163        // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
13164        // surfaces here as a test failure rather than a silent
13165        // contract narrowing.
13166        let mut s = three_member_spec();
13167        s.politicas.retries = Some(POLICY_RETRIES_MAX);
13168        s.validate()
13169            .expect("retries == POLICY_RETRIES_MAX must validate");
13170    }
13171
13172    #[test]
13173    fn accepts_policy_retries_typical_values() {
13174        // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
13175        // every value in the validated set must pass. The
13176        // Envoy / Istio production-playbook recommendation band
13177        // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
13178        // (`maxRetries ≤ 10`) both lie within this set.
13179        for r in 1..=POLICY_RETRIES_MAX {
13180            let mut s = three_member_spec();
13181            s.politicas.retries = Some(r);
13182            s.validate()
13183                .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
13184        }
13185    }
13186
13187    #[test]
13188    fn policy_retries_zero_takes_precedence_over_cap() {
13189        // The cross-arm ordering pin: `Some(0)` is structurally
13190        // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
13191        // (cap), but the zero-floor diagnostic is the more
13192        // self-locating one (it directly names the omit-axis
13193        // remediation), so the validate gate must fire on zero
13194        // first. Pin the order so a future refactor that reorders
13195        // the arms surfaces here as a test failure rather than a
13196        // silent diagnostic regression. Same shape every other
13197        // zero-then-shape ordering on this surface uses
13198        // ([`AplicacaoError::PolicyTimeoutZero`] then
13199        // [`AplicacaoError::PolicyTimeoutNotCanonical`];
13200        // [`AplicacaoError::PolicyBreakerZeroWindow`] then
13201        // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
13202        let mut s = three_member_spec();
13203        s.politicas.retries = Some(0);
13204        assert_eq!(
13205            s.validate().unwrap_err(),
13206            AplicacaoError::PolicyRetriesZero,
13207            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
13208        );
13209    }
13210
13211    #[test]
13212    fn policy_retries_cap_diagnostic_carries_offending_value() {
13213        // The diagnostic-shape pin: the offending `u32` is carried
13214        // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
13215        // variant so the surfaced error message names the value the
13216        // author wrote (`":politicas :retries (47) exceeds the
13217        // mesh-policy ceiling …"`), not just the cap. Same
13218        // self-locating diagnostic shape every other typed-cap arm
13219        // on this surface carries
13220        // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
13221        // offending byte count verbatim).
13222        let mut s = three_member_spec();
13223        s.politicas.retries = Some(47);
13224        let err = s.validate().unwrap_err();
13225        assert!(
13226            matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
13227            "got {err:?}"
13228        );
13229        let msg = err.to_string();
13230        assert!(
13231            msg.contains("47"),
13232            ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
13233        );
13234    }
13235
13236    #[test]
13237    fn policy_retries_cap_is_aws_app_mesh_aligned() {
13238        // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
13239        // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
13240        // schema cap — the only upstream mesh-policy schema that
13241        // documents an explicit hard cap. Pinning the literal value
13242        // here surfaces a future drift (a relaxation to 20, a
13243        // tightening to 5) as a deliberate test edit, not a silent
13244        // contract narrowing.
13245        assert_eq!(POLICY_RETRIES_MAX, 10);
13246    }
13247
13248    #[test]
13249    fn rejects_circuit_breaker_zero_max_failures() {
13250        let mut s = three_member_spec();
13251        s.politicas.circuit_breaker = Some(CircuitBreaker {
13252            max_failures: 0,
13253            window: Duration::from_secs(60),
13254        });
13255        assert_eq!(
13256            s.validate().unwrap_err(),
13257            AplicacaoError::PolicyBreakerZeroFailures
13258        );
13259    }
13260
13261    #[test]
13262    fn rejects_circuit_breaker_max_failures_above_cap() {
13263        // The fail-before-pass-after pin: `1001` is structurally one
13264        // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
13265        // silently passed validate on every pre-gate codebase
13266        // because the typed slot's only check was the zero-floor
13267        // arm. The breaker-no-op vector only surfaced at the runtime
13268        // substrate (Envoy / Cilium L7 outlier-detection overlay)
13269        // far from the source caixa.lisp with no field naming the
13270        // offending policy.
13271        let mut s = three_member_spec();
13272        s.politicas.circuit_breaker = Some(CircuitBreaker {
13273            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
13274            window: Duration::from_secs(60),
13275        });
13276        assert_eq!(
13277            s.validate().unwrap_err(),
13278            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
13279                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
13280            }
13281        );
13282    }
13283
13284    #[test]
13285    fn rejects_circuit_breaker_max_failures_far_above_cap() {
13286        // The `u32::MAX` worst case — the four-billion-failure
13287        // threshold a typo (`(:max-failures 4294967295)`) or a
13288        // struct-literal copy-paste lands in the slot. Pin the cap
13289        // arm's coverage explicitly across the full `u32` overflow
13290        // so a future relaxation that drops the upper bound surfaces
13291        // here.
13292        let mut s = three_member_spec();
13293        s.politicas.circuit_breaker = Some(CircuitBreaker {
13294            max_failures: u32::MAX,
13295            window: Duration::from_secs(60),
13296        });
13297        assert_eq!(
13298            s.validate().unwrap_err(),
13299            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
13300                max_failures: u32::MAX,
13301            }
13302        );
13303    }
13304
13305    #[test]
13306    fn accepts_circuit_breaker_max_failures_at_cap() {
13307        // The boundary value — exactly
13308        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
13309        // cap is inclusive on the top edge, matching the
13310        // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
13311        // discipline on the sibling capped axes. Pin the boundary
13312        // explicitly so a future off-by-one tightening
13313        // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
13314        // surfaces here as a test failure rather than a silent
13315        // contract narrowing.
13316        let mut s = three_member_spec();
13317        s.politicas.circuit_breaker = Some(CircuitBreaker {
13318            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
13319            window: Duration::from_secs(60),
13320        });
13321        s.validate()
13322            .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
13323    }
13324
13325    #[test]
13326    fn accepts_circuit_breaker_max_failures_typical_values() {
13327        // The documented production-playbook band positive-control
13328        // sweep — every value Hystrix / Istio / Envoy / Polly /
13329        // Resilience4j recommend (5..=50) must pass, plus a sweep
13330        // through the hyperscale band (100, 500, 1000) the cap
13331        // accepts. Pin the inclusive validated set explicitly so a
13332        // future tightening of the ceiling surfaces here.
13333        for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
13334            let mut s = three_member_spec();
13335            s.politicas.circuit_breaker = Some(CircuitBreaker {
13336                max_failures: n,
13337                window: Duration::from_secs(60),
13338            });
13339            s.validate()
13340                .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
13341        }
13342    }
13343
13344    #[test]
13345    fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
13346        // The cross-arm ordering pin: `0` is structurally outside
13347        // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
13348        // (cap), but the zero-floor diagnostic is the more
13349        // self-locating one (it directly names the omit-axis
13350        // remediation), so the validate gate must fire on zero
13351        // first. Same shape every other zero-then-shape ordering on
13352        // this surface uses
13353        // ([`AplicacaoError::PolicyRetriesZero`] then
13354        // [`AplicacaoError::PolicyRetriesExceedsCap`];
13355        // [`AplicacaoError::PolicyTimeoutZero`] then
13356        // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
13357        let mut s = three_member_spec();
13358        s.politicas.circuit_breaker = Some(CircuitBreaker {
13359            max_failures: 0,
13360            window: Duration::from_secs(60),
13361        });
13362        assert_eq!(
13363            s.validate().unwrap_err(),
13364            AplicacaoError::PolicyBreakerZeroFailures,
13365            "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
13366        );
13367    }
13368
13369    #[test]
13370    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
13371        // The cross-arm ordering pin between the cap and the
13372        // sibling `:window` gates (zero-window, canonical-window).
13373        // A breaker carrying both an over-cap `max_failures` AND a
13374        // structurally invalid window (zero, sub-ms) must surface
13375        // the cap diagnostic first — the cap arm is wired
13376        // immediately after the zero-failure arm and strictly
13377        // before the window arms, so the offending value the
13378        // diagnostic names matches the order the author would
13379        // discover the gates by reading top-to-bottom through
13380        // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
13381        // future refactor that reorders the arms surfaces here as a
13382        // test failure rather than a silent diagnostic regression.
13383        let mut s = three_member_spec();
13384        s.politicas.circuit_breaker = Some(CircuitBreaker {
13385            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
13386            window: Duration::ZERO,
13387        });
13388        assert_eq!(
13389            s.validate().unwrap_err(),
13390            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
13391                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
13392            },
13393            "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
13394        );
13395    }
13396
13397    #[test]
13398    fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
13399        // The diagnostic-shape pin: the offending `u32` is carried
13400        // verbatim into the
13401        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
13402        // variant so the surfaced error message names the value the
13403        // author wrote (`":politicas :circuit-breaker :max-failures
13404        // (50000) exceeds the mesh-policy ceiling …"`), not just
13405        // the cap. Same self-locating diagnostic shape every other
13406        // typed-cap arm on this surface carries
13407        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
13408        // offending retry count verbatim,
13409        // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
13410        // offending byte count verbatim).
13411        let mut s = three_member_spec();
13412        s.politicas.circuit_breaker = Some(CircuitBreaker {
13413            max_failures: 50_000,
13414            window: Duration::from_secs(60),
13415        });
13416        let err = s.validate().unwrap_err();
13417        assert!(
13418            matches!(
13419                err,
13420                AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
13421                    max_failures: 50_000
13422                }
13423            ),
13424            "got {err:?}"
13425        );
13426        let msg = err.to_string();
13427        assert!(
13428            msg.contains("50000"),
13429            ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
13430        );
13431    }
13432
13433    #[test]
13434    fn policy_breaker_max_failures_cap_pins_canonical_value() {
13435        // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
13436        // value at 1000 — an order of magnitude above every
13437        // documented production-playbook recommendation band
13438        // (Hystrix `requestVolumeThreshold` default 20, Istio
13439        // `outlierDetection.consecutive5xxErrors` default 5, Envoy
13440        // `outlier_detection.consecutive_5xx` default 5, Polly /
13441        // Resilience4j typical 5..=50) and below the
13442        // clearly-pathological "effectively no protection" floor
13443        // (10_000, 100_000, u32::MAX). Pinning the literal value
13444        // here surfaces a future drift (a relaxation to 10_000, a
13445        // tightening to 100) as a deliberate test edit, not a
13446        // silent contract narrowing.
13447        assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
13448    }
13449
13450    #[test]
13451    fn rejects_circuit_breaker_zero_window() {
13452        let mut s = three_member_spec();
13453        s.politicas.circuit_breaker = Some(CircuitBreaker {
13454            max_failures: 5,
13455            window: Duration::ZERO,
13456        });
13457        assert_eq!(
13458            s.validate().unwrap_err(),
13459            AplicacaoError::PolicyBreakerZeroWindow
13460        );
13461    }
13462
13463    #[test]
13464    fn rejects_zero_rate_limit() {
13465        let mut s = three_member_spec();
13466        s.politicas.rate_limit = Some(RateLimit {
13467            rate: 0,
13468            window: Duration::from_secs(1),
13469        });
13470        assert_eq!(
13471            s.validate().unwrap_err(),
13472            AplicacaoError::PolicyRateLimitZero
13473        );
13474    }
13475
13476    #[test]
13477    fn rejects_rate_limit_zero_window() {
13478        // `RateLimit { rate: 100, window: Duration::ZERO }` is
13479        // constructible programmatically (the typed `Duration` field
13480        // imposes no nonzero invariant) but renders through
13481        // `rate_limit_codec::render` as `"100/0s"` — a fragment the
13482        // codec's `parse` rejects as `unknown rate-limit window unit
13483        // "0s"`. Until this validate-time gate landed the typed slot
13484        // accepted the value silently and the round-trip break only
13485        // surfaced at deserialize time (potentially in a downstream
13486        // consumer that never re-validates). Pin the rejection at
13487        // `AplicacaoSpec::validate` so the typed slot's valid set
13488        // matches the codec's round-trippable set structurally.
13489        let mut s = three_member_spec();
13490        s.politicas.rate_limit = Some(RateLimit {
13491            rate: 100,
13492            window: Duration::ZERO,
13493        });
13494        assert_eq!(
13495            s.validate().unwrap_err(),
13496            AplicacaoError::PolicyRateLimitWindowNotCanonical {
13497                window: Duration::ZERO
13498            }
13499        );
13500    }
13501
13502    #[test]
13503    fn rejects_rate_limit_arbitrary_seconds_window() {
13504        // 45 seconds is a valid `Duration` but not one of the three
13505        // canonical rate-limit windows the codec round-trips
13506        // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
13507        // refuses on round-trip — same round-trip-break shape the
13508        // zero-window arm above pins, with a non-zero magnitude to
13509        // guard against a future "reject only zero" half-measure.
13510        let mut s = three_member_spec();
13511        let window = Duration::from_secs(45);
13512        s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
13513        assert_eq!(
13514            s.validate().unwrap_err(),
13515            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
13516        );
13517    }
13518
13519    #[test]
13520    fn rejects_rate_limit_two_minute_window() {
13521        // 120 seconds = 2 minutes is a "looks-canonical" but
13522        // not-canonical window: it's a clean integer multiple of the
13523        // minute unit, but the codec only round-trips the
13524        // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
13525        // A `Duration::from_secs(120)` window renders as `"100/120s"`
13526        // which the parser rejects. Pinning this case rules out a
13527        // future "accept any clean multiple of s/m/h" relaxation
13528        // that would silently break the codec contract.
13529        let mut s = three_member_spec();
13530        let window = Duration::from_secs(120);
13531        s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
13532        assert_eq!(
13533            s.validate().unwrap_err(),
13534            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
13535        );
13536    }
13537
13538    #[test]
13539    fn rejects_rate_limit_subsecond_window() {
13540        // A sub-second window (e.g. 500ms) is a valid `Duration` but
13541        // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
13542        // Pin the rejection so a future relaxation can't silently
13543        // admit fractional-second windows that the codec can't
13544        // round-trip.
13545        let mut s = three_member_spec();
13546        let window = Duration::from_millis(500);
13547        s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
13548        assert_eq!(
13549            s.validate().unwrap_err(),
13550            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
13551        );
13552    }
13553
13554    #[test]
13555    fn rejects_policy_rate_limit_above_cap() {
13556        // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
13557        // is structurally one past the cap and silently passed
13558        // validate on every pre-gate codebase because the typed slot's
13559        // only `rate` check was the zero-floor arm. The no-op-limiter
13560        // shape only surfaced at the runtime substrate (Envoy's
13561        // `local_rate_limit.token_bucket.max_tokens`, the future
13562        // Cilium L7 rate-limit overlay) far from the source caixa.lisp
13563        // with no field naming the offending policy.
13564        let mut s = three_member_spec();
13565        s.politicas.rate_limit = Some(RateLimit {
13566            rate: POLICY_RATE_LIMIT_MAX + 1,
13567            window: Duration::from_secs(1),
13568        });
13569        assert_eq!(
13570            s.validate().unwrap_err(),
13571            AplicacaoError::PolicyRateLimitExceedsCap {
13572                rate: POLICY_RATE_LIMIT_MAX + 1
13573            }
13574        );
13575    }
13576
13577    #[test]
13578    fn rejects_policy_rate_limit_far_above_cap() {
13579        // The `u32::MAX` worst case — the four-billion-token rate-limit
13580        // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
13581        // copy-paste lands in the slot. Pin the cap arm's coverage
13582        // explicitly across the full `u32` overflow so a future
13583        // relaxation that drops the upper bound surfaces here. Peer to
13584        // `rejects_policy_retries_far_above_cap` on the sibling
13585        // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
13586        // on the sibling `:max-failures` axis.
13587        let mut s = three_member_spec();
13588        s.politicas.rate_limit = Some(RateLimit {
13589            rate: u32::MAX,
13590            window: Duration::from_secs(1),
13591        });
13592        assert_eq!(
13593            s.validate().unwrap_err(),
13594            AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
13595        );
13596    }
13597
13598    #[test]
13599    fn accepts_policy_rate_limit_at_cap() {
13600        // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
13601        // must validate. The cap is inclusive on the top edge, matching
13602        // every other typed upper bound in this crate
13603        // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
13604        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
13605        // across all three canonical windows so a future off-by-one
13606        // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
13607        // window-conditional cap surfaces here as a test failure rather
13608        // than a silent contract narrowing.
13609        for secs in [1u64, 60, 3600] {
13610            let mut s = three_member_spec();
13611            s.politicas.rate_limit = Some(RateLimit {
13612                rate: POLICY_RATE_LIMIT_MAX,
13613                window: Duration::from_secs(secs),
13614            });
13615            s.validate().unwrap_or_else(|e| {
13616                panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
13617            });
13618        }
13619    }
13620
13621    #[test]
13622    fn accepts_policy_rate_limit_typical_values() {
13623        // The documented production-playbook recommendation band —
13624        // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
13625        // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
13626        // Enterprise ~1M per-hour. Every value in the validated set
13627        // must pass; pin the band explicitly so a future tightening
13628        // surfaces here.
13629        for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
13630            for secs in [1u64, 60, 3600] {
13631                let mut s = three_member_spec();
13632                s.politicas.rate_limit = Some(RateLimit {
13633                    rate,
13634                    window: Duration::from_secs(secs),
13635                });
13636                s.validate().unwrap_or_else(|e| {
13637                    panic!("rate={rate} window={secs}s must validate; got {e:?}")
13638                });
13639            }
13640        }
13641    }
13642
13643    #[test]
13644    fn policy_rate_limit_zero_takes_precedence_over_cap() {
13645        // The cross-arm ordering pin: `rate == 0` is structurally
13646        // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
13647        // (cap), but the zero-floor diagnostic is the more
13648        // self-locating one (it directly names the omit-axis
13649        // remediation). Pin the order so a future refactor that
13650        // reorders the arms surfaces here as a test failure rather
13651        // than a silent diagnostic regression. Same shape every other
13652        // zero-then-cap ordering on this surface uses
13653        // ([`AplicacaoError::PolicyRetriesZero`] then
13654        // [`AplicacaoError::PolicyRetriesExceedsCap`];
13655        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
13656        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
13657        let mut s = three_member_spec();
13658        s.politicas.rate_limit = Some(RateLimit {
13659            rate: 0,
13660            window: Duration::from_secs(1),
13661        });
13662        assert_eq!(
13663            s.validate().unwrap_err(),
13664            AplicacaoError::PolicyRateLimitZero,
13665            "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
13666        );
13667    }
13668
13669    #[test]
13670    fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
13671        // Two-axis-bad pin: rate above cap *and* window non-canonical.
13672        // The validate gate must fire on the rate cap first — the
13673        // amplification-shape (no-op limiter) diagnostic is the more
13674        // fundamental one; the window-canonical diagnostic is the
13675        // narrower codec-round-trip shape. Pin the ordering so a future
13676        // refactor that reorders the rate-then-window check arms
13677        // surfaces here as a test failure rather than a silent
13678        // diagnostic regression.
13679        let mut s = three_member_spec();
13680        s.politicas.rate_limit = Some(RateLimit {
13681            rate: POLICY_RATE_LIMIT_MAX + 1,
13682            window: Duration::from_secs(45),
13683        });
13684        assert_eq!(
13685            s.validate().unwrap_err(),
13686            AplicacaoError::PolicyRateLimitExceedsCap {
13687                rate: POLICY_RATE_LIMIT_MAX + 1
13688            },
13689            "above-cap rate must surface the cap diagnostic, not the window diagnostic"
13690        );
13691    }
13692
13693    #[test]
13694    fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
13695        // The diagnostic-shape pin: the offending `u32` is carried
13696        // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
13697        // variant so the surfaced error message names the value the
13698        // author wrote (`":politicas :rate-limit rate (5000000) exceeds
13699        // the mesh-policy ceiling …"`), not just the cap. Same
13700        // self-locating diagnostic shape every other typed-cap arm on
13701        // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
13702        // carries the offending retries count verbatim,
13703        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
13704        // the offending failure count verbatim).
13705        let mut s = three_member_spec();
13706        s.politicas.rate_limit = Some(RateLimit {
13707            rate: 5_000_000,
13708            window: Duration::from_secs(1),
13709        });
13710        let err = s.validate().unwrap_err();
13711        assert!(
13712            matches!(
13713                err,
13714                AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
13715            ),
13716            "got {err:?}"
13717        );
13718        let msg = err.to_string();
13719        assert!(
13720            msg.contains("5000000"),
13721            ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
13722        );
13723    }
13724
13725    #[test]
13726    fn policy_rate_limit_cap_pins_canonical_value() {
13727        // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
13728        // 1_000_000 — two-to-three orders of magnitude above every
13729        // documented production-playbook recommendation band (Envoy /
13730        // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
13731        // Gateway 10_000..=100_000 per-minute) and below the
13732        // clearly-pathological "paste-from-binary blob" floor
13733        // (100_000_000, u32::MAX). Pinning the literal value here
13734        // surfaces a future drift (a relaxation to 10_000_000, a
13735        // tightening to 100_000) as a deliberate test edit, not a
13736        // silent contract narrowing.
13737        assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
13738    }
13739
13740    #[test]
13741    fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
13742        // Both axes are invalid here: rate == 0 *and* window is
13743        // non-canonical. The validate gate must fire on rate first
13744        // (matching the existing `rejects_zero_rate_limit` ordering),
13745        // so the existing diagnostic continues to lead with the
13746        // simpler "zero rate" framing. Pinning the order of checks
13747        // so a future refactor that reorders the arms surfaces here
13748        // as a test failure rather than a silent diagnostic
13749        // regression.
13750        let mut s = three_member_spec();
13751        s.politicas.rate_limit = Some(RateLimit {
13752            rate: 0,
13753            window: Duration::from_secs(45),
13754        });
13755        assert_eq!(
13756            s.validate().unwrap_err(),
13757            AplicacaoError::PolicyRateLimitZero
13758        );
13759    }
13760
13761    #[test]
13762    fn rate_limit_canonical_windows_validate() {
13763        // The three canonical windows the codec round-trips
13764        // losslessly — 1s / 60s / 3600s — must all pass `validate()`
13765        // unchanged. Pin the full canonical set as a positive case
13766        // (the existing `rate_limit_round_trip_seconds` /
13767        // `rate_limit_round_trip_minutes` tests pin the
13768        // serialize-then-deserialize property at the codec layer; this
13769        // test pins the validate-side complement so a future tightening
13770        // of the canonical set — e.g. dropping `:hour` — surfaces here
13771        // as a test failure rather than a silent contract narrowing).
13772        for secs in [1u64, 60, 3600] {
13773            let mut s = three_member_spec();
13774            s.politicas.rate_limit = Some(RateLimit {
13775                rate: 100,
13776                window: Duration::from_secs(secs),
13777            });
13778            s.validate().expect("canonical window must validate");
13779        }
13780    }
13781
13782    #[test]
13783    fn rate_limit_validated_value_round_trips_through_codec() {
13784        // The structural property the validate gate enforces:
13785        // every `RateLimit` past `AplicacaoSpec::validate` round-trips
13786        // losslessly through the `rate_limit_codec` (serialize → string
13787        // → deserialize → equal value). Pin this end-to-end so a future
13788        // change to either side (the validate gate's accepted window
13789        // set, the codec's parse/render unit set) that breaks the
13790        // alignment surfaces here. The previous-state shape (typed
13791        // slot accepts arbitrary `Duration`, codec only round-trips
13792        // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
13793        // window — the validate gate now forecloses that.
13794        for secs in [1u64, 60, 3600] {
13795            let mut s = three_member_spec();
13796            s.politicas.rate_limit = Some(RateLimit {
13797                rate: 250,
13798                window: Duration::from_secs(secs),
13799            });
13800            s.validate().unwrap();
13801            let json = serde_json::to_string(&s.politicas).unwrap();
13802            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
13803            assert_eq!(
13804                back.rate_limit, s.politicas.rate_limit,
13805                "every validated :rate-limit must round-trip losslessly through the codec"
13806            );
13807        }
13808    }
13809
13810    #[test]
13811    fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
13812        // The hour-window canonical form (`"<n>/h"`) was missing from
13813        // the prior `rate_limit_round_trip_seconds` / `_minutes` test
13814        // pair. Now that the validate gate pins 3600s as part of the
13815        // canonical set, pin its serialize-side render shape too so
13816        // the third leg of the s/m/h tripod is explicitly tested.
13817        let policy = MeshPolicy {
13818            rate_limit: Some(RateLimit {
13819                rate: 10000,
13820                window: Duration::from_secs(3600),
13821            }),
13822            ..Default::default()
13823        };
13824        let json = serde_json::to_string(&policy).unwrap();
13825        assert!(
13826            json.contains("\"10000/h\""),
13827            "hour-window canonical form must render with `h` suffix (got: {json})"
13828        );
13829        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
13830        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
13831    }
13832
13833    #[test]
13834    fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
13835        // Pin the substrate-primitive [`RateLimit::canonical_unit`]
13836        // typed accessor's accepted-window set against the codec's
13837        // accepted set explicitly. A future addition to the codec
13838        // (e.g. accepting `:day`/`:week` as authoring units) must be
13839        // accompanied by a parallel addition here, and a regression
13840        // that drops one of the three canonical units from either
13841        // side surfaces as a test failure. The accessor is the
13842        // single source of truth for the canonical-window set —
13843        // [`AplicacaoSpec::validate_politicas`]'s canonical-window
13844        // gate and [`rate_limit_codec::render`]'s canonical arm both
13845        // read through it — this test enshrines that its
13846        // `Duration → Option<RateLimitUnit>` projection matches the
13847        // codec's parse / render arms' accepted-window set exactly.
13848        //
13849        // Predecessor: this pin previously read the module-private
13850        // free helper `is_canonical_rate_limit_window` — a delegate
13851        // that composed [`RateLimitUnit::from_window`] with `.is_some()`
13852        // — but the helper had no production consumers left after the
13853        // validate-gate migration onto [`RateLimit::canonical_unit`]
13854        // and was deleted; the closed-set arm-window bijection now
13855        // lives on exactly one typed dispatch on the substrate
13856        // primitive.
13857        let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
13858            RateLimit { rate: 1, window }.canonical_unit()
13859        };
13860        assert!(canonical_unit(Duration::from_secs(1)).is_some());
13861        assert!(canonical_unit(Duration::from_secs(60)).is_some());
13862        assert!(canonical_unit(Duration::from_secs(3600)).is_some());
13863        // Non-canonical windows the accessor rejects.
13864        assert!(canonical_unit(Duration::ZERO).is_none());
13865        assert!(canonical_unit(Duration::from_secs(2)).is_none());
13866        assert!(canonical_unit(Duration::from_secs(30)).is_none());
13867        assert!(canonical_unit(Duration::from_secs(120)).is_none());
13868        assert!(canonical_unit(Duration::from_secs(86400)).is_none());
13869        // Sub-second windows: even `Duration::from_millis(1000)` is
13870        // exactly 1s and accepted; `Duration::from_millis(500)` is
13871        // sub-second and rejected.
13872        assert!(canonical_unit(Duration::from_millis(1000)).is_some());
13873        assert!(canonical_unit(Duration::from_millis(500)).is_none());
13874        assert!(canonical_unit(Duration::from_millis(1500)).is_none());
13875    }
13876
13877    #[test]
13878    fn rate_limit_unit_table_projections_are_mutual_inverses() {
13879        // Bidirection pin against the closed-set typed enum
13880        // [`RateLimitUnit`] arm-table (the canonical
13881        // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
13882        // of the rate-limit unit surface reads from). The two
13883        // projection directions [`RateLimitUnit::from_suffix`] /
13884        // [`RateLimitUnit::window`] (str → Duration) and
13885        // [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
13886        // (Duration → str) are the substrate primitives the codec's
13887        // parse arm ([`rate_limit_codec::parse`] via
13888        // [`rate_limit_window_from_unit`]), the codec's render arm
13889        // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
13890        // and the validate gate ([`AplicacaoSpec::validate_politicas`]
13891        // via [`RateLimit::canonical_unit`]) all key off. A future
13892        // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
13893        // sub-second window) is one variant + one arm per method on the
13894        // closed-set enum; the compiler-enforced exhaustiveness on
13895        // every consumer's `match self` arms picks it up by
13896        // construction. This pin enshrines that both projection
13897        // directions agree on every canonical arm row and neither
13898        // leaks a spurious entry the other doesn't recognize.
13899        //
13900        // Predecessor: this test previously read the two vestigial
13901        // module-private free helpers `rate_limit_window_unit` and
13902        // `rate_limit_window_from_unit` on the `Duration → &str` and
13903        // `&str → Duration` axes; the former was deleted after its
13904        // sole production consumer ([`rate_limit_codec::render`])
13905        // migrated onto [`RateLimit::canonical_unit`], so the
13906        // `Duration → &str` half now composes [`RateLimit::canonical_unit`]
13907        // with [`RateLimitUnit::as_suffix`] directly. The `&str → Duration`
13908        // axis stays on the surviving [`rate_limit_window_from_unit`]
13909        // delegate the codec's parse arm still reads through.
13910        for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
13911            let window = super::rate_limit_window_from_unit(unit)
13912                .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
13913            assert_eq!(
13914                window,
13915                Duration::from_secs(secs),
13916                "unit {unit:?} must resolve to {secs}s"
13917            );
13918            let projected_suffix = RateLimit { rate: 1, window }
13919                .canonical_unit()
13920                .map(super::RateLimitUnit::as_suffix);
13921            assert_eq!(
13922                projected_suffix,
13923                Some(unit),
13924                "Duration({secs}s) must render as {unit:?} \
13925                 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
13926            );
13927        }
13928        // Non-table units yield None on the `unit → Duration`
13929        // projection — a future `"d"` addition to the table would
13930        // flip this arm; today it pins the current three-row table's
13931        // rejection semantics.
13932        assert!(super::rate_limit_window_from_unit("d").is_none());
13933        assert!(super::rate_limit_window_from_unit("ms").is_none());
13934        assert!(super::rate_limit_window_from_unit("").is_none());
13935        // Non-table Durations yield None on the `Duration → unit`
13936        // projection — pins that the two projections agree on the
13937        // "not in the table" semantic too, so a drift where the
13938        // parse-side accepts a value the render-side can't emit is
13939        // a build error at the two-arm pair, not a silent codec
13940        // round-trip break.
13941        let projected_suffix = |window: Duration| -> Option<&'static str> {
13942            RateLimit { rate: 1, window }
13943                .canonical_unit()
13944                .map(super::RateLimitUnit::as_suffix)
13945        };
13946        assert!(projected_suffix(Duration::from_secs(2)).is_none());
13947        assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
13948        assert!(projected_suffix(Duration::from_millis(1500)).is_none());
13949    }
13950
13951    #[test]
13952    fn rate_limit_unit_all_enumerates_every_arm_once() {
13953        // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
13954        // enumerate every arm of the closed-set enum exactly once, in
13955        // the canonical shortest-to-longest window order (Second before
13956        // Minute before Hour) — the same order the sibling
13957        // [`crate::supervisor::RestartStrategy`] /
13958        // [`crate::supervisor::RestartPolicy`] /
13959        // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
13960        // typed enums carry (the arm declared first is the arm listed
13961        // first). A future variant addition that extends the enum
13962        // without appending to [`RateLimitUnit::ALL`] leaves the
13963        // exhaustive iteration surface silently short one arm — the
13964        // codec's parse arm would then reject the new suffix even
13965        // though the enum knows it. This pin closes the drift.
13966        assert_eq!(
13967            super::RateLimitUnit::ALL,
13968            &[
13969                super::RateLimitUnit::Second,
13970                super::RateLimitUnit::Minute,
13971                super::RateLimitUnit::Hour,
13972            ],
13973            "RateLimitUnit::ALL must enumerate every arm exactly once, \
13974             in canonical shortest-to-longest window order"
13975        );
13976    }
13977
13978    #[test]
13979    fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
13980        // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
13981        // every arm's [`RateLimitUnit::as_suffix`] output must parse
13982        // back through [`RateLimitUnit::from_suffix`] to the same
13983        // variant. A future arm addition that lands `as_suffix` but
13984        // forgets `from_suffix` (`from_suffix` iterates
13985        // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
13986        // is the load-bearing carrier of the round-trip; the sibling
13987        // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
13988        // the `ALL` half) trips here at caixa-core build time rather
13989        // than surfacing as a codec round-trip miss (a `render` emit
13990        // that lands a suffix the paired `parse` cannot decode).
13991        for unit in super::RateLimitUnit::ALL {
13992            let suffix = unit.as_suffix();
13993            let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
13994                panic!(
13995                    "RateLimitUnit::from_suffix({suffix:?}) must accept every \
13996                     RateLimitUnit::as_suffix output — got None for {unit:?}"
13997                )
13998            });
13999            assert_eq!(
14000                parsed, *unit,
14001                "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
14002                 must return RateLimitUnit::{unit:?}"
14003            );
14004        }
14005    }
14006
14007    #[test]
14008    fn rate_limit_unit_from_window_and_window_round_trip() {
14009        // Total round-trip pin on the `(from_window, window)` pair:
14010        // every arm's [`RateLimitUnit::window`] output must parse back
14011        // through [`RateLimitUnit::from_window`] to the same variant.
14012        // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
14013        // on the peer `Duration` axis — the two round-trip pins
14014        // together enshrine that both projections of the typed
14015        // canonical-unit bijection are total on the arm-set.
14016        for unit in super::RateLimitUnit::ALL {
14017            let window = unit.window();
14018            let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
14019                panic!(
14020                    "RateLimitUnit::from_window({window:?}) must accept every \
14021                     RateLimitUnit::window output — got None for {unit:?}"
14022                )
14023            });
14024            assert_eq!(
14025                parsed, *unit,
14026                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
14027                 must return RateLimitUnit::{unit:?}"
14028            );
14029        }
14030    }
14031
14032    #[test]
14033    fn rate_limit_unit_projections_are_pairwise_distinct() {
14034        // Distinctness pin: [`RateLimitUnit::as_suffix`] and
14035        // [`RateLimitUnit::window`] outputs must be pairwise distinct
14036        // across every arm — an accidental copy-paste flip that
14037        // reroutes one arm's suffix or window to also match another
14038        // silently collapses two arms onto one, so
14039        // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
14040        // (both using `find` on `Self::ALL`) would return whichever
14041        // arm the linear scan lands on first — a match-arm-ordering-
14042        // dependent outcome the closed-set typed-enum shape is meant
14043        // to rule out structurally. Peer of the sibling
14044        // `caixa_kind_wire_consts_are_pairwise_distinct` /
14045        // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
14046        // other closed-set typed-enum discriminator axes.
14047        let all = super::RateLimitUnit::ALL;
14048        for (i, a) in all.iter().enumerate() {
14049            for (j, b) in all.iter().enumerate() {
14050                if i != j {
14051                    assert_ne!(
14052                        a.as_suffix(),
14053                        b.as_suffix(),
14054                        "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
14055                         must be distinct — a collision silently collapses two \
14056                         arms onto one under from_suffix's linear scan"
14057                    );
14058                    assert_ne!(
14059                        a.window(),
14060                        b.window(),
14061                        "RateLimitUnit::{a:?}.window() and {b:?}.window() \
14062                         must be distinct — a collision silently collapses two \
14063                         arms onto one under from_window's linear scan"
14064                    );
14065                }
14066            }
14067        }
14068    }
14069
14070    #[test]
14071    fn rate_limit_unit_display_routes_through_as_suffix() {
14072        // Route pin: [`std::fmt::Display`] must byte-equal
14073        // [`RateLimitUnit::as_suffix`] on every arm — the single
14074        // source of truth for the canonical suffix. A future
14075        // reimplementation that hand-rolls the arms instead of
14076        // delegating to [`RateLimitUnit::as_suffix`] would silently
14077        // desynchronize `format!("{u}")` from the codec's parse arm
14078        // (which uses `as_suffix` to compare suffixes). Peer of the
14079        // sibling `caixa_kind_display_routes_through_as_str_helper` /
14080        // `placement_strategy_display_routes_through_as_str_helper`
14081        // pins on the peer closed-set typed-enum Display axes.
14082        for unit in super::RateLimitUnit::ALL {
14083            assert_eq!(
14084                unit.to_string(),
14085                unit.as_suffix(),
14086                "RateLimitUnit::{unit:?} Display must route through \
14087                 as_suffix (single source of truth: the canonical suffix \
14088                 the codec parses and renders)"
14089            );
14090        }
14091    }
14092
14093    #[test]
14094    fn rate_limit_unit_from_window_rejects_non_canonical() {
14095        // Rejection pin on the parser's accept-set: any Duration
14096        // outside the three-arm [`RateLimitUnit::window`] output set
14097        // (sub-second residue, or a second-magnitude outside `{1, 60,
14098        // 3600}`) must return `None`. A future accidental widening of
14099        // the accept-set (rounding down sub-second residue to the
14100        // nearest arm, admitting `Duration::from_secs(30)` as a
14101        // half-minute unit) would silently drift the parser's accept-
14102        // set from the emitter's — a validated slot with a
14103        // non-canonical window would then round-trip through the
14104        // codec to a canonical form the author never wrote.
14105        assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
14106        assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
14107        assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
14108        assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
14109        assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
14110        assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
14111        assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
14112    }
14113
14114    #[test]
14115    fn rate_limit_unit_from_suffix_rejects_unknown() {
14116        // Rejection pin on the suffix parser's accept-set: any string
14117        // outside the three-arm [`RateLimitUnit::as_suffix`] output
14118        // set must return `None`. Peer of the sibling
14119        // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
14120        // the [`crate::CaixaKind`] `from_wire` accept-set.
14121        for bad in [
14122            "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
14123            " s",
14124        ] {
14125            assert!(
14126                super::RateLimitUnit::from_suffix(bad).is_none(),
14127                "RateLimitUnit::from_suffix({bad:?}) must return None — the \
14128                 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
14129                 outputs"
14130            );
14131        }
14132    }
14133
14134    #[test]
14135    fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
14136        // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
14137        // every canonical `:window` magnitude the validate gate
14138        // accepts must map to the paired [`RateLimitUnit`] arm through
14139        // this accessor. A future validate-gate rebrand that widened
14140        // the accepted-window set without extending [`RateLimitUnit`]
14141        // would silently split the accessor's `Some`-return set from
14142        // the validate gate's accept-set — a slot that satisfies
14143        // validate would land at the accessor with `None`, so a
14144        // consumer past validate that pattern-matches on the returned
14145        // `Some` would silently miss the newly-accepted magnitude.
14146        for (window_secs, expected) in [
14147            (1u64, super::RateLimitUnit::Second),
14148            (60, super::RateLimitUnit::Minute),
14149            (3600, super::RateLimitUnit::Hour),
14150        ] {
14151            let rl = RateLimit {
14152                rate: 100,
14153                window: Duration::from_secs(window_secs),
14154            };
14155            assert_eq!(
14156                rl.canonical_unit(),
14157                Some(expected),
14158                "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
14159                 must return Some({expected:?})"
14160            );
14161        }
14162        // Non-canonical windows the validate gate rejects also return
14163        // None here — the accessor is the typed-enum projection of
14164        // the sibling `is_canonical_rate_limit_window` predicate.
14165        let bad = RateLimit {
14166            rate: 100,
14167            window: Duration::from_secs(30),
14168        };
14169        assert!(
14170            bad.canonical_unit().is_none(),
14171            "RateLimit with a non-canonical window must return None from \
14172             canonical_unit — the validate gate rejects the same set"
14173        );
14174    }
14175
14176    #[test]
14177    fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
14178        // Fail-before-pass-after byte-parity pin: for every canonical
14179        // window the [`rate_limit_codec::render`] arm's emitted string
14180        // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
14181        // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
14182        // the vestigial free helper [`rate_limit_window_unit`] (a
14183        // `find_map`-walked `Duration → &'static str` delegate) onto the
14184        // substrate primitive [`RateLimit::canonical_unit`] typed method
14185        // (a closed-set `match self.window` arm on
14186        // [`RateLimitUnit::from_window`], projected through
14187        // [`RateLimitUnit::as_suffix`] via the enum's
14188        // [`std::fmt::Display`] impl). A future re-routing of the render
14189        // arm through a differently-computed unit projection would break
14190        // this pin at build time rather than as a silent per-consumer
14191        // codec round-trip drift far from the substrate primitive edit.
14192        //
14193        // Sibling to the peer
14194        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
14195        // on the free-helper axis: that pin locks the two projections
14196        // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
14197        // on the closed-set arm table; this pin locks the codec's render
14198        // arm reads through the typed accessor rather than the free
14199        // helper. Two production consumers of the canonical-unit axis
14200        // now key off one typed dispatch on the substrate primitive.
14201        for (window_secs, unit) in [
14202            (1u64, super::RateLimitUnit::Second),
14203            (60, super::RateLimitUnit::Minute),
14204            (3600, super::RateLimitUnit::Hour),
14205        ] {
14206            let rl = RateLimit {
14207                rate: 42,
14208                window: Duration::from_secs(window_secs),
14209            };
14210            let policy = MeshPolicy {
14211                rate_limit: Some(rl),
14212                ..Default::default()
14213            };
14214            let json = serde_json::to_string(&policy).unwrap();
14215            let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
14216            assert!(
14217                json.contains(&expected),
14218                "rate_limit_codec::render must emit {expected} (via \
14219                 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
14220                 for a {window_secs}s window; serialized MeshPolicy was: {json}"
14221            );
14222            // And the accessor route resolves to the same typed unit
14223            // the render arm's Display formatting is asked to produce —
14224            // so a future edit that split the two paths (one through
14225            // the accessor, one through a re-introduced free helper)
14226            // trips this pin.
14227            assert_eq!(
14228                rl.canonical_unit(),
14229                Some(unit),
14230                "RateLimit::canonical_unit must return Some({unit:?}) for a \
14231                 {window_secs}s window; the codec render arm reads the same \
14232                 typed unit through this accessor"
14233            );
14234        }
14235    }
14236
14237    #[test]
14238    fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
14239        // Fail-before-pass-after byte-parity pin on the validate gate's
14240        // canonical-window shape probe: every non-canonical `:window`
14241        // the free-helper predicate [`is_canonical_rate_limit_window`]
14242        // rejects is also rejected by the substrate primitive
14243        // [`RateLimit::canonical_unit`] `.is_none()` route the validate
14244        // gate now reads through, and vice versa on the accepted set
14245        // (the three canonical windows). Locks the migration from the
14246        // free helper onto the substrate primitive: a future re-routing
14247        // of one of the two paths through a differently-computed unit
14248        // projection would silently split the codec's accepted set from
14249        // the validate gate's accepted set — a two-consumer drift the
14250        // codec-round-trip pin
14251        // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
14252        // above closes on the render arm and this pin closes on the
14253        // validate arm.
14254        for canonical_window_secs in [1u64, 60, 3600] {
14255            let mut s = three_member_spec();
14256            let rl = RateLimit {
14257                rate: 100,
14258                window: Duration::from_secs(canonical_window_secs),
14259            };
14260            s.politicas.rate_limit = Some(rl);
14261            assert!(
14262                s.validate().is_ok(),
14263                "canonical {canonical_window_secs}s window must pass \
14264                 validate_politicas — the validate gate now reads \
14265                 RateLimit::canonical_unit().is_none() and the accessor \
14266                 returns Some on every canonical arm"
14267            );
14268            assert!(
14269                rl.canonical_unit().is_some(),
14270                "canonical {canonical_window_secs}s window must resolve to \
14271                 Some on RateLimit::canonical_unit — the validate gate reads \
14272                 this accessor directly"
14273            );
14274        }
14275        for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
14276            let mut s = three_member_spec();
14277            let rl = RateLimit {
14278                rate: 100,
14279                window: Duration::from_secs(non_canonical_window_secs),
14280            };
14281            s.politicas.rate_limit = Some(rl);
14282            assert_eq!(
14283                s.validate().unwrap_err(),
14284                AplicacaoError::PolicyRateLimitWindowNotCanonical {
14285                    window: rl.window(),
14286                },
14287                "non-canonical {non_canonical_window_secs}s window must be \
14288                 rejected by validate_politicas — the validate gate now \
14289                 keys off RateLimit::canonical_unit().is_none()"
14290            );
14291            assert!(
14292                rl.canonical_unit().is_none(),
14293                "non-canonical {non_canonical_window_secs}s window must \
14294                 resolve to None on RateLimit::canonical_unit — the two \
14295                 paths (the free helper the validate gate previously read \
14296                 and the substrate primitive the validate gate now reads) \
14297                 must agree on the same rejected set"
14298            );
14299        }
14300        // And the substrate-primitive [`RateLimit::canonical_unit`]
14301        // accessor's accepted-window set matches the codec's parse arm's
14302        // accepted-suffix set on every canonical / non-canonical shape,
14303        // so a future silent drift between the codec's accepted set and
14304        // the validate gate's accepted set is a build error at test time
14305        // (both consumers key off the same closed-set enum's `match self`
14306        // arms). The predecessor free helper `is_canonical_rate_limit_window`
14307        // — a delegate that composed [`RateLimitUnit::from_window`] with
14308        // `.is_some()` — was deleted after this migration; the
14309        // canonical-window set now lives on exactly one typed dispatch
14310        // on the substrate primitive.
14311        for (secs, expected) in [
14312            (1u64, true),
14313            (60, true),
14314            (3600, true),
14315            (2, false),
14316            (30, false),
14317            (86_400, false),
14318        ] {
14319            let window = Duration::from_secs(secs);
14320            let rl = RateLimit { rate: 1, window };
14321            assert_eq!(
14322                rl.canonical_unit().is_some(),
14323                expected,
14324                "RateLimit::canonical_unit().is_some() must agree with the \
14325                 codec-accepted canonical-window set on {secs}s"
14326            );
14327            let suffix_from_axis = super::rate_limit_window_from_unit(match secs {
14328                1 => "s",
14329                60 => "m",
14330                3600 => "h",
14331                _ => return,
14332            })
14333            .is_some_and(|d| d == window);
14334            if expected {
14335                assert!(
14336                    suffix_from_axis,
14337                    "the codec's `&str → Duration` axis \
14338                     ({secs}s) must round-trip to the same Duration the \
14339                     substrate primitive's accessor returns Some on"
14340                );
14341            }
14342        }
14343    }
14344
14345    #[test]
14346    fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
14347        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
14348        // derive: for each of the three variants, exactly one of the
14349        // generated `is_second` / `is_minute` / `is_hour` predicates
14350        // returns `true` and the other two return `false`. Peer of
14351        // the sibling
14352        // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
14353        // sibling `IsVariant`-derived closed-set typed-enum pins.
14354        let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
14355            (super::RateLimitUnit::Second, [true, false, false]),
14356            (super::RateLimitUnit::Minute, [false, true, false]),
14357            (super::RateLimitUnit::Hour, [false, false, true]),
14358        ];
14359        for (variant, expected) in rows {
14360            let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
14361            assert_eq!(
14362                observed, expected,
14363                "RateLimitUnit::{variant:?} is_* predicates must partition \
14364                 the arm set (second, minute, hour); got {observed:?}"
14365            );
14366        }
14367    }
14368
14369    #[test]
14370    fn rejects_policy_timeout_sub_millisecond() {
14371        // A purely sub-millisecond `Duration` (`from_micros(500)` =
14372        // 500_000 ns) is not the zero `Duration` — the `is_zero()`
14373        // arm passes — but `as_millis() == 0`, so the shared codec's
14374        // `render` arm returns the literal `"0s"`, which the
14375        // codec's `parse` arm then deserializes as `Duration::ZERO`
14376        // and the `PolicyTimeoutZero` zero-floor gate would reject
14377        // on re-validate. Pin the rejection at the typed slot's
14378        // canonical-floor gate so the round-trip break surfaces at
14379        // validate time, naming the offending `Duration`, rather
14380        // than at the next serialize → deserialize round-trip far
14381        // from the source `caixa.lisp`.
14382        let mut s = three_member_spec();
14383        let timeout = Duration::from_micros(500);
14384        s.politicas.timeout = Some(timeout);
14385        assert_eq!(
14386            s.validate().unwrap_err(),
14387            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
14388        );
14389    }
14390
14391    #[test]
14392    fn rejects_policy_timeout_non_integer_millisecond() {
14393        // A `Duration` with non-integer-millisecond residue
14394        // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
14395        // through the shared codec's `render` arm as `"1ms"` (the
14396        // `as_millis()` floor truncates), which the codec's `parse`
14397        // arm then deserializes as `Duration::from_millis(1)` =
14398        // 1_000_000 ns — silently *different* from the original.
14399        // Pin the rejection so this round-trip break surfaces at
14400        // validate time, where the offending `Duration` is named,
14401        // rather than as a silent value-laundered round-trip on the
14402        // next codec round-trip.
14403        let mut s = three_member_spec();
14404        let timeout = Duration::from_micros(1500);
14405        s.politicas.timeout = Some(timeout);
14406        assert_eq!(
14407            s.validate().unwrap_err(),
14408            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
14409        );
14410    }
14411
14412    #[test]
14413    fn accepts_policy_timeout_integer_millisecond_forms() {
14414        // The codec's accepted set — integer multiples of 1ms — is
14415        // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
14416        // `1h` all pass the canonical gate. Pin the canonical-forms
14417        // sweep so a future tightening of the codec's grammar (e.g.
14418        // dropping `:ms`) surfaces here as a test failure rather
14419        // than a silent contract narrowing on the typed slot.
14420        for timeout in [
14421            Duration::from_millis(1),
14422            Duration::from_millis(500),
14423            Duration::from_millis(1500),
14424            Duration::from_secs(30),
14425            Duration::from_secs(120),
14426            Duration::from_secs(3600),
14427        ] {
14428            let mut s = three_member_spec();
14429            s.politicas.timeout = Some(timeout);
14430            s.validate()
14431                .expect("integer-millisecond :timeout must validate");
14432        }
14433    }
14434
14435    #[test]
14436    fn policy_timeout_zero_takes_precedence_over_canonical() {
14437        // `Duration::ZERO` carries `subsec_nanos() == 0` and would
14438        // pass the canonical-millisecond gate; the more self-locating
14439        // `PolicyTimeoutZero` arm (which names the omit-axis
14440        // remediation directly) must fire first. Pin the ordering so
14441        // a future refactor that reorders the arms surfaces here as a
14442        // test failure rather than a silent diagnostic regression.
14443        let mut s = three_member_spec();
14444        s.politicas.timeout = Some(Duration::ZERO);
14445        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
14446    }
14447
14448    #[test]
14449    fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
14450        // The diagnostic envelope carries the offending `Duration`
14451        // verbatim so the author can grep their `caixa.lisp` for
14452        // `:timeout "<value>"` and fix it in one edit. Same
14453        // diagnostic shape every other typed-slot canonical-form
14454        // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
14455        // peer `:rate-limit :window` axis.
14456        let mut s = three_member_spec();
14457        let timeout = Duration::from_nanos(1_000_001);
14458        s.politicas.timeout = Some(timeout);
14459        match s.validate().unwrap_err() {
14460            AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
14461                assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
14462            }
14463            other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
14464        }
14465    }
14466
14467    #[test]
14468    fn rejects_policy_timeout_above_cap() {
14469        // The fail-before-pass-after pin: 3601s = 1h + 1s is
14470        // structurally one canonical-tick past the
14471        // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
14472        // integer-millisecond magnitude the canonical-form arm above
14473        // accepts cleanly, that the codec round-trips losslessly as
14474        // `"3601s"`, and that silently passed validate on every
14475        // pre-gate codebase because the typed slot's only checks were
14476        // the zero-floor and canonical-form arms. The mesh-level
14477        // deadline degenerates only at the runtime substrate (Envoy
14478        // / Cilium L7 timeout overlay) far from the source
14479        // `caixa.lisp` with no field naming the offending policy.
14480        let mut s = three_member_spec();
14481        let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
14482        s.politicas.timeout = Some(timeout);
14483        assert_eq!(
14484            s.validate().unwrap_err(),
14485            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
14486        );
14487    }
14488
14489    #[test]
14490    fn rejects_policy_timeout_one_millisecond_above_cap() {
14491        // Boundary case: exactly 1ms past the cap (the granularity
14492        // the canonical-form gate enforces). Catches a future
14493        // "strictly less than" half-measure and pins the diagnostic
14494        // to name the offending `Duration` verbatim. Peer of
14495        // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
14496        // boundary pin on the sibling `:limits :memory` top edge.
14497        let mut s = three_member_spec();
14498        let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
14499        s.politicas.timeout = Some(timeout);
14500        assert_eq!(
14501            s.validate().unwrap_err(),
14502            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
14503        );
14504    }
14505
14506    #[test]
14507    fn rejects_policy_timeout_far_above_cap() {
14508        // The "obvious authoring footgun" case: a `(:timeout "24h")`
14509        // or `(:timeout "86400s")` — values the canonical-form arm
14510        // accepts as integer-millisecond magnitudes, the codec
14511        // round-trips losslessly through serde, but the mesh-level
14512        // policy cannot honor (a 24-hour synchronous-`:contratos`
14513        // deadline is operationally indistinguishable from
14514        // omit-the-axis). Until this gate landed validate accepted
14515        // it. Pin both common above-cap values (24h, 7d) so a future
14516        // relaxation that drops the upper bound surfaces here.
14517        for timeout in [
14518            Duration::from_secs(86_400),    // 24h
14519            Duration::from_secs(604_800),   // 7d
14520            Duration::from_secs(1_000_000), // ~11.5 days
14521        ] {
14522            let mut s = three_member_spec();
14523            s.politicas.timeout = Some(timeout);
14524            assert_eq!(
14525                s.validate().unwrap_err(),
14526                AplicacaoError::PolicyTimeoutExceedsCap { timeout }
14527            );
14528        }
14529    }
14530
14531    #[test]
14532    fn accepts_policy_timeout_at_cap() {
14533        // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
14534        // must validate. The cap is inclusive on the top edge,
14535        // matching the [`POLICY_RETRIES_MAX`] /
14536        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
14537        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
14538        // sibling capped axes. Pin the boundary explicitly so a
14539        // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
14540        // instead of `>`) surfaces here as a test failure rather
14541        // than a silent contract narrowing.
14542        let mut s = three_member_spec();
14543        s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
14544        s.validate()
14545            .expect("timeout == POLICY_TIMEOUT_MAX must validate");
14546    }
14547
14548    #[test]
14549    fn accepts_policy_timeout_typical_values() {
14550        // The documented production-playbook band positive-control
14551        // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
14552        // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
14553        // plus a sweep through the long-running-workflow band
14554        // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
14555        // validated set explicitly so a future tightening of the
14556        // ceiling surfaces here as a deliberate test edit, not a
14557        // silent contract narrowing.
14558        for timeout in [
14559            Duration::from_millis(1),
14560            Duration::from_millis(500),
14561            Duration::from_secs(1),
14562            Duration::from_secs(10),
14563            Duration::from_secs(15), // Envoy default
14564            Duration::from_secs(30),
14565            Duration::from_secs(60), // AWS App Mesh typical
14566            Duration::from_secs(300),
14567            Duration::from_secs(900),
14568            Duration::from_secs(1800),
14569            Duration::from_secs(3600), // exactly 1h, the cap
14570        ] {
14571            let mut s = three_member_spec();
14572            s.politicas.timeout = Some(timeout);
14573            s.validate()
14574                .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
14575        }
14576    }
14577
14578    #[test]
14579    fn policy_timeout_zero_takes_precedence_over_cap() {
14580        // The cross-arm ordering pin: `Duration::ZERO` is
14581        // structurally outside both `>= 1ms` (zero-floor) and
14582        // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
14583        // diagnostic is the more self-locating one (it directly
14584        // names the omit-axis remediation), so the validate gate
14585        // must fire on zero first. Same shape every other
14586        // zero-then-shape ordering on this surface uses
14587        // ([`AplicacaoError::PolicyRetriesZero`] then
14588        // [`AplicacaoError::PolicyRetriesExceedsCap`];
14589        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
14590        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
14591        let mut s = three_member_spec();
14592        s.politicas.timeout = Some(Duration::ZERO);
14593        assert_eq!(
14594            s.validate().unwrap_err(),
14595            AplicacaoError::PolicyTimeoutZero,
14596            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
14597        );
14598    }
14599
14600    #[test]
14601    fn policy_timeout_canonical_takes_precedence_over_cap() {
14602        // The cross-arm ordering pin: a `Duration` that is *both*
14603        // sub-millisecond (non-canonical-form) and structurally
14604        // above the cap surfaces the canonical-form diagnostic
14605        // first, because the round-trip-shape break is the more
14606        // fundamental issue (the value can't even round-trip
14607        // through the codec, so the cap diagnostic naming
14608        // `1ms..=1h` would be misleading — there's no integer-ms
14609        // form of the offending value). Pin the order so a future
14610        // refactor that reorders the arms surfaces here as a test
14611        // failure rather than a silent diagnostic regression.
14612        let mut s = three_member_spec();
14613        // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
14614        // *and* total magnitude above the 1h cap.
14615        let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
14616        s.politicas.timeout = Some(timeout);
14617        assert_eq!(
14618            s.validate().unwrap_err(),
14619            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
14620            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
14621        );
14622    }
14623
14624    #[test]
14625    fn policy_timeout_cap_diagnostic_carries_offending_value() {
14626        // The diagnostic-shape pin: the offending `Duration` is
14627        // carried verbatim into the
14628        // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
14629        // surfaced error message names the value the author wrote
14630        // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
14631        // exceeds the mesh-policy ceiling …"`), not just the cap.
14632        // Same self-locating diagnostic shape every other typed-cap
14633        // arm on this surface carries
14634        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
14635        // offending retry count verbatim).
14636        let mut s = three_member_spec();
14637        let timeout = Duration::from_secs(7200); // 2h
14638        s.politicas.timeout = Some(timeout);
14639        let err = s.validate().unwrap_err();
14640        assert!(
14641            matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
14642            "got {err:?}"
14643        );
14644        let msg = err.to_string();
14645        assert!(
14646            msg.contains("7200"),
14647            ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
14648        );
14649    }
14650
14651    #[test]
14652    fn policy_timeout_cap_pins_canonical_value() {
14653        // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
14654        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
14655        // the shared duration codec emits as a clean canonical
14656        // string (`"<n>h"`). Pinning the literal value here surfaces
14657        // a future drift (a relaxation to 24h, a tightening to 5m)
14658        // as a deliberate test edit, not a silent contract
14659        // narrowing. Same shape every other typed-cap value pin on
14660        // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
14661        assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
14662        assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
14663    }
14664
14665    #[test]
14666    fn policy_timeout_cap_value_round_trips_through_codec() {
14667        // The codec round-trip property the cap arm preserves: the
14668        // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
14669        // the shared duration codec — every value at the cap renders
14670        // to a clean canonical string (`"1h"`) and parses back to
14671        // the same `Duration`. Pin this so a future drift between
14672        // the cap constant and the codec's largest emitted unit
14673        // surfaces here. Same shape every other typed boundary pin
14674        // on this surface uses
14675        // (`wasm32_memory_cap_matches_parsed_4_gib`).
14676        let policy = MeshPolicy {
14677            timeout: Some(POLICY_TIMEOUT_MAX),
14678            ..Default::default()
14679        };
14680        let json = serde_json::to_string(&policy).unwrap();
14681        // The codec emits `"1h"` for the canonical 1-hour magnitude.
14682        assert!(
14683            json.contains("\"1h\""),
14684            "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
14685        );
14686        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
14687        assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
14688    }
14689
14690    #[test]
14691    fn rejects_circuit_breaker_window_sub_millisecond() {
14692        // Peer of the `:timeout` sub-millisecond arm on the second
14693        // typed-`Duration` `:politicas` axis: a purely sub-ms
14694        // `Duration` (`from_micros(500)`) renders through the shared
14695        // codec as `"0s"`, which the codec parses back to
14696        // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
14697        // zero-floor gate then rejects on re-validate.
14698        let mut s = three_member_spec();
14699        let window = Duration::from_micros(500);
14700        s.politicas.circuit_breaker = Some(CircuitBreaker {
14701            max_failures: 5,
14702            window,
14703        });
14704        assert_eq!(
14705            s.validate().unwrap_err(),
14706            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
14707        );
14708    }
14709
14710    #[test]
14711    fn rejects_circuit_breaker_window_non_integer_millisecond() {
14712        // Peer of the `:timeout` non-integer-ms arm: a `Duration`
14713        // with non-integer-millisecond residue renders through the
14714        // shared codec as the truncated `"<n>ms"` form, parsing back
14715        // to a *different* `Duration` on the next round-trip.
14716        let mut s = three_member_spec();
14717        let window = Duration::from_micros(1500);
14718        s.politicas.circuit_breaker = Some(CircuitBreaker {
14719            max_failures: 5,
14720            window,
14721        });
14722        assert_eq!(
14723            s.validate().unwrap_err(),
14724            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
14725        );
14726    }
14727
14728    #[test]
14729    fn accepts_circuit_breaker_window_integer_millisecond_forms() {
14730        // The canonical-forms sweep on the breaker axis: every
14731        // integer-ms multiple the codec round-trips losslessly
14732        // passes the canonical gate.
14733        for window in [
14734            Duration::from_millis(1),
14735            Duration::from_millis(500),
14736            Duration::from_millis(1500),
14737            Duration::from_secs(30),
14738            Duration::from_secs(60),
14739            Duration::from_secs(3600),
14740        ] {
14741            let mut s = three_member_spec();
14742            s.politicas.circuit_breaker = Some(CircuitBreaker {
14743                max_failures: 5,
14744                window,
14745            });
14746            s.validate()
14747                .expect("integer-millisecond :circuit-breaker :window must validate");
14748        }
14749    }
14750
14751    #[test]
14752    fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
14753        // `Duration::ZERO` would pass the canonical-ms gate (the
14754        // sub-ns residue is zero) but must surface the narrower
14755        // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
14756        // remediation.
14757        let mut s = three_member_spec();
14758        s.politicas.circuit_breaker = Some(CircuitBreaker {
14759            max_failures: 5,
14760            window: Duration::ZERO,
14761        });
14762        assert_eq!(
14763            s.validate().unwrap_err(),
14764            AplicacaoError::PolicyBreakerZeroWindow
14765        );
14766    }
14767
14768    #[test]
14769    fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
14770        // Both axes invalid: max_failures == 0 *and* window is
14771        // sub-ms. The validate gate must fire on max_failures first
14772        // (matching the existing ordering pin
14773        // `rejects_circuit_breaker_zero_max_failures` enshrines), so
14774        // the existing diagnostic continues to lead with the simpler
14775        // "zero threshold" framing.
14776        let mut s = three_member_spec();
14777        s.politicas.circuit_breaker = Some(CircuitBreaker {
14778            max_failures: 0,
14779            window: Duration::from_micros(500),
14780        });
14781        assert_eq!(
14782            s.validate().unwrap_err(),
14783            AplicacaoError::PolicyBreakerZeroFailures
14784        );
14785    }
14786
14787    #[test]
14788    fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
14789        let mut s = three_member_spec();
14790        let window = Duration::from_nanos(60_000_000_001);
14791        s.politicas.circuit_breaker = Some(CircuitBreaker {
14792            max_failures: 5,
14793            window,
14794        });
14795        match s.validate().unwrap_err() {
14796            AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
14797                assert_eq!(w, window, "diagnostic must carry the offending Duration");
14798            }
14799            other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
14800        }
14801    }
14802
14803    #[test]
14804    fn rejects_circuit_breaker_window_above_cap() {
14805        // The fail-before-pass-after pin: 3601s = 1h + 1s is
14806        // structurally one canonical-tick past the
14807        // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
14808        // integer-millisecond magnitude the canonical-form arm above
14809        // accepts cleanly, that the codec round-trips losslessly as
14810        // `"3601s"`, and that silently passed validate on every
14811        // pre-gate codebase because the typed slot's only checks were
14812        // the zero-floor and canonical-form arms. The
14813        // rolling-window-to-lifetime-counter degeneration surfaces
14814        // only at the runtime substrate (Envoy's outlier_detection
14815        // interval, the future CiliumClusterwideEnvoyConfig overlay)
14816        // far from the source `caixa.lisp` with no field naming the
14817        // offending policy.
14818        let mut s = three_member_spec();
14819        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
14820        s.politicas.circuit_breaker = Some(CircuitBreaker {
14821            max_failures: 5,
14822            window,
14823        });
14824        assert_eq!(
14825            s.validate().unwrap_err(),
14826            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
14827        );
14828    }
14829
14830    #[test]
14831    fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
14832        // Boundary case: exactly 1ms past the cap (the granularity the
14833        // canonical-form gate enforces). Catches a future "strictly
14834        // less than" half-measure and pins the diagnostic to name the
14835        // offending `Duration` verbatim. Peer of
14836        // `rejects_policy_timeout_one_millisecond_above_cap` on the
14837        // sibling duration-typed `:politicas :timeout` top edge.
14838        let mut s = three_member_spec();
14839        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
14840        s.politicas.circuit_breaker = Some(CircuitBreaker {
14841            max_failures: 5,
14842            window,
14843        });
14844        assert_eq!(
14845            s.validate().unwrap_err(),
14846            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
14847        );
14848    }
14849
14850    #[test]
14851    fn rejects_circuit_breaker_window_far_above_cap() {
14852        // The "obvious authoring footgun" case: a `(:window "24h")` or
14853        // `(:window "86400s")` — values the canonical-form arm
14854        // accepts as integer-millisecond magnitudes, the codec
14855        // round-trips losslessly through serde, but the
14856        // rolling-window breaker contract cannot honor (a 24-hour
14857        // rolling failure window is operationally a lifetime counter).
14858        // Until this gate landed validate accepted it. Pin both common
14859        // above-cap values (24h, 7d) so a future relaxation that
14860        // drops the upper bound surfaces here.
14861        for window in [
14862            Duration::from_secs(86_400),    // 24h
14863            Duration::from_secs(604_800),   // 7d
14864            Duration::from_secs(1_000_000), // ~11.5 days
14865        ] {
14866            let mut s = three_member_spec();
14867            s.politicas.circuit_breaker = Some(CircuitBreaker {
14868                max_failures: 5,
14869                window,
14870            });
14871            assert_eq!(
14872                s.validate().unwrap_err(),
14873                AplicacaoError::PolicyBreakerWindowExceedsCap { window }
14874            );
14875        }
14876    }
14877
14878    #[test]
14879    fn accepts_circuit_breaker_window_at_cap() {
14880        // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
14881        // (1h) — must validate. The cap is inclusive on the top edge,
14882        // matching the [`POLICY_TIMEOUT_MAX`] /
14883        // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
14884        // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
14885        // sibling capped axes. Pin the boundary explicitly so a
14886        // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
14887        // instead of `>`) surfaces here as a test failure rather than
14888        // a silent contract narrowing.
14889        let mut s = three_member_spec();
14890        s.politicas.circuit_breaker = Some(CircuitBreaker {
14891            max_failures: 5,
14892            window: POLICY_BREAKER_WINDOW_MAX,
14893        });
14894        s.validate()
14895            .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
14896    }
14897
14898    #[test]
14899    fn accepts_circuit_breaker_window_typical_values() {
14900        // The documented production-playbook band positive-control
14901        // sweep — every value Hystrix / resilience4j / Istio / Envoy
14902        // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
14903        // through the long-tail failure-detection band (15m, 30m, 1h)
14904        // the cap accepts. Pin the inclusive validated set explicitly
14905        // so a future tightening of the ceiling surfaces here as a
14906        // deliberate test edit, not a silent contract narrowing.
14907        for window in [
14908            Duration::from_millis(1),
14909            Duration::from_millis(500),
14910            Duration::from_secs(1),
14911            Duration::from_secs(10), // Hystrix / Istio / Envoy default
14912            Duration::from_secs(30),
14913            Duration::from_secs(60),  // resilience4j typical
14914            Duration::from_secs(300), // AWS App Mesh typical
14915            Duration::from_secs(900),
14916            Duration::from_secs(1800),
14917            Duration::from_secs(3600), // exactly 1h, the cap
14918        ] {
14919            let mut s = three_member_spec();
14920            s.politicas.circuit_breaker = Some(CircuitBreaker {
14921                max_failures: 5,
14922                window,
14923            });
14924            s.validate()
14925                .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
14926        }
14927    }
14928
14929    #[test]
14930    fn circuit_breaker_zero_window_takes_precedence_over_cap() {
14931        // The cross-arm ordering pin: `Duration::ZERO` is structurally
14932        // outside both `>= 1ms` (zero-floor) and
14933        // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
14934        // diagnostic is the more self-locating one (it directly names
14935        // the omit-axis remediation), so the validate gate must fire
14936        // on zero first. Same shape every other zero-then-cap
14937        // ordering on this surface uses
14938        // ([`AplicacaoError::PolicyTimeoutZero`] then
14939        // [`AplicacaoError::PolicyTimeoutExceedsCap`];
14940        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
14941        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
14942        let mut s = three_member_spec();
14943        s.politicas.circuit_breaker = Some(CircuitBreaker {
14944            max_failures: 5,
14945            window: Duration::ZERO,
14946        });
14947        assert_eq!(
14948            s.validate().unwrap_err(),
14949            AplicacaoError::PolicyBreakerZeroWindow,
14950            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
14951        );
14952    }
14953
14954    #[test]
14955    fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
14956        // The cross-arm ordering pin: a `Duration` that is *both*
14957        // sub-millisecond (non-canonical-form) and structurally above
14958        // the cap surfaces the canonical-form diagnostic first,
14959        // because the round-trip-shape break is the more fundamental
14960        // issue (the value can't even round-trip through the codec, so
14961        // the cap diagnostic naming `1ms..=1h` would be misleading —
14962        // there's no integer-ms form of the offending value). Pin the
14963        // order so a future refactor that reorders the arms surfaces
14964        // here as a test failure rather than a silent diagnostic
14965        // regression. Peer of
14966        // `policy_timeout_canonical_takes_precedence_over_cap` on the
14967        // sibling duration-typed `:politicas :timeout` axis.
14968        let mut s = three_member_spec();
14969        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
14970        s.politicas.circuit_breaker = Some(CircuitBreaker {
14971            max_failures: 5,
14972            window,
14973        });
14974        assert_eq!(
14975            s.validate().unwrap_err(),
14976            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
14977            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
14978        );
14979    }
14980
14981    #[test]
14982    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
14983        // The cross-arm ordering pin between the two breaker axes: a
14984        // `CircuitBreaker` whose *both* `max_failures` is above its
14985        // cap *and* `window` is above its cap surfaces the
14986        // max-failures cap diagnostic first, because the validate
14987        // gate visits the failures arm before the window arm. Pin the
14988        // order so a future refactor that reorders the breaker arms
14989        // surfaces here.
14990        let mut s = three_member_spec();
14991        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
14992        s.politicas.circuit_breaker = Some(CircuitBreaker {
14993            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
14994            window,
14995        });
14996        assert_eq!(
14997            s.validate().unwrap_err(),
14998            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
14999                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
15000            },
15001            "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
15002        );
15003    }
15004
15005    #[test]
15006    fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
15007        // The diagnostic-shape pin: the offending `Duration` is
15008        // carried verbatim into the
15009        // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
15010        // the surfaced error message names the value the author wrote
15011        // (`":politicas :circuit-breaker :window (Duration { secs:
15012        // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
15013        // just the cap. Same self-locating diagnostic shape every
15014        // other typed-cap arm on this surface carries
15015        // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
15016        // offending `Duration` verbatim).
15017        let mut s = three_member_spec();
15018        let window = Duration::from_secs(7200); // 2h
15019        s.politicas.circuit_breaker = Some(CircuitBreaker {
15020            max_failures: 5,
15021            window,
15022        });
15023        let err = s.validate().unwrap_err();
15024        assert!(
15025            matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
15026            "got {err:?}"
15027        );
15028        let msg = err.to_string();
15029        assert!(
15030            msg.contains("7200"),
15031            ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
15032        );
15033    }
15034
15035    #[test]
15036    fn circuit_breaker_window_cap_pins_canonical_value() {
15037        // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
15038        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
15039        // shared duration codec emits as a clean canonical string
15040        // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
15041        // the sibling duration-typed `:politicas :timeout` axis (the
15042        // two duration-typed `:politicas` axes share a uniform top
15043        // edge). Pinning the literal value here surfaces a future
15044        // drift (a relaxation to 24h, a tightening to 5m) as a
15045        // deliberate test edit, not a silent contract narrowing. Same
15046        // shape every other typed-cap value pin on this surface uses
15047        // (`policy_timeout_cap_pins_canonical_value`).
15048        assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
15049        assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
15050        assert_eq!(
15051            POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
15052            "the two duration-typed `:politicas` caps share the same top edge"
15053        );
15054    }
15055
15056    #[test]
15057    fn circuit_breaker_window_cap_value_round_trips_through_codec() {
15058        // The codec round-trip property the cap arm preserves: the
15059        // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
15060        // through the shared duration codec — every value at the cap
15061        // renders to a clean canonical string (`"1h"`) and parses back
15062        // to the same `Duration`. Pin this so a future drift between
15063        // the cap constant and the codec's largest emitted unit
15064        // surfaces here. Same shape every other typed boundary pin on
15065        // this surface uses
15066        // (`policy_timeout_cap_value_round_trips_through_codec`).
15067        let policy = MeshPolicy {
15068            circuit_breaker: Some(CircuitBreaker {
15069                max_failures: 5,
15070                window: POLICY_BREAKER_WINDOW_MAX,
15071            }),
15072            ..Default::default()
15073        };
15074        let json = serde_json::to_string(&policy).unwrap();
15075        // The codec emits `"1h"` for the canonical 1-hour magnitude.
15076        assert!(
15077            json.contains("\"1h\""),
15078            "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
15079        );
15080        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
15081        assert_eq!(
15082            back.circuit_breaker.unwrap().window,
15083            POLICY_BREAKER_WINDOW_MAX
15084        );
15085    }
15086
15087    #[test]
15088    fn is_integer_millisecond_duration_predicate_tracks_codec() {
15089        // Pin the predicate's accepted set against the codec's
15090        // accepted set explicitly. The codec parses
15091        // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
15092        // accepted value is an integer-millisecond multiple — so the
15093        // predicate must accept exactly that set. Same shape every
15094        // other predicate-on-the-typed-slot helper carries
15095        // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
15096        // Read directly from the codec-owned predicate — the crate's
15097        // single source of truth every typed-`Duration` axis now routes
15098        // through via
15099        // [`crate::render::require_positive_canonical_bounded_duration`].
15100        use super::supervisor::duration_codec::is_integer_millisecond_duration;
15101        assert!(is_integer_millisecond_duration(Duration::ZERO));
15102        assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
15103        assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
15104        assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
15105        assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
15106        assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
15107        // Non-integer-millisecond residue: rejected.
15108        assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
15109        assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
15110        assert!(!is_integer_millisecond_duration(Duration::from_micros(
15111            1500
15112        )));
15113        assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
15114        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
15115            999_999
15116        )));
15117        // The 1-ns-past-1ms boundary: rejected (no longer a clean
15118        // integer-millisecond multiple).
15119        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
15120            1_000_001
15121        )));
15122    }
15123
15124    #[test]
15125    fn policy_timeout_validated_value_round_trips_through_codec() {
15126        // The structural property the canonical-ms gate enforces:
15127        // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
15128        // round-trips losslessly through the shared `duration_codec`
15129        // (serialize → string → deserialize → equal value). Pin this
15130        // end-to-end so a future change to either side (the validate
15131        // gate's accepted granularity, the codec's parse/render unit
15132        // set) that breaks the alignment surfaces here. The
15133        // previous-state shape (typed slot accepts arbitrary
15134        // `Duration`, codec only round-trips integer-ms) would fail
15135        // this test for any `Duration::from_micros(1500)` timeout —
15136        // the validate gate now forecloses that.
15137        for timeout in [
15138            Duration::from_millis(1),
15139            Duration::from_millis(1500),
15140            Duration::from_secs(30),
15141            Duration::from_secs(3600),
15142        ] {
15143            let mut s = three_member_spec();
15144            s.politicas.timeout = Some(timeout);
15145            s.validate().unwrap();
15146            let json = serde_json::to_string(&s.politicas).unwrap();
15147            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
15148            assert_eq!(
15149                back.timeout, s.politicas.timeout,
15150                "every validated :timeout must round-trip losslessly through the codec"
15151            );
15152        }
15153    }
15154
15155    #[test]
15156    fn circuit_breaker_window_validated_value_round_trips_through_codec() {
15157        // Peer of the `:timeout` round-trip property on the breaker
15158        // axis.
15159        for window in [
15160            Duration::from_millis(1),
15161            Duration::from_millis(1500),
15162            Duration::from_secs(30),
15163            Duration::from_secs(3600),
15164        ] {
15165            let mut s = three_member_spec();
15166            s.politicas.circuit_breaker = Some(CircuitBreaker {
15167                max_failures: 5,
15168                window,
15169            });
15170            s.validate().unwrap();
15171            let json = serde_json::to_string(&s.politicas).unwrap();
15172            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
15173            assert_eq!(
15174                back.circuit_breaker.unwrap().window,
15175                window,
15176                "every validated :circuit-breaker :window must round-trip losslessly"
15177            );
15178        }
15179    }
15180
15181    #[test]
15182    fn empty_politicas_validates() {
15183        // Omitting every policy axis is fine — defaults express "no
15184        // policy on this axis", not "policy = 0". The fixture's typical
15185        // values continue to validate; this test pins that
15186        // MeshPolicy::default() is a clean pass through validate().
15187        let mut s = three_member_spec();
15188        s.politicas = MeshPolicy::default();
15189        s.validate().unwrap();
15190    }
15191
15192    #[test]
15193    fn typical_politicas_validates_with_every_axis_set() {
15194        // The full §III.1 example block (timeout + retries + breaker +
15195        // mtls + rate-limit) — every axis nonzero — must remain a
15196        // clean pass.
15197        let mut s = three_member_spec();
15198        s.politicas = MeshPolicy {
15199            timeout: Some(Duration::from_secs(30)),
15200            retries: Some(3),
15201            circuit_breaker: Some(CircuitBreaker {
15202                max_failures: 5,
15203                window: Duration::from_secs(60),
15204            }),
15205            mtls_required: Some(true),
15206            rate_limit: Some(RateLimit {
15207                rate: 100,
15208                window: Duration::from_secs(1),
15209            }),
15210        };
15211        s.validate().unwrap();
15212    }
15213
15214    #[test]
15215    fn rejects_empty_cluster_name() {
15216        let mut s = three_member_spec();
15217        s.placement.clusters = vec!["rio".into(), "".into()];
15218        assert_eq!(
15219            s.validate().unwrap_err(),
15220            AplicacaoError::PlacementClusterEmpty
15221        );
15222    }
15223
15224    #[test]
15225    fn rejects_duplicate_cluster_names() {
15226        let mut s = three_member_spec();
15227        s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
15228        let err = s.validate().unwrap_err();
15229        assert!(
15230            matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
15231            "got {err:?}"
15232        );
15233    }
15234
15235    #[test]
15236    fn rejects_placement_cluster_with_uppercase() {
15237        // The canonical "I copied the cluster's display name verbatim"
15238        // typo — K8s context names are lowercase per DNS-1123 label
15239        // rule, but org docs often round-trip a TitleCase identifier
15240        // (`Rio`, `Mar-East`) from an ADR. Mirrors the
15241        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
15242        // on the peer name axis.
15243        let mut s = three_member_spec();
15244        s.placement.clusters = vec!["Rio".into(), "mar".into()];
15245        let err = s.validate().unwrap_err();
15246        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
15247            panic!("expected PlacementClusterInvalid, got other variant");
15248        };
15249        assert_eq!(cluster, "Rio");
15250        assert!(
15251            reason.contains("uppercase"),
15252            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
15253        );
15254        assert!(
15255            reason.contains("\"rio\""),
15256            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
15257        );
15258    }
15259
15260    #[test]
15261    fn rejects_placement_cluster_with_underscore() {
15262        // The canonical "I'm thinking of an env var / hostname slug"
15263        // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
15264        // schema. K8s context filtering on `my_cluster` silently misses
15265        // the cluster the author intended; the gate moves it to caixa-
15266        // build time. Same shape as `rejects_membro_caixa_with_underscore`
15267        // (3f9d7a0).
15268        let mut s = three_member_spec();
15269        s.placement.clusters = vec!["my_cluster".into()];
15270        let err = s.validate().unwrap_err();
15271        assert!(
15272            matches!(
15273                err,
15274                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
15275                    if cluster == "my_cluster" && reason.contains('_')
15276            ),
15277            "got {err:?}"
15278        );
15279    }
15280
15281    #[test]
15282    fn rejects_placement_cluster_with_dot() {
15283        // A `:placement :clusters` entry is a single DNS-1123 *label*,
15284        // not a subdomain — even though K8s context names sometimes
15285        // carry a dotted form via kubeconfig conventions, the strictest
15286        // floor among the use sites (DNS-1035 cluster.x-k8s.io
15287        // `metadata.name`, Cilium identity label values) wins. The "I
15288        // want to namespace my cluster names with `.`" intent is
15289        // expressed via `-` (`mar-east`).
15290        let mut s = three_member_spec();
15291        s.placement.clusters = vec!["team.rio".into()];
15292        let err = s.validate().unwrap_err();
15293        assert!(
15294            matches!(
15295                err,
15296                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
15297                    if cluster == "team.rio" && reason.contains('.')
15298            ),
15299            "got {err:?}"
15300        );
15301    }
15302
15303    #[test]
15304    fn rejects_placement_cluster_with_leading_hyphen() {
15305        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
15306        // with an alphanumeric. The K8s apiserver rejects `-rio`
15307        // outright; the rendered fan-out would emit a `metadata.name:
15308        // "-rio"` that fails admission far from the source caixa.lisp.
15309        let mut s = three_member_spec();
15310        s.placement.clusters = vec!["-rio".into()];
15311        let err = s.validate().unwrap_err();
15312        assert!(
15313            matches!(
15314                err,
15315                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
15316                    if cluster == "-rio" && reason.contains("start and end")
15317            ),
15318            "got {err:?}"
15319        );
15320    }
15321
15322    #[test]
15323    fn rejects_placement_cluster_with_trailing_hyphen() {
15324        // The symmetric arm of the boundary rule. Pin separately so
15325        // both ends are covered against a future relaxation that only
15326        // checks one boundary (parallel to
15327        // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
15328        let mut s = three_member_spec();
15329        s.placement.clusters = vec!["rio-".into()];
15330        let err = s.validate().unwrap_err();
15331        assert!(
15332            matches!(
15333                err,
15334                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
15335                    if cluster == "rio-"
15336            ),
15337            "got {err:?}"
15338        );
15339    }
15340
15341    #[test]
15342    fn rejects_placement_cluster_with_unicode() {
15343        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
15344        // before it reaches K8s. The byte-by-byte ASCII validity check
15345        // rejects multi-byte UTF-8 sequences by the first byte that
15346        // fails `[a-z0-9-]`.
15347        let mut s = three_member_spec();
15348        s.placement.clusters = vec!["rió".into()];
15349        let err = s.validate().unwrap_err();
15350        assert!(
15351            matches!(
15352                err,
15353                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
15354                    if cluster == "rió"
15355            ),
15356            "got {err:?}"
15357        );
15358    }
15359
15360    #[test]
15361    fn rejects_placement_cluster_with_whitespace() {
15362        // Whitespace is the canonical "I pasted from a sketch / doc"
15363        // footgun. The apiserver rejects every cluster `metadata.name`
15364        // value carrying whitespace.
15365        let mut s = three_member_spec();
15366        s.placement.clusters = vec!["rio cluster".into()];
15367        let err = s.validate().unwrap_err();
15368        assert!(
15369            matches!(
15370                err,
15371                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
15372                    if cluster == "rio cluster"
15373            ),
15374            "got {err:?}"
15375        );
15376    }
15377
15378    #[test]
15379    fn rejects_placement_cluster_too_long() {
15380        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
15381        // pin. The diagnostic names both the cap (63) and the actual
15382        // length so the author can shorten in one edit. Mirrors
15383        // `rejects_membro_caixa_too_long` (3f9d7a0).
15384        let mut s = three_member_spec();
15385        let too_long = "a".repeat(64);
15386        s.placement.clusters = vec![too_long.clone()];
15387        let err = s.validate().unwrap_err();
15388        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
15389            panic!("expected PlacementClusterInvalid");
15390        };
15391        assert_eq!(cluster, too_long);
15392        assert!(
15393            reason.contains("63") && reason.contains("64"),
15394            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
15395        );
15396    }
15397
15398    #[test]
15399    fn placement_cluster_max_length_validates() {
15400        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
15401        // future tightening (e.g. dropping to 62) surfaces here as a
15402        // regression, mirroring `membro_caixa_max_length_validates`
15403        // (3f9d7a0).
15404        let mut s = three_member_spec();
15405        s.placement.clusters = vec!["a".repeat(63)];
15406        s.validate().unwrap();
15407    }
15408
15409    #[test]
15410    fn accepts_canonical_placement_cluster_forms() {
15411        // The DNS-1123 label shapes a caixa author is realistically
15412        // going to write for cluster names: single-word lowercase
15413        // (`rio`), regional hyphen-joined (`mar-east`), single
15414        // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
15415        // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
15416        // Pin every leg so a future tightening that bans (e.g.) digit-
15417        // start identifiers surfaces here.
15418        for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
15419            let mut s = three_member_spec();
15420            s.placement.clusters = vec![form.into()];
15421            s.validate().unwrap_or_else(|e| {
15422                panic!("canonical cluster form {form:?} must validate, got {e:?}")
15423            });
15424        }
15425    }
15426
15427    #[test]
15428    fn placement_cluster_empty_takes_precedence_over_invalid() {
15429        // Order pin: the existing `PlacementClusterEmpty` diagnostic
15430        // (which doesn't try to parse) fires before the new
15431        // `PlacementClusterInvalid` parse-side diagnostic, so an empty
15432        // `:clusters` entry keeps its narrower error message — the new
15433        // gate would also reject `""`, but the empty-string arm is the
15434        // more self-locating diagnostic. Mirrors the
15435        // `membro_caixa_empty_takes_precedence_over_invalid` pin
15436        // (3f9d7a0).
15437        let mut s = three_member_spec();
15438        s.placement.clusters = vec!["rio".into(), "".into()];
15439        let err = s.validate().unwrap_err();
15440        assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
15441    }
15442
15443    #[test]
15444    fn placement_cluster_invalid_fires_before_duplicate_check() {
15445        // Order pin: a malformed-shape `:clusters` entry surfaces *its
15446        // own* diagnostic, even when a later entry would otherwise
15447        // collapse onto a duplicate name. The per-entry shape gate runs
15448        // inline before the duplicate-key insert, parallel to
15449        // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
15450        let mut s = three_member_spec();
15451        s.placement.clusters = vec!["Rio".into(), "rio".into()];
15452        let err = s.validate().unwrap_err();
15453        assert!(
15454            matches!(
15455                err,
15456                AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
15457            ),
15458            "got {err:?}"
15459        );
15460    }
15461
15462    #[test]
15463    fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
15464        // The diagnostic-shape pin: the error names the offending
15465        // `:clusters` value verbatim so the author can grep their
15466        // caixa.lisp without re-running the build, and carries a
15467        // non-empty `reason` naming the specific violation. Same shape
15468        // every typed-shape gate enshrines
15469        // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
15470        // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
15471        let mut s = three_member_spec();
15472        s.placement.clusters = vec!["BAD_CLUSTER".into()];
15473        let err = s.validate().unwrap_err();
15474        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
15475            panic!("expected PlacementClusterInvalid");
15476        };
15477        assert_eq!(cluster, "BAD_CLUSTER");
15478        assert!(
15479            !reason.is_empty(),
15480            "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
15481        );
15482    }
15483
15484    #[test]
15485    fn rejects_sharded_with_empty_clusters() {
15486        // §III.1: Sharded uses :clusters as the shard pool. An empty
15487        // pool means "shard across no clusters" — meaningless, same as
15488        // Replicated with no hosts.
15489        let mut s = three_member_spec();
15490        s.placement.estrategia = PlacementStrategy::Sharded;
15491        s.placement.shard_key = Some("$tenantId".into());
15492        s.placement.clusters = vec![];
15493        assert!(matches!(
15494            s.validate().unwrap_err(),
15495            AplicacaoError::PlacementWithoutClusters {
15496                estrategia: PlacementStrategy::Sharded
15497            }
15498        ));
15499    }
15500
15501    #[test]
15502    fn rejects_sharded_with_empty_shard_key() {
15503        let mut s = three_member_spec();
15504        s.placement.estrategia = PlacementStrategy::Sharded;
15505        s.placement.shard_key = Some("".into());
15506        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
15507    }
15508
15509    #[test]
15510    fn rejects_shard_key_under_replicated_strategy() {
15511        // The fail-before-pass-after pin: a `:placement (:estrategia
15512        // Replicated :shard-key "tenantId")` manifest carries the
15513        // hash-keyed-distribution slot on a strategy that never consumes
15514        // it. Before the gate the typed slot's value silently vanished
15515        // at the renderer layer (caixa-mesh emits `placement.shardKey`
15516        // verbatim regardless of strategy; the Akka-style cluster-
15517        // sharding reconciler keys off `estrategia == Sharded` and
15518        // ignores the slot otherwise), with no diagnostic. Lifting the
15519        // rejection to a build-time gate makes the
15520        // `shard_key.is_some() == matches!(estrategia, Sharded)`
15521        // partition a structural property of every validated
15522        // [`Placement`].
15523        let mut s = three_member_spec();
15524        // The fixture already uses Replicated; just add a shard-key.
15525        s.placement.shard_key = Some("$tenantId".into());
15526        let err = s.validate().unwrap_err();
15527        let AplicacaoError::ShardKeyOnNonSharded {
15528            estrategia,
15529            shard_key,
15530        } = err
15531        else {
15532            panic!("expected ShardKeyOnNonSharded, got {err:?}");
15533        };
15534        assert_eq!(estrategia, PlacementStrategy::Replicated);
15535        assert_eq!(shard_key, "$tenantId");
15536    }
15537
15538    #[test]
15539    fn rejects_shard_key_under_singlenode_strategy() {
15540        // Peer of the Replicated case above on the SingleNode arm: OTP
15541        // distributed-app takeover (one cluster runs at a time) has no
15542        // hash-keyed routing axis to consume `:shard-key` either, so
15543        // the rejection fires on both non-Sharded arms uniformly.
15544        let mut s = three_member_spec();
15545        s.placement.estrategia = PlacementStrategy::SingleNode;
15546        s.placement.shard_key = Some("$tenantId".into());
15547        let err = s.validate().unwrap_err();
15548        let AplicacaoError::ShardKeyOnNonSharded {
15549            estrategia,
15550            shard_key,
15551        } = err
15552        else {
15553            panic!("expected ShardKeyOnNonSharded, got {err:?}");
15554        };
15555        assert_eq!(estrategia, PlacementStrategy::SingleNode);
15556        assert_eq!(shard_key, "$tenantId");
15557    }
15558
15559    #[test]
15560    fn rejects_empty_shard_key_under_replicated_strategy() {
15561        // The `Some("")` case under non-Sharded is rejected by
15562        // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
15563        // fires before the empty-value gate), not
15564        // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
15565        // the `Sharded` arm). Pin the partition so a future reorder of
15566        // the validate_placement match arms doesn't silently swap which
15567        // diagnostic the author sees — both are author errors, but
15568        // ShardKeyOnNonSharded names which strategy is the actual fix
15569        // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
15570        // only says "pick a non-empty key".
15571        let mut s = three_member_spec();
15572        s.placement.shard_key = Some(String::new());
15573        let err = s.validate().unwrap_err();
15574        assert!(
15575            matches!(
15576                err,
15577                AplicacaoError::ShardKeyOnNonSharded {
15578                    estrategia: PlacementStrategy::Replicated,
15579                    ref shard_key,
15580                } if shard_key.is_empty()
15581            ),
15582            "got {err:?}"
15583        );
15584    }
15585
15586    #[test]
15587    fn replicated_without_shard_key_validates() {
15588        // The complement of the rejection: `:placement :estrategia
15589        // Replicated` with `:shard-key None` is the canonical happy
15590        // path on every existing fixture. Pin the no-shard-key case so
15591        // the new gate doesn't accidentally fire on `None`.
15592        let mut s = three_member_spec();
15593        assert!(matches!(
15594            s.placement.estrategia,
15595            PlacementStrategy::Replicated
15596        ));
15597        s.placement.shard_key = None;
15598        s.validate().unwrap();
15599    }
15600
15601    #[test]
15602    fn singlenode_without_shard_key_validates() {
15603        // Peer of the Replicated no-shard-key case on the SingleNode
15604        // arm — both non-Sharded strategies must validate cleanly when
15605        // the slot is omitted.
15606        let mut s = three_member_spec();
15607        s.placement.estrategia = PlacementStrategy::SingleNode;
15608        s.placement.shard_key = None;
15609        s.validate().unwrap();
15610    }
15611
15612    fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
15613        // Fixture builder for the `:placement :shard-key` shape gate
15614        // tests: a three-member Aplicacao on the `Sharded` strategy
15615        // with the supplied `:shard-key` slot. Co-locates the
15616        // arm-construction so every test below carries one line of
15617        // setup (the offending `:shard-key` value) and the assertion.
15618        let mut s = three_member_spec();
15619        s.placement.estrategia = PlacementStrategy::Sharded;
15620        s.placement.shard_key = Some(key.into());
15621        s
15622    }
15623
15624    #[test]
15625    fn rejects_shard_key_with_embedded_space() {
15626        // The canonical paste-from-aligned-doc footgun:
15627        // `:shard-key "$tenant Id"` — the Akka-style entity-id
15628        // extractor reads the slot as a single-token reference, and an
15629        // embedded space breaks the token boundary at the runtime
15630        // hash-extractor pass with no diagnostic naming the offending
15631        // entry.
15632        let s = sharded_spec_with_key("$tenant Id");
15633        let err = s.validate().unwrap_err();
15634        assert!(
15635            matches!(
15636                err,
15637                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
15638                    if shard_key == "$tenant Id" && reason.contains("space")
15639            ),
15640            "got {err:?}"
15641        );
15642    }
15643
15644    #[test]
15645    fn rejects_shard_key_with_leading_space() {
15646        // Leading-space arm of the embedded-whitespace footgun — the
15647        // paste-from-aligned-doc / paste-from-CSV-cell variant where
15648        // the leading column-padding leaked into the slot.
15649        let s = sharded_spec_with_key(" $tenantId");
15650        let err = s.validate().unwrap_err();
15651        assert!(
15652            matches!(
15653                err,
15654                AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
15655                    if shard_key == " $tenantId"
15656            ),
15657            "got {err:?}"
15658        );
15659    }
15660
15661    #[test]
15662    fn rejects_shard_key_with_trailing_newline() {
15663        // The canonical paste-from-shell-heredoc footgun — every
15664        // `<<EOF` heredoc terminator paste leaves a trailing newline
15665        // the YAML emitter then folds away inconsistently across
15666        // emitter implementations.
15667        let s = sharded_spec_with_key("$tenantId\n");
15668        let err = s.validate().unwrap_err();
15669        assert!(
15670            matches!(
15671                err,
15672                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
15673                    if shard_key == "$tenantId\n" && reason.contains("0x0a")
15674            ),
15675            "got {err:?}"
15676        );
15677    }
15678
15679    #[test]
15680    fn rejects_shard_key_with_embedded_tab() {
15681        // The paste-from-aligned-doc tab-stop variant — tabs land
15682        // alongside spaces in copy-paste from formatted columns.
15683        let s = sharded_spec_with_key("$tenant\tId");
15684        let err = s.validate().unwrap_err();
15685        assert!(
15686            matches!(
15687                err,
15688                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
15689                    if shard_key == "$tenant\tId" && reason.contains("tab")
15690            ),
15691            "got {err:?}"
15692        );
15693    }
15694
15695    #[test]
15696    fn rejects_shard_key_with_control_character() {
15697        // The paste-from-binary / paste-from-screen-cleared-terminal
15698        // footgun — an embedded `\x01` (SOH) byte that some YAML
15699        // emitters silently strip and others escape as ``,
15700        // breaking round-trip across emitter implementations.
15701        let s = sharded_spec_with_key("$tenant\u{0001}Id");
15702        let err = s.validate().unwrap_err();
15703        assert!(
15704            matches!(
15705                err,
15706                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
15707                    if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
15708            ),
15709            "got {err:?}"
15710        );
15711    }
15712
15713    #[test]
15714    fn rejects_shard_key_with_non_ascii() {
15715        // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
15716        // footgun — non-ASCII bytes normalize differently between the
15717        // caixa-mesh-side YAML emitter and the in-cluster reconciler's
15718        // YAML parser, the same entity ID can silently map to two
15719        // distinct shards on a re-render.
15720        let s = sharded_spec_with_key("$tenàntId");
15721        let err = s.validate().unwrap_err();
15722        assert!(
15723            matches!(
15724                err,
15725                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
15726                    if shard_key == "$tenàntId" && reason.contains("non-ASCII")
15727            ),
15728            "got {err:?}"
15729        );
15730    }
15731
15732    #[test]
15733    fn rejects_shard_key_too_long() {
15734        // Length cap pin: 64 bytes — one byte over the
15735        // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
15736        // here is a paste-from-doc multi-line blob landing in
15737        // `:shard-key` instead of a single-token extractor expression.
15738        let too_long = "a".repeat(64);
15739        let s = sharded_spec_with_key(&too_long);
15740        let err = s.validate().unwrap_err();
15741        let AplicacaoError::ShardKeyInvalid {
15742            ref shard_key,
15743            ref reason,
15744        } = err
15745        else {
15746            panic!("expected ShardKeyInvalid, got {err:?}");
15747        };
15748        assert_eq!(shard_key, &too_long);
15749        assert!(
15750            reason.contains("63") && reason.contains("64"),
15751            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
15752        );
15753    }
15754
15755    #[test]
15756    fn shard_key_max_length_validates() {
15757        // Boundary pin: 63 bytes exactly — the
15758        // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
15759        // dropping to 62) surfaces here as a regression, mirroring
15760        // `placement_cluster_max_length_validates` /
15761        // `placement_affinity_max_length_validates` on the peer
15762        // identifier-shaped slots.
15763        let s = sharded_spec_with_key(&"a".repeat(63));
15764        s.validate().unwrap();
15765    }
15766
15767    #[test]
15768    fn accepts_canonical_shard_key_forms() {
15769        // The Akka-style entity-id extractor shapes a caixa author is
15770        // realistically going to write — pin every leg so a future
15771        // tightening that bans (e.g.) the `${...}` interpolation
15772        // variant or the `metadata.<field>` JSONPath form surfaces
15773        // here as a regression. The canonical forms span:
15774        //
15775        //   - bare property name (`tenantId`, `customerId`)
15776        //   - Akka `ExtractEntityId` placeholder (`$tenantId`)
15777        //   - JSONPath-style nested reference (`metadata.tenantId`,
15778        //     `$.user.id`)
15779        //   - interpolation-style template (`${tenant}`)
15780        //   - snake_case property name (`customer_id`)
15781        //   - kebab-case property name (`customer-id` — accepted
15782        //     because the slot is a printable-ASCII single-token
15783        //     reference, not a DNS-1123 label like
15784        //     `:placement :affinity` / `:clusters`)
15785        //   - single character (`a`, `$` — boundary)
15786        for form in [
15787            "tenantId",
15788            "customerId",
15789            "$tenantId",
15790            "metadata.tenantId",
15791            "$.user.id",
15792            "${tenant}",
15793            "customer_id",
15794            "customer-id",
15795            "a",
15796            "$",
15797        ] {
15798            let s = sharded_spec_with_key(form);
15799            s.validate().unwrap_or_else(|e| {
15800                panic!("canonical shard-key form {form:?} must validate, got {e:?}")
15801            });
15802        }
15803    }
15804
15805    #[test]
15806    fn shard_key_empty_takes_precedence_over_invalid() {
15807        // Order pin: the existing `ShardedKeyEmpty` diagnostic
15808        // (reserved for the `Sharded` `Some("")` arm) fires before the
15809        // new `ShardKeyInvalid` parse-side diagnostic, so an empty
15810        // `:shard-key` keeps its narrower error message — the new gate
15811        // would also reject `""` defensively, but the empty-string arm
15812        // is the more self-locating diagnostic. Mirrors the
15813        // `placement_cluster_empty_takes_precedence_over_invalid` pin
15814        // on the peer identifier-shaped slot.
15815        let s = sharded_spec_with_key("");
15816        let err = s.validate().unwrap_err();
15817        assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
15818    }
15819
15820    #[test]
15821    fn shard_key_invalid_diagnostic_carries_offending_value() {
15822        // The diagnostic-shape pin: the error names the offending
15823        // `:shard-key` value verbatim so the author can grep their
15824        // caixa.lisp without re-running the build, and carries a
15825        // parser-shaped `reason:` naming the specific violation —
15826        // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
15827        // on the peer identifier-shaped slot.
15828        let s = sharded_spec_with_key("$tenant Id");
15829        let err = s.validate().unwrap_err();
15830        let AplicacaoError::ShardKeyInvalid {
15831            ref shard_key,
15832            ref reason,
15833        } = err
15834        else {
15835            panic!("expected ShardKeyInvalid, got {err:?}");
15836        };
15837        assert_eq!(shard_key, "$tenant Id");
15838        assert!(
15839            !reason.is_empty(),
15840            "reason must name the specific violation, got empty string"
15841        );
15842    }
15843
15844    #[test]
15845    fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
15846        // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
15847        // `:shard-key` carried on non-Sharded strategies) fires before
15848        // the shape gate, so a malformed `:shard-key` carried on (e.g.)
15849        // a `Replicated` strategy surfaces the more self-locating
15850        // strategy-mismatch diagnostic (naming the actual fix — drop
15851        // the slot, or switch to Sharded) rather than the shape
15852        // diagnostic. The strategy-mismatch arm is the more actionable
15853        // diagnostic: a malformed shard-key on Replicated is "you
15854        // shouldn't have a :shard-key here at all", not "your
15855        // :shard-key value is malformed".
15856        let mut s = three_member_spec();
15857        // Replicated is the default fixture strategy.
15858        s.placement.shard_key = Some("$tenant Id".into());
15859        let err = s.validate().unwrap_err();
15860        assert!(
15861            matches!(
15862                err,
15863                AplicacaoError::ShardKeyOnNonSharded {
15864                    estrategia: PlacementStrategy::Replicated,
15865                    ..
15866                }
15867            ),
15868            "got {err:?}"
15869        );
15870    }
15871
15872    #[test]
15873    fn rejects_empty_affinity_hint() {
15874        let mut s = three_member_spec();
15875        s.placement.affinity = Some("".into());
15876        assert_eq!(
15877            s.validate().unwrap_err(),
15878            AplicacaoError::PlacementAffinityEmpty
15879        );
15880    }
15881
15882    #[test]
15883    fn placement_without_affinity_validates() {
15884        // Omitting :affinity is fine — the placement engine falls back
15885        // to the default heuristic. Pin the no-hint case so the
15886        // affinity-empty rejection doesn't accidentally fire on `None`.
15887        let mut s = three_member_spec();
15888        s.placement.affinity = None;
15889        s.validate().unwrap();
15890    }
15891
15892    #[test]
15893    fn rejects_placement_affinity_with_uppercase() {
15894        // The canonical "I copied the ADR's display name verbatim" typo
15895        // — placement hints land verbatim in K8s label-selector
15896        // territory, where the apiserver enforces the DNS-1123 label
15897        // rule (lowercase-only) on every identity-keyed admission axis.
15898        // Mirrors `rejects_placement_cluster_with_uppercase` on the
15899        // sibling slot.
15900        let mut s = three_member_spec();
15901        s.placement.affinity = Some("DataLocality".into());
15902        let err = s.validate().unwrap_err();
15903        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
15904            panic!("expected PlacementAffinityInvalid, got other variant");
15905        };
15906        assert_eq!(affinity, "DataLocality");
15907        assert!(
15908            reason.contains("uppercase"),
15909            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
15910        );
15911        assert!(
15912            reason.contains("\"datalocality\""),
15913            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
15914        );
15915    }
15916
15917    #[test]
15918    fn rejects_placement_affinity_with_underscore() {
15919        // The canonical "I'm thinking of an env var / Python identifier"
15920        // leak — `_` is forbidden by every DNS-1123 label schema. Same
15921        // shape as `rejects_placement_cluster_with_underscore` on the
15922        // sibling slot.
15923        let mut s = three_member_spec();
15924        s.placement.affinity = Some("data_locality".into());
15925        let err = s.validate().unwrap_err();
15926        assert!(
15927            matches!(
15928                err,
15929                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
15930                    if affinity == "data_locality" && reason.contains('_')
15931            ),
15932            "got {err:?}"
15933        );
15934    }
15935
15936    #[test]
15937    fn rejects_placement_affinity_with_dot() {
15938        // A `:placement :affinity` value is a single DNS-1123 *label*
15939        // (it lands as a K8s label value selector key), not a subdomain.
15940        // The "I want to namespace my hint with `.`" intent is expressed
15941        // via `-` (`data-locality-east`).
15942        let mut s = three_member_spec();
15943        s.placement.affinity = Some("data.locality".into());
15944        let err = s.validate().unwrap_err();
15945        assert!(
15946            matches!(
15947                err,
15948                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
15949                    if affinity == "data.locality" && reason.contains('.')
15950            ),
15951            "got {err:?}"
15952        );
15953    }
15954
15955    #[test]
15956    fn rejects_placement_affinity_with_unicode() {
15957        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
15958        // before it reaches K8s. The byte-by-byte ASCII validity check
15959        // rejects multi-byte UTF-8 sequences by the first byte that
15960        // fails `[a-z0-9-]`.
15961        let mut s = three_member_spec();
15962        s.placement.affinity = Some("data-localité".into());
15963        let err = s.validate().unwrap_err();
15964        assert!(
15965            matches!(
15966                err,
15967                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
15968                    if affinity == "data-localité"
15969            ),
15970            "got {err:?}"
15971        );
15972    }
15973
15974    #[test]
15975    fn rejects_placement_affinity_with_leading_hyphen() {
15976        // DNS-1123 boundary rule: labels must start with an
15977        // alphanumeric. Pin separately from the trailing-hyphen arm so
15978        // a future relaxation that only checks one boundary surfaces
15979        // here as a regression (parallel to
15980        // `rejects_placement_cluster_with_leading_hyphen`).
15981        let mut s = three_member_spec();
15982        s.placement.affinity = Some("-data-locality".into());
15983        let err = s.validate().unwrap_err();
15984        assert!(
15985            matches!(
15986                err,
15987                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
15988                    if affinity == "-data-locality" && reason.contains("start and end")
15989            ),
15990            "got {err:?}"
15991        );
15992    }
15993
15994    #[test]
15995    fn rejects_placement_affinity_with_trailing_hyphen() {
15996        // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
15997        // ends are covered against a future relaxation.
15998        let mut s = three_member_spec();
15999        s.placement.affinity = Some("data-locality-".into());
16000        let err = s.validate().unwrap_err();
16001        assert!(
16002            matches!(
16003                err,
16004                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
16005                    if affinity == "data-locality-"
16006            ),
16007            "got {err:?}"
16008        );
16009    }
16010
16011    #[test]
16012    fn rejects_placement_affinity_with_whitespace() {
16013        // Whitespace is the canonical "I pasted from a sketch / doc"
16014        // footgun. The apiserver rejects every label-selector value
16015        // carrying whitespace.
16016        let mut s = three_member_spec();
16017        s.placement.affinity = Some("data locality".into());
16018        let err = s.validate().unwrap_err();
16019        assert!(
16020            matches!(
16021                err,
16022                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
16023                    if affinity == "data locality"
16024            ),
16025            "got {err:?}"
16026        );
16027    }
16028
16029    #[test]
16030    fn rejects_placement_affinity_too_long() {
16031        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
16032        // pin. The diagnostic names both the cap (63) and the actual
16033        // length so the author can shorten in one edit. Mirrors
16034        // `rejects_placement_cluster_too_long`.
16035        let mut s = three_member_spec();
16036        let too_long = "a".repeat(64);
16037        s.placement.affinity = Some(too_long.clone());
16038        let err = s.validate().unwrap_err();
16039        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
16040            panic!("expected PlacementAffinityInvalid");
16041        };
16042        assert_eq!(affinity, too_long);
16043        assert!(
16044            reason.contains("63") && reason.contains("64"),
16045            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
16046        );
16047    }
16048
16049    #[test]
16050    fn placement_affinity_max_length_validates() {
16051        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
16052        // future tightening (e.g. dropping to 62) surfaces here as a
16053        // regression, mirroring `placement_cluster_max_length_validates`.
16054        let mut s = three_member_spec();
16055        s.placement.affinity = Some("a".repeat(63));
16056        s.validate().unwrap();
16057    }
16058
16059    #[test]
16060    fn accepts_canonical_placement_affinity_forms() {
16061        // The DNS-1123 label shapes a caixa author is realistically
16062        // going to write for placement hints: the M3 canonical examples
16063        // (`data-locality`, `low-latency`, `anti-affinity`), the
16064        // single-token form (`affinity`), the single-character boundary
16065        // (`a`), the digit-start (DNS-1123 allows this, unlike
16066        // DNS-1035), and a regional-suffixed form. Pin every leg so a
16067        // future tightening that bans (e.g.) digit-start identifiers
16068        // surfaces here.
16069        for form in [
16070            "data-locality",
16071            "low-latency",
16072            "anti-affinity",
16073            "affinity",
16074            "a",
16075            "3-tier",
16076            "locality-east",
16077        ] {
16078            let mut s = three_member_spec();
16079            s.placement.affinity = Some(form.into());
16080            s.validate().unwrap_or_else(|e| {
16081                panic!("canonical affinity form {form:?} must validate, got {e:?}")
16082            });
16083        }
16084    }
16085
16086    #[test]
16087    fn placement_affinity_empty_takes_precedence_over_invalid() {
16088        // Order pin: the existing `PlacementAffinityEmpty` diagnostic
16089        // (which doesn't try to parse) fires before the new
16090        // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
16091        // `:affinity` keeps its narrower error message — the new gate
16092        // would also reject `""`, but the empty-string arm is the more
16093        // self-locating diagnostic. Mirrors the
16094        // `placement_cluster_empty_takes_precedence_over_invalid` pin.
16095        let mut s = three_member_spec();
16096        s.placement.affinity = Some(String::new());
16097        let err = s.validate().unwrap_err();
16098        assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
16099    }
16100
16101    #[test]
16102    fn placement_affinity_invalid_diagnostic_carries_offending_value() {
16103        // The diagnostic shape pin: every rejection carries the offending
16104        // `affinity:` verbatim plus a parser-shaped `reason:` so the
16105        // author can grep their caixa.lisp for `:affinity "<hint>"` and
16106        // fix it in one edit. Mirrors the
16107        // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
16108        // pin on the sibling slot.
16109        let mut s = three_member_spec();
16110        s.placement.affinity = Some("Data_Locality".into());
16111        let err = s.validate().unwrap_err();
16112        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
16113            panic!("expected PlacementAffinityInvalid");
16114        };
16115        assert_eq!(affinity, "Data_Locality");
16116        assert!(
16117            !reason.is_empty(),
16118            "diagnostic reason must not be empty (got: {reason:?})"
16119        );
16120    }
16121
16122    #[test]
16123    fn singlenode_with_takeover_candidates_validates() {
16124        // OTP distributed-application convention (MESH-COMPOSITION
16125        // §II.1): SingleNode runs on one cluster at a time but the
16126        // :clusters list enumerates the takeover candidates. Multiple
16127        // entries are not a contradiction — they are the failover pool.
16128        let mut s = three_member_spec();
16129        s.placement.estrategia = PlacementStrategy::SingleNode;
16130        s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
16131        s.validate().unwrap();
16132    }
16133
16134    // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
16135
16136    #[test]
16137    fn mesh_policy_default_is_empty() {
16138        // The Default impl carries None on every axis — the typed
16139        // analog of an unset `:politicas (())` slot. Renderers that
16140        // overlay the policy onto a cluster artifact key off this
16141        // predicate to skip the slot entirely; pinning so a future
16142        // axis added to MeshPolicy can't silently break the contract
16143        // (a new field whose Default is non-None would flip is_empty
16144        // to false on every existing caixa, surfacing here).
16145        assert!(MeshPolicy::default().is_empty());
16146    }
16147
16148    #[test]
16149    fn mesh_policy_with_only_timeout_is_not_empty() {
16150        let p = MeshPolicy {
16151            timeout: Some(Duration::from_secs(30)),
16152            ..Default::default()
16153        };
16154        assert!(!p.is_empty());
16155    }
16156
16157    #[test]
16158    fn mesh_policy_with_only_retries_is_not_empty() {
16159        let p = MeshPolicy {
16160            retries: Some(3),
16161            ..Default::default()
16162        };
16163        assert!(!p.is_empty());
16164    }
16165
16166    #[test]
16167    fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
16168        let p = MeshPolicy {
16169            circuit_breaker: Some(CircuitBreaker {
16170                max_failures: 5,
16171                window: Duration::from_secs(60),
16172            }),
16173            ..Default::default()
16174        };
16175        assert!(!p.is_empty());
16176    }
16177
16178    #[test]
16179    fn mesh_policy_with_only_mtls_required_is_not_empty() {
16180        // Even `mtls_required: Some(false)` (an explicit opt-out) is
16181        // not empty — the author *named* the axis, the renderer needs
16182        // to honor that vs. fall back to the cluster default.
16183        let p = MeshPolicy {
16184            mtls_required: Some(false),
16185            ..Default::default()
16186        };
16187        assert!(!p.is_empty());
16188    }
16189
16190    #[test]
16191    fn mesh_policy_with_only_rate_limit_is_not_empty() {
16192        let p = MeshPolicy {
16193            rate_limit: Some(RateLimit {
16194                rate: 100,
16195                window: Duration::from_secs(1),
16196            }),
16197            ..Default::default()
16198        };
16199        assert!(!p.is_empty());
16200    }
16201
16202    #[test]
16203    fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
16204        // The three-member happy-path fixture sets timeout + retries +
16205        // mtls_required — every populated axis must read non-empty.
16206        // Pin the round-trip so the M3.x per-:politicas emitter (the
16207        // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
16208        // on is_empty() to decide whether to emit at all without
16209        // re-deriving the contract from inline field probes.
16210        assert!(!three_member_spec().politicas.is_empty());
16211    }
16212
16213    // ── shared duration codec: cross-slot integer-magnitude gate ──
16214    //
16215    // The integer-magnitude discipline applied to
16216    // `supervisor::duration_codec::parse` lifts onto every typed slot
16217    // that routes through the shared codec — `MeshPolicy::timeout`
16218    // (`:politicas :timeout`) and `CircuitBreaker::window`
16219    // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
16220    // These cross-slot tests pin that the gate fires at the serde
16221    // layer for both typed slots, not just for the supervisor side.
16222
16223    #[test]
16224    fn policy_timeout_serde_rejects_fractional_seconds() {
16225        // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
16226        // so the shared codec's integer-magnitude gate applies on
16227        // deserialize. `"1.5s"` previously parsed to 1500ms and round-
16228        // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
16229        // deserialize with the canonical-form diagnostic naming the
16230        // offending `"1.5"` and the remediation `"1500ms"`.
16231        let payload = r#"{"timeout":"1.5s"}"#;
16232        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16233        let msg = err.to_string();
16234        assert!(
16235            msg.contains("not a non-negative integer"),
16236            "expected integer-magnitude diagnostic in {msg:?}"
16237        );
16238        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
16239        assert!(
16240            msg.contains("\"1500ms\""),
16241            "missing canonical-form remediation in {msg:?}"
16242        );
16243    }
16244
16245    #[test]
16246    fn policy_timeout_serde_rejects_leading_plus_sign() {
16247        // Pin the leading-`+` arm cross-slot — the prior f64 parser
16248        // accepted `"+30s"` silently and round-tripped to `"30s"`.
16249        let payload = r#"{"timeout":"+30s"}"#;
16250        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16251        let msg = err.to_string();
16252        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
16253    }
16254
16255    #[test]
16256    fn circuit_breaker_window_serde_rejects_fractional_minutes() {
16257        // `CircuitBreaker::window` uses `with =
16258        // "supervisor::duration_codec_required"` (the required-Duration
16259        // variant that delegates to the same shared parser). `"0.5m"`
16260        // parsed to 30s and round-tripped to `"30s"` on next emit —
16261        // DRIFT closed.
16262        let payload = format!(
16263            r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
16264            max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
16265            window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
16266        );
16267        let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
16268        let msg = err.to_string();
16269        assert!(
16270            msg.contains("not a non-negative integer"),
16271            "expected integer-magnitude diagnostic in {msg:?}"
16272        );
16273        assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
16274        assert!(
16275            msg.contains("\"30s\""),
16276            "missing canonical-form remediation in {msg:?}"
16277        );
16278    }
16279
16280    #[test]
16281    fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
16282        // Pin the happy-path on the cross-slot side: every canonical
16283        // author shape `render` ever emits parses cleanly through the
16284        // shared codec on the `CircuitBreaker` slot. The
16285        // codec's accepted set (post-gate) is exactly its emitted set
16286        // for the integer-magnitude class.
16287        for window_lit in ["30s", "500ms", "2m", "1h"] {
16288            let payload = format!(
16289                r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
16290                max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
16291                window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
16292            );
16293            let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
16294                panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
16295            });
16296            assert_eq!(cb.max_failures, 5);
16297        }
16298    }
16299
16300    // ── rate_limit_codec: integer-magnitude gate ──
16301    //
16302    // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
16303    // / 737a676 / d53c922 trajectory landed on every typed-duration /
16304    // typed-byte-size codec in caixa-core lifts onto the fifth typed
16305    // codec — `rate_limit_codec` — through the digit-only magnitude
16306    // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
16307    // These tests pin the gate at the serde layer for `:politicas
16308    // :rate-limit` (the only typed slot the codec backs), and at the
16309    // codec-internal `parse` layer for the canonical positive cases.
16310
16311    #[test]
16312    fn rate_limit_serde_rejects_fractional_rate() {
16313        // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
16314        // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
16315        // wording, which didn't name the canonical-form remediation or
16316        // the round-trip drift the next emit would produce. Now refused
16317        // at deserialize with the canonical-form diagnostic naming the
16318        // offending `"1.5"` magnitude and the round-trip drift wording.
16319        let payload = r#"{"rateLimit":"1.5/s"}"#;
16320        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16321        let msg = err.to_string();
16322        assert!(
16323            msg.contains("not a non-negative integer"),
16324            "expected integer-magnitude diagnostic in {msg:?}"
16325        );
16326        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
16327        assert!(
16328            msg.contains("THEORY.md"),
16329            "missing render-determinism contract citation in {msg:?}"
16330        );
16331    }
16332
16333    #[test]
16334    fn rate_limit_serde_rejects_leading_plus_sign() {
16335        // `u32::from_str("+100")` returns `Ok(100)` (Rust's
16336        // permissive-`+` parse), so `"+100/s"` silently parsed to
16337        // `RateLimit { 100, 1s }` and round-tripped through `render` to
16338        // `"100/s"` — a *different* canonical string on the next emit,
16339        // breaking the THEORY.md Part V render-determinism contract
16340        // exactly the way the peer duration codecs' `"+30s"` case did.
16341        // This is the load-bearing class the digit-only gate closes
16342        // beyond what `u32::from_str`'s strictness covers on its own.
16343        let payload = r#"{"rateLimit":"+100/s"}"#;
16344        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16345        let msg = err.to_string();
16346        assert!(
16347            msg.contains("not a non-negative integer"),
16348            "expected integer-magnitude diagnostic in {msg:?}"
16349        );
16350        assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
16351    }
16352
16353    #[test]
16354    fn rate_limit_serde_rejects_leading_minus_sign() {
16355        // The signed-negative arm: `"-1/s"` lands on the
16356        // non-canonical-but-numeric branch via the `i64` fallback (the
16357        // `f64` parse also succeeds), surfacing the canonical-form
16358        // diagnostic. Replaces the prior value-laundered "not a u32"
16359        // wording with the unified diagnostic across signs.
16360        let payload = r#"{"rateLimit":"-1/s"}"#;
16361        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16362        let msg = err.to_string();
16363        assert!(
16364            msg.contains("not a non-negative integer"),
16365            "expected integer-magnitude diagnostic in {msg:?}"
16366        );
16367        assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
16368    }
16369
16370    #[test]
16371    fn rate_limit_serde_rejects_decimal_shaped_integer() {
16372        // `"100.0/s"` is integer-valued numerically but not in the
16373        // codec's accepted set — `render` emits `"100/s"`, so the
16374        // round-trip would drift. Lifted to the canonical-form
16375        // diagnostic peer with the duration codec's `"1.0s"` case
16376        // (1c55a2a).
16377        let payload = r#"{"rateLimit":"100.0/s"}"#;
16378        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16379        let msg = err.to_string();
16380        assert!(
16381            msg.contains("not a non-negative integer"),
16382            "expected integer-magnitude diagnostic in {msg:?}"
16383        );
16384        assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
16385    }
16386
16387    #[test]
16388    fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
16389        // Non-numeric, non-digit-only input lands on the existing
16390        // narrower `"not a u32"` arm (preserved for diagnostic-shape
16391        // stability on the parser-shape footgun case). Pin this so a
16392        // future relaxation of the numeric-fallback predicate doesn't
16393        // silently collapse garbage onto the canonical-form arm — same
16394        // partition the peer duration codecs draw between
16395        // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
16396        let payload = r#"{"rateLimit":"abc/s"}"#;
16397        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16398        let msg = err.to_string();
16399        assert!(
16400            msg.contains("not a u32"),
16401            "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
16402        );
16403        assert!(
16404            !msg.contains("not a non-negative integer"),
16405            "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
16406        );
16407    }
16408
16409    #[test]
16410    fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
16411        // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
16412        // u32's range. The digit-only gate passes; `u32::from_str`
16413        // fails on overflow. Surface that with the overflow-shaped
16414        // diagnostic naming the offending magnitude verbatim, peer
16415        // with `supervisor::duration_codec`'s overflow arm. Pinning
16416        // the wording so a future refactor doesn't silently collapse
16417        // overflow onto the canonical-form arm.
16418        let payload = r#"{"rateLimit":"4294967296/s"}"#;
16419        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16420        let msg = err.to_string();
16421        assert!(
16422            msg.contains("overflows u32"),
16423            "expected overflow diagnostic in {msg:?}"
16424        );
16425        assert!(
16426            msg.contains("\"4294967296\""),
16427            "missing offending magnitude in {msg:?}"
16428        );
16429    }
16430
16431    #[test]
16432    fn rate_limit_serde_rejects_leading_zero_magnitude() {
16433        // `"0100/s"` is digit-only, so the existing
16434        // non-digit-only / sign / fractional arm doesn't catch it —
16435        // `u32::from_str("0100")` returns `Ok(100)`, so before this
16436        // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
16437        // round-tripped through `render` to `"100/s"` — a *different*
16438        // canonical string on the next emit, breaking the THEORY.md
16439        // Part V render-determinism contract exactly the way the
16440        // peer `"+100/s"` case did before the leading-`+` arm landed.
16441        // This is the load-bearing class the leading-zero gate closes
16442        // beyond what the existing digit-only / sign / fractional
16443        // gates cover, and the peer arm to the leading-`+` test
16444        // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
16445        // canonical-form-drift axis.
16446        let payload = r#"{"rateLimit":"0100/s"}"#;
16447        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16448        let msg = err.to_string();
16449        assert!(
16450            msg.contains("non-canonical leading zero"),
16451            "expected leading-zero diagnostic in {msg:?}"
16452        );
16453        assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
16454        assert!(
16455            msg.contains("THEORY.md"),
16456            "missing render-determinism contract citation in {msg:?}"
16457        );
16458    }
16459
16460    #[test]
16461    fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
16462        // `"00/s"` is the degenerate leading-zero case — every byte
16463        // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
16464        // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
16465        // a *different* canonical string, same render-determinism
16466        // violation. The single-byte `"0/s"` itself is in the
16467        // accepted set (round-trips losslessly through `render`,
16468        // refused downstream by `PolicyRateLimitZero`); the
16469        // multi-byte `"00/s"` is not. Pins the boundary between the
16470        // accepted single-`0` and the rejected leading-zero class.
16471        let payload = r#"{"rateLimit":"00/s"}"#;
16472        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16473        let msg = err.to_string();
16474        assert!(
16475            msg.contains("non-canonical leading zero"),
16476            "expected leading-zero diagnostic in {msg:?}"
16477        );
16478        assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
16479    }
16480
16481    #[test]
16482    fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
16483        // Cross-window pin — the gate is window-agnostic; the
16484        // leading-zero class is a property of the magnitude, not the
16485        // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
16486        // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
16487        // single-window coverage extended across the three canonical
16488        // windows the codec accepts.
16489        let payload = r#"{"rateLimit":"007/h"}"#;
16490        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16491        let msg = err.to_string();
16492        assert!(
16493            msg.contains("non-canonical leading zero"),
16494            "expected leading-zero diagnostic in {msg:?}"
16495        );
16496        assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
16497    }
16498
16499    #[test]
16500    fn rate_limit_serde_rejects_leading_whitespace() {
16501        // `" 100/s"` — the canonical paste-from-aligned-doc /
16502        // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
16503        // the top-level `s.trim()` silently ate the leading space and
16504        // parsed the value to `RateLimit { 100, 1s }`, which then
16505        // round-tripped through `render` to `"100/s"` (a *different*
16506        // canonical string on the next emit) — the exact
16507        // canonical-form-drift class the leading-`+` / leading-zero
16508        // arms already close, extended to the whitespace byte class.
16509        let payload = r#"{"rateLimit":" 100/s"}"#;
16510        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16511        let msg = err.to_string();
16512        assert!(
16513            msg.contains("contains whitespace byte"),
16514            "expected whitespace diagnostic in {msg:?}"
16515        );
16516        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
16517        assert!(
16518            msg.contains("THEORY.md"),
16519            "missing render-determinism contract citation in {msg:?}"
16520        );
16521    }
16522
16523    #[test]
16524    fn rate_limit_serde_rejects_trailing_whitespace() {
16525        // `"100/s "` — the canonical shell-history / trailing-space
16526        // paste footgun. Before this gate the top-level `s.trim()`
16527        // silently ate the trailing space and parsed to
16528        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
16529        // next emit — same canonical-form drift as the leading-space
16530        // sibling, closed on the same whitespace-byte arm.
16531        let payload = r#"{"rateLimit":"100/s "}"#;
16532        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16533        let msg = err.to_string();
16534        assert!(
16535            msg.contains("contains whitespace byte"),
16536            "expected whitespace diagnostic in {msg:?}"
16537        );
16538        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
16539    }
16540
16541    #[test]
16542    fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
16543        // `"100 / s"` — the canonical typographically-spaced author
16544        // shape (the same idiom every prose reference to a rate limit
16545        // renders as, mistakenly retained when the value is pasted
16546        // into a codec-shaped slot). Before this gate the per-part
16547        // `rate_str.trim()` / `unit.trim()` calls silently ate both
16548        // spaces on either side of `/` and parsed to
16549        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
16550        // codec's *internal* whitespace-tolerance vector, orthogonal
16551        // to the leading / trailing surface but the same canonical-
16552        // form-drift class. Pins the arm as strictly stronger than the
16553        // pre-existing top-level `s.trim()` behavior: it fires on
16554        // whitespace anywhere in the value, not just at the string
16555        // boundary.
16556        let payload = r#"{"rateLimit":"100 / s"}"#;
16557        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16558        let msg = err.to_string();
16559        assert!(
16560            msg.contains("contains whitespace byte"),
16561            "expected whitespace diagnostic in {msg:?}"
16562        );
16563        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
16564    }
16565
16566    #[test]
16567    fn rate_limit_serde_rejects_tab_byte() {
16568        // `"\t100/s"` — the canonical paste-from-indented-doc /
16569        // paste-from-YAML-block-scalar footgun where a tab byte leads
16570        // the magnitude. Pins that the gate covers tab (`0x09`) as
16571        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
16572        // members and both would be silently swallowed by `s.trim()`
16573        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
16574        // space alone to the full ASCII-whitespace set (space `0x20`,
16575        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
16576        // the tab arm as a representative of the non-space members.
16577        let payload = r#"{"rateLimit":"\t100/s"}"#;
16578        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16579        let msg = err.to_string();
16580        assert!(
16581            msg.contains("contains whitespace byte"),
16582            "expected whitespace diagnostic in {msg:?}"
16583        );
16584        assert!(
16585            msg.contains("0x09"),
16586            "missing offending tab byte in {msg:?}"
16587        );
16588    }
16589
16590    // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
16591    //
16592    // Successor to the ASCII-whitespace arm (1ad7755) on
16593    // `rate_limit_codec` — closes the strictly-complementary class the
16594    // byte-scan cannot see, through the lifted
16595    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
16596
16597    #[test]
16598    fn rate_limit_serde_rejects_leading_nbsp() {
16599        // NBSP prefix — paste-from-typography footgun. Byte-scan
16600        // misses, `str::trim` silently strips it, value drifts to
16601        // `"100/s"` on next serialize.
16602        let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
16603        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16604        let msg = err.to_string();
16605        assert!(
16606            msg.contains("non-ASCII Unicode whitespace character"),
16607            "expected non-ASCII whitespace diagnostic in {msg:?}"
16608        );
16609        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
16610    }
16611
16612    #[test]
16613    fn rate_limit_serde_rejects_internal_em_space() {
16614        // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
16615        // paste-from-typography footgun on the `<integer>/<unit>`
16616        // shape.
16617        let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
16618        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16619        let msg = err.to_string();
16620        assert!(
16621            msg.contains("non-ASCII Unicode whitespace character"),
16622            "expected non-ASCII whitespace diagnostic in {msg:?}"
16623        );
16624        assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
16625    }
16626
16627    #[test]
16628    fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
16629        // Positive-control pin: every ASCII-only canonical form the
16630        // renderer emits stays accepted through the new arm.
16631        for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
16632            let payload = format!(r#"{{"rateLimit":{lit}}}"#);
16633            let p: MeshPolicy = serde_json::from_str(&payload)
16634                .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
16635            assert!(p.rate_limit.is_some());
16636        }
16637    }
16638
16639    #[test]
16640    fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
16641        // The boundary case — `"0/s"` is the canonical form
16642        // `render(RateLimit { 0, 1s })` emits, so the codec accepts
16643        // it at the parse layer; the downstream
16644        // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
16645        // `rate == 0` at the typed-validate layer above. Pins the
16646        // partition: the leading-zero gate at the codec layer does
16647        // not poach the rate-zero semantic-validation arm at the
16648        // typed-validate layer above (a future stricter codec must
16649        // not reject `"0/s"` here, or it'd collapse the diagnostic
16650        // partitioning that lets `PolicyRateLimitZero` name the
16651        // offending typed slot).
16652        let payload = r#"{"rateLimit":"0/s"}"#;
16653        let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
16654            panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
16655        });
16656        let rl = policy.rate_limit.expect("rate_limit must be Some");
16657        assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
16658        assert_eq!(
16659            rl.window,
16660            Duration::from_secs(1),
16661            "single-`0` magnitude with `s` unit must parse to window=1s"
16662        );
16663    }
16664
16665    #[test]
16666    fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
16667        // The complementary boundary pin — every magnitude
16668        // `render` emits starts with `[1-9]` (or is the single byte
16669        // `"0"`), so the canonical-form predicate is `(len == 1) ||
16670        // (first byte != '0')`. Pinning the `len > 1 && first byte ==
16671        // '1'` case explicitly so a future tightening of the gate
16672        // (e.g. an over-eager "no leading digit < 5" rule, or a
16673        // mistakenly anchored start-of-magnitude byte check) lands
16674        // here before the canonical-forms-iterating test would catch
16675        // it.
16676        let payload = r#"{"rateLimit":"100/s"}"#;
16677        let policy: MeshPolicy = serde_json::from_str(payload)
16678            .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
16679        let rl = policy.rate_limit.expect("rate_limit must be Some");
16680        assert_eq!(
16681            rl.rate, 100,
16682            "canonical-100 magnitude must parse to rate=100"
16683        );
16684    }
16685
16686    #[test]
16687    fn rate_limit_serde_accepts_integer_canonical_forms() {
16688        // Pin the happy-path: every canonical author shape `render`
16689        // ever emits parses cleanly through the codec post-gate. The
16690        // codec's accepted set (post-gate) is exactly its emitted set
16691        // for the integer-magnitude class — same property
16692        // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
16693        // gates guarantee on the peer codecs. Iterating across rate
16694        // magnitudes (including `"0"`, which the codec accepts even
16695        // though `validate_politicas` rejects `rate == 0` at the typed
16696        // layer above) closes the codec contract at the parse layer
16697        // independently of the validate layer.
16698        for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
16699            for unit_lit in ["s", "m", "h"] {
16700                let lit = format!("{rate_lit}/{unit_lit}");
16701                let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
16702                let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
16703                    panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
16704                });
16705                let rl = policy.rate_limit.expect("rate_limit must be Some");
16706                assert_eq!(
16707                    rl.rate,
16708                    rate_lit.parse::<u32>().unwrap(),
16709                    "rate mismatch for {lit:?}"
16710                );
16711            }
16712        }
16713    }
16714
16715    #[test]
16716    fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
16717        // The structural property the gate enforces: serialize ∘
16718        // deserialize is the identity on every canonical author shape.
16719        // Peer of `parse_byte_size`'s and `parse_duration`'s
16720        // `_round_trips_through_render_for_every_canonical_form` tests
16721        // on the rate-limit axis. Before the gate, `"+100/s"` violated
16722        // this (`parse` → `RateLimit { 100, 1s }` → `render` →
16723        // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
16724        for rate in [1u32, 100, 5000, 1_000_000] {
16725            for (window, unit) in [
16726                (Duration::from_secs(1), "s"),
16727                (Duration::from_secs(60), "m"),
16728                (Duration::from_secs(3600), "h"),
16729            ] {
16730                let policy = MeshPolicy {
16731                    rate_limit: Some(RateLimit { rate, window }),
16732                    ..Default::default()
16733                };
16734                let json = serde_json::to_string(&policy).unwrap();
16735                let expected = format!("\"{rate}/{unit}\"");
16736                assert!(
16737                    json.contains(&expected),
16738                    "expected {expected:?} in {json:?}"
16739                );
16740                let back: MeshPolicy = serde_json::from_str(&json).unwrap();
16741                assert_eq!(
16742                    back.rate_limit, policy.rate_limit,
16743                    "round-trip for {json:?}"
16744                );
16745            }
16746        }
16747    }
16748
16749    // ── self-membership cross-slot gate ──────────────────────────────
16750
16751    #[test]
16752    fn validate_no_self_membership_rejects_self_named_membro() {
16753        // An Aplicacao whose `:membros` lists its own `:nome` is a
16754        // one-node lacre-closure recursion — rejected, naming the parent.
16755        let membros = vec![
16756            membro("catalog", "^0.1"),
16757            membro("checkout", "^0.1"),
16758            membro("cart", "^0.1"),
16759        ];
16760        let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
16761        assert!(
16762            matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
16763            "got {err:?}"
16764        );
16765    }
16766
16767    #[test]
16768    fn validate_no_self_membership_accepts_distinct_membros() {
16769        // Positive control: distinct member names (including a member
16770        // that is itself an Aplicacao — recursive composition is valid,
16771        // MESH-COMPOSITION §V) pass the gate.
16772        let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
16773        validate_no_self_membership(&membros, "checkout").unwrap();
16774    }
16775
16776    #[test]
16777    fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
16778        // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
16779        // `NoMembros` arm (the more-fundamental "graph must have nodes"
16780        // gate), not by this cross-slot self-edge gate. Keeping the
16781        // self-membership predicate vacuously-ok on the empty input
16782        // matches its supervisor-axis peer
16783        // (`validate_no_self_supervision_empty_children_is_ok`) and
16784        // makes the gate composable from any future call site (an M4
16785        // CR materializer's per-membros validator) without re-checking
16786        // emptiness.
16787        validate_no_self_membership(&[], "checkout").unwrap();
16788    }
16789
16790    #[test]
16791    fn validate_no_self_membership_diagnostic_names_offending_caixa() {
16792        // Pinning the Display: the self-membership diagnostic must name
16793        // the offending caixa verbatim + the "lists itself" framing the
16794        // author can grep for, so the cluster-far failure surfaces at
16795        // build time with one-line remediation. Same diagnostic shape
16796        // as the supervisor-axis `ChildSupervisesSelf` peer.
16797        let membros = vec![membro("orquestra", "^0.1")];
16798        let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
16799        let msg = err.to_string();
16800        assert!(
16801            msg.contains("orquestra"),
16802            "diagnostic must name the offending caixa nome (got: {msg:?})"
16803        );
16804        assert!(
16805            msg.contains("lists itself"),
16806            "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
16807        );
16808    }
16809
16810    #[test]
16811    fn default_servico_port_constant_pins_canonical_8080_literal() {
16812        // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
16813        // at the verbatim `8080` literal both consumers (the
16814        // `Entrada::port` serde default via [`default_port`] and the
16815        // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
16816        // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
16817        // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
16818        // discipline (a085b26) on the per-renderer canonical-K8s-axis
16819        // string-constant axis: a future refactor that drifts the
16820        // constant out from under either consumer surfaces here ahead
16821        // of every per-renderer's first emission. The literal value
16822        // matches the well-known HTTP-alt port the `pleme-computeunit`
16823        // library chart already emits as its `trigger.service.port`
16824        // default — by construction the same value the substrate
16825        // assumes about every Servico's in-cluster L4 listener.
16826        assert_eq!(
16827            DEFAULT_SERVICO_PORT, 8080,
16828            "canonical Servico port literal must remain `8080` verbatim — \
16829             this is the value both the `Entrada::port` serde default and the \
16830             caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
16831        );
16832    }
16833
16834    #[test]
16835    fn default_port_helper_returns_canonical_servico_port_constant() {
16836        // The bridge-arm — pins that the [`default_port`] helper
16837        // [`Entrada::port`]'s `#[serde(default = "default_port")]`
16838        // attribute hooks routes through the lifted
16839        // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
16840        // literal. A future refactor that re-introduces the `8080`
16841        // literal at the helper's return site (silently re-opening
16842        // the drift footgun this lift closed) surfaces here ahead of
16843        // every author-side `(:entrada (:host … :para …))` slot
16844        // without an explicit `:port`. Peer with the
16845        // `default_namespace_re_export_points_at_caixa_core_canonical`
16846        // pin on the caixa-mesh-side re-export axis.
16847        assert_eq!(
16848            default_port(),
16849            DEFAULT_SERVICO_PORT,
16850            "the serde-default helper must route through the lifted constant"
16851        );
16852    }
16853
16854    #[test]
16855    fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
16856        // The end-to-end pin — an author-surface `(:entrada (:host …
16857        // :para …))` without an explicit `:port` slot deserializes to
16858        // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
16859        // verbatim. Routes the canonical lifted constant through both
16860        // the serde-default machinery (the `#[serde(default =
16861        // "default_port")]` attribute) and the typed-value-shape
16862        // contract (the resulting [`Entrada::port`] value). A future
16863        // refactor that drifts either axis — replacing the serde
16864        // hook's helper, changing the typed slot's wire shape — would
16865        // surface here before any per-renderer's CNP / Gateway /
16866        // HTTPRoute emission consumed the drifted default.
16867        let entrada: Entrada =
16868            serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
16869        assert_eq!(
16870            entrada.port, DEFAULT_SERVICO_PORT,
16871            "the serde default must materialize as the lifted canonical Servico port"
16872        );
16873    }
16874
16875    #[test]
16876    fn servico_port_min_pins_canonical_accept_set_floor() {
16877        // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
16878        // verbatim `1` literal every typed `:entrada :port` acceptance
16879        // gate keys off. Peer with the
16880        // [`default_servico_port_constant_pins_canonical_8080_literal`]
16881        // discipline on the canonical-Servico-port-constant axis: a
16882        // future refactor that drifts the accept-set floor out from
16883        // under the sole consumer at [`AplicacaoSpec::validate`]'s
16884        // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
16885        // every per-`:entrada` `EntradaPortZero` diagnostic. The
16886        // literal value matches the IANA-registered TCP/UDP port
16887        // space floor (`1..=65535` — port `0` is the "any ephemeral"
16888        // sentinel, not a well-defined destination the substrate's
16889        // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
16890        // axis can honor).
16891        assert_eq!(
16892            SERVICO_PORT_MIN, 1,
16893            "canonical Servico port accept-set floor must remain `1` verbatim — \
16894             this is the value the `AplicacaoSpec::validate` gate at \
16895             `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
16896        );
16897    }
16898
16899    #[test]
16900    fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
16901        // The cross-const invariant pin — the substrate's canonical
16902        // default port must satisfy its own accept-set floor by
16903        // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
16904        // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
16905        // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
16906        // override the operator pins through a future
16907        // `:placement :default-port` slot that lands out-of-range, a
16908        // per-edition Servico-port migration that lifted the floor
16909        // above the previous default without coordinating the pair —
16910        // would silently invalidate the serde-default emission at
16911        // every author-side `(:entrada (:host … :para …))` slot
16912        // without an explicit `:port`: the default port would fall
16913        // below the accept-set floor, the `AplicacaoSpec::validate`
16914        // gate would reject every default-carrying Aplicacao as
16915        // `EntradaPortZero`, and the substrate's typed
16916        // `(defcaixa … :kind Aplicacao)` surface would fail validate
16917        // on every Aplicacao whose author omitted `:entrada :port`
16918        // for the substrate's chosen default — a class of authoring-
16919        // surface footguns the compile-time pin structurally closes.
16920        // Peer with the
16921        // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
16922        // (27f9b34) cross-const invariant pin discipline on the peer
16923        // canonical-Helm-per-values-block child-chart-enablement-toggle
16924        // axis pair.
16925        assert!(
16926            SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
16927            "the substrate's canonical default port ({DEFAULT_SERVICO_PORT}) must \
16928             satisfy its own accept-set floor (SERVICO_PORT_MIN = {SERVICO_PORT_MIN}) — \
16929             every default-carrying `(:entrada (:host … :para …))` slot without an \
16930             explicit `:port` inherits `DEFAULT_SERVICO_PORT` through the serde default \
16931             hook and must pass the `AplicacaoSpec::validate` floor gate by construction"
16932        );
16933    }
16934
16935    #[test]
16936    fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
16937        // The gate-site pin — asserts the `AplicacaoSpec::validate`
16938        // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
16939        // `EntradaPortZero` diagnostic on the below-floor input
16940        // `port: 0` (the only below-floor value the `u16` field can
16941        // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
16942        // is the singleton `{0}`). A future refactor that drifts the
16943        // gate off the lifted const (silently re-introducing an
16944        // inline `if e.port == 0` byte-check) surfaces here — the
16945        // pin cannot distinguish `< 1` from `== 0` on the current
16946        // floor, but it *does* pin that the diagnostic fires on `0`
16947        // through whichever gate is wired, so any future accept-set
16948        // floor migration (a hypothetical unprivileged-only
16949        // migration lifting `SERVICO_PORT_MIN` to `1024`) must
16950        // update this test alongside the const declaration —
16951        // structurally guaranteeing the gate + accept-set + pin
16952        // trio move together. Peer with the
16953        // [`rejects_zero_entrada_port`] behavioral pin on the same
16954        // per-`:entrada :port` axis — that pin asserts the pre-lift
16955        // behavioral contract (`port: 0` → `EntradaPortZero`); this
16956        // pin adds the structural link to the lifted floor const.
16957        assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
16958        let mut s = three_member_spec();
16959        s.entrada.as_mut().unwrap().port = 0;
16960        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
16961    }
16962
16963    // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
16964
16965    #[test]
16966    fn membro_serde_keys_match_lifted_membro_key_consts() {
16967        // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
16968        // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
16969        // name the exact camelCase JSON keys the
16970        // `#[serde(rename_all = "camelCase")]` attribute on
16971        // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
16972        // that each canonical byte-sequence appears verbatim in the
16973        // JSON — a future accidental `rename_all = "snake_case"` /
16974        // `"kebab-case"` / verbatim-field-name flip at the derive
16975        // attribute (any of which would silently break every downstream
16976        // JSON consumer that reaches for one of the two consts via
16977        // `Value::get(...)`) surfaces here as a build-time test failure
16978        // at `aplicacao.rs`, not as an apply-time
16979        // `.get(<stale-canonical-const>)` returning `None` far from the
16980        // derive-attr drift's commit. Peer with the sibling
16981        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
16982        // (40cc4e5) pin on the M2 supervision-tree top-level axis —
16983        // same discipline the SupervisorSpec top-level lift established,
16984        // extended here to the M3 [`Membro`] per-`:membros` axis.
16985        let m = Membro {
16986            caixa: "catalog".into(),
16987            versao: "^0.1".into(),
16988        };
16989        let json = serde_json::to_string(&m).unwrap();
16990        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
16991            let quoted = format!("\"{key}\"");
16992            assert!(
16993                json.contains(&quoted),
16994                "serialized Membro must carry the lifted MEMBRO_KEY_* \
16995                 byte-sequence {quoted} verbatim in the JSON emission \
16996                 (got: {json})",
16997            );
16998        }
16999    }
17000
17001    #[test]
17002    fn membro_key_consts_are_pairwise_distinct() {
17003        // Cross-axis drift-detection pin: a future collapse of the two
17004        // canonical [`Membro`] per-entry byte-strings onto the same
17005        // value (e.g. an accidental copy-paste flip of
17006        // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
17007        // silently reroute every downstream probe on one axis onto the
17008        // sibling axis's overlay entry and pass every propagation-probe
17009        // test that expected only the stale axis's value. Peer of the
17010        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
17011        // (40cc4e5).
17012        let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
17013        for (i, a) in all.iter().enumerate() {
17014            for b in all.iter().skip(i + 1) {
17015                assert_ne!(
17016                    a, b,
17017                    "MEMBRO_KEY_* consts must be pairwise-distinct \
17018                     canonical byte-sequences — got `{a}` == `{b}`",
17019                );
17020            }
17021        }
17022    }
17023
17024    // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
17025    //    URL-path fallback resolver every HTTPRoute-aware renderer
17026    //    reaching for a per-rule path-list resolution routes through.
17027    //    The four pin tests below fix the four-way accept-set the
17028    //    resolver must always honor: (:paths-non-empty-verbatim,
17029    //    :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
17030    //    :paths-preserves-order-across-multiple-entries) — drift on any
17031    //    arm surfaces at caixa-core build time rather than at cluster-
17032    //    apply time. Peer discipline with `MeshPolicy::is_empty` on the
17033    //    sibling `:politicas` typed-primitive dispatch axis.
17034
17035    fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
17036        Entrada {
17037            host: "example.com".into(),
17038            para: "cart".into(),
17039            paths: paths.into_iter().map(String::from).collect(),
17040            port: DEFAULT_SERVICO_PORT,
17041        }
17042    }
17043
17044    #[test]
17045    fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
17046        // The typed `:entrada :paths` slot carries an author-declared
17047        // list — the resolver returns each entry verbatim, no
17048        // catch-all substitution. The canonical "author declared
17049        // paths, honor them verbatim" arm of the path-list dispatch.
17050        let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
17051        assert_eq!(
17052            e.resolved_paths(),
17053            vec!["/api/cart", "/api/products"],
17054            "resolved_paths must return each `:entrada :paths` entry \
17055             verbatim when the typed slot is non-empty (got {:?})",
17056            e.resolved_paths(),
17057        );
17058    }
17059
17060    #[test]
17061    fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
17062        // Empty `:entrada :paths` slot — the resolver substitutes the
17063        // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
17064        // catch-all fallback verbatim. Pins the empty-arm of the
17065        // resolver's four-way accept-set against a future silent
17066        // detour that returned an empty Vec (which would emit an
17067        // HTTPRoute with zero rules — silently dropping every
17068        // external `:entrada` flow at admission time), routed to a
17069        // different fallback shape, or dropped the catch-all
17070        // altogether.
17071        let e = entrada_with_paths(vec![]);
17072        assert_eq!(
17073            e.resolved_paths(),
17074            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
17075            "resolved_paths on empty `:entrada :paths` must fall back \
17076             to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
17077             all — got {:?}",
17078            e.resolved_paths(),
17079        );
17080    }
17081
17082    #[test]
17083    fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
17084        // Single-entry `:entrada :paths` — the resolver returns the
17085        // single declared path verbatim, NOT the catch-all fallback
17086        // (author declared a path, honor it — the empty-arm and the
17087        // len-1 arm are semantically distinct axes of the resolver's
17088        // accept-set). Pins that the resolver treats "author declared
17089        // one path" as authored input, not as the empty case.
17090        let e = entrada_with_paths(vec!["/api/only"]);
17091        assert_eq!(
17092            e.resolved_paths(),
17093            vec!["/api/only"],
17094            "resolved_paths on single-entry `:entrada :paths` must \
17095             return the declared path verbatim, NOT the catch-all \
17096             fallback (got {:?})",
17097            e.resolved_paths(),
17098        );
17099    }
17100
17101    #[test]
17102    fn resolved_paths_preserves_author_declared_order() {
17103        // The `:entrada :paths` list is author-ordered — the resolver
17104        // preserves the author's declaration order verbatim, since
17105        // per-rule dispatch order at the K8s Gateway API HTTPRoute
17106        // consumer is significant (first-match-wins under the
17107        // path-prefix matcher). Pins against a future silent
17108        // re-sort / dedup / normalize detour that reordered author
17109        // input.
17110        let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
17111        assert_eq!(
17112            e.resolved_paths(),
17113            vec!["/z/last", "/a/first", "/m/mid"],
17114            "resolved_paths must preserve author-declared `:entrada \
17115             :paths` order verbatim — got {:?}",
17116            e.resolved_paths(),
17117        );
17118    }
17119
17120    // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
17121    //    slot `&[String]` slice accessor every per-`:entrada` consumer
17122    //    that must see the author's declaration verbatim (not the
17123    //    fallback-applied projection the sibling `resolved_paths`
17124    //    returns) routes through. The three pin tests below fix the
17125    //    accept-set the accessor must honor: (:non-empty-byte-equal,
17126    //    :empty-projects-empty-slice, :preserves-author-declared-order)
17127    //    — drift on any arm surfaces at caixa-core build time rather
17128    //    than at cluster-apply time. Peer discipline with the sibling
17129    //    [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
17130    //    peer M3 mesh-slot `Vec<String>`-carry axis.
17131
17132    #[test]
17133    fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
17134        // Byte-equal pin: [`Entrada::paths`] must project the raw
17135        // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
17136        // slice borrowed from the typed slot's own [`Vec<String>`]
17137        // storage — no re-ordering, no dedup, no per-entry normalization,
17138        // no fallback substitution (the fallback-applying projection is
17139        // the sibling [`Entrada::resolved_paths`] resolver). Pins against
17140        // a future silent detour that re-normalized the list, dropped
17141        // duplicates the [`AplicacaoSpec::validate`]
17142        // `EntradaPathDuplicate` refusal already rejects at build time,
17143        // or (most severe) accidentally routed through the fallback-
17144        // applying sibling and returned the substrate catch-all when
17145        // the author declared an empty list — collapsing the raw-slot
17146        // and fallback-applied axes into one and breaking the
17147        // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
17148        //
17149        // Peer of the sibling
17150        // [`Placement::clusters`]-shape byte-equal pin
17151        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
17152        // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
17153        let fixtures: Vec<Vec<String>> = vec![
17154            Vec::new(),
17155            vec!["/api/cart".into()],
17156            vec!["/api/cart".into(), "/api/products".into()],
17157            vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
17158        ];
17159        for paths in fixtures {
17160            let e = Entrada {
17161                host: "example.com".into(),
17162                para: "cart".into(),
17163                paths: paths.clone(),
17164                port: DEFAULT_SERVICO_PORT,
17165            };
17166            assert_eq!(
17167                e.paths(),
17168                paths.as_slice(),
17169                "Entrada::paths must return :entrada :paths verbatim \
17170                 (got {:?}, expected {:?})",
17171                e.paths(),
17172                paths.as_slice(),
17173            );
17174            assert_eq!(
17175                e.paths(),
17176                e.paths.as_slice(),
17177                "Entrada::paths accessor and .paths.as_slice() field \
17178                 access must byte-equal — the accessor is the substrate-\
17179                 primitive typed dispatch every downstream per-`:entrada` \
17180                 raw-slot path-list consumer must route through",
17181            );
17182            assert_eq!(
17183                e.paths().len(),
17184                e.paths.len(),
17185                "Entrada::paths().len() must byte-equal self.paths.len() \
17186                 — a length drift would silently split the paired \
17187                 pre-flight cascade-head `.is_empty()` probe input in \
17188                 the sibling [`Entrada::resolved_paths`] resolver from \
17189                 the per-entry validate loop's traversal input in \
17190                 [`AplicacaoSpec::validate`]",
17191            );
17192        }
17193    }
17194
17195    #[test]
17196    fn resolved_paths_reads_through_lifted_paths_accessor() {
17197        // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
17198        // pre-flight `.paths().is_empty()` cascade-head probe (which
17199        // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
17200        // catch-all fallback arm when the accessor projects the empty
17201        // slice) and the per-entry `.paths().iter().map(String::as_str)`
17202        // projection (which must reach every entry in the same order
17203        // the accessor projects, so the sibling
17204        // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
17205        // per-entry projection stay in lockstep by construction) must
17206        // both key off the lifted accessor. Pins the two-site coherence
17207        // by exercising each production consumer end-to-end: (1) the
17208        // catch-all-fallback arm under the empty slice, (2) the
17209        // author-declared-verbatim arm under a two-entry cohort whose
17210        // per-entry projection must byte-equal the input's per-entry
17211        // author-declared paths in the author's declared order.
17212        //
17213        // Peer of the sibling M3
17214        // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
17215        // `validate_placement_reads_through_lifted_clusters_accessor`
17216        // on the sibling `Placement::clusters` reader-site convergence.
17217        let empty = entrada_with_paths(vec![]);
17218        assert_eq!(
17219            empty.resolved_paths(),
17220            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
17221            "resolved_paths on empty :entrada :paths must trip the \
17222             lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
17223             catch-all fallback — routing through the lifted paths() \
17224             accessor must not silently drop the fallback arm",
17225        );
17226
17227        let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
17228        assert_eq!(
17229            declared.resolved_paths(),
17230            vec!["/api/cart", "/api/products"],
17231            "resolved_paths on non-empty :entrada :paths must return each \
17232             entry verbatim in the author's declared order — routing \
17233             through the lifted paths() accessor must not silently \
17234             reorder or drop entries",
17235        );
17236        // Byte-equal pin against the raw-slot accessor to keep the
17237        // fallback-applying resolver's per-entry projection input in
17238        // lockstep with the raw-slot accessor's projection.
17239        let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
17240        assert_eq!(
17241            declared.resolved_paths(),
17242            raw_projected,
17243            "resolved_paths non-empty projection must byte-equal the \
17244             lifted paths() accessor's per-entry String::as_str projection \
17245             — the two projections share the same input slice by \
17246             construction, so any drift here would surface a silent \
17247             re-ordering / dedup / normalization detour in the resolver",
17248        );
17249    }
17250
17251    #[test]
17252    fn validate_reads_through_lifted_entrada_paths_accessor() {
17253        // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
17254        // per-entry value-shape gate's `for p in e.paths()` traversal
17255        // (which must reach every entry in the same order the accessor
17256        // projects, so both the per-entry `EntradaPathEmpty` /
17257        // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
17258        // the duplicate-detection HashSet insert that trips
17259        // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
17260        // projection) must route through the lifted accessor. Pins the
17261        // coherence by exercising each production consumer end-to-end:
17262        // (1) the `EntradaPathEmpty` refusal fires on the second entry
17263        // of a two-entry cohort whose head is valid but tail is empty
17264        // (which requires the loop to reach the second entry through
17265        // the accessor), and (2) the `EntradaPathDuplicate` refusal
17266        // fires on the second entry of a two-entry cohort that shares
17267        // a path (which requires the loop to reach both entries — a
17268        // first-entry-only projection would silently pass since the
17269        // dedup HashSet has room for the first insert).
17270        //
17271        // Peer of the sibling
17272        // `validate_placement_reads_through_lifted_clusters_accessor`
17273        // on the sibling `Placement::clusters` reader-site convergence.
17274        let base = crate::AplicacaoSpec {
17275            membros: vec![crate::Membro {
17276                caixa: "cart".into(),
17277                versao: "^0.1".into(),
17278            }],
17279            contratos: Vec::new(),
17280            politicas: crate::MeshPolicy::default(),
17281            placement: crate::Placement {
17282                estrategia: crate::PlacementStrategy::SingleNode,
17283                clusters: vec!["rio".into()],
17284                shard_key: None,
17285                affinity: None,
17286            },
17287            entrada: Some(Entrada {
17288                host: "example.com".into(),
17289                para: "cart".into(),
17290                paths: vec!["/api/cart".into(), String::new()],
17291                port: DEFAULT_SERVICO_PORT,
17292            }),
17293        };
17294        assert_eq!(
17295            base.validate(),
17296            Err(crate::AplicacaoError::EntradaPathEmpty),
17297            "validate must trip EntradaPathEmpty on the second entry of \
17298             a two-entry cohort — routing through the lifted paths() \
17299             accessor must not silently short-circuit the loop at the \
17300             valid head entry",
17301        );
17302
17303        let mut dup = base;
17304        dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
17305        assert_eq!(
17306            dup.validate(),
17307            Err(crate::AplicacaoError::EntradaPathDuplicate {
17308                path: "/api/cart".into(),
17309            }),
17310            "validate must trip EntradaPathDuplicate on the second entry \
17311             of a two-entry cohort that shares a path — routing through \
17312             the lifted paths() accessor must not silently short-circuit \
17313             the dedup HashSet insert at the first entry",
17314        );
17315    }
17316
17317    // ── Entrada::hostname / Entrada::hostnames — the substrate-
17318    //    canonical per-`:entrada` DNS-hostname resolver pair every
17319    //    Gateway-API-aware renderer reaching for a per-listener
17320    //    singular `hostname:` filter (Gateway) or a per-route plural
17321    //    `spec.hostnames[]` filter list (HTTPRoute) routes through.
17322    //    The three pin tests below fix the two-way accept-set the pair
17323    //    must always honor: (:singular-byte-equal-to-host,
17324    //    :plural-is-singleton-of-singular, :plural-len-is-one) — drift
17325    //    on any arm surfaces at caixa-core build time rather than at
17326    //    cluster-apply time when the API server refuses the HTTPRoute
17327    //    for non-intersecting hostname filters. Peer discipline with
17328    //    the sibling `resolved_paths` accept-set pin block above on the
17329    //    per-`:entrada` path-list resolver axis.
17330
17331    fn entrada_with_host(host: &str) -> Entrada {
17332        Entrada {
17333            host: host.into(),
17334            para: "cart".into(),
17335            paths: Vec::new(),
17336            port: DEFAULT_SERVICO_PORT,
17337        }
17338    }
17339
17340    #[test]
17341    fn hostname_returns_entrada_host_byte_equal() {
17342        // The canonical singular-axis pin: [`Entrada::hostname`] must
17343        // return the `:entrada :host` field byte-for-byte, borrowed
17344        // from the typed slot's own [`String`] storage. Pins against a
17345        // future silent detour that re-normalized the host (an
17346        // accidental `.to_lowercase()` — validate_entrada_host already
17347        // enforces lowercase, so any re-normalization is redundant + a
17348        // drift surface between the validator and the accessor), a
17349        // trailing-`.` fully-qualified DNS shape substitution, or a
17350        // Punycode round-trip that lowered a Unicode host through IDNA.
17351        let e = entrada_with_host("checkout.quero.cloud");
17352        assert_eq!(
17353            e.hostname(),
17354            "checkout.quero.cloud",
17355            "Entrada::hostname must return :entrada :host verbatim \
17356             (got {:?})",
17357            e.hostname(),
17358        );
17359        assert_eq!(
17360            e.hostname(),
17361            e.host.as_str(),
17362            "Entrada::hostname must byte-equal the .host field access",
17363        );
17364    }
17365
17366    #[test]
17367    fn hostnames_returns_singleton_of_hostname_accessor() {
17368        // The pair-invariant pin: [`Entrada::hostnames`] must always
17369        // return exactly `vec![hostname()]` — the singleton list whose
17370        // sole entry is the substrate's canonical per-`:entrada`
17371        // singular hostname. Pins the two-consumer coherence axis: the
17372        // Gateway listener's singular `hostname:` filter and the
17373        // HTTPRoute's plural `spec.hostnames[]` filter list must
17374        // agree, else the Gateway API v1.x conformance layer rejects
17375        // the HTTPRoute at attach time with
17376        // `Accepted:False/NoMatchingParent` (the parent Gateway's
17377        // listener hostname doesn't intersect the route's hostname
17378        // filter list) — a divergence whose apply-time symptom is far
17379        // from any single-site commit and never surfaces in the
17380        // emitted YAML. Pinning the pair-invariant here makes any
17381        // future accidental split (an accidental `.to_string() + "."`
17382        // trailing-`.` on the plural side that didn't land on the
17383        // singular side, an accidental prefix stripping on one axis,
17384        // an accidental wildcard prepend the SNI fan-out overlay
17385        // authors on the plural side without a paired singular
17386        // migration) trip at caixa-core build time.
17387        let e = entrada_with_host("checkout.quero.cloud");
17388        assert_eq!(
17389            e.hostnames(),
17390            vec![e.hostname()],
17391            "Entrada::hostnames must return `vec![hostname()]` under \
17392             the pair-invariant — got {:?} vs. singleton {:?}",
17393            e.hostnames(),
17394            vec![e.hostname()],
17395        );
17396    }
17397
17398    #[test]
17399    fn hostnames_is_singleton_under_single_host_author_surface() {
17400        // The singleton-shape pin: under today's single-hostname-per-
17401        // `:entrada` author surface (the `:host` slot is a single
17402        // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
17403        // must always return a list of length exactly one. Pins
17404        // against a future silent detour that returned an empty list
17405        // (which would emit an HTTPRoute with `spec.hostnames: []` —
17406        // matching every incoming Host header regardless of the
17407        // Aplicacao's declared ingress apex, silently over-matching
17408        // every foreign VirtualHost the parent Gateway also fronts) or
17409        // a duplicated entry (which the Gateway API v1.x parser
17410        // accepts as a `[]-length-2 list of equal hostnames]` but
17411        // whose semantics differ from the intended singleton). The
17412        // author-surface extension point ("a future `:entrada
17413        // :alt-hosts` list overlay" the docstring names) is the sole
17414        // future axis that flips this pin — that migration will re-
17415        // author this test to pin the new plural cardinality.
17416        let e = entrada_with_host("checkout.quero.cloud");
17417        assert_eq!(
17418            e.hostnames().len(),
17419            1,
17420            "Entrada::hostnames must be a singleton under today's \
17421             single-hostname-per-`:entrada` author surface — got \
17422             length {}: {:?}",
17423            e.hostnames().len(),
17424            e.hostnames(),
17425        );
17426    }
17427
17428    // ── Entrada::destination — the substrate-canonical per-`:entrada`
17429    //    destination-Servico scalar accessor every Gateway-API
17430    //    HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
17431    //    discriminator arg (HTTPRoute name composer) or a per-rule
17432    //    `backendRefs[0].name` axis routes through. The two pin tests
17433    //    below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
17434    //    either arm surfaces at caixa-core build time rather than at
17435    //    cluster-apply time when an HTTPRoute's `metadata.name` and
17436    //    `backendRefs[]` silently disagree on which destination Servico
17437    //    the ingress fronts. Peer discipline with the sibling
17438    //    `resolved_paths` + `hostname` + `hostnames` accept-set pin
17439    //    blocks above on the per-`:entrada` path-list / DNS-hostname
17440    //    resolver axes.
17441
17442    #[test]
17443    fn destination_returns_entrada_para_byte_equal() {
17444        // The canonical destination-scalar pin: [`Entrada::destination`]
17445        // must return the `:entrada :para` field byte-for-byte, borrowed
17446        // from the typed slot's own [`String`] storage. Pins against a
17447        // future silent detour that re-normalized the destination (an
17448        // accidental `.to_lowercase()` — the destination Servico is
17449        // already validated as a DNS-1123 label upstream, so any
17450        // re-normalization is redundant + a drift surface between the
17451        // validator and the accessor), a namespace-prefix rewrite (an
17452        // accidental `format!("{namespace}/{para}")` per-CR fully-
17453        // qualified rewrite that didn't land on the peer axis), or a
17454        // per-cluster suffix stamp the operator authors on one
17455        // consumer without the other.
17456        for para in ["cart", "checkout", "catalog", "orders-v2"] {
17457            let e = Entrada {
17458                host: "checkout.quero.cloud".into(),
17459                para: para.into(),
17460                paths: Vec::new(),
17461                port: DEFAULT_SERVICO_PORT,
17462            };
17463            assert_eq!(
17464                e.destination(),
17465                para,
17466                "Entrada::destination must return :entrada :para verbatim \
17467                 (got {:?}, expected {para:?})",
17468                e.destination(),
17469            );
17470            assert_eq!(
17471                e.destination(),
17472                e.para.as_str(),
17473                "Entrada::destination must byte-equal the .para field access",
17474            );
17475        }
17476    }
17477
17478    #[test]
17479    fn destination_borrows_from_entrada_para_storage() {
17480        // The borrow-not-copy pin: [`Entrada::destination`] must
17481        // return a `&str` slice that borrows from the typed slot's
17482        // own [`String`] storage — same-address invariant with
17483        // `entrada.para.as_str()`. Pins against a future silent detour
17484        // that allocated a fresh `String` (`self.para.clone()` in the
17485        // body would type-check but silently drop the borrow, and
17486        // every downstream consumer that assumed the returned slice
17487        // outlives `&self` would break on a stale-reference use-after-
17488        // free). Peer with the sibling `hostname_returns_entrada_
17489        // host_byte_equal` on the singular-DNS-hostname axis.
17490        let e = entrada_with_host("checkout.quero.cloud");
17491        let dest = e.destination();
17492        let para_slice = e.para.as_str();
17493        assert_eq!(
17494            dest.as_ptr(),
17495            para_slice.as_ptr(),
17496            "Entrada::destination must borrow from the .para String's \
17497             backing storage — a fresh allocation here means the \
17498             accessor no longer names the substrate-primitive typed \
17499             dispatch and every downstream consumer would silently \
17500             carry a detached copy",
17501        );
17502        assert_eq!(
17503            dest.len(),
17504            para_slice.len(),
17505            "Entrada::destination and .para.as_str() must byte-equal in \
17506             length as well as in address",
17507        );
17508    }
17509
17510    #[test]
17511    fn port_returns_entrada_port_verbatim_across_permutations() {
17512        // The canonical L4-port-scalar pin: [`Entrada::port`] must
17513        // return the `:entrada :port` field verbatim as a `u16` across
17514        // every author-declared value in the validated accept-set
17515        // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
17516        // silent detour that clamped the port (an accidental
17517        // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
17518        // land on the peer [`AplicacaoSpec::port_for_destination`]
17519        // resolver), rewrote it through a per-cluster port-remap table
17520        // the operator authors on one consumer without the other, or
17521        // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
17522        // serde-default value (which would silently collapse the
17523        // distinction between "author explicitly declared `:port 8080`"
17524        // and "author omitted the slot and inherited the default" the
17525        // future per-cluster override slot depends on). Peer with the
17526        // sibling `destination_returns_entrada_para_byte_equal` +
17527        // `hostname_returns_entrada_host_byte_equal` pins on the
17528        // per-`:entrada` `&str` scalar axes.
17529        for port in [
17530            SERVICO_PORT_MIN,
17531            DEFAULT_SERVICO_PORT,
17532            8443u16,
17533            9090u16,
17534            u16::MAX,
17535        ] {
17536            let e = Entrada {
17537                host: "checkout.quero.cloud".into(),
17538                para: "cart".into(),
17539                paths: Vec::new(),
17540                port,
17541            };
17542            assert_eq!(
17543                e.port(),
17544                port,
17545                "Entrada::port must return :entrada :port verbatim \
17546                 (got {}, expected {port})",
17547                e.port(),
17548            );
17549            assert_eq!(
17550                e.port(),
17551                e.port,
17552                "Entrada::port accessor and .port field access must \
17553                 byte-equal — the accessor is the substrate-primitive \
17554                 typed dispatch every downstream L4-port consumer must \
17555                 route through",
17556            );
17557        }
17558    }
17559
17560    #[test]
17561    fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
17562        // Two-consumer coherence pin: the
17563        // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
17564        // (which reads through [`Entrada::port`] to compare against
17565        // [`SERVICO_PORT_MIN`]) and the
17566        // [`AplicacaoSpec::port_for_destination`] resolver (which reads
17567        // through [`Entrada::port`] to emit the per-destination
17568        // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
17569        // lifted accessor, so any future rebrand on the typed slot's
17570        // reader shape lands at exactly one place. Pins the two-site
17571        // coherence by exercising a below-floor port through validate
17572        // (which must reject) and a validated in-accept-set port through
17573        // port_for_destination (which must emit the same value the
17574        // accessor returns).
17575        let mut spec = three_member_spec();
17576        if let Some(e) = spec.entrada.as_mut() {
17577            e.port = 0;
17578        }
17579        assert_eq!(
17580            spec.validate().unwrap_err(),
17581            AplicacaoError::EntradaPortZero,
17582            "validate must reject `:entrada :port 0` through the lifted \
17583             Entrada::port accessor — port zero lies below \
17584             SERVICO_PORT_MIN and the validator routes through port() \
17585             to name the floor",
17586        );
17587
17588        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
17589            let mut spec = three_member_spec();
17590            if let Some(e) = spec.entrada.as_mut() {
17591                e.port = port;
17592            }
17593            spec.validate().expect(
17594                "entrada with in-accept-set :port must validate — the \
17595                 structural-floor gate reads through Entrada::port",
17596            );
17597            let entrada_ref = spec.entrada.as_ref().expect(":entrada present");
17598            assert_eq!(
17599                spec.port_for_destination(entrada_ref.destination()),
17600                entrada_ref.port(),
17601                "port_for_destination(entrada.destination()) must equal \
17602                 entrada.port() — the two consumers of the per-:entrada \
17603                 L4-port axis (validator, per-destination resolver) both \
17604                 route through Entrada::port",
17605            );
17606        }
17607    }
17608
17609    #[test]
17610    fn wit_contract_source_returns_de_byte_equal_across_permutations() {
17611        // The canonical caller-Servico-scalar pin: [`WitContract::source`]
17612        // must return the `:contratos :de` field byte-for-byte, borrowed
17613        // from the typed slot's own [`String`] storage. Peer of the
17614        // sibling `destination_returns_entrada_para_byte_equal` pin on
17615        // the per-`:entrada` axis — same "the substrate-primitive
17616        // accessor must byte-equal the raw field access verbatim across
17617        // every author-declared value" discipline extended to the
17618        // per-`:contratos` caller arm. Pins against a future silent
17619        // detour that re-normalized the caller (an accidental
17620        // `.to_lowercase()` — every `:contratos :de` is validated as a
17621        // DNS-1123 label upstream via `validate_contrato_caixa`, so any
17622        // re-normalization is redundant + a drift surface between the
17623        // validator and the accessor), a namespace-prefix rewrite (an
17624        // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
17625        // rewrite that didn't land on the peer axis), or a per-cluster
17626        // suffix stamp the operator authors on one consumer without the
17627        // other.
17628        for de in ["cart", "checkout", "catalog", "orders-v2"] {
17629            let c = WitContract {
17630                de: de.into(),
17631                para: "downstream".into(),
17632                wit: "wasi:http/proxy".into(),
17633                endpoint: Some("/lookup".into()),
17634                subject: None,
17635                slot: None,
17636            };
17637            assert_eq!(
17638                c.source(),
17639                de,
17640                "WitContract::source must return :contratos :de verbatim \
17641                 (got {:?}, expected {de:?})",
17642                c.source(),
17643            );
17644            assert_eq!(
17645                c.source(),
17646                c.de.as_str(),
17647                "WitContract::source must byte-equal the .de field access",
17648            );
17649        }
17650    }
17651
17652    #[test]
17653    fn wit_contract_source_borrows_from_de_storage() {
17654        // The borrow-not-copy pin: [`WitContract::source`] must return a
17655        // `&str` slice that borrows from the typed slot's own [`String`]
17656        // storage — same-address invariant with `c.de.as_str()`. Pins
17657        // against a future silent detour that allocated a fresh `String`
17658        // (`self.de.clone()` in the body would type-check but silently
17659        // drop the borrow, and every downstream consumer that assumed
17660        // the returned slice outlives `&self` would break on a stale-
17661        // reference use-after-free). Peer of the sibling
17662        // `destination_borrows_from_entrada_para_storage` on the
17663        // per-`:entrada` axis.
17664        let c = WitContract {
17665            de: "cart".into(),
17666            para: "catalog".into(),
17667            wit: "wasi:http/proxy".into(),
17668            endpoint: Some("/lookup".into()),
17669            subject: None,
17670            slot: None,
17671        };
17672        let src = c.source();
17673        let de_slice = c.de.as_str();
17674        assert_eq!(
17675            src.as_ptr(),
17676            de_slice.as_ptr(),
17677            "WitContract::source must borrow from the .de String's \
17678             backing storage — a fresh allocation here means the \
17679             accessor no longer names the substrate-primitive typed \
17680             dispatch and every downstream consumer would silently \
17681             carry a detached copy",
17682        );
17683        assert_eq!(
17684            src.len(),
17685            de_slice.len(),
17686            "WitContract::source and .de.as_str() must byte-equal in \
17687             length as well as in address",
17688        );
17689    }
17690
17691    #[test]
17692    fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
17693        // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
17694        // must return the `:contratos :para` field byte-for-byte,
17695        // borrowed from the typed slot's own [`String`] storage. Peer of
17696        // the sibling `destination_returns_entrada_para_byte_equal` on
17697        // the per-`:entrada` axis — both accessors name "the destination-
17698        // Servico byte-string" concept on their respective mesh-slot
17699        // atoms (per-ingress apex vs. per-typed-edge callee) and both
17700        // must project the underlying `.para` field verbatim so every
17701        // downstream renderer that composes them with peer accessors
17702        // (e.g. `spec.port_for_destination(c.destination())` at the CNP
17703        // per-edge L4 port emit site) reads the same byte-string the
17704        // author declared.
17705        for para in ["catalog", "payment", "orders", "inventory-v3"] {
17706            let c = WitContract {
17707                de: "cart".into(),
17708                para: para.into(),
17709                wit: "wasi:http/proxy".into(),
17710                endpoint: Some("/lookup".into()),
17711                subject: None,
17712                slot: None,
17713            };
17714            assert_eq!(
17715                c.destination(),
17716                para,
17717                "WitContract::destination must return :contratos :para \
17718                 verbatim (got {:?}, expected {para:?})",
17719                c.destination(),
17720            );
17721            assert_eq!(
17722                c.destination(),
17723                c.para.as_str(),
17724                "WitContract::destination must byte-equal the .para \
17725                 field access",
17726            );
17727        }
17728    }
17729
17730    #[test]
17731    fn wit_contract_destination_borrows_from_para_storage() {
17732        // The borrow-not-copy pin: [`WitContract::destination`] must
17733        // return a `&str` slice that borrows from the typed slot's own
17734        // [`String`] storage — same-address invariant with
17735        // `c.para.as_str()`. Peer of the sibling
17736        // `destination_borrows_from_entrada_para_storage` on the
17737        // per-`:entrada` axis.
17738        let c = WitContract {
17739            de: "cart".into(),
17740            para: "catalog".into(),
17741            wit: "wasi:http/proxy".into(),
17742            endpoint: Some("/lookup".into()),
17743            subject: None,
17744            slot: None,
17745        };
17746        let dest = c.destination();
17747        let para_slice = c.para.as_str();
17748        assert_eq!(
17749            dest.as_ptr(),
17750            para_slice.as_ptr(),
17751            "WitContract::destination must borrow from the .para \
17752             String's backing storage — a fresh allocation here means \
17753             the accessor no longer names the substrate-primitive typed \
17754             dispatch and every downstream consumer would silently \
17755             carry a detached copy",
17756        );
17757        assert_eq!(
17758            dest.len(),
17759            para_slice.len(),
17760            "WitContract::destination and .para.as_str() must byte-equal \
17761             in length as well as in address",
17762        );
17763    }
17764
17765    #[test]
17766    fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
17767        // The canonical per-`:contratos` WIT-world-reference scalar pin:
17768        // [`WitContract::world_ref`] must return the `:contratos :wit`
17769        // field byte-for-byte, borrowed from the typed slot's own
17770        // [`String`] storage. Sibling of the peer per-`:contratos`
17771        // [`WitContract::source`] / [`WitContract::destination`]
17772        // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
17773        // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
17774        // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
17775        // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
17776        // "the substrate-primitive accessor must byte-equal the raw
17777        // field access verbatim across every author-declared value"
17778        // discipline extended to the per-`:contratos` WIT-world arm.
17779        // Pins against a future silent detour that re-canonicalized the
17780        // WIT world reference (an accidental `.to_lowercase()` pass that
17781        // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
17782        // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
17783        // gate is already lowercase-prefixed so any re-normalization is
17784        // redundant + a drift surface between the validator and the
17785        // accessor), an M4-promotion-shape rewrite that formatted a
17786        // typed WIT-world enum through [`Display`] and silently drifted
17787        // the printer output from the source `caixa.lisp`, or a per-
17788        // cluster WIT-alias rewrite that didn't land on the peer field-
17789        // access sites. Five values sweep the shape-dispatch accept-set
17790        // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
17791        // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
17792        // `wasi:keyvalue/`).
17793        for (wit, endpoint, subject, slot) in [
17794            ("wasi:http/proxy", Some("/lookup"), None, None),
17795            ("http:proxy", Some("/health"), None, None),
17796            ("nats:pub-sub", None, Some("orders.paid"), None),
17797            ("kafka:events", None, Some("checkout-events"), None),
17798            ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
17799        ] {
17800            let c = WitContract {
17801                de: "cart".into(),
17802                para: "downstream".into(),
17803                wit: wit.into(),
17804                endpoint: endpoint.map(str::to_string),
17805                subject: subject.map(str::to_string),
17806                slot: slot.map(str::to_string),
17807            };
17808            assert_eq!(
17809                c.world_ref(),
17810                wit,
17811                "WitContract::world_ref must return :contratos :wit \
17812                 verbatim (got {:?}, expected {wit:?})",
17813                c.world_ref(),
17814            );
17815            assert_eq!(
17816                c.world_ref(),
17817                c.wit.as_str(),
17818                "WitContract::world_ref must byte-equal the .wit field \
17819                 access",
17820            );
17821        }
17822    }
17823
17824    #[test]
17825    fn wit_contract_world_ref_borrows_from_wit_storage() {
17826        // The borrow-not-copy pin: [`WitContract::world_ref`] must
17827        // return a `&str` slice that borrows from the typed slot's own
17828        // [`String`] storage — same-address invariant with
17829        // `c.wit.as_str()`. Pins against a future silent detour that
17830        // allocated a fresh `String` (`self.wit.clone()` in the body
17831        // would type-check but silently drop the borrow, and every
17832        // downstream consumer that assumed the returned slice outlives
17833        // `&self` would break on a stale-reference use-after-free — the
17834        // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
17835        // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
17836        // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
17837        // / [`is_pubsub`][WitContract::is_pubsub] /
17838        // [`is_store`][WitContract::is_store] methods route through —
17839        // each borrow from the WitContract's own storage and each would
17840        // silently misbehave if this accessor produced a detached copy).
17841        // Peer of the sibling per-`:contratos` [`WitContract::source`] /
17842        // [`WitContract::destination`] and per-`:entrada`
17843        // [`Entrada::destination`] / [`Entrada::hostname`] and
17844        // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
17845        // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
17846        let c = WitContract {
17847            de: "cart".into(),
17848            para: "catalog".into(),
17849            wit: "wasi:http/proxy".into(),
17850            endpoint: Some("/lookup".into()),
17851            subject: None,
17852            slot: None,
17853        };
17854        let world = c.world_ref();
17855        let wit_slice = c.wit.as_str();
17856        assert_eq!(
17857            world.as_ptr(),
17858            wit_slice.as_ptr(),
17859            "WitContract::world_ref must borrow from the .wit String's \
17860             backing storage — a fresh allocation here means the \
17861             accessor no longer names the substrate-primitive typed \
17862             dispatch and every downstream consumer would silently carry \
17863             a detached copy",
17864        );
17865        assert_eq!(
17866            world.len(),
17867            wit_slice.len(),
17868            "WitContract::world_ref and .wit.as_str() must byte-equal in \
17869             length as well as in address",
17870        );
17871    }
17872
17873    #[test]
17874    fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
17875        // Sibling-triple invariant pin composing all three per-`:contratos`
17876        // substrate-primitive typed dispatches — [`WitContract::source`]
17877        // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
17878        // [`WitContract::world_ref`] — at the joint
17879        // `(source(), destination(), world_ref())` call shape every
17880        // renderer that fans on per-edge caller-callee-shape identity
17881        // keys off. The invariant, evaluated per-contract:
17882        //
17883        //   (c.source(), c.destination(), c.world_ref())
17884        //   == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
17885        //
17886        // Closes the last unlifted per-`:contratos` scalar axis — every
17887        // downstream consumer that reads the triple now routes through
17888        // exactly three typed dispatches on the substrate primitive,
17889        // not two typed + one open-coded field access. A future refactor
17890        // that silently split any one accessor's projection (an
17891        // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
17892        // canonicalization that didn't reach the peer `source`/
17893        // `destination` arms, an accidental `source()` per-cluster
17894        // caller-alias rewrite that didn't land on the `world_ref` peer)
17895        // surfaces at caixa-core build time. Peer of the sibling per-
17896        // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
17897        // per-`:entrada` `(hostname(), destination())` (6db982c /
17898        // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
17899        // axes, extended to the per-`:contratos` triple.
17900        for (de, para, wit, endpoint, subject, slot) in [
17901            (
17902                "cart",
17903                "catalog",
17904                "wasi:http/proxy",
17905                Some("/lookup"),
17906                None,
17907                None,
17908            ),
17909            (
17910                "checkout",
17911                "orders",
17912                "nats:pub-sub",
17913                None,
17914                Some("orders.paid"),
17915                None,
17916            ),
17917            (
17918                "cart",
17919                "kv",
17920                "wasi:keyvalue/store",
17921                None,
17922                None,
17923                Some("carts/{cart_id}"),
17924            ),
17925            (
17926                "orders-v2",
17927                "inventory-v3",
17928                "http:proxy",
17929                Some("/reserve"),
17930                None,
17931                None,
17932            ),
17933        ] {
17934            let c = WitContract {
17935                de: de.into(),
17936                para: para.into(),
17937                wit: wit.into(),
17938                endpoint: endpoint.map(str::to_string),
17939                subject: subject.map(str::to_string),
17940                slot: slot.map(str::to_string),
17941            };
17942            assert_eq!(
17943                (c.source(), c.destination(), c.world_ref()),
17944                (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
17945                "(WitContract::source, ::destination, ::world_ref) must \
17946                 project (.de, .para, .wit) verbatim across every author-\
17947                 declared triple (got ({:?}, {:?}, {:?}), expected \
17948                 ({de:?}, {para:?}, {wit:?}))",
17949                c.source(),
17950                c.destination(),
17951                c.world_ref(),
17952            );
17953        }
17954    }
17955
17956    #[test]
17957    fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
17958        // The canonical per-`:contratos` owned-form caller-callee-pair
17959        // pin: [`WitContract::edge_pair`] must return the
17960        // `(source(), destination())` tuple in owned form byte-for-byte,
17961        // projected through the lifted [`WitContract::source`] /
17962        // [`WitContract::destination`] scalar accessors. Pins the
17963        // composite-projection invariant on the per-`:contratos`
17964        // mesh-slot atom — every author-declared `(de, para)` pair must
17965        // round-trip verbatim through the substrate primitive's typed
17966        // dispatch, so the nine [`AplicacaoError`] diagnostic-
17967        // construction sites the accessor now feeds
17968        // ([`AplicacaoError::EmptyWit`],
17969        // [`AplicacaoError::ContratoEndpointEmpty`],
17970        // [`AplicacaoError::ContratoEndpointNotAbsolute`],
17971        // [`AplicacaoError::ContratoEndpointInvalid`],
17972        // [`AplicacaoError::ContratoSubjectEmpty`],
17973        // [`AplicacaoError::ContratoSubjectInvalid`],
17974        // [`AplicacaoError::ContratoSlotEmpty`],
17975        // [`AplicacaoError::ContratoSlotInvalid`],
17976        // [`AplicacaoError::ContratoDuplicate`]) all read the same
17977        // `(de, para)` label pair every author sees at the source
17978        // `caixa.lisp`. Pins against a future silent detour that swapped
17979        // the `.0` / `.1` arms (an accidental `(destination(),
17980        // source())` re-order in the body would silently invert every
17981        // downstream diagnostic's `de:` / `para:` label pair, silently
17982        // reversing the direction of every operator-facing typed error
17983        // arrow), a fresh-allocation shape drift (an accidental
17984        // `.to_string()` on one arm but not the other would leave the
17985        // owned/borrowed pair mismatched vs. the sibling `source()` /
17986        // `destination()` returns), or an M4 per-cluster caller/callee-
17987        // alias rewrite that landed on `source()` without reaching
17988        // `destination()` (or vice versa). Peer of the sibling per-
17989        // `:contratos` `(source, destination, world_ref)` triple
17990        // pin above on the mesh-slot-atom scalar-value axes, extended
17991        // to the owned-form pair-projection axis.
17992        for (de, para, wit, endpoint, subject, slot) in [
17993            (
17994                "cart",
17995                "catalog",
17996                "wasi:http/proxy",
17997                Some("/lookup"),
17998                None,
17999                None,
18000            ),
18001            (
18002                "checkout",
18003                "orders",
18004                "nats:pub-sub",
18005                None,
18006                Some("orders.paid"),
18007                None,
18008            ),
18009            (
18010                "cart",
18011                "kv",
18012                "wasi:keyvalue/store",
18013                None,
18014                None,
18015                Some("carts/{cart_id}"),
18016            ),
18017            (
18018                "orders-v2",
18019                "inventory-v3",
18020                "http:proxy",
18021                Some("/reserve"),
18022                None,
18023                None,
18024            ),
18025        ] {
18026            let c = WitContract {
18027                de: de.into(),
18028                para: para.into(),
18029                wit: wit.into(),
18030                endpoint: endpoint.map(str::to_string),
18031                subject: subject.map(str::to_string),
18032                slot: slot.map(str::to_string),
18033            };
18034            assert_eq!(
18035                c.edge_pair(),
18036                (de.to_string(), para.to_string()),
18037                "WitContract::edge_pair must return (:contratos :de, \
18038                 :contratos :para) as an owned tuple verbatim (got {:?}, \
18039                 expected ({de:?}, {para:?}))",
18040                c.edge_pair(),
18041            );
18042        }
18043    }
18044
18045    #[test]
18046    fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
18047        // The composition pin: [`WitContract::edge_pair`] must return
18048        // exactly `(source().to_string(), destination().to_string())` —
18049        // the owned form of the sibling accessor pair — so any future
18050        // refactor that silently re-authored the caller-arm / callee-arm
18051        // projection to bypass the lifted scalar accessors (an accidental
18052        // `(self.de.clone(), self.para.clone())` regression back to the
18053        // raw field-access shape, an M4-typed-caller-enum `Display`
18054        // re-canonicalization on `source()` that didn't reach
18055        // `edge_pair()`, a per-cluster alias rewrite the operator lands
18056        // on `destination()` without reaching this composite projection)
18057        // trips at caixa-core build time. Pins the "typed dispatch
18058        // composes with typed dispatch, not with raw field access"
18059        // discipline every downstream diagnostic-construction site now
18060        // routes through — a `de:` / `para:` label pair whose
18061        // projection silently drifted off the substrate primitive's
18062        // scalar accessors would silently split the diagnostic's self-
18063        // locating signal from the source `caixa.lisp` author's view.
18064        // Peer of the sibling per-`:politicas` `is_empty` /
18065        // `validate_politicas` accessor-routing-pin family on the M3
18066        // mesh-slot family (18575, 18739, 18918, 19140, 19371).
18067        let c = WitContract {
18068            de: "cart".into(),
18069            para: "catalog".into(),
18070            wit: "wasi:http/proxy".into(),
18071            endpoint: Some("/lookup".into()),
18072            subject: None,
18073            slot: None,
18074        };
18075        assert_eq!(
18076            c.edge_pair(),
18077            (c.source().to_string(), c.destination().to_string()),
18078            "WitContract::edge_pair must compose exactly \
18079             (source().to_string(), destination().to_string()) — a \
18080             bypass of either sibling accessor here would silently \
18081             decouple the composite-projection axis from the \
18082             substrate-primitive scalar accessors every downstream \
18083             consumer routes through",
18084        );
18085    }
18086
18087    #[test]
18088    fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
18089     {
18090        // The canonical per-`:contratos` owned-form
18091        // caller-callee-world-ref-triple pin:
18092        // [`WitContract::edge_triple`] must return the
18093        // `(source(), destination(), world_ref())` tuple in owned form
18094        // byte-for-byte, projected through the lifted
18095        // [`WitContract::source`] / [`WitContract::destination`] /
18096        // [`WitContract::world_ref`] scalar accessors. Pins the
18097        // composite-projection invariant on the per-`:contratos`
18098        // mesh-slot atom — every author-declared `(de, para, wit)`
18099        // triple must round-trip verbatim through the substrate
18100        // primitive's typed dispatch, so the nine
18101        // [`AplicacaoError`] diagnostic-construction sites the
18102        // accessor now feeds (the [`WitTarget`]-dispatch's eight
18103        // wrong-target / missing-target / invalid-wit / capability-
18104        // with-payload arms in [`WitContract::target`], plus the
18105        // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
18106        // diagnostic constructor in [`AplicacaoSpec::validate`]) all
18107        // read the same `(de, para, wit)` triple every author sees at
18108        // the source `caixa.lisp`. Pins against a future silent
18109        // detour that swapped any two arms (an accidental `(destination(),
18110        // source(), world_ref())` re-order in the body would silently
18111        // invert every downstream diagnostic's `de:` / `para:` label
18112        // pair, silently reversing the direction of every operator-
18113        // facing typed error arrow), a fresh-allocation shape drift
18114        // (an accidental `.to_string()` skipped on one arm would leave
18115        // the owned/borrowed triple mismatched vs. the sibling
18116        // `source()` / `destination()` / `world_ref()` returns), or an
18117        // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
18118        // canonicalization pass that landed on one accessor without
18119        // reaching the peers. Peer of the sibling per-`:contratos`
18120        // caller-callee-pair
18121        // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
18122        // pin on the mesh-slot-atom composite-projection axis,
18123        // extended to the triple-projection axis.
18124        for (de, para, wit, endpoint, subject, slot) in [
18125            (
18126                "cart",
18127                "catalog",
18128                "wasi:http/proxy",
18129                Some("/lookup"),
18130                None,
18131                None,
18132            ),
18133            (
18134                "checkout",
18135                "orders",
18136                "nats:pub-sub",
18137                None,
18138                Some("orders.paid"),
18139                None,
18140            ),
18141            (
18142                "cart",
18143                "kv",
18144                "wasi:keyvalue/store",
18145                None,
18146                None,
18147                Some("carts/{cart_id}"),
18148            ),
18149            (
18150                "orders-v2",
18151                "inventory-v3",
18152                "http:proxy",
18153                Some("/reserve"),
18154                None,
18155                None,
18156            ),
18157        ] {
18158            let c = WitContract {
18159                de: de.into(),
18160                para: para.into(),
18161                wit: wit.into(),
18162                endpoint: endpoint.map(str::to_string),
18163                subject: subject.map(str::to_string),
18164                slot: slot.map(str::to_string),
18165            };
18166            assert_eq!(
18167                c.edge_triple(),
18168                (de.to_string(), para.to_string(), wit.to_string()),
18169                "WitContract::edge_triple must return (:contratos :de, \
18170                 :contratos :para, :contratos :wit) as an owned triple \
18171                 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
18172                c.edge_triple(),
18173            );
18174        }
18175    }
18176
18177    #[test]
18178    fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
18179        // The composition pin: [`WitContract::edge_triple`] must return
18180        // exactly `(source().to_string(), destination().to_string(),
18181        // world_ref().to_string())` — the owned form of the sibling
18182        // scalar-accessor triple — so any future refactor that silently
18183        // re-authored one arm's projection to bypass the lifted scalar
18184        // accessors (an accidental `(self.de.clone(), self.para.clone(),
18185        // self.wit.clone())` regression back to the raw field-access
18186        // shape the internal `edge` closure and the ContratoDuplicate
18187        // diagnostic both carried before this lift landed, an
18188        // M4-typed-caller-enum `Display` re-canonicalization on
18189        // `source()` that didn't reach `edge_triple()`, a per-cluster
18190        // alias rewrite the operator lands on `destination()` /
18191        // `world_ref()` without reaching this composite projection)
18192        // trips at caixa-core build time. Pins the "typed dispatch
18193        // composes with typed dispatch, not with raw field access"
18194        // discipline every downstream diagnostic-construction site now
18195        // routes through — a `de:` / `para:` / `wit:` triple whose
18196        // projection silently drifted off the substrate primitive's
18197        // scalar accessors would silently split the diagnostic's self-
18198        // locating signal from the source `caixa.lisp` author's view.
18199        // Peer of the sibling per-`:contratos` edge_pair composition-
18200        // pin above on the mesh-slot-atom composite-projection axis.
18201        let c = WitContract {
18202            de: "cart".into(),
18203            para: "catalog".into(),
18204            wit: "wasi:http/proxy".into(),
18205            endpoint: Some("/lookup".into()),
18206            subject: None,
18207            slot: None,
18208        };
18209        assert_eq!(
18210            c.edge_triple(),
18211            (
18212                c.source().to_string(),
18213                c.destination().to_string(),
18214                c.world_ref().to_string(),
18215            ),
18216            "WitContract::edge_triple must compose exactly \
18217             (source().to_string(), destination().to_string(), \
18218             world_ref().to_string()) — a bypass of any sibling accessor \
18219             here would silently decouple the composite-projection axis \
18220             from the substrate-primitive scalar accessors every \
18221             downstream consumer routes through",
18222        );
18223    }
18224
18225    #[test]
18226    fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
18227        // The canonical semantics-pin: [`WitContract::edge_triple`] must
18228        // project the full `(de, para, wit)` identity of a `:contratos`
18229        // edge — the sub-triple every triple-carrying
18230        // [`AplicacaoError::Contrato*`] diagnostic weaves into its
18231        // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
18232        // missing-target, capability-with-payload, invalid-wit, and the
18233        // duplicate-gate). Rejects a drift in shape (an accidental
18234        // silent detour that returned a `(de, para)` pair or added an
18235        // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
18236        // would trip here because the return type would no longer
18237        // pattern-match the eight `let (de, para, wit) = edge();`
18238        // destructures the [`WitContract::target`] dispatch feeds off
18239        // + the paired duplicate-gate `let (de, para, wit) =
18240        // c.edge_triple();` destructure in
18241        // [`AplicacaoSpec::validate`]). Peer of the sibling per-
18242        // `:contratos` caller-callee-pair pin above extended to the
18243        // triple projection surface: closes the "one composite
18244        // accessor per typed diagnostic-construction sub-tuple"
18245        // discipline on the per-`:contratos` mesh-slot-atom axis.
18246        let c = WitContract {
18247            de: "checkout".into(),
18248            para: "orders".into(),
18249            wit: "nats:pub-sub".into(),
18250            endpoint: None,
18251            subject: Some("orders.paid".into()),
18252            slot: None,
18253        };
18254        let (de, para, wit) = c.edge_triple();
18255        assert_eq!(de, "checkout");
18256        assert_eq!(para, "orders");
18257        assert_eq!(wit, "nats:pub-sub");
18258    }
18259
18260    #[test]
18261    fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
18262     {
18263        // The composition pin: [`WitContract::identity`] must return
18264        // exactly `(source(), destination(), world_ref(), endpoint(),
18265        // subject(), slot())` — the borrowed form of the six-scalar-
18266        // accessor identity axis. Any future refactor that silently
18267        // re-authored one arm's projection to bypass a scalar accessor
18268        // (a `self.de.as_str()` regression back to raw field access on
18269        // any of the three required arms, a `self.endpoint.as_deref()`
18270        // regression on any of the three optional arms, an M4 per-
18271        // cluster caller/callee-alias rewrite the operator lands on
18272        // `source()` / `destination()` without reaching this composite
18273        // projection) trips at caixa-core build time. Sweeps four
18274        // permutations of the WIT-shape × payload lattice — HTTP with
18275        // endpoint, pub-sub with subject, store with slot, payload-less
18276        // capability — so every payload arm is exercised. Peer of the
18277        // sibling per-`:contratos`
18278        // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
18279        // composition pin on the mesh-slot-atom composite-projection
18280        // axis; extends the discipline from the (de, para, wit) prefix
18281        // onto the full-identity axis carrying the three payload arms.
18282        for (de, para, wit, endpoint, subject, slot) in [
18283            (
18284                "cart",
18285                "catalog",
18286                "wasi:http/proxy",
18287                Some("/lookup"),
18288                None,
18289                None,
18290            ),
18291            (
18292                "checkout",
18293                "orders",
18294                "nats:pub-sub",
18295                None,
18296                Some("orders.paid"),
18297                None,
18298            ),
18299            (
18300                "cart",
18301                "kv",
18302                "wasi:keyvalue/store",
18303                None,
18304                None,
18305                Some("carts/{cart_id}"),
18306            ),
18307            ("audit", "sink", "wasi:logging", None, None, None),
18308        ] {
18309            let c = WitContract {
18310                de: de.into(),
18311                para: para.into(),
18312                wit: wit.into(),
18313                endpoint: endpoint.map(str::to_owned),
18314                subject: subject.map(str::to_owned),
18315                slot: slot.map(str::to_owned),
18316            };
18317            assert_eq!(
18318                c.identity(),
18319                (
18320                    c.source(),
18321                    c.destination(),
18322                    c.world_ref(),
18323                    c.endpoint(),
18324                    c.subject(),
18325                    c.slot(),
18326                ),
18327                "WitContract::identity must compose exactly \
18328                 (source(), destination(), world_ref(), endpoint(), \
18329                 subject(), slot()) — a bypass of any sibling accessor \
18330                 here would silently decouple the identity-projection \
18331                 axis from the substrate-primitive scalar accessors \
18332                 every dedup-key consumer routes through",
18333            );
18334        }
18335    }
18336
18337    #[test]
18338    fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
18339        // The canonical semantics-pin: [`WitContract::identity`] must
18340        // project the six-axis (de, para, wit, endpoint, subject, slot)
18341        // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
18342        // gate keys off — two `WitContract`s that agree on all six axes
18343        // are the same typed edge declared twice, the graph-edge
18344        // analogue of duplicate `:membros` / `:placement :clusters` /
18345        // `:entrada :paths` entries. Rejects a shape drift (an
18346        // accidental silent detour that returned a prefix tuple or
18347        // added an extra field) by pattern-matching the six-arm shape.
18348        // Peer of the sibling per-`:contratos`
18349        // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
18350        // pin extended from the (de, para, wit) prefix onto the full
18351        // six-axis identity that the dedup key rides.
18352        let c = WitContract {
18353            de: "cart".into(),
18354            para: "catalog".into(),
18355            wit: "wasi:http/proxy".into(),
18356            endpoint: Some("/products/:id".into()),
18357            subject: None,
18358            slot: None,
18359        };
18360        let (de, para, wit, endpoint, subject, slot) = c.identity();
18361        assert_eq!(de, "cart");
18362        assert_eq!(para, "catalog");
18363        assert_eq!(wit, "wasi:http/proxy");
18364        assert_eq!(endpoint, Some("/products/:id"));
18365        assert_eq!(subject, None);
18366        assert_eq!(slot, None);
18367
18368        // Two byte-identical contracts must produce equal identities —
18369        // the dedup key's foundational invariant.
18370        let c2 = c.clone();
18371        assert_eq!(c.identity(), c2.identity());
18372
18373        // Any change on any of the six axes must break the identity —
18374        // sweeps by mutating one axis at a time.
18375        let mut mutated = c.clone();
18376        mutated.de = "search".into();
18377        assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
18378        let mut mutated = c.clone();
18379        mutated.para = "warehouse".into();
18380        assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
18381        let mut mutated = c.clone();
18382        mutated.wit = "http:legacy".into();
18383        assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
18384        let mut mutated = c.clone();
18385        mutated.endpoint = Some("/search".into());
18386        assert_ne!(
18387            c.identity(),
18388            mutated.identity(),
18389            "endpoint axis must partition"
18390        );
18391        let mut mutated = c.clone();
18392        mutated.subject = Some("orders.paid".into());
18393        assert_ne!(
18394            c.identity(),
18395            mutated.identity(),
18396            "subject axis must partition"
18397        );
18398        let mut mutated = c;
18399        mutated.slot = Some("carts/{id}".into());
18400        assert_ne!(mutated.identity().5, None, "slot axis must partition");
18401    }
18402
18403    #[test]
18404    fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
18405        // The canonical per-`:contratos` structural-self-edge pin:
18406        // [`WitContract::is_self_loop`] must return `true` when the
18407        // `:de` and `:para` fields agree byte-for-byte, across every
18408        // WIT-shape variant the per-edge shape family carries. Pins
18409        // the shape-agnostic identity-space partition the
18410        // [`AplicacaoSpec::validate`] self-edge gate at
18411        // caixa-core/src/aplicacao.rs:5559 fires against — all four
18412        // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
18413        // under the same one predicate. Four permutations sweep the
18414        // accept-set: HTTP with endpoint, pub-sub with subject, KV
18415        // store with slot, and payload-less capability.
18416        for (nome, wit, endpoint, subject, slot) in [
18417            ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
18418            ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
18419            (
18420                "kv",
18421                "wasi:keyvalue/store",
18422                None,
18423                None,
18424                Some("carts/{cart_id}"),
18425            ),
18426            ("audit", "wasi:logging", None, None, None),
18427        ] {
18428            let c = WitContract {
18429                de: nome.into(),
18430                para: nome.into(),
18431                wit: wit.into(),
18432                endpoint: endpoint.map(str::to_string),
18433                subject: subject.map(str::to_string),
18434                slot: slot.map(str::to_string),
18435            };
18436            assert!(
18437                c.is_self_loop(),
18438                "WitContract::is_self_loop must return true when \
18439                 :contratos :de == :contratos :para (got false on \
18440                 {nome:?} under {wit:?})",
18441            );
18442        }
18443    }
18444
18445    #[test]
18446    fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
18447        // The complement pin: [`WitContract::is_self_loop`] must return
18448        // `false` on every well-shaped inter-Servico contract (the
18449        // author-intended `:contratos` shape MESH-COMPOSITION §III.1
18450        // names — "Servico A calls Servico B" between two distinct
18451        // graph nodes). Pins against a future silent detour that
18452        // inverted the predicate (an accidental `!= ` swap for `==`
18453        // would silently reject every legitimate inter-Servico edge
18454        // and admit every self-edge — the exact inversion of the
18455        // author-intended shape). Four permutations sweep the same
18456        // WIT-shape accept-set the sibling positive-arm test carries.
18457        for (de, para, wit, endpoint, subject, slot) in [
18458            (
18459                "cart",
18460                "catalog",
18461                "wasi:http/proxy",
18462                Some("/lookup"),
18463                None,
18464                None,
18465            ),
18466            (
18467                "checkout",
18468                "orders",
18469                "nats:pub-sub",
18470                None,
18471                Some("orders.paid"),
18472                None,
18473            ),
18474            (
18475                "cart",
18476                "kv",
18477                "wasi:keyvalue/store",
18478                None,
18479                None,
18480                Some("carts/{cart_id}"),
18481            ),
18482            ("audit", "sink", "wasi:logging", None, None, None),
18483        ] {
18484            let c = WitContract {
18485                de: de.into(),
18486                para: para.into(),
18487                wit: wit.into(),
18488                endpoint: endpoint.map(str::to_string),
18489                subject: subject.map(str::to_string),
18490                slot: slot.map(str::to_string),
18491            };
18492            assert!(
18493                !c.is_self_loop(),
18494                "WitContract::is_self_loop must return false when \
18495                 :contratos :de differs from :contratos :para (got true \
18496                 on {de:?} → {para:?} under {wit:?})",
18497            );
18498        }
18499    }
18500
18501    #[test]
18502    fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
18503        // The composition pin: [`WitContract::is_self_loop`] must
18504        // resolve to exactly `self.source() == self.destination()` —
18505        // the equality probe of the sibling scalar-accessor pair — so
18506        // any future refactor that silently re-authored the predicate
18507        // to bypass the lifted scalar accessors (an accidental
18508        // `self.de == self.para` regression back to the raw field-
18509        // access shape, an M4-typed-caller-enum identity-comparison
18510        // rule that landed on `source()` without reaching
18511        // `destination()`, a per-cluster alias rewrite the operator
18512        // pins on `destination()` without reaching this predicate)
18513        // trips at caixa-core build time. Pins the "typed dispatch
18514        // composes with typed dispatch, not with raw field access"
18515        // discipline the sibling [`WitContract::edge_pair`] /
18516        // [`WitContract::edge_triple`] composite-projection accessors
18517        // already carry, extended onto the per-edge endpoint-equality
18518        // predicate axis. Positive and complement arms both fire.
18519        let self_edge = WitContract {
18520            de: "cart".into(),
18521            para: "cart".into(),
18522            wit: "wasi:http/proxy".into(),
18523            endpoint: Some("/lookup".into()),
18524            subject: None,
18525            slot: None,
18526        };
18527        assert_eq!(
18528            self_edge.is_self_loop(),
18529            self_edge.source() == self_edge.destination(),
18530            "WitContract::is_self_loop must compose exactly \
18531             `source() == destination()` — a bypass of either sibling \
18532             accessor here would silently decouple the endpoint-\
18533             equality predicate from the substrate-primitive scalar \
18534             accessors every downstream consumer routes through",
18535        );
18536        let inter_edge = WitContract {
18537            de: "cart".into(),
18538            para: "catalog".into(),
18539            wit: "wasi:http/proxy".into(),
18540            endpoint: Some("/lookup".into()),
18541            subject: None,
18542            slot: None,
18543        };
18544        assert_eq!(
18545            inter_edge.is_self_loop(),
18546            inter_edge.source() == inter_edge.destination(),
18547            "WitContract::is_self_loop must compose exactly \
18548             `source() == destination()` on the complement arm too",
18549        );
18550    }
18551
18552    #[test]
18553    fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
18554        // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
18555        // pin: [`WitContract::endpoint`] must return the `:contratos
18556        // :endpoint` field byte-for-byte, borrowed from the typed slot's
18557        // own `Option<String>` storage. Peer of the sibling
18558        // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
18559        // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
18560        // mesh-slot `Option<String>` optional-scalar axes — same "the
18561        // substrate-primitive accessor must byte-equal the raw field
18562        // access verbatim across every author-declared value" discipline
18563        // extended to the per-`:contratos` HTTP-payload-carrier arm.
18564        // Pins against a future silent detour that re-canonicalized the
18565        // endpoint (an accidental percent-encoding pass that didn't
18566        // reach the peer field-access site at the dedup key, a per-CR
18567        // fully-qualified prefix rewrite the operator authors on one
18568        // consumer without the other, or an M4 typed-path-template
18569        // `Display` re-canonicalization that silently drifted the
18570        // printer output from the source `caixa.lisp`). Four values
18571        // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
18572        // gate upstream admits (short root-path, dashed, param-shaped,
18573        // deep-hierarchy).
18574        for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
18575            let c = WitContract {
18576                de: "cart".into(),
18577                para: "catalog".into(),
18578                wit: "wasi:http/proxy".into(),
18579                endpoint: Some(endpoint.into()),
18580                subject: None,
18581                slot: None,
18582            };
18583            assert_eq!(
18584                c.endpoint(),
18585                Some(endpoint),
18586                "WitContract::endpoint must return :contratos :endpoint \
18587                 verbatim (got {:?}, expected Some({endpoint:?}))",
18588                c.endpoint(),
18589            );
18590            assert_eq!(
18591                c.endpoint(),
18592                c.endpoint.as_deref(),
18593                "WitContract::endpoint must byte-equal the .endpoint \
18594                 field's `.as_deref()` projection",
18595            );
18596        }
18597    }
18598
18599    #[test]
18600    fn wit_contract_endpoint_none_when_field_is_none() {
18601        // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
18602        // payload-carrier accessor pin: when the typed slot is absent —
18603        // the canonical shape under a non-HTTP `:wit` world per the
18604        // [`WitContract::target`]-enforced shape ↔ target partition
18605        // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
18606        // carries `:slot`, [`WitTarget::Capability`] carries none) —
18607        // [`WitContract::endpoint`] must return `None`. Pins against a
18608        // future silent detour that projected the absent slot to a
18609        // `Some("")` empty-string default (the canonical `Option<String>`
18610        // → `String` collapse footgun the sibling M2
18611        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
18612        // emptiness predicates already guard on the peer M2 typed-slot
18613        // surfaces), a `Some("None")` stringified-None round-trip, or a
18614        // `Some` arm whose contents were derived from a sibling slot (an
18615        // accidental fallback to the `:subject` / `:slot` payload that
18616        // read the pub-sub / store payload into the endpoint axis).
18617        // Three contracts sweep the accept-set every non-HTTP `:wit`
18618        // world lands on — pub-sub NATS, key/value, and payload-less
18619        // capability.
18620        for (wit, subject, slot) in [
18621            ("nats:pub-sub", Some("orders.paid"), None),
18622            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
18623            ("wasi:cli/environment", None, None),
18624        ] {
18625            let c = WitContract {
18626                de: "cart".into(),
18627                para: "downstream".into(),
18628                wit: wit.into(),
18629                endpoint: None,
18630                subject: subject.map(str::to_string),
18631                slot: slot.map(str::to_string),
18632            };
18633            assert!(
18634                c.endpoint().is_none(),
18635                "WitContract::endpoint must return None when the typed \
18636                 slot is absent under :wit {wit:?} (got {:?})",
18637                c.endpoint(),
18638            );
18639            assert_eq!(
18640                c.endpoint(),
18641                c.endpoint.as_deref(),
18642                "WitContract::endpoint must byte-equal the .endpoint \
18643                 field's `.as_deref()` projection in the absent arm",
18644            );
18645        }
18646    }
18647
18648    #[test]
18649    fn wit_contract_endpoint_borrows_from_endpoint_storage() {
18650        // The borrow-not-copy pin: [`WitContract::endpoint`] must return
18651        // an `Option<&str>` whose `Some` arm borrows from the typed
18652        // slot's own [`String`] storage — same-address invariant with
18653        // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
18654        // detour that allocated a fresh `String`
18655        // (`self.endpoint.clone().map(...)` in the body would type-check
18656        // but silently drop the borrow, and every downstream consumer
18657        // that assumed the returned slice outlives `&self` would break
18658        // on a stale-reference use-after-free — the [`WitContract::target`]
18659        // Http-arm payload extraction rebinds the returned `Option<&str>`
18660        // through `.ok_or_else(...)` and threads the `&str` payload into
18661        // [`WitTarget::Http { endpoint: &'a str }`], the
18662        // [`AplicacaoSpec::validate`] duplicate-`:contratos`
18663        // [`ContratoIdentity`] dedup key threads the returned
18664        // `Option<&str>` into the six-tuple's HTTP arm — each borrow
18665        // from the WitContract's own storage and each would silently
18666        // misbehave if this accessor produced a detached copy). Peer of
18667        // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
18668        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
18669        // shaped optional-scalar axes — first extension of the
18670        // `Option<&str>` borrow-not-copy discipline onto the
18671        // per-`:contratos` HTTP-shaped payload-carrier axis.
18672        let c = WitContract {
18673            de: "cart".into(),
18674            para: "catalog".into(),
18675            wit: "wasi:http/proxy".into(),
18676            endpoint: Some("/lookup".into()),
18677            subject: None,
18678            slot: None,
18679        };
18680        let ep = c.endpoint().expect("Some arm");
18681        let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
18682        assert_eq!(
18683            ep.as_ptr(),
18684            storage_slice.as_ptr(),
18685            "WitContract::endpoint must borrow from the .endpoint \
18686             String's backing storage — a fresh allocation here means \
18687             the accessor no longer names the substrate-primitive typed \
18688             dispatch and every downstream consumer would silently \
18689             carry a detached copy",
18690        );
18691        assert_eq!(
18692            ep.len(),
18693            storage_slice.len(),
18694            "WitContract::endpoint and .endpoint.as_deref() must byte-\
18695             equal in length as well as in address",
18696        );
18697    }
18698
18699    #[test]
18700    fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
18701        // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
18702        // pin: [`WitContract::subject`] must return the `:contratos
18703        // :subject` field byte-for-byte, borrowed from the typed slot's
18704        // own `Option<String>` storage. Peer of the sibling per-`:contratos`
18705        // [`WitContract::endpoint`] (7020470) accessor pin on the M3
18706        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
18707        // optional-scalar axis — same "the substrate-primitive accessor
18708        // must byte-equal the raw field access verbatim across every
18709        // author-declared value" discipline extended to the pub-sub arm.
18710        // Pins against a future silent detour that re-canonicalized the
18711        // subject (an accidental `.to_lowercase()` normalization that
18712        // didn't reach the peer field-access site at the dedup key, a
18713        // per-CR fully-qualified prefix rewrite the operator authors on
18714        // one consumer without the other, or an M4 typed-subject-template
18715        // `Display` re-canonicalization that silently drifted the printer
18716        // output from the source `caixa.lisp`). Four values sweep the
18717        // NATS accept-set every pub-sub author-declared subject lands on
18718        // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
18719        for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
18720            let c = WitContract {
18721                de: "cart".into(),
18722                para: "notifier".into(),
18723                wit: "nats:pub-sub".into(),
18724                endpoint: None,
18725                subject: Some(subject.into()),
18726                slot: None,
18727            };
18728            assert_eq!(
18729                c.subject(),
18730                Some(subject),
18731                "WitContract::subject must return :contratos :subject \
18732                 verbatim (got {:?}, expected Some({subject:?}))",
18733                c.subject(),
18734            );
18735            assert_eq!(
18736                c.subject(),
18737                c.subject.as_deref(),
18738                "WitContract::subject must byte-equal the .subject \
18739                 field's `.as_deref()` projection",
18740            );
18741        }
18742    }
18743
18744    #[test]
18745    fn wit_contract_subject_none_when_field_is_none() {
18746        // The absent-`:subject` arm of the per-`:contratos` pub-sub-
18747        // shaped payload-carrier accessor pin: when the typed slot is
18748        // absent — the canonical shape under a non-pub-sub `:wit` world
18749        // per the [`WitContract::target`]-enforced shape ↔ target
18750        // partition ([`WitTarget::Http`] carries `:endpoint`,
18751        // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
18752        // carries none) — [`WitContract::subject`] must return `None`.
18753        // Pins against a future silent detour that projected the absent
18754        // slot to a `Some("")` empty-string default (the canonical
18755        // `Option<String>` → `String` collapse footgun the sibling M2
18756        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
18757        // emptiness predicates already guard on the peer M2 typed-slot
18758        // surfaces), a `Some("None")` stringified-None round-trip, or a
18759        // `Some` arm whose contents were derived from a sibling slot (an
18760        // accidental fallback to the `:endpoint` / `:slot` payload that
18761        // read the HTTP / store payload into the subject axis). Three
18762        // contracts sweep the accept-set every non-pub-sub `:wit` world
18763        // lands on — HTTP proxy, key/value store, and payload-less
18764        // capability.
18765        for (wit, endpoint, slot) in [
18766            ("wasi:http/proxy", Some("/lookup"), None),
18767            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
18768            ("wasi:cli/environment", None, None),
18769        ] {
18770            let c = WitContract {
18771                de: "cart".into(),
18772                para: "downstream".into(),
18773                wit: wit.into(),
18774                endpoint: endpoint.map(str::to_string),
18775                subject: None,
18776                slot: slot.map(str::to_string),
18777            };
18778            assert!(
18779                c.subject().is_none(),
18780                "WitContract::subject must return None when the typed \
18781                 slot is absent under :wit {wit:?} (got {:?})",
18782                c.subject(),
18783            );
18784            assert_eq!(
18785                c.subject(),
18786                c.subject.as_deref(),
18787                "WitContract::subject must byte-equal the .subject \
18788                 field's `.as_deref()` projection in the absent arm",
18789            );
18790        }
18791    }
18792
18793    #[test]
18794    fn wit_contract_subject_borrows_from_subject_storage() {
18795        // The borrow-not-copy pin: [`WitContract::subject`] must return
18796        // an `Option<&str>` whose `Some` arm borrows from the typed
18797        // slot's own [`String`] storage — same-address invariant with
18798        // `c.subject.as_deref().unwrap()`. Pins against a future silent
18799        // detour that allocated a fresh `String`
18800        // (`self.subject.clone().map(...)` in the body would type-check
18801        // but silently drop the borrow, and every downstream consumer
18802        // that assumed the returned slice outlives `&self` would break
18803        // on a stale-reference use-after-free — the [`WitContract::target`]
18804        // PubSub-arm payload extraction rebinds the returned
18805        // `Option<&str>` through `.ok_or_else(...)` and threads the
18806        // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
18807        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
18808        // [`ContratoIdentity`] dedup key threads the returned
18809        // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
18810        // from the WitContract's own storage and each would silently
18811        // misbehave if this accessor produced a detached copy). Peer of
18812        // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
18813        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
18814        // shaped optional-scalar axis — second extension of the
18815        // `Option<&str>` borrow-not-copy discipline onto the
18816        // per-`:contratos` payload-carrier family, this time on the
18817        // pub-sub arm.
18818        let c = WitContract {
18819            de: "cart".into(),
18820            para: "notifier".into(),
18821            wit: "nats:pub-sub".into(),
18822            endpoint: None,
18823            subject: Some("orders.paid".into()),
18824            slot: None,
18825        };
18826        let sub = c.subject().expect("Some arm");
18827        let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
18828        assert_eq!(
18829            sub.as_ptr(),
18830            storage_slice.as_ptr(),
18831            "WitContract::subject must borrow from the .subject \
18832             String's backing storage — a fresh allocation here means \
18833             the accessor no longer names the substrate-primitive typed \
18834             dispatch and every downstream consumer would silently \
18835             carry a detached copy",
18836        );
18837        assert_eq!(
18838            sub.len(),
18839            storage_slice.len(),
18840            "WitContract::subject and .subject.as_deref() must byte-\
18841             equal in length as well as in address",
18842        );
18843    }
18844
18845    #[test]
18846    fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
18847        // The canonical per-`:contratos` key/value-store-shaped
18848        // `:slot`-scalar pin: [`WitContract::slot`] must return the
18849        // `:contratos :slot` field byte-for-byte, borrowed from the
18850        // typed slot's own `Option<String>` storage. Peer of the
18851        // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
18852        // [`WitContract::subject`] (90de675) accessor pins on the M3
18853        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
18854        // optional-scalar axis — same "the substrate-primitive
18855        // accessor must byte-equal the raw field access verbatim
18856        // across every author-declared value" discipline extended to
18857        // the store arm. Pins against a future silent detour that
18858        // re-canonicalized the slot template (an accidental
18859        // `.to_lowercase()` bucket-prefix normalization that didn't
18860        // reach the peer field-access site at the dedup key, a per-CR
18861        // fully-qualified prefix rewrite the operator authors on one
18862        // consumer without the other, or an M4 typed-key-template
18863        // `Display` re-canonicalization that silently drifted the
18864        // printer output from the source `caixa.lisp`). Four values
18865        // sweep the wasi:keyvalue accept-set every store-shaped
18866        // author-declared slot lands on (flat bucket, single-param
18867        // template, multi-param template, nested-hierarchy template).
18868        for slot in [
18869            "sessions",
18870            "carts/{cart_id}",
18871            "orders/{tenant}/{order_id}",
18872            "cache/tenant-a/orders/{id}",
18873        ] {
18874            let c = WitContract {
18875                de: "cart".into(),
18876                para: "kv".into(),
18877                wit: "wasi:keyvalue/store".into(),
18878                endpoint: None,
18879                subject: None,
18880                slot: Some(slot.into()),
18881            };
18882            assert_eq!(
18883                c.slot(),
18884                Some(slot),
18885                "WitContract::slot must return :contratos :slot \
18886                 verbatim (got {:?}, expected Some({slot:?}))",
18887                c.slot(),
18888            );
18889            assert_eq!(
18890                c.slot(),
18891                c.slot.as_deref(),
18892                "WitContract::slot must byte-equal the .slot field's \
18893                 `.as_deref()` projection",
18894            );
18895        }
18896    }
18897
18898    #[test]
18899    fn wit_contract_slot_none_when_field_is_none() {
18900        // The absent-`:slot` arm of the per-`:contratos` store-shaped
18901        // payload-carrier accessor pin: when the typed slot is absent —
18902        // the canonical shape under a non-store `:wit` world per the
18903        // [`WitContract::target`]-enforced shape ↔ target partition
18904        // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
18905        // carries `:subject`, [`WitTarget::Capability`] carries none) —
18906        // [`WitContract::slot`] must return `None`. Pins against a
18907        // future silent detour that projected the absent slot to a
18908        // `Some("")` empty-string default (the canonical
18909        // `Option<String>` → `String` collapse footgun the sibling M2
18910        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
18911        // emptiness predicates already guard on the peer M2 typed-slot
18912        // surfaces), a `Some("None")` stringified-None round-trip, or
18913        // a `Some` arm whose contents were derived from a sibling
18914        // slot (an accidental fallback to the `:endpoint` / `:subject`
18915        // payload that read the HTTP / pub-sub payload into the store
18916        // axis). Three contracts sweep the accept-set every non-store
18917        // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
18918        // payload-less capability.
18919        for (wit, endpoint, subject) in [
18920            ("wasi:http/proxy", Some("/lookup"), None),
18921            ("nats:pub-sub", None, Some("orders.paid")),
18922            ("wasi:cli/environment", None, None),
18923        ] {
18924            let c = WitContract {
18925                de: "cart".into(),
18926                para: "downstream".into(),
18927                wit: wit.into(),
18928                endpoint: endpoint.map(str::to_string),
18929                subject: subject.map(str::to_string),
18930                slot: None,
18931            };
18932            assert!(
18933                c.slot().is_none(),
18934                "WitContract::slot must return None when the typed \
18935                 slot is absent under :wit {wit:?} (got {:?})",
18936                c.slot(),
18937            );
18938            assert_eq!(
18939                c.slot(),
18940                c.slot.as_deref(),
18941                "WitContract::slot must byte-equal the .slot field's \
18942                 `.as_deref()` projection in the absent arm",
18943            );
18944        }
18945    }
18946
18947    #[test]
18948    fn wit_contract_slot_borrows_from_slot_storage() {
18949        // The borrow-not-copy pin: [`WitContract::slot`] must return
18950        // an `Option<&str>` whose `Some` arm borrows from the typed
18951        // slot's own [`String`] storage — same-address invariant with
18952        // `c.slot.as_deref().unwrap()`. Pins against a future silent
18953        // detour that allocated a fresh `String`
18954        // (`self.slot.clone().map(...)` in the body would type-check
18955        // but silently drop the borrow, and every downstream consumer
18956        // that assumed the returned slice outlives `&self` would
18957        // break on a stale-reference use-after-free — the
18958        // [`WitContract::target`] Store-arm payload extraction rebinds
18959        // the returned `Option<&str>` through `.ok_or_else(...)` and
18960        // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
18961        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
18962        // [`ContratoIdentity`] dedup key threads the returned
18963        // `Option<&str>` into the six-tuple's store arm — each borrow
18964        // from the WitContract's own storage and each would silently
18965        // misbehave if this accessor produced a detached copy). Peer
18966        // of the sibling per-`:contratos` [`WitContract::endpoint`]
18967        // (7020470) / [`WitContract::subject`] (90de675)
18968        // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
18969        // shaped optional-scalar axis — third and final extension of
18970        // the `Option<&str>` borrow-not-copy discipline onto the
18971        // per-`:contratos` payload-carrier family, this time on the
18972        // store arm.
18973        let c = WitContract {
18974            de: "cart".into(),
18975            para: "kv".into(),
18976            wit: "wasi:keyvalue/store".into(),
18977            endpoint: None,
18978            subject: None,
18979            slot: Some("carts/{cart_id}".into()),
18980        };
18981        let slot = c.slot().expect("Some arm");
18982        let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
18983        assert_eq!(
18984            slot.as_ptr(),
18985            storage_slice.as_ptr(),
18986            "WitContract::slot must borrow from the .slot String's \
18987             backing storage — a fresh allocation here means the \
18988             accessor no longer names the substrate-primitive typed \
18989             dispatch and every downstream consumer would silently \
18990             carry a detached copy",
18991        );
18992        assert_eq!(
18993            slot.len(),
18994            storage_slice.len(),
18995            "WitContract::slot and .slot.as_deref() must byte-equal \
18996             in length as well as in address",
18997        );
18998    }
18999
19000    #[test]
19001    fn membro_nome_returns_caixa_byte_equal_across_permutations() {
19002        // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
19003        // [`Membro::nome`] must return the `:membros :caixa` field
19004        // byte-for-byte, borrowed from the typed slot's own [`String`]
19005        // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
19006        // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
19007        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
19008        // slot-atom scalar-value axes — same "the substrate-primitive
19009        // accessor must byte-equal the raw field access verbatim across
19010        // every author-declared value" discipline extended to the
19011        // per-`:membros` member-identity arm. Pins against a future
19012        // silent detour that re-normalized the member identity (an
19013        // accidental `.to_lowercase()` — every `:membros :caixa` is
19014        // validated as a DNS-1123 label upstream via
19015        // [`validate_membro_caixa`], so any re-normalization is
19016        // redundant + a drift surface between the validator and the
19017        // accessor), a namespace-prefix rewrite (an accidental
19018        // `format!("{namespace}/{caixa}")` per-CR fully-qualified
19019        // rewrite that didn't land on the peer axes), or a per-cluster
19020        // alias stamp the operator authors on one consumer without the
19021        // other. Four values sweep the accept-set the DNS-1123 gate
19022        // upstream admits (short single-word / dashed / v-suffixed
19023        // member names).
19024        for name in ["cart", "checkout", "catalog", "orders-v2"] {
19025            let m = Membro {
19026                caixa: name.into(),
19027                versao: "^0.1".into(),
19028            };
19029            assert_eq!(
19030                m.nome(),
19031                name,
19032                "Membro::nome must return :membros :caixa verbatim \
19033                 (got {:?}, expected {name:?})",
19034                m.nome(),
19035            );
19036            assert_eq!(
19037                m.nome(),
19038                m.caixa.as_str(),
19039                "Membro::nome must byte-equal the .caixa field access",
19040            );
19041        }
19042    }
19043
19044    #[test]
19045    fn membro_nome_borrows_from_caixa_storage() {
19046        // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
19047        // slice that borrows from the typed slot's own [`String`]
19048        // storage — same-address invariant with `m.caixa.as_str()`. Pins
19049        // against a future silent detour that allocated a fresh `String`
19050        // (`self.caixa.clone()` in the body would type-check but
19051        // silently drop the borrow, and every downstream consumer that
19052        // assumed the returned slice outlives `&self` would break on a
19053        // stale-reference use-after-free — the `HashSet<&str>` collector
19054        // at [`AplicacaoSpec::validate`]'s `names` seed, the
19055        // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
19056        // [`AplicacaoSpec::detect_sync_cycles`], the
19057        // [`crate::render::insert_first_seen`] dedup key at
19058        // [`AplicacaoSpec::validate_membros`] — each borrow from the
19059        // Membro's own storage and each would silently misbehave if
19060        // this accessor produced a detached copy). Peer of the sibling
19061        // per-`:contratos` [`WitContract::source`] /
19062        // [`WitContract::destination`] and per-`:entrada`
19063        // [`Entrada::destination`] borrow-invariant pins on the mesh-
19064        // slot-atom scalar-value axes.
19065        let m = Membro {
19066            caixa: "checkout".into(),
19067            versao: "^0.1".into(),
19068        };
19069        let name = m.nome();
19070        let caixa_slice = m.caixa.as_str();
19071        assert_eq!(
19072            name.as_ptr(),
19073            caixa_slice.as_ptr(),
19074            "Membro::nome must borrow from the .caixa String's backing \
19075             storage — a fresh allocation here means the accessor no \
19076             longer names the substrate-primitive typed dispatch and \
19077             every downstream consumer would silently carry a detached \
19078             copy",
19079        );
19080        assert_eq!(
19081            name.len(),
19082            caixa_slice.len(),
19083            "Membro::nome and .caixa.as_str() must byte-equal in length \
19084             as well as in address",
19085        );
19086    }
19087
19088    #[test]
19089    fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
19090        // The canonical per-`:membros` member-`:versao`-scalar pin:
19091        // [`Membro::versao_requirement`] must return the
19092        // `:membros :versao` field byte-for-byte, borrowed from the typed
19093        // slot's own [`String`] storage. Sibling of the peer
19094        // `membro_nome_returns_caixa_byte_equal_across_permutations`
19095        // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
19096        // — same "the substrate-primitive accessor must byte-equal the
19097        // raw field access verbatim across every author-declared value"
19098        // discipline extended to the per-`:membros` member-`:versao`
19099        // requirement-string arm. Pins against a future silent detour
19100        // that re-canonicalized the requirement (an accidental
19101        // `.to_string()` via [`parse_requirement`] → [`Display`] round-
19102        // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
19103        // drifted the printer output away from the source `caixa.lisp`,
19104        // an accidental whitespace trim on `"^ 0.1"` that no consumer
19105        // ever produced from the field-access side, an accidental
19106        // per-cluster lacre-projected concrete-version rewrite that
19107        // didn't land on the peer field-access sites). Five values sweep
19108        // the accept-set the shared
19109        // [`crate::render::require_valid_versao_requirement`] gate
19110        // admits (caret / tilde / exact / wildcard / bare-major).
19111        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
19112            let m = Membro {
19113                caixa: "cart".into(),
19114                versao: req.into(),
19115            };
19116            assert_eq!(
19117                m.versao_requirement(),
19118                req,
19119                "Membro::versao_requirement must return :membros :versao \
19120                 verbatim (got {:?}, expected {req:?})",
19121                m.versao_requirement(),
19122            );
19123            assert_eq!(
19124                m.versao_requirement(),
19125                m.versao.as_str(),
19126                "Membro::versao_requirement must byte-equal the .versao \
19127                 field access",
19128            );
19129        }
19130    }
19131
19132    #[test]
19133    fn membro_versao_requirement_borrows_from_versao_storage() {
19134        // The borrow-not-copy pin: [`Membro::versao_requirement`] must
19135        // return a `&str` slice that borrows from the typed slot's own
19136        // [`String`] storage — same-address invariant with
19137        // `m.versao.as_str()`. Pins against a future silent detour that
19138        // allocated a fresh `String` (`self.versao.clone()` in the body
19139        // would type-check but silently drop the borrow, and every
19140        // downstream consumer that assumed the returned slice outlives
19141        // `&self` would break on a stale-reference use-after-free). Peer
19142        // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
19143        // per-`:contratos` [`WitContract::source`] /
19144        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
19145        // [`Entrada::destination`] (6db982c) borrow-invariant pins on
19146        // the mesh-slot-atom scalar-value axes.
19147        let m = Membro {
19148            caixa: "checkout".into(),
19149            versao: "^0.1".into(),
19150        };
19151        let req = m.versao_requirement();
19152        let versao_slice = m.versao.as_str();
19153        assert_eq!(
19154            req.as_ptr(),
19155            versao_slice.as_ptr(),
19156            "Membro::versao_requirement must borrow from the .versao \
19157             String's backing storage — a fresh allocation here means \
19158             the accessor no longer names the substrate-primitive typed \
19159             dispatch and every downstream consumer would silently carry \
19160             a detached copy",
19161        );
19162        assert_eq!(
19163            req.len(),
19164            versao_slice.len(),
19165            "Membro::versao_requirement and .versao.as_str() must byte-\
19166             equal in length as well as in address",
19167        );
19168    }
19169
19170    #[test]
19171    fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
19172        // Sibling-pair invariant pin composing both per-`:membros`
19173        // substrate-primitive typed dispatches — [`Membro::nome`]
19174        // (4a32abf) and [`Membro::versao_requirement`] — at the joint
19175        // `(nome(), versao_requirement())` call shape every renderer
19176        // that fans on per-member identity + version pin keys off. The
19177        // invariant, evaluated per-member:
19178        //
19179        //   (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
19180        //
19181        // Closes the last unlifted per-`:membros` scalar axis — every
19182        // downstream consumer that reads the pair now routes through
19183        // exactly two typed dispatches on the substrate primitive, not
19184        // one typed + one open-coded field access. A future refactor
19185        // that silently split either accessor's projection (an
19186        // accidental `nome()` namespace-prefix rewrite that didn't
19187        // reach the peer, an accidental `versao_requirement()` lacre-
19188        // projected concrete-version rewrite that didn't land on the
19189        // `nome()` peer) surfaces at caixa-core build time. Peer of the
19190        // sibling per-`:entrada` `(hostname(), destination())` and
19191        // per-`:contratos` `(source(), destination())` pair invariants
19192        // on the mesh-slot-atom scalar-value axes.
19193        for (caixa, versao) in [
19194            ("cart", "^0.1"),
19195            ("checkout", "~0.1.2"),
19196            ("catalog", "0.1.0"),
19197            ("orders-v2", "*"),
19198        ] {
19199            let m = Membro {
19200                caixa: caixa.into(),
19201                versao: versao.into(),
19202            };
19203            assert_eq!(
19204                (m.nome(), m.versao_requirement()),
19205                (m.caixa.as_str(), m.versao.as_str()),
19206                "(Membro::nome, Membro::versao_requirement) must project \
19207                 (.caixa, .versao) verbatim across every author-declared \
19208                 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
19209                m.nome(),
19210                m.versao_requirement(),
19211            );
19212        }
19213    }
19214
19215    #[test]
19216    fn validate_membros_empty_gate_routes_through_nome_accessor() {
19217        // Composition pin: [`AplicacaoSpec::validate_membros`]'s
19218        // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
19219        // not the raw `.caixa` field access. Structurally: setting
19220        // ONLY the `.caixa` field to `""` on an otherwise-well-formed
19221        // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
19222        // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
19223        // (i.e. the empty string) — so the emptiness predicate the
19224        // refusal arm reaches under is the accessor-projected value,
19225        // not a peer field that would silently drift under a future
19226        // accessor-side rewrite.
19227        //
19228        // Pins against a future silent detour that (a) re-derived the
19229        // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
19230        // instead of `self.nome().is_empty()`, silently disagreeing with
19231        // every peer consumer (the `validate_membro_caixa(m.nome())`
19232        // call one line below, the dedup-key `insert_first_seen(&mut
19233        // seen, m.nome(), …)` two lines below, the emit-side per-
19234        // `programs[]` entry-`name:` at caixa-mesh/src/lib.rs:133),
19235        // (b) accessor-side introduced a per-tenant alias arm the
19236        // caller was unaware of, silently rewriting an author-declared
19237        // `:caixa "checkout"` to `""` — the raw-field-access gate
19238        // would fail-open while the accessor-routed peer consumers
19239        // would fail-closed, splitting the diagnostic from the actual
19240        // failure surface.
19241        //
19242        // Peer of the sibling
19243        // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
19244        // (c0110f1) composition pin — same "the shape-gate predicate
19245        // must route through the substrate-primitive typed dispatch"
19246        // discipline extended onto the per-`:membros` empty-`:caixa`
19247        // refusal-arm axis. Closes the last unlifted `.caixa` production-
19248        // code read site on `Membro` — after this converge every
19249        // caixa-core `.caixa` field access outside the accessor's own
19250        // body is either a test-side field-setter (in-module tests
19251        // constructing invalid-shape inputs) or a doc-comment reference.
19252        let mut s = three_member_spec();
19253        s.membros[1].caixa = String::new();
19254        assert!(
19255            s.membros[1].nome().is_empty(),
19256            "Membro::nome must byte-equal the .caixa field access — an \
19257             accessor-side detour that no longer projects the raw field \
19258             would silently split this drift-detection test from the \
19259             validate() refusal arm",
19260        );
19261        assert_eq!(
19262            s.membros[1].nome(),
19263            s.membros[1].caixa.as_str(),
19264            "Membro::nome and .caixa.as_str() must byte-equal on an \
19265             empty-`:caixa` entry — the emptiness gate keys off the \
19266             accessor by construction",
19267        );
19268        assert_eq!(
19269            s.validate().unwrap_err(),
19270            AplicacaoError::MembroCaixaEmpty,
19271            "validate_membros' emptiness gate must fire MembroCaixaEmpty \
19272             on an entry whose accessor-projected `nome()` is empty",
19273        );
19274    }
19275
19276    #[test]
19277    fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
19278        // The canonical per-`:placement` Akka-cluster-sharding
19279        // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
19280        // the `:placement :shard-key` field byte-for-byte, borrowed
19281        // from the typed slot's own `Option<String>` storage. Peer of
19282        // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
19283        // per-`:contratos` [`WitContract::source`] /
19284        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
19285        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
19286        // slot-atom scalar-value axes — same "the substrate-primitive
19287        // accessor must byte-equal the raw field access verbatim across
19288        // every author-declared value" discipline extended to the
19289        // per-`:placement` Akka-cluster-sharding key extractor arm.
19290        // Pins against a future silent detour that re-normalized the
19291        // key (an accidental `.to_lowercase()` — every non-empty
19292        // `:shard-key` is validated as a printable-ASCII single-token
19293        // reference upstream via [`validate_placement_shard_key`], so
19294        // any re-normalization is redundant + a drift surface between
19295        // the validator and the accessor), a per-cluster alias rewrite
19296        // the operator authors on one consumer without the other, or an
19297        // accidental variable-prefix strip (`$tenantId` → `tenantId`)
19298        // that didn't land on the peer field-access sites. Four values
19299        // sweep the accept-set the shape gate admits — bare identifier,
19300        // `$`-prefixed variable, dotted path, `${}`-quoted variable —
19301        // the four canonical Akka-style entity-id extractor shapes the
19302        // future M4 cluster-sharding reconciler hashes.
19303        for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
19304            let p = Placement {
19305                estrategia: PlacementStrategy::Sharded,
19306                clusters: vec!["rio".into()],
19307                affinity: None,
19308                shard_key: Some(key.into()),
19309            };
19310            assert_eq!(
19311                p.shard_key(),
19312                Some(key),
19313                "Placement::shard_key must return :placement :shard-key \
19314                 verbatim (got {:?}, expected Some({key:?}))",
19315                p.shard_key(),
19316            );
19317            assert_eq!(
19318                p.shard_key(),
19319                p.shard_key.as_deref(),
19320                "Placement::shard_key must byte-equal the .shard_key \
19321                 field's `.as_deref()` projection",
19322            );
19323        }
19324    }
19325
19326    #[test]
19327    fn placement_shard_key_none_when_field_is_none() {
19328        // The absent-`:shard-key` arm of the per-`:placement`
19329        // Akka-cluster-sharding accessor pin: when the typed slot is
19330        // absent — the canonical shape under `:estrategia Replicated` /
19331        // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
19332        // enforced `shard_key.is_some() == matches!(estrategia,
19333        // Sharded)` partition — [`Placement::shard_key`] must return
19334        // `None`. Pins against a future silent detour that projected
19335        // the absent slot to a `Some("")` empty-string default (the
19336        // canonical `Option<String>` → `String` collapse footgun the
19337        // sibling M2 [`crate::LimitsSpec::is_empty`] /
19338        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
19339        // already guard on the peer M2 typed-slot surfaces), a
19340        // `Some("None")` stringified-None round-trip, or a `Some` arm
19341        // whose contents were derived from a sibling slot (an
19342        // accidental fallback to `estrategia.as_str()` that read the
19343        // strategy discriminator into the key axis). Two placements
19344        // sweep the accept-set every `validate`-passing non-`Sharded`
19345        // shape lands on — `Replicated` (Erlang/OTP distributed-app
19346        // takeover) and `SingleNode` (single-node hosting).
19347        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
19348            let p = Placement {
19349                estrategia,
19350                clusters: vec!["rio".into()],
19351                affinity: None,
19352                shard_key: None,
19353            };
19354            assert!(
19355                p.shard_key().is_none(),
19356                "Placement::shard_key must return None when the typed \
19357                 slot is absent under :estrategia {estrategia:?} (got {:?})",
19358                p.shard_key(),
19359            );
19360            assert_eq!(
19361                p.shard_key(),
19362                p.shard_key.as_deref(),
19363                "Placement::shard_key must byte-equal the .shard_key \
19364                 field's `.as_deref()` projection in the absent arm",
19365            );
19366        }
19367    }
19368
19369    #[test]
19370    fn placement_shard_key_borrows_from_shard_key_storage() {
19371        // The borrow-not-copy pin: [`Placement::shard_key`] must return
19372        // an `Option<&str>` whose `Some` arm borrows from the typed
19373        // slot's own [`String`] storage — same-address invariant with
19374        // `p.shard_key.as_deref().unwrap()`. Pins against a future
19375        // silent detour that allocated a fresh `String`
19376        // (`self.shard_key.clone().map(...)` in the body would type-
19377        // check but silently drop the borrow, and every downstream
19378        // consumer that assumed the returned slice outlives `&self`
19379        // would break on a stale-reference use-after-free — the
19380        // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
19381        // gate's `Some(k)`-bound match arm reads `k: &str` under the
19382        // accessor's return type and would silently misbehave if this
19383        // accessor produced a detached copy). Peer of the sibling
19384        // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
19385        // [`WitContract::source`] / [`WitContract::destination`]
19386        // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
19387        // (6db982c) borrow-invariant pins on the mesh-slot-atom
19388        // scalar-value axes — first extension of the discipline onto
19389        // an `Option<String>`-shaped optional-scalar axis.
19390        let p = Placement {
19391            estrategia: PlacementStrategy::Sharded,
19392            clusters: vec!["rio".into()],
19393            affinity: None,
19394            shard_key: Some("tenantId".into()),
19395        };
19396        let key = p.shard_key().expect("Some arm");
19397        let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
19398        assert_eq!(
19399            key.as_ptr(),
19400            storage_slice.as_ptr(),
19401            "Placement::shard_key must borrow from the .shard_key \
19402             String's backing storage — a fresh allocation here means \
19403             the accessor no longer names the substrate-primitive typed \
19404             dispatch and every downstream consumer would silently \
19405             carry a detached copy",
19406        );
19407        assert_eq!(
19408            key.len(),
19409            storage_slice.len(),
19410            "Placement::shard_key and .shard_key.as_deref() must byte-\
19411             equal in length as well as in address",
19412        );
19413    }
19414
19415    #[test]
19416    fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
19417        // The canonical per-`:placement` M3-Adaptive-compression-hint
19418        // scalar pin: [`Placement::affinity`] must return the
19419        // `:placement :affinity` field byte-for-byte, borrowed from the
19420        // typed slot's own `Option<String>` storage. Peer of the sibling
19421        // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
19422        // pin on the sibling `Option<&str>` optional-scalar axis — same
19423        // "the substrate-primitive accessor must byte-equal the raw
19424        // field access verbatim across every author-declared value"
19425        // discipline extended to the peer per-`:placement` M3-Adaptive-
19426        // compression-hint arm. Pins against a future silent detour
19427        // that re-normalized the hint (an accidental `.to_lowercase()`
19428        // — every `:affinity` is already validated as a DNS-1123 label
19429        // upstream via [`validate_placement_affinity`], so any re-
19430        // normalization is redundant + a drift surface between the
19431        // validator and the accessor), a per-cluster alias rewrite the
19432        // operator authors on one consumer without the other, or an
19433        // accidental hint-family collapse (`low-latency` → `latency`
19434        // that dropped the qualifier prefix). Four values sweep the
19435        // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
19436        // canonical adaptive-compression-weight biases the future M4
19437        // placement engine reads.
19438        for hint in [
19439            "data-locality",
19440            "low-latency",
19441            "high-throughput",
19442            "cost-optimized",
19443        ] {
19444            let p = Placement {
19445                estrategia: PlacementStrategy::Replicated,
19446                clusters: vec!["rio".into()],
19447                affinity: Some(hint.into()),
19448                shard_key: None,
19449            };
19450            assert_eq!(
19451                p.affinity(),
19452                Some(hint),
19453                "Placement::affinity must return :placement :affinity \
19454                 verbatim (got {:?}, expected Some({hint:?}))",
19455                p.affinity(),
19456            );
19457            assert_eq!(
19458                p.affinity(),
19459                p.affinity.as_deref(),
19460                "Placement::affinity must byte-equal the .affinity \
19461                 field's `.as_deref()` projection",
19462            );
19463        }
19464    }
19465
19466    #[test]
19467    fn placement_affinity_none_when_field_is_none() {
19468        // The absent-`:affinity` arm of the per-`:placement`
19469        // M3-Adaptive-compression-hint accessor pin: when the typed
19470        // slot is absent — the canonical shape of an Aplicacao that
19471        // leaves the compression weighting up to the placement engine's
19472        // cluster-default arm — [`Placement::affinity`] must return
19473        // `None`. Pins against a future silent detour that projected
19474        // the absent slot to a `Some("")` empty-string default (the
19475        // canonical `Option<String>` → `String` collapse footgun the
19476        // sibling M2 [`crate::LimitsSpec::is_empty`] /
19477        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
19478        // already guard on the peer M2 typed-slot surfaces), a
19479        // `Some("None")` stringified-None round-trip, a `Some` arm
19480        // whose contents were derived from a sibling slot (an
19481        // accidental fallback to `estrategia.as_str()` that read the
19482        // strategy discriminator into the hint axis), or a
19483        // `Some("default")` implicit-default that would silently biases
19484        // the routing without the author having written one. Three
19485        // placements sweep the accept-set every `validate`-passing
19486        // `:affinity None` shape lands on — one per PlacementStrategy
19487        // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
19488        // with a shard-key), since `:affinity` is orthogonal to
19489        // `:estrategia` in the typed grammar.
19490        for (estrategia, shard_key) in [
19491            (PlacementStrategy::SingleNode, None),
19492            (PlacementStrategy::Replicated, None),
19493            (PlacementStrategy::Sharded, Some("tenantId".to_string())),
19494        ] {
19495            let p = Placement {
19496                estrategia,
19497                clusters: vec!["rio".into()],
19498                affinity: None,
19499                shard_key,
19500            };
19501            assert!(
19502                p.affinity().is_none(),
19503                "Placement::affinity must return None when the typed \
19504                 slot is absent under :estrategia {estrategia:?} (got {:?})",
19505                p.affinity(),
19506            );
19507            assert_eq!(
19508                p.affinity(),
19509                p.affinity.as_deref(),
19510                "Placement::affinity must byte-equal the .affinity \
19511                 field's `.as_deref()` projection in the absent arm",
19512            );
19513        }
19514    }
19515
19516    #[test]
19517    fn placement_affinity_borrows_from_affinity_storage() {
19518        // The borrow-not-copy pin: [`Placement::affinity`] must return
19519        // an `Option<&str>` whose `Some` arm borrows from the typed
19520        // slot's own [`String`] storage — same-address invariant with
19521        // `p.affinity.as_deref().unwrap()`. Pins against a future
19522        // silent detour that allocated a fresh `String`
19523        // (`self.affinity.clone().map(...)` in the body would type-
19524        // check but silently drop the borrow, and every downstream
19525        // consumer that assumed the returned slice outlives `&self`
19526        // would break on a stale-reference use-after-free — the
19527        // [`AplicacaoSpec::validate_placement`] per-hint value-shape
19528        // gate reads the accessor's `&str` return through the
19529        // [`validate_placement_affinity`] `&str` parameter and would
19530        // silently misbehave if this accessor produced a detached
19531        // copy). Peer of the sibling per-`:placement`
19532        // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
19533        // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
19534        // extends the discipline onto the sibling per-`:placement`
19535        // M3-Adaptive-compression-hint arm.
19536        let p = Placement {
19537            estrategia: PlacementStrategy::Replicated,
19538            clusters: vec!["rio".into()],
19539            affinity: Some("data-locality".into()),
19540            shard_key: None,
19541        };
19542        let hint = p.affinity().expect("Some arm");
19543        let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
19544        assert_eq!(
19545            hint.as_ptr(),
19546            storage_slice.as_ptr(),
19547            "Placement::affinity must borrow from the .affinity \
19548             String's backing storage — a fresh allocation here means \
19549             the accessor no longer names the substrate-primitive typed \
19550             dispatch and every downstream consumer would silently \
19551             carry a detached copy",
19552        );
19553        assert_eq!(
19554            hint.len(),
19555            storage_slice.len(),
19556            "Placement::affinity and .affinity.as_deref() must byte-\
19557             equal in length as well as in address",
19558        );
19559    }
19560
19561    #[test]
19562    fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
19563        // The canonical per-`:placement` distribution-strategy-scalar
19564        // pin: [`Placement::estrategia`] must return the `:placement
19565        // :estrategia` field verbatim as a [`PlacementStrategy`],
19566        // `Copy`-projected from the typed slot's own `PlacementStrategy`
19567        // storage across every variant in the closed accept-set
19568        // (`SingleNode` — Erlang/OTP distributed-app takeover;
19569        // `Replicated` — active-active across every named cluster;
19570        // `Sharded` — Akka-style hash-keyed entity distribution). Pins
19571        // against a future silent detour that re-derived the strategy
19572        // from a peer axis (an accidental fallback to
19573        // `if shard_key.is_some() { Sharded } else { Replicated }`
19574        // collapse that read the shard-key axis into the strategy
19575        // discriminator), a variant remap the operator authors on one
19576        // consumer without the other, or a stale-derive detour that
19577        // substituted [`PlacementStrategy::default`] when the field
19578        // held any explicit variant (which would silently collapse the
19579        // distinction between "author explicitly declared `:estrategia
19580        // Replicated`" and "author omitted the slot and inherited the
19581        // default" the future per-cluster override slot depends on).
19582        // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
19583        // pin on the `Copy`-return `u16` scalar axis — same "the
19584        // substrate-primitive accessor must byte-equal the raw field
19585        // access verbatim across every author-declared value" discipline
19586        // extended onto the per-`:placement` distribution-strategy
19587        // `Copy`-composite-enum scalar axis.
19588        for estrategia in [
19589            PlacementStrategy::SingleNode,
19590            PlacementStrategy::Replicated,
19591            PlacementStrategy::Sharded,
19592        ] {
19593            let shard_key = estrategia.is_sharded().then(|| "tenantId".to_string());
19594            let p = Placement {
19595                estrategia,
19596                clusters: vec!["rio".into()],
19597                affinity: None,
19598                shard_key,
19599            };
19600            assert_eq!(
19601                p.estrategia(),
19602                estrategia,
19603                "Placement::estrategia must return :placement :estrategia \
19604                 verbatim (got {:?}, expected {estrategia:?})",
19605                p.estrategia(),
19606            );
19607            assert_eq!(
19608                p.estrategia(),
19609                p.estrategia,
19610                "Placement::estrategia accessor and .estrategia field \
19611                 access must byte-equal — the accessor is the substrate-\
19612                 primitive typed dispatch every downstream distribution-\
19613                 strategy consumer must route through",
19614            );
19615        }
19616    }
19617
19618    #[test]
19619    fn validate_placement_reads_through_lifted_estrategia_accessor() {
19620        // Three-consumer coherence pin: the
19621        // [`AplicacaoSpec::validate_placement`]
19622        // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
19623        // `estrategia:` field (which reads through
19624        // [`Placement::estrategia`] to name the strategy the empty
19625        // `:clusters` list was declared against), the same method's
19626        // `Sharded ↔ non-Sharded` `match` partition dispatch (which
19627        // reads through [`Placement::estrategia`] to fan across the
19628        // shape-gate cascades), and the non-`Sharded`-arm
19629        // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
19630        // `estrategia:` field (which reads through
19631        // [`Placement::estrategia`] to name the strategy the declared-
19632        // but-inert `:shard-key` was authored under) must all key off
19633        // the lifted accessor, so any future rebrand on the typed
19634        // slot's reader shape lands at exactly one place. Pins the
19635        // three-site coherence by exercising each error surface end-
19636        // to-end and asserting the surfaced `estrategia:` field byte-
19637        // equals the accessor's return. Peer of the sibling per-
19638        // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
19639        // pin on the M3 mesh-slot `Copy`-return scalar axis.
19640
19641        // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
19642        // whose `estrategia:` field must byte-equal the accessor's return
19643        // for every variant in the closed accept-set.
19644        for estrategia in [
19645            PlacementStrategy::SingleNode,
19646            PlacementStrategy::Replicated,
19647            PlacementStrategy::Sharded,
19648        ] {
19649            let mut spec = three_member_spec();
19650            spec.placement.estrategia = estrategia;
19651            spec.placement.clusters = Vec::new();
19652            spec.placement.shard_key = estrategia.is_sharded().then(|| "tenantId".to_string());
19653            let err = spec.validate().unwrap_err();
19654            match err {
19655                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
19656                    assert_eq!(
19657                        e,
19658                        spec.placement.estrategia(),
19659                        "PlacementWithoutClusters.estrategia must byte-equal \
19660                         Placement::estrategia() — the error carrier reads \
19661                         through the lifted accessor",
19662                    );
19663                }
19664                other => panic!(
19665                    "expected PlacementWithoutClusters, got {other:?} for \
19666                     estrategia={estrategia:?}"
19667                ),
19668            }
19669        }
19670
19671        // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
19672        // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
19673        // must byte-equal the accessor's return for both non-`Sharded`
19674        // strategies.
19675        for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
19676            let mut spec = three_member_spec();
19677            spec.placement.estrategia = estrategia;
19678            spec.placement.shard_key = Some("tenantId".into());
19679            let err = spec.validate().unwrap_err();
19680            match err {
19681                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
19682                    assert_eq!(
19683                        e,
19684                        spec.placement.estrategia(),
19685                        "ShardKeyOnNonSharded.estrategia must byte-equal \
19686                         Placement::estrategia() — the non-Sharded-arm \
19687                         refusal reads through the lifted accessor",
19688                    );
19689                }
19690                other => panic!(
19691                    "expected ShardKeyOnNonSharded, got {other:?} for \
19692                     estrategia={estrategia:?}"
19693                ),
19694            }
19695        }
19696    }
19697
19698    // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
19699    //
19700    // The [`Placement::clusters`] accessor lift is the second slice-return
19701    // (`&[T]`) accessor on any typed slot — sibling to the seed M2
19702    // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
19703    // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
19704    // below cover (1) the accessor's byte-equal projection against the raw
19705    // field access across the empty / singleton / cohort fixtures the
19706    // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
19707    // and the per-cluster validate loop fan between, and (2) the two-
19708    // consumer coherence of the paired pre-flight refusal probe and the
19709    // per-cluster validate loop routing through the accessor on both arms.
19710
19711    #[test]
19712    fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
19713        // The canonical per-`:placement` cluster-pool-scalar-shape pin:
19714        // [`Placement::clusters`] must return the `:placement :clusters`
19715        // typed `Vec<String>` verbatim as a `&[String]` slice-view over
19716        // the same backing buffer the raw `self.clusters.as_slice()`
19717        // field access borrows from, byte-equal across every
19718        // representative fixture in the accept-set — the empty slice
19719        // (the pre-validation sentinel every
19720        // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
19721        // the singleton slice (the minimal `SingleNode`-shape cohort),
19722        // and multi-entry cohorts (the peer `Replicated` / `Sharded`
19723        // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
19724        //
19725        // Pins against a future silent detour that returned
19726        // `&Vec<String>` (which would type-check but leak the storage-
19727        // side `Vec`'s grow/push/reserve surface no consumer of the
19728        // typed view reaches for), a fresh-allocated `Vec<String>` copy
19729        // (which would type-check via a coercion but silently break
19730        // every downstream caller that relied on the slice sharing the
19731        // backing buffer's identity), or an out-of-order or length-
19732        // drifted projection (which would silently split the paired
19733        // pre-flight `.is_empty()` refusal probe's input from the per-
19734        // cluster validate loop's traversal input).
19735        //
19736        // Peer of the sibling M2
19737        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
19738        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
19739        // `:supervisor` static-child-list axis, extended onto the M3
19740        // per-`:placement` distribution-target-list `Vec`-carry axis.
19741        let fixtures: Vec<Vec<String>> = vec![
19742            Vec::new(),
19743            vec!["rio".into()],
19744            vec!["rio".into(), "mar".into()],
19745            vec!["rio".into(), "mar".into(), "plo".into()],
19746        ];
19747        for clusters in fixtures {
19748            let p = Placement {
19749                clusters: clusters.clone(),
19750                ..Placement::default()
19751            };
19752            assert_eq!(
19753                p.clusters(),
19754                clusters.as_slice(),
19755                "Placement::clusters must return :placement :clusters \
19756                 verbatim (got {:?}, expected {:?})",
19757                p.clusters(),
19758                clusters.as_slice(),
19759            );
19760            assert_eq!(
19761                p.clusters(),
19762                p.clusters.as_slice(),
19763                "Placement::clusters accessor and .clusters.as_slice() \
19764                 field access must byte-equal — the accessor is the \
19765                 substrate-primitive typed dispatch every downstream \
19766                 cluster-pool consumer must route through",
19767            );
19768            assert_eq!(
19769                p.clusters().len(),
19770                p.clusters.len(),
19771                "Placement::clusters().len() must byte-equal \
19772                 self.clusters.len() — a length-drift would silently \
19773                 split the paired pre-flight `.is_empty()` refusal \
19774                 probe input from the per-cluster validate loop's \
19775                 traversal input",
19776            );
19777        }
19778    }
19779
19780    #[test]
19781    fn validate_placement_reads_through_lifted_clusters_accessor() {
19782        // Two-consumer coherence pin: the
19783        // [`AplicacaoSpec::validate_placement`] pre-flight
19784        // `self.placement.clusters().is_empty()` refusal probe (which
19785        // must trip [`AplicacaoError::PlacementWithoutClusters`] when
19786        // the accessor projects the empty slice) and the per-cluster
19787        // validate loop's `for c in self.placement.clusters()`
19788        // traversal (which must reach every entry in the same order
19789        // the accessor projects, so both the per-entry value-shape
19790        // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
19791        // and the duplicate-detection HashSet insert that trips
19792        // [`AplicacaoError::PlacementClusterDuplicate`] key off the
19793        // accessor's projection) must both key off the lifted
19794        // accessor, so any future rebrand on the typed slot's reader
19795        // shape lands at exactly one place. Pins the two-site
19796        // coherence by exercising each production consumer end-to-end:
19797        // (1) the `PlacementWithoutClusters` refusal under the empty
19798        // slice, (2) the `PlacementClusterInvalid` refusal fires on
19799        // the second entry of a two-cluster cohort whose head is
19800        // valid but tail is not (which requires the loop to reach the
19801        // second entry through the accessor), and (3) the
19802        // `PlacementClusterDuplicate` refusal fires on the second
19803        // entry of a two-cluster cohort that shares a name (which
19804        // requires the loop to reach both entries — a first-entry-only
19805        // projection would silently pass since the dedup HashSet has
19806        // room for the first insert).
19807        //
19808        // Peer of the sibling M2
19809        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
19810        // (bc92bce) coherence pin on the per-`:supervisor` static-
19811        // child-list axis, extended onto the M3 per-`:placement`
19812        // distribution-target-list `Vec`-carry axis.
19813
19814        // (1) Pre-flight `.is_empty()` probe: the empty slice must
19815        // trip `PlacementWithoutClusters`.
19816        let mut spec = three_member_spec();
19817        spec.placement.clusters = Vec::new();
19818        match spec.validate().unwrap_err() {
19819            AplicacaoError::PlacementWithoutClusters { .. } => {}
19820            other => panic!("expected PlacementWithoutClusters, got {other:?}"),
19821        }
19822        assert!(
19823            spec.placement.clusters().is_empty(),
19824            "the pre-flight refusal input must be the empty slice per \
19825             the accessor's projection",
19826        );
19827
19828        // (2) Per-cluster validate loop: a two-cluster cohort with an
19829        // invalid tail entry must trip `PlacementClusterInvalid` on
19830        // the tail — the loop must reach the second entry through
19831        // the accessor.
19832        let mut spec = three_member_spec();
19833        spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
19834        match spec.validate().unwrap_err() {
19835            AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
19836                assert_eq!(
19837                    cluster, "BAD_CLUSTER",
19838                    "PlacementClusterInvalid.cluster must carry the \
19839                     tail entry the loop reached through the accessor",
19840                );
19841            }
19842            other => panic!("expected PlacementClusterInvalid, got {other:?}"),
19843        }
19844        assert_eq!(
19845            spec.placement.clusters().len(),
19846            2,
19847            "the per-cluster validate loop's traversal input must be \
19848             a two-element slice per the accessor's projection",
19849        );
19850
19851        // (3) Per-cluster validate loop: a two-cluster cohort that
19852        // shares a name must trip `PlacementClusterDuplicate` on the
19853        // second entry — the loop must reach both entries through the
19854        // accessor for the dedup HashSet's second insert to collide.
19855        let mut spec = three_member_spec();
19856        spec.placement.clusters = vec!["rio".into(), "rio".into()];
19857        match spec.validate().unwrap_err() {
19858            AplicacaoError::PlacementClusterDuplicate { cluster } => {
19859                assert_eq!(
19860                    cluster, "rio",
19861                    "PlacementClusterDuplicate.cluster must carry the \
19862                     shared cluster name verbatim",
19863                );
19864            }
19865            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
19866        }
19867        assert_eq!(
19868            spec.placement.clusters().len(),
19869            2,
19870            "the per-cluster validate loop's traversal input must be \
19871             a two-element slice per the accessor's projection",
19872        );
19873    }
19874
19875    #[test]
19876    fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
19877        // The canonical per-`:membros` member-list-slice-shape pin:
19878        // [`AplicacaoSpec::membros`] must return the `:membros` typed
19879        // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
19880        // same backing buffer the raw `self.membros.as_slice()` field
19881        // access borrows from, byte-equal across every representative
19882        // fixture in the accept-set — the empty slice (the pre-
19883        // validation sentinel every [`AplicacaoError::NoMembros`]
19884        // refusal keys off), the singleton slice (the minimal one-
19885        // Servico Aplicacao shape), and multi-entry cohorts (the peer
19886        // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
19887        // load-bearing identity of the application graph).
19888        //
19889        // Pins against a future silent detour that returned
19890        // `&Vec<Membro>` (which would type-check but leak the storage-
19891        // side `Vec`'s grow/push/reserve surface no consumer of the
19892        // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
19893        // (which would type-check via a coercion but silently break
19894        // every downstream caller that relied on the slice sharing the
19895        // backing buffer's identity), or an out-of-order or length-
19896        // drifted projection (which would silently split the paired
19897        // `HashSet<&str>` name-set seed's collect input from the
19898        // pre-flight `.is_empty()` refusal probe's input from the per-
19899        // member validate loop's traversal input from the
19900        // programs.yaml emitter's per-entry fan-out loop's input from
19901        // the `feira app graph` per-member print traversal's input).
19902        //
19903        // Peer of the sibling M2
19904        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
19905        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
19906        // `:supervisor` static-child-list axis and the sibling M3
19907        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
19908        // (a6e18d7) `&[String]` byte-equal pin on the per-
19909        // `:placement` distribution-target-list axis — extends the
19910        // slice-return-accessor byte-equal-projection discipline onto
19911        // the outermost M3 mesh-slot type's per-Aplicacao member-list
19912        // `Vec`-carry axis.
19913        let fixtures: Vec<Vec<Membro>> = vec![
19914            Vec::new(),
19915            vec![membro("catalog", "^0.1")],
19916            vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
19917            vec![
19918                membro("catalog", "^0.1"),
19919                membro("cart", "^0.1"),
19920                membro("payment", "^0.2"),
19921            ],
19922        ];
19923        for membros in fixtures {
19924            let s = AplicacaoSpec {
19925                membros: membros.clone(),
19926                contratos: Vec::new(),
19927                politicas: MeshPolicy::default(),
19928                placement: Placement::default(),
19929                entrada: None,
19930            };
19931            assert_eq!(
19932                s.membros(),
19933                membros.as_slice(),
19934                "AplicacaoSpec::membros must return :membros verbatim \
19935                 (got {:?}, expected {:?})",
19936                s.membros(),
19937                membros.as_slice(),
19938            );
19939            assert_eq!(
19940                s.membros(),
19941                s.membros.as_slice(),
19942                "AplicacaoSpec::membros accessor and .membros.as_slice() \
19943                 field access must byte-equal — the accessor is the \
19944                 substrate-primitive typed dispatch every downstream \
19945                 member-list consumer must route through",
19946            );
19947            assert_eq!(
19948                s.membros().len(),
19949                s.membros.len(),
19950                "AplicacaoSpec::membros().len() must byte-equal \
19951                 self.membros.len() — a length-drift would silently \
19952                 split the paired `HashSet<&str>` name-set seed's \
19953                 collect input from the pre-flight `.is_empty()` \
19954                 refusal probe input from the per-member validate \
19955                 loop's traversal input",
19956            );
19957        }
19958    }
19959
19960    #[test]
19961    fn validate_reads_through_lifted_membros_accessor() {
19962        // Three-consumer coherence pin: the
19963        // [`AplicacaoSpec::validate_membros`] pre-flight
19964        // `self.membros().is_empty()` refusal probe (which must trip
19965        // [`AplicacaoError::NoMembros`] when the accessor projects the
19966        // empty slice), the same method's per-member validate loop's
19967        // `for m in self.membros()` traversal (which must reach every
19968        // entry in the same order the accessor projects, so both the
19969        // per-entry empty-`:caixa` gate that trips
19970        // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
19971        // detection `insert_first_seen` that trips
19972        // [`AplicacaoError::MembroDuplicate`] key off the accessor's
19973        // projection), and the peer [`AplicacaoSpec::validate`]'s
19974        // `HashSet<&str>` name-set seed's
19975        // `self.membros().iter().map(Membro::nome).collect()` collect
19976        // input (which every `:contratos` `:de` / `:para` membership
19977        // lookup rejects an unknown name against) must all three key
19978        // off the lifted accessor, so any future rebrand on the typed
19979        // slot's reader shape lands at exactly one place. Pins the
19980        // three-site coherence by exercising each production consumer
19981        // end-to-end: (1) the `NoMembros` refusal under the empty
19982        // slice, (2) the `MembroCaixaEmpty` refusal fires on the
19983        // second entry of a two-member cohort whose head is valid but
19984        // tail has an empty `:caixa` (which requires the loop to
19985        // reach the second entry through the accessor), and (3) the
19986        // `MembroDuplicate` refusal fires on the second entry of a
19987        // two-member cohort that shares a `:caixa` name (which
19988        // requires the loop to reach both entries through the
19989        // accessor for the dedup HashSet's second insert to collide).
19990        //
19991        // Peer of the sibling M2
19992        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
19993        // (bc92bce) coherence pin on the per-`:supervisor` static-
19994        // child-list axis and the sibling M3
19995        // `validate_placement_reads_through_lifted_clusters_accessor`
19996        // (a6e18d7) coherence pin on the per-`:placement` distribution-
19997        // target-list axis — extends the slice-return-accessor
19998        // multi-consumer coherence discipline onto the outermost M3
19999        // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
20000
20001        // (1) Pre-flight `.is_empty()` probe: the empty slice must
20002        // trip `NoMembros`.
20003        let mut spec = three_member_spec();
20004        spec.membros = Vec::new();
20005        assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
20006        assert!(
20007            spec.membros().is_empty(),
20008            "the pre-flight refusal input must be the empty slice per \
20009             the accessor's projection",
20010        );
20011
20012        // (2) Per-member validate loop: a two-member cohort with an
20013        // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
20014        // the tail — the loop must reach the second entry through
20015        // the accessor.
20016        let mut spec = three_member_spec();
20017        spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
20018        assert_eq!(
20019            spec.validate().unwrap_err(),
20020            AplicacaoError::MembroCaixaEmpty,
20021        );
20022        assert_eq!(
20023            spec.membros().len(),
20024            2,
20025            "the per-member validate loop's traversal input must be \
20026             a two-element slice per the accessor's projection",
20027        );
20028
20029        // (3) Per-member validate loop: a two-member cohort that
20030        // shares a `:caixa` name must trip `MembroDuplicate` on the
20031        // second entry — the loop must reach both entries through the
20032        // accessor for the dedup HashSet's second insert to collide.
20033        let mut spec = three_member_spec();
20034        spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
20035        match spec.validate().unwrap_err() {
20036            AplicacaoError::MembroDuplicate { caixa } => {
20037                assert_eq!(
20038                    caixa, "catalog",
20039                    "MembroDuplicate.caixa must carry the shared \
20040                     member name verbatim",
20041                );
20042            }
20043            other => panic!("expected MembroDuplicate, got {other:?}"),
20044        }
20045        assert_eq!(
20046            spec.membros().len(),
20047            2,
20048            "the per-member validate loop's traversal input must be \
20049             a two-element slice per the accessor's projection",
20050        );
20051    }
20052
20053    #[test]
20054    fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
20055        // The canonical per-`:contratos` contract-list-slice-shape pin:
20056        // [`AplicacaoSpec::contratos`] must return the `:contratos`
20057        // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
20058        // slice-view over the same backing buffer the raw
20059        // `self.contratos.as_slice()` field access borrows from, byte-
20060        // equal across every representative fixture in the accept-set —
20061        // the empty slice (the pre-validation "internal-only mesh" shape
20062        // an Aplicacao whose members exchange no typed edges renders
20063        // through), the singleton slice (the minimal one-edge Aplicacao
20064        // shape), and multi-entry cohorts (the peer multi-edge shapes
20065        // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
20066        // of the application graph).
20067        //
20068        // Pins against a future silent detour that returned
20069        // `&Vec<WitContract>` (which would type-check but leak the
20070        // storage-side `Vec`'s grow/push/reserve surface no consumer of
20071        // the typed view reaches for), a fresh-allocated
20072        // `Vec<WitContract>` copy (which would type-check via a coercion
20073        // but silently break every downstream caller that relied on the
20074        // slice sharing the backing buffer's identity), or an out-of-
20075        // order or length-drifted projection (which would silently split
20076        // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
20077        // seed's traversal input from the `detect_sync_cycles` per-edge
20078        // adjacency-list seed's traversal input from the
20079        // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
20080        // BTreeMap grouping loop's traversal input from the
20081        // `feira app graph` per-contract print traversal's input).
20082        //
20083        // Peer of the immediately-adjacent sibling M3
20084        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
20085        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
20086        // node-list axis, the sibling M3
20087        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
20088        // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
20089        // distribution-target-list axis, and the sibling M2
20090        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
20091        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
20092        // `:supervisor` static-child-list axis — extends the slice-
20093        // return-accessor byte-equal-projection discipline onto the
20094        // outermost M3 mesh-slot type's per-Aplicacao contract-list
20095        // `Vec`-carry axis, closing the last unlifted per-
20096        // `AplicacaoSpec` `Vec`-carry axis.
20097        let fixtures: Vec<Vec<WitContract>> = vec![
20098            Vec::new(),
20099            vec![contract_http("cart", "catalog", "/products/:id")],
20100            vec![
20101                contract_http("cart", "catalog", "/products/:id"),
20102                contract_http("cart", "payment", "/charge"),
20103            ],
20104            vec![
20105                contract_http("cart", "catalog", "/products/:id"),
20106                contract_http("cart", "payment", "/charge"),
20107                contract_http("payment", "catalog", "/audit"),
20108            ],
20109        ];
20110        for contratos in fixtures {
20111            let s = AplicacaoSpec {
20112                membros: vec![
20113                    membro("catalog", "^0.1"),
20114                    membro("cart", "^0.1"),
20115                    membro("payment", "^0.2"),
20116                ],
20117                contratos: contratos.clone(),
20118                politicas: MeshPolicy::default(),
20119                placement: Placement::default(),
20120                entrada: None,
20121            };
20122            assert_eq!(
20123                s.contratos(),
20124                contratos.as_slice(),
20125                "AplicacaoSpec::contratos must return :contratos verbatim \
20126                 (got {:?}, expected {:?})",
20127                s.contratos(),
20128                contratos.as_slice(),
20129            );
20130            assert_eq!(
20131                s.contratos(),
20132                s.contratos.as_slice(),
20133                "AplicacaoSpec::contratos accessor and \
20134                 .contratos.as_slice() field access must byte-equal — \
20135                 the accessor is the substrate-primitive typed dispatch \
20136                 every downstream contract-list consumer must route \
20137                 through",
20138            );
20139            assert_eq!(
20140                s.contratos().len(),
20141                s.contratos.len(),
20142                "AplicacaoSpec::contratos().len() must byte-equal \
20143                 self.contratos.len() — a length-drift would silently \
20144                 split the paired per-edge validate-loop's traversal \
20145                 input from the sync-cycle adjacency-list seed's \
20146                 traversal input from the cilium_network_policies \
20147                 per-`(:de, :para)` BTreeMap grouping loop's traversal \
20148                 input from the `feira app graph` per-contract print \
20149                 traversal's input",
20150            );
20151        }
20152    }
20153
20154    #[test]
20155    fn validate_reads_through_lifted_contratos_accessor() {
20156        // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
20157        // per-`:contratos` validate-loop's `for c in self.contratos()`
20158        // traversal (which must reach every entry in the same order the
20159        // accessor projects, so both the per-entry
20160        // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
20161        // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
20162        // dedup `HashSet` insert key off the accessor's projection),
20163        // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
20164        // `for c in self.contratos()` adjacency-list seed (which drives
20165        // the sync-subgraph deadlock-detection gate via
20166        // [`AplicacaoError::SyncCycle`]), and the peer
20167        // [`caixa_mesh::cilium_network_policies`]'s
20168        // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
20169        // grouping loop (which drives the per-CNP fan-out) must all
20170        // three key off the lifted accessor, so any future rebrand on
20171        // the typed slot's reader shape lands at exactly one place. Pins
20172        // the three-site coherence by exercising the two caixa-core
20173        // production consumers end-to-end: (1) the empty-`:contratos`
20174        // slice must validate without a per-edge diagnostic (the
20175        // per-edge loop is a no-op under the empty projection), (2) the
20176        // `ContratoMemberMissing` refusal fires on the second entry of a
20177        // two-edge cohort whose head references a valid member but tail
20178        // references a phantom name (which requires the loop to reach
20179        // the second entry through the accessor), and (3) the
20180        // `SyncCycle` refusal fires on a self-referential two-edge
20181        // cohort through the sync-cycle detector's peer projection
20182        // (which requires the detector to iterate the accessor's
20183        // projection to add the back-edge to its adjacency list).
20184        //
20185        // Peer of the sibling M3
20186        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
20187        // three-consumer coherence pin on the per-`:membros` node-list
20188        // axis and the sibling M3
20189        // `validate_placement_reads_through_lifted_clusters_accessor`
20190        // (a6e18d7) coherence pin on the per-`:placement` distribution-
20191        // target-list axis — extends the slice-return-accessor multi-
20192        // consumer coherence discipline onto the outermost M3 mesh-slot
20193        // type's per-Aplicacao contract-list `Vec`-carry axis.
20194
20195        // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
20196        // and no per-edge diagnostic surfaces. Validate succeeds on
20197        // the well-formed `:membros` head.
20198        let mut spec = three_member_spec();
20199        spec.contratos = Vec::new();
20200        assert!(
20201            spec.validate().is_ok(),
20202            "empty :contratos must validate — the per-edge loop is a \
20203             no-op under the accessor's empty projection",
20204        );
20205        assert!(
20206            spec.contratos().is_empty(),
20207            "the per-edge validate loop's traversal input must be the \
20208             empty slice per the accessor's projection",
20209        );
20210
20211        // (2) Per-edge validate loop: a two-edge cohort whose tail
20212        // references a phantom `:para` member must trip
20213        // `ContratoMemberMissing` on the tail — the loop must reach
20214        // the second entry through the accessor for the membership
20215        // lookup to fail on the phantom name.
20216        let mut spec = three_member_spec();
20217        spec.contratos = vec![
20218            contract_http("cart", "catalog", "/products/:id"),
20219            contract_http("cart", "phantom", "/x"),
20220        ];
20221        let err = spec.validate().unwrap_err();
20222        assert!(
20223            matches!(
20224                err,
20225                AplicacaoError::ContratoMemberMissing { ref caixa }
20226                    if caixa == "phantom"
20227            ),
20228            "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
20229        );
20230        assert_eq!(
20231            spec.contratos().len(),
20232            2,
20233            "the per-edge validate loop's traversal input must be \
20234             a two-element slice per the accessor's projection",
20235        );
20236
20237        // (3) Sync-cycle detector: a two-edge synchronous cohort
20238        // whose second edge closes the sync-subgraph back onto the
20239        // first must trip [`AplicacaoError::ContratoCycle`] — the
20240        // detector must iterate the accessor's projection to add
20241        // both edges to its adjacency list, so a length-drift on
20242        // the accessor's projection would silently disagree with
20243        // the sync-cycle detector on which edge closes the loop.
20244        // Peer projection to the `validate` per-edge loop above:
20245        // the sync-cycle detector routes through the same lifted
20246        // accessor, so a rebrand of the reader shape lands at one
20247        // place. Uses a two-edge cohort (cart → catalog → cart)
20248        // because the per-edge `ContratoSelfLoop` gate fires before
20249        // the sync-cycle detector on a single self-referential edge
20250        // (`cart → cart`) — the cycle-detector's input must be a
20251        // multi-edge cohort for its per-edge traversal input to be
20252        // observably wider than the per-edge validate loop's input.
20253        let mut spec = three_member_spec();
20254        spec.contratos = vec![
20255            contract_http("cart", "catalog", "/products/:id"),
20256            contract_http("catalog", "cart", "/callback"),
20257        ];
20258        let err = spec.validate().unwrap_err();
20259        assert!(
20260            matches!(err, AplicacaoError::ContratoCycle { .. }),
20261            "expected ContratoCycle from the sync-cycle detector on a \
20262             two-edge back-edge cohort, got {err:?}",
20263        );
20264        assert_eq!(
20265            spec.contratos().len(),
20266            2,
20267            "the sync-cycle detector's traversal input must be a \
20268             two-element slice per the accessor's projection",
20269        );
20270    }
20271
20272    #[test]
20273    fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
20274        // The canonical per-`:politicas` outer-composite-reference-shape
20275        // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
20276        // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
20277        // the same backing storage the raw `&self.politicas` field
20278        // access borrows from, byte-equal across every representative
20279        // fixture in the accept-set — the default `MeshPolicy` (the
20280        // author-empty "no policy on any axis" shape whose
20281        // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
20282        // shapes carrying one axis at a time
20283        // (`{mtls_required, timeout, retries, circuit_breaker,
20284        // rate_limit}` — the minimal five-axis fan-out over the
20285        // per-axis lifted accessor family every downstream mesh-artifact
20286        // emitter dispatches on), and the multi-axis composite (the
20287        // canonical `three_member_spec` fixture's `{timeout, retries,
20288        // mtls_required}` triple — the load-bearing shape every
20289        // Aplicacao-scoped fixture in this suite constructs).
20290        //
20291        // Pins against a future silent detour that returned a fresh-
20292        // cloned `MeshPolicy` copy (which would type-check via a `Clone`
20293        // impl but silently break every downstream caller that relied
20294        // on the reference sharing the composite's backing identity), a
20295        // reference to an operator-resolved overlay (the future
20296        // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
20297        // acknowledges — its resolution must land at exactly this
20298        // accessor body, not silently divert the raw slot away from a
20299        // second consumer), or an axis-shuffled projection (a future
20300        // detour that swapped `timeout` and `retries` through the
20301        // accessor would silently split the paired `validate_politicas`
20302        // per-axis bracket-dispatch's traversal input from the peer
20303        // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
20304        // emitter's fan-out input from the peer
20305        // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
20306        // overlay emitter's fan-out input).
20307        //
20308        // Peer of the sibling M3
20309        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
20310        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
20311        // node-list `Vec`-carry axis and the sibling M3
20312        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
20313        // (0dcc926) `&[WitContract]` byte-equal pin on the per-
20314        // `:contratos` edge-list `Vec`-carry axis — extends the outer-
20315        // accessor byte-equal-projection discipline onto the outermost
20316        // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
20317        // reference axis, the first `&Composite`-return accessor on the
20318        // outer [`AplicacaoSpec`] type.
20319        let fixtures: Vec<MeshPolicy> = vec![
20320            MeshPolicy::default(),
20321            MeshPolicy {
20322                mtls_required: Some(true),
20323                ..MeshPolicy::default()
20324            },
20325            MeshPolicy {
20326                mtls_required: Some(false),
20327                ..MeshPolicy::default()
20328            },
20329            MeshPolicy {
20330                timeout: Some(Duration::from_secs(30)),
20331                ..MeshPolicy::default()
20332            },
20333            MeshPolicy {
20334                retries: Some(3),
20335                ..MeshPolicy::default()
20336            },
20337            MeshPolicy {
20338                circuit_breaker: Some(CircuitBreaker {
20339                    max_failures: 5,
20340                    window: Duration::from_secs(30),
20341                }),
20342                ..MeshPolicy::default()
20343            },
20344            MeshPolicy {
20345                rate_limit: Some(RateLimit {
20346                    rate: 100,
20347                    window: Duration::from_secs(1),
20348                }),
20349                ..MeshPolicy::default()
20350            },
20351            MeshPolicy {
20352                timeout: Some(Duration::from_secs(30)),
20353                retries: Some(3),
20354                mtls_required: Some(true),
20355                ..MeshPolicy::default()
20356            },
20357        ];
20358        for politicas in fixtures {
20359            let s = AplicacaoSpec {
20360                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
20361                contratos: Vec::new(),
20362                politicas: politicas.clone(),
20363                placement: Placement::default(),
20364                entrada: None,
20365            };
20366            assert_eq!(
20367                *s.politicas(),
20368                politicas,
20369                "AplicacaoSpec::politicas must return :politicas verbatim \
20370                 (got {:?}, expected {:?})",
20371                s.politicas(),
20372                politicas,
20373            );
20374            assert!(
20375                std::ptr::eq(s.politicas(), &s.politicas),
20376                "AplicacaoSpec::politicas accessor and &self.politicas \
20377                 field access must borrow the same backing storage — \
20378                 the accessor is the substrate-primitive typed dispatch \
20379                 every downstream mesh-policy composite consumer must \
20380                 route through, and a reference-identity split would \
20381                 silently break every consumer that relied on the \
20382                 borrow sharing the composite's storage",
20383            );
20384            assert_eq!(
20385                s.politicas().is_empty(),
20386                s.politicas.is_empty(),
20387                "AplicacaoSpec::politicas().is_empty() must byte-equal \
20388                 self.politicas.is_empty() — an emptiness-drift would \
20389                 silently split the paired `validate_politicas` \
20390                 per-axis bracket-dispatch's seed from the peer \
20391                 caixa-mesh CNP mTLS-overlay emitter's key from the \
20392                 peer caixa-mesh HTTPRoute timeout+retry overlay \
20393                 emitter's key",
20394            );
20395        }
20396    }
20397
20398    #[test]
20399    fn validate_politicas_reads_through_lifted_politicas_accessor() {
20400        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
20401        // per-axis bracket-dispatch seed (`let p = self.politicas();`,
20402        // followed by the per-axis fan-out `p.timeout()` /
20403        // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
20404        // the lifted axis-level accessor family) must key off the
20405        // lifted outer accessor, so any future rebrand on the typed
20406        // slot's outer-composite reader shape lands at exactly one
20407        // place. Pins the multi-axis coherence by exercising each
20408        // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
20409        // a `Some(Duration::ZERO)` timeout under the outer accessor's
20410        // reference projection, (2) `PolicyRetriesZero` fires on a
20411        // `Some(0)` retries under the same projection, and (3) an
20412        // empty [`MeshPolicy::default`] passes `validate_politicas` —
20413        // the outer accessor's reference-projection reaches every
20414        // per-axis branch without silently short-circuiting any.
20415        //
20416        // Peer of the sibling M3
20417        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
20418        // three-consumer coherence pin on the per-`:membros` node-list
20419        // axis and the sibling M3
20420        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
20421        // three-consumer coherence pin on the per-`:contratos`
20422        // edge-list axis — extends the multi-consumer coherence
20423        // discipline onto the outermost M3 mesh-slot type's per-
20424        // Aplicacao mesh-policy composite-reference axis, the first
20425        // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
20426        // type.
20427
20428        // (1) `PolicyTimeoutZero` refusal under the outer accessor's
20429        // reference projection: a `Some(Duration::ZERO)` timeout must
20430        // trip the zero-floor gate. The bracket-dispatch's first arm
20431        // reads `p.timeout()` on the reference returned by the outer
20432        // accessor.
20433        let mut spec = three_member_spec();
20434        spec.politicas.timeout = Some(Duration::ZERO);
20435        spec.politicas.retries = None;
20436        spec.politicas.circuit_breaker = None;
20437        spec.politicas.rate_limit = None;
20438        assert_eq!(
20439            spec.validate().unwrap_err(),
20440            AplicacaoError::PolicyTimeoutZero,
20441        );
20442        assert!(
20443            std::ptr::eq(spec.politicas(), &spec.politicas),
20444            "the `validate_politicas` per-axis bracket-dispatch's \
20445             traversal input must be the same backing composite the \
20446             accessor's reference projection borrows from",
20447        );
20448
20449        // (2) `PolicyRetriesZero` refusal under the outer accessor's
20450        // reference projection: a `Some(0)` retries must trip the
20451        // zero-floor gate. The bracket-dispatch's second arm reads
20452        // `p.retries()` on the reference returned by the outer accessor.
20453        let mut spec = three_member_spec();
20454        spec.politicas.timeout = None;
20455        spec.politicas.retries = Some(0);
20456        spec.politicas.circuit_breaker = None;
20457        spec.politicas.rate_limit = None;
20458        assert_eq!(
20459            spec.validate().unwrap_err(),
20460            AplicacaoError::PolicyRetriesZero,
20461        );
20462
20463        // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
20464        // — every per-axis arm short-circuits on `None`, so the outer
20465        // accessor's reference projection reaches the fall-through
20466        // `Ok(())` without any per-axis refusal firing.
20467        let mut spec = three_member_spec();
20468        spec.politicas = MeshPolicy::default();
20469        assert!(
20470            spec.validate().is_ok(),
20471            "an empty `MeshPolicy` must pass `validate_politicas` — \
20472             every per-axis arm short-circuits on `None` under the \
20473             outer accessor's reference projection",
20474        );
20475        assert!(
20476            spec.politicas().is_empty(),
20477            "the outer accessor's reference projection must be the \
20478             empty composite per the `MeshPolicy::default()` fixture",
20479        );
20480    }
20481
20482    #[test]
20483    #[allow(clippy::too_many_lines)]
20484    fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
20485        // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
20486        // per-axis bracket-dispatch's `:timeout` and `:retries` arms
20487        // must both key off the lifted axis-level accessors
20488        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
20489        // the peer `:circuit-breaker` / `:rate-limit` arms already
20490        // routing through [`MeshPolicy::circuit_breaker`] /
20491        // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
20492        // per axis on the substrate primitive" shape at the fan-out
20493        // (four axes, four accessors, no raw-field-access site
20494        // anywhere on the bracket-dispatch). Pins the per-axis
20495        // coherence at the accept-set boundaries the bracket carves:
20496        //   1. accessor byte-equal to raw field on every representative
20497        //      accept-set value (`None`, sub-cap, at-cap, past-cap
20498        //      sentinel) — a future accessor drift that no longer
20499        //      shipped the raw slot verbatim would surface here,
20500        //   2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
20501        //      routed through the accessor's projection, proving the
20502        //      first arm reads through the accessor rather than a
20503        //      silent-detour peer-axis field access,
20504        //   3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
20505        //      through the accessor's projection, proving the second
20506        //      arm reads through the accessor,
20507        //   4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
20508        //      passes validate under the accessor projection (paired
20509        //      with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
20510        //      sibling axis), pinning the upper-boundary accept-arm
20511        //      also routes through the accessor.
20512        //
20513        // Peer of the sibling M3
20514        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
20515        // outer-composite-reference coherence pin (which asserts the
20516        // `let p = self.politicas()` seed); extends the discipline onto
20517        // the per-axis fan-out layer that consumes the seed's
20518        // reference. Same shape as
20519        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
20520        // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
20521        // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
20522        // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
20523
20524        // (1) Accessor byte-equal to raw field on the `:timeout` axis
20525        // across the accept-set boundaries the bracket dispatch's
20526        // three-arm gate carves out
20527        // ([`crate::render::require_positive_canonical_bounded_duration`]
20528        // — zero-floor + canonical-form + upper-cap).
20529        for timeout in [
20530            None,
20531            Some(Duration::ZERO),
20532            Some(Duration::from_millis(1)),
20533            Some(POLICY_TIMEOUT_MAX),
20534        ] {
20535            let p = MeshPolicy {
20536                timeout,
20537                ..MeshPolicy::default()
20538            };
20539            assert_eq!(
20540                p.timeout(),
20541                p.timeout,
20542                "MeshPolicy::timeout accessor must byte-equal the raw \
20543                 .timeout field across every accept-set boundary the \
20544                 validate_politicas :timeout arm carves out — a drift \
20545                 here would silently split the validate bracket's arm \
20546                 from the peer caixa-mesh HTTPRoute timeout-overlay \
20547                 emitter's read",
20548            );
20549        }
20550
20551        // (2) Accessor byte-equal to raw field on the `:retries` axis
20552        // across the accept-set boundaries the bracket dispatch's
20553        // two-arm gate carves out
20554        // ([`crate::render::require_positive_bounded_u32`] — zero-floor
20555        // + upper-cap).
20556        for retries in [
20557            None,
20558            Some(0u32),
20559            Some(1u32),
20560            Some(POLICY_RETRIES_MAX),
20561            Some(POLICY_RETRIES_MAX + 1),
20562            Some(u32::MAX),
20563        ] {
20564            let p = MeshPolicy {
20565                retries,
20566                ..MeshPolicy::default()
20567            };
20568            assert_eq!(
20569                p.retries(),
20570                p.retries,
20571                "MeshPolicy::retries accessor must byte-equal the raw \
20572                 .retries field across every accept-set boundary the \
20573                 validate_politicas :retries arm carves out — a drift \
20574                 here would silently split the validate bracket's arm \
20575                 from the peer caixa-mesh HTTPRoute retry-overlay \
20576                 emitter's read",
20577            );
20578        }
20579
20580        // (3) `PolicyTimeoutZero` fires on the accessor-projected
20581        // zero-floor boundary. A silent detour that no longer read
20582        // through `p.timeout()` (a peer-axis field read, an accidental
20583        // Option::and-then chain that collapsed the None arm to Some,
20584        // an accessor rebrand that clamped the return through the
20585        // upper cap) would fail to refuse here.
20586        let mut spec = three_member_spec();
20587        spec.politicas.timeout = Some(Duration::ZERO);
20588        spec.politicas.retries = None;
20589        spec.politicas.circuit_breaker = None;
20590        spec.politicas.rate_limit = None;
20591        assert_eq!(
20592            spec.politicas().timeout(),
20593            Some(Duration::ZERO),
20594            "the accessor projection must reflect the fixture's \
20595             `Some(Duration::ZERO)` :timeout verbatim",
20596        );
20597        assert_eq!(
20598            spec.validate().unwrap_err(),
20599            AplicacaoError::PolicyTimeoutZero,
20600            "the validate_politicas :timeout zero-floor arm must fire \
20601             through the lifted accessor's projection — a silent \
20602             detour to a peer-axis field would fail to refuse",
20603        );
20604
20605        // (4) `PolicyRetriesZero` fires on the accessor-projected
20606        // zero-floor boundary on the sibling `:retries` axis.
20607        let mut spec = three_member_spec();
20608        spec.politicas.timeout = None;
20609        spec.politicas.retries = Some(0);
20610        spec.politicas.circuit_breaker = None;
20611        spec.politicas.rate_limit = None;
20612        assert_eq!(
20613            spec.politicas().retries(),
20614            Some(0),
20615            "the accessor projection must reflect the fixture's \
20616             `Some(0)` :retries verbatim",
20617        );
20618        assert_eq!(
20619            spec.validate().unwrap_err(),
20620            AplicacaoError::PolicyRetriesZero,
20621            "the validate_politicas :retries zero-floor arm must fire \
20622             through the lifted accessor's projection — a silent \
20623             detour to a peer-axis field would fail to refuse",
20624        );
20625
20626        // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
20627        // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
20628        // must pass validate under the accessor projection — pins the
20629        // upper-boundary accept-arm also routes through the lifted
20630        // accessor (a drift that clamped or short-circuited at the
20631        // upper boundary would fail the whole-spec validate here).
20632        let mut spec = three_member_spec();
20633        spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
20634        spec.politicas.retries = Some(POLICY_RETRIES_MAX);
20635        spec.politicas.circuit_breaker = None;
20636        spec.politicas.rate_limit = None;
20637        assert_eq!(
20638            spec.politicas().timeout(),
20639            Some(POLICY_TIMEOUT_MAX),
20640            "the accessor projection must reflect the fixture's \
20641             at-cap :timeout verbatim",
20642        );
20643        assert_eq!(
20644            spec.politicas().retries(),
20645            Some(POLICY_RETRIES_MAX),
20646            "the accessor projection must reflect the fixture's \
20647             at-cap :retries verbatim",
20648        );
20649        assert!(
20650            spec.validate().is_ok(),
20651            "at-cap :timeout + :retries must pass validate under the \
20652             accessor projection — the upper-boundary accept-arm on \
20653             both axes routes through the lifted accessor",
20654        );
20655    }
20656
20657    #[test]
20658    fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
20659        // The canonical per-`:placement` outer-composite-reference-shape
20660        // pin: [`AplicacaoSpec::placement`] must return the `:placement`
20661        // typed `Placement` verbatim as a `&Placement` reference over the
20662        // same backing storage the raw `&self.placement` field access
20663        // borrows from, byte-equal across every representative fixture in
20664        // the accept-set — the default `Placement` (the substrate seed
20665        // shape whose [`PlacementStrategy::default`] evaluates to
20666        // `SingleNode` with an empty `:clusters` pool and both
20667        // optional-scalar axes `None`), and every canonical strategy /
20668        // cluster-pool / optional-scalar combination the
20669        // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
20670        // three [`PlacementStrategy`] variants — `SingleNode`,
20671        // `Replicated`, `Sharded` — cross-projected with a non-empty
20672        // `:clusters` pool and, on the `Sharded` arm, a non-empty
20673        // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
20674        // canonical `three_member_spec` `Replicated` fixture's
20675        // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
20676        //
20677        // Pins against a future silent detour that returned a fresh-
20678        // cloned `Placement` copy (which would type-check via a `Clone`
20679        // impl but silently break every downstream caller that relied on
20680        // the reference sharing the composite's backing identity), a
20681        // reference to an operator-resolved overlay (the future per-
20682        // cluster `:placement-overrides` slot MESH-COMPOSITION §V
20683        // acknowledges — its resolution must land at exactly this
20684        // accessor body, not silently divert the raw slot away from a
20685        // second consumer), or an axis-shuffled projection (a future
20686        // detour that swapped `clusters` and `affinity` through the
20687        // accessor would silently split the paired `validate_placement`
20688        // per-axis bracket-dispatch's traversal input from the peer
20689        // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
20690        // programs.yaml distribution-annotation emitter's fan-out input
20691        // from the peer `feira app graph` per-Aplicacao print line's
20692        // input).
20693        //
20694        // Peer of the sibling M3
20695        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
20696        // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
20697        // outer mesh-policy composite-reference axis, and of the sibling
20698        // slice-return `aplicacao_spec_membros_returns_membros_slice_
20699        // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
20700        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
20701        // across_permutations` (0dcc926) `&[WitContract]` pins — extends
20702        // the outer-accessor byte-equal-projection discipline onto the
20703        // outermost M3 mesh-slot type's per-Aplicacao distribution
20704        // composite-reference axis, the second `&Composite`-return
20705        // accessor on the outer [`AplicacaoSpec`] type.
20706        let fixtures: Vec<Placement> = vec![
20707            Placement::default(),
20708            Placement {
20709                estrategia: PlacementStrategy::SingleNode,
20710                clusters: vec!["rio".into()],
20711                affinity: None,
20712                shard_key: None,
20713            },
20714            Placement {
20715                estrategia: PlacementStrategy::Replicated,
20716                clusters: vec!["rio".into(), "mar".into()],
20717                affinity: None,
20718                shard_key: None,
20719            },
20720            Placement {
20721                estrategia: PlacementStrategy::Replicated,
20722                clusters: vec!["rio".into(), "mar".into()],
20723                affinity: Some("data-locality".into()),
20724                shard_key: None,
20725            },
20726            Placement {
20727                estrategia: PlacementStrategy::Sharded,
20728                clusters: vec!["rio".into(), "mar".into()],
20729                affinity: None,
20730                shard_key: Some("tenantId".into()),
20731            },
20732            Placement {
20733                estrategia: PlacementStrategy::Sharded,
20734                clusters: vec!["rio".into(), "mar".into(), "sol".into()],
20735                affinity: Some("low-latency".into()),
20736                shard_key: Some("metadata.tenantId".into()),
20737            },
20738        ];
20739        for placement in fixtures {
20740            let s = AplicacaoSpec {
20741                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
20742                contratos: Vec::new(),
20743                politicas: MeshPolicy::default(),
20744                placement: placement.clone(),
20745                entrada: None,
20746            };
20747            assert_eq!(
20748                *s.placement(),
20749                placement,
20750                "AplicacaoSpec::placement must return :placement verbatim \
20751                 (got {:?}, expected {:?})",
20752                s.placement(),
20753                placement,
20754            );
20755            assert!(
20756                std::ptr::eq(s.placement(), &s.placement),
20757                "AplicacaoSpec::placement accessor and &self.placement \
20758                 field access must borrow the same backing storage — the \
20759                 accessor is the substrate-primitive typed dispatch every \
20760                 downstream distribution-composite consumer must route \
20761                 through, and a reference-identity split would silently \
20762                 break every consumer that relied on the borrow sharing \
20763                 the composite's storage",
20764            );
20765            assert_eq!(
20766                s.placement().estrategia(),
20767                s.placement.estrategia,
20768                "AplicacaoSpec::placement().estrategia() must byte-equal \
20769                 self.placement.estrategia — a strategy-drift would \
20770                 silently split the paired `validate_placement` \
20771                 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
20772                 peer caixa-mesh programs.yaml `placement.estrategia` \
20773                 emitter's key from the peer `feira app graph` printer's \
20774                 strategy label",
20775            );
20776            assert_eq!(
20777                s.placement().clusters(),
20778                s.placement.clusters.as_slice(),
20779                "AplicacaoSpec::placement().clusters() must byte-equal \
20780                 self.placement.clusters — a cluster-pool drift would \
20781                 silently split the paired `validate_placement` \
20782                 pre-flight `.is_empty()` refusal probe's traversal from \
20783                 the peer caixa-mesh programs.yaml `placement.clusters` \
20784                 emitter's fan-out from the peer `feira app graph` \
20785                 printer's cluster list",
20786            );
20787        }
20788    }
20789
20790    #[test]
20791    fn validate_placement_reads_through_lifted_placement_accessor() {
20792        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
20793        // per-axis bracket-dispatch seed (`let p = self.placement();`,
20794        // followed by the per-axis fan-out `p.clusters()` /
20795        // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
20796        // lifted axis-level accessor family) must key off the lifted
20797        // outer accessor, so any future rebrand on the typed slot's
20798        // outer-composite reader shape lands at exactly one place. Pins
20799        // the multi-axis coherence by exercising each per-axis refusal
20800        // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
20801        // `:clusters` pool under the outer accessor's reference
20802        // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
20803        // strategy with a `None` `:shard-key` under the same projection,
20804        // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
20805        // with a `Some` `:shard-key` under the same projection, and
20806        // (4) the canonical `three_member_spec` `Replicated` fixture
20807        // passes `validate_placement` under the outer accessor's
20808        // reference projection — the accessor's reference-projection
20809        // reaches every per-axis branch (cluster-pool refusal, `Sharded`
20810        // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
20811        // without silently short-circuiting any.
20812        //
20813        // Peer of the sibling M3
20814        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
20815        // (534dc21) multi-axis coherence pin on the per-`:politicas`
20816        // outer mesh-policy composite-reference axis — extends the
20817        // multi-consumer coherence discipline onto the outermost M3
20818        // mesh-slot type's per-Aplicacao distribution composite-
20819        // reference axis, the second `&Composite`-return accessor on
20820        // the outer [`AplicacaoSpec`] type.
20821
20822        // (1) `PlacementWithoutClusters` refusal under the outer
20823        // accessor's reference projection: an empty `:clusters` pool
20824        // must trip the pre-flight refusal probe. The bracket-dispatch's
20825        // first arm reads `p.clusters()` on the reference returned by
20826        // the outer accessor.
20827        let mut spec = three_member_spec();
20828        spec.placement.clusters = Vec::new();
20829        assert_eq!(
20830            spec.validate().unwrap_err(),
20831            AplicacaoError::PlacementWithoutClusters {
20832                estrategia: PlacementStrategy::Replicated,
20833            },
20834        );
20835        assert!(
20836            std::ptr::eq(spec.placement(), &spec.placement),
20837            "the `validate_placement` per-axis bracket-dispatch's \
20838             traversal input must be the same backing composite the \
20839             accessor's reference projection borrows from",
20840        );
20841
20842        // (2) `ShardedWithoutKey` refusal under the outer accessor's
20843        // reference projection: a `Sharded` strategy with a `None`
20844        // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
20845        // The bracket-dispatch's third arm reads `p.estrategia()` for
20846        // the match scrutinee then `p.shard_key()` for the cascade
20847        // scrutinee, both on the reference returned by the outer
20848        // accessor.
20849        let mut spec = three_member_spec();
20850        spec.placement.estrategia = PlacementStrategy::Sharded;
20851        spec.placement.shard_key = None;
20852        assert_eq!(
20853            spec.validate().unwrap_err(),
20854            AplicacaoError::ShardedWithoutKey,
20855        );
20856
20857        // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
20858        // reference projection: a non-`Sharded` strategy with a `Some`
20859        // `:shard-key` must trip the declared-but-inert refusal. The
20860        // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
20861        // + `p.estrategia()` for the diagnostic on the reference
20862        // returned by the outer accessor.
20863        let mut spec = three_member_spec();
20864        spec.placement.estrategia = PlacementStrategy::Replicated;
20865        spec.placement.shard_key = Some("tenantId".into());
20866        assert_eq!(
20867            spec.validate().unwrap_err(),
20868            AplicacaoError::ShardKeyOnNonSharded {
20869                estrategia: PlacementStrategy::Replicated,
20870                shard_key: "tenantId".into(),
20871            },
20872        );
20873
20874        // (4) Canonical `three_member_spec` `Replicated` fixture passes
20875        // `validate_placement` — every per-axis arm reaches the fall-
20876        // through `Ok(())` without any per-axis refusal firing under the
20877        // outer accessor's reference projection.
20878        let spec = three_member_spec();
20879        assert!(
20880            spec.validate().is_ok(),
20881            "the canonical Replicated placement fixture must pass \
20882             `validate_placement` — every per-axis arm short-circuits on \
20883             valid input under the outer accessor's reference projection",
20884        );
20885        assert_eq!(
20886            spec.placement().estrategia(),
20887            PlacementStrategy::Replicated,
20888            "the outer accessor's reference projection must be the \
20889             canonical Replicated fixture's strategy",
20890        );
20891        assert_eq!(
20892            spec.placement().clusters(),
20893            &["rio", "mar"],
20894            "the outer accessor's reference projection must be the \
20895             canonical Replicated fixture's cluster pool",
20896        );
20897    }
20898
20899    #[test]
20900    fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
20901        // The canonical per-`:entrada` outer-composite-optional-
20902        // reference-shape pin: [`AplicacaoSpec::entrada`] must return
20903        // the `:entrada` typed `Option<Entrada>` verbatim as an
20904        // `Option<&Entrada>` reference over the same backing storage
20905        // the raw `self.entrada.as_ref()` field access borrows from,
20906        // byte-equal across every representative fixture in the
20907        // accept-set — the author-omitted `None` shape (the
20908        // "internal-only mesh" partition every downstream external-
20909        // gateway emitter treats as "emit nothing"), the minimal
20910        // singleton `:entrada` composite (host + destination + empty
20911        // paths + default port), the paths-carrying composite (the
20912        // canonical `three_member_spec` fixture's ["/api" "/health"]
20913        // path-list shape every HTTPRoute per-rule fan-out emitter
20914        // reads), and the non-default port composite (the canonical
20915        // custom-port shape the port-fallback resolver reads).
20916        //
20917        // Pins against a future silent detour that returned a fresh-
20918        // cloned `Entrada` copy (which would type-check via a `Clone`
20919        // impl but silently break every downstream caller that
20920        // relied on the reference sharing the composite's backing
20921        // identity), a reference to an operator-resolved overlay
20922        // (the future per-cluster `:entrada-overrides` slot the
20923        // MESH-COMPOSITION §V federation roadmap acknowledges — its
20924        // resolution must land at exactly this accessor body, not
20925        // silently divert the raw slot away from a second consumer),
20926        // a `None` → `Some(Entrada::default)` cluster-default
20927        // projection (which would collapse the load-bearing
20928        // "author-omitted `:entrada` ⇒ internal-only mesh" partition
20929        // the peer `gateway_routes` early-return + `feira app graph`
20930        // internal-only-mesh partition both read), or an axis-
20931        // shuffled projection (a future detour that swapped
20932        // `host` and `para` through the accessor would silently
20933        // split the paired `validate` per-`:entrada` shape-and-
20934        // membership gate's traversal input from the peer
20935        // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
20936        // fan-out input from the peer `feira app graph` external-
20937        // gateway summary line).
20938        //
20939        // Peer of the sibling M3
20940        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
20941        // (534dc21) `&MeshPolicy` byte-equal pin on the per-
20942        // `:politicas` outer mesh-policy composite-reference axis
20943        // and of the sibling M3
20944        // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
20945        // (9abb8f0) `&Placement` byte-equal pin on the per-
20946        // `:placement` outer distribution-composite composite-
20947        // reference axis — extends the outer-accessor byte-equal-
20948        // projection discipline onto the last unlifted outermost M3
20949        // mesh-slot type's per-Aplicacao external-gateway composite-
20950        // reference axis, the third and final `&Composite`-return
20951        // accessor on the outer [`AplicacaoSpec`] type.
20952        let fixtures: Vec<Option<Entrada>> = vec![
20953            None,
20954            Some(Entrada {
20955                host: "checkout.quero.cloud".into(),
20956                para: "cart".into(),
20957                paths: Vec::new(),
20958                port: DEFAULT_SERVICO_PORT,
20959            }),
20960            Some(Entrada {
20961                host: "checkout.quero.cloud".into(),
20962                para: "cart".into(),
20963                paths: vec!["/api".into(), "/health".into()],
20964                port: DEFAULT_SERVICO_PORT,
20965            }),
20966            Some(Entrada {
20967                host: "checkout.quero.cloud".into(),
20968                para: "cart".into(),
20969                paths: vec!["/api".into()],
20970                port: 9443,
20971            }),
20972        ];
20973        for entrada in fixtures {
20974            let s = AplicacaoSpec {
20975                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
20976                contratos: Vec::new(),
20977                politicas: MeshPolicy::default(),
20978                placement: Placement::default(),
20979                entrada: entrada.clone(),
20980            };
20981            assert_eq!(
20982                s.entrada(),
20983                entrada.as_ref(),
20984                "AplicacaoSpec::entrada must return :entrada verbatim \
20985                 (got {:?}, expected {:?})",
20986                s.entrada(),
20987                entrada.as_ref(),
20988            );
20989            match (s.entrada(), s.entrada.as_ref()) {
20990                (Some(a), Some(b)) => assert!(
20991                    std::ptr::eq(a, b),
20992                    "AplicacaoSpec::entrada accessor and \
20993                     self.entrada.as_ref() field access must borrow \
20994                     the same backing storage — the accessor is the \
20995                     substrate-primitive typed dispatch every \
20996                     downstream external-gateway composite consumer \
20997                     must route through, and a reference-identity \
20998                     split would silently break every consumer that \
20999                     relied on the borrow sharing the composite's \
21000                     storage",
21001                ),
21002                (None, None) => {}
21003                _ => panic!(
21004                    "AplicacaoSpec::entrada presence bit must byte-\
21005                     equal self.entrada.is_some() — a presence-bit \
21006                     drift would silently split the paired `validate` \
21007                     per-`:entrada` shape-and-membership gate's \
21008                     traversal head from the peer \
21009                     caixa-mesh gateway_routes early-return partition \
21010                     from the peer `feira app graph` internal-only-\
21011                     mesh partition",
21012                ),
21013            }
21014            assert_eq!(
21015                s.entrada().is_some(),
21016                s.entrada.is_some(),
21017                "AplicacaoSpec::entrada().is_some() must byte-equal \
21018                 self.entrada.is_some() — a presence-bit drift would \
21019                 silently split every downstream `Option<&Entrada>` \
21020                 consumer's partition on the internal-only-mesh arm",
21021            );
21022        }
21023    }
21024
21025    #[test]
21026    fn validate_reads_through_lifted_entrada_accessor() {
21027        // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
21028        // per-`:entrada` shape-and-membership gate (`if let Some(e) =
21029        // self.entrada() { … }`, followed by the per-axis fan-out
21030        // `validate_entrada_para(&e.para)` /
21031        // `EntradaMemberMissing` membership lookup /
21032        // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
21033        // per-`e.paths` `validate_entrada_path` traversal) must key
21034        // off the lifted outer accessor, so any future rebrand on
21035        // the typed slot's outer-composite reader shape lands at
21036        // exactly one place. Pins the multi-axis coherence by
21037        // exercising each per-axis refusal end-to-end: (1) the
21038        // author-omitted `None` shape short-circuits past every
21039        // per-`:entrada` refusal (the internal-only mesh partition
21040        // the accessor's `None` arm names), (2) `EntradaMemberMissing`
21041        // fires on a well-shaped but phantom `:para` under the outer
21042        // accessor's reference projection, and (3) the canonical
21043        // `three_member_spec` `:entrada` fixture passes `validate`
21044        // under the outer accessor's reference projection.
21045        //
21046        // Peer of the sibling M3
21047        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
21048        // (534dc21) multi-axis coherence pin on the per-`:politicas`
21049        // outer mesh-policy composite-reference axis and the sibling
21050        // M3
21051        // [`validate_placement_reads_through_lifted_placement_accessor`]
21052        // (9abb8f0) multi-axis coherence pin on the per-`:placement`
21053        // outer distribution-composite composite-reference axis —
21054        // extends the multi-consumer coherence discipline onto the
21055        // last unlifted outermost M3 mesh-slot type's per-Aplicacao
21056        // external-gateway composite-reference axis, the third and
21057        // final `&Composite`-return accessor on the outer
21058        // [`AplicacaoSpec`] type.
21059
21060        // (1) `None` :entrada — the internal-only-mesh partition
21061        // short-circuits past every per-`:entrada` refusal. The outer
21062        // accessor's reference projection reaches the fall-through
21063        // `Ok(())` on the `None` arm without any per-axis refusal
21064        // firing.
21065        let mut spec = three_member_spec();
21066        spec.entrada = None;
21067        assert!(
21068            spec.validate().is_ok(),
21069            "an author-omitted `:entrada` must pass `validate` — the \
21070             internal-only-mesh partition short-circuits past every \
21071             per-`:entrada` refusal under the outer accessor's \
21072             reference projection",
21073        );
21074        assert!(
21075            spec.entrada().is_none(),
21076            "the outer accessor's reference projection must name the \
21077             internal-only-mesh partition per the `None` fixture",
21078        );
21079
21080        // (2) `EntradaMemberMissing` refusal under the outer accessor's
21081        // reference projection: a well-shaped but phantom `:para` must
21082        // trip the membership-lookup refusal. The gate's second arm
21083        // reads `e.para` on the reference returned by the outer
21084        // accessor.
21085        let mut spec = three_member_spec();
21086        if let Some(e) = spec.entrada.as_mut() {
21087            e.para = "phantom".into();
21088        }
21089        assert_eq!(
21090            spec.validate().unwrap_err(),
21091            AplicacaoError::EntradaMemberMissing {
21092                para: "phantom".into(),
21093            },
21094        );
21095        match (spec.entrada(), spec.entrada.as_ref()) {
21096            (Some(a), Some(b)) => assert!(
21097                std::ptr::eq(a, b),
21098                "the `validate` per-`:entrada` gate's traversal head \
21099                 must be the same backing composite the accessor's \
21100                 reference projection borrows from",
21101            ),
21102            _ => panic!("fixture must carry Some(:entrada)"),
21103        }
21104
21105        // (3) Canonical `three_member_spec` `:entrada` fixture passes
21106        // `validate` — every per-axis arm reaches the fall-through
21107        // `Ok(())` without any per-axis refusal firing under the
21108        // outer accessor's reference projection.
21109        let spec = three_member_spec();
21110        assert!(
21111            spec.validate().is_ok(),
21112            "the canonical `:entrada` fixture must pass `validate` — \
21113             every per-axis arm short-circuits on valid input under \
21114             the outer accessor's reference projection",
21115        );
21116        assert!(
21117            spec.entrada().is_some(),
21118            "the outer accessor's reference projection must be the \
21119             canonical `:entrada` fixture's composite",
21120        );
21121    }
21122
21123    #[test]
21124    fn port_for_destination_reads_through_lifted_entrada_accessor() {
21125        // Peer coherence pin: the
21126        // [`AplicacaoSpec::port_for_destination`] per-destination
21127        // L4-port fallback resolver's composite-projection seed
21128        // (`self.entrada().filter(…).map_or(…)`) must key off the
21129        // lifted outer accessor. Pins the coherence by exercising
21130        // the resolver end-to-end: (1) the `None` `:entrada` shape
21131        // falls through to `DEFAULT_SERVICO_PORT` under the outer
21132        // accessor's reference projection, (2) a non-matching
21133        // destination falls through to `DEFAULT_SERVICO_PORT` under
21134        // the outer accessor's reference projection, and (3) the
21135        // matching destination resolves to the `:entrada :port`
21136        // value under the outer accessor's reference projection.
21137        //
21138        // Peer of the sibling
21139        // [`validate_reads_through_lifted_entrada_accessor`] multi-
21140        // consumer coherence pin on the same per-`:entrada` outer-
21141        // composite axis — extends the multi-consumer coherence
21142        // discipline onto the second per-`:entrada` production
21143        // consumer, the L4-port fallback resolver.
21144
21145        // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
21146        // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
21147        // arm under the outer accessor's reference projection.
21148        let mut spec = three_member_spec();
21149        spec.entrada = None;
21150        assert_eq!(
21151            spec.port_for_destination("cart"),
21152            DEFAULT_SERVICO_PORT,
21153            "the port-fallback resolver must fall through to \
21154             DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
21155             under the outer accessor's reference projection",
21156        );
21157
21158        // (2) Non-matching destination — the resolver's `filter(…)`
21159        // arm rejects a mismatched destination and falls through
21160        // to `DEFAULT_SERVICO_PORT` under the outer accessor's
21161        // reference projection.
21162        let mut spec = three_member_spec();
21163        if let Some(e) = spec.entrada.as_mut() {
21164            e.para = "cart".into();
21165            e.port = 9443;
21166        }
21167        assert_eq!(
21168            spec.port_for_destination("catalog"),
21169            DEFAULT_SERVICO_PORT,
21170            "the port-fallback resolver must fall through to \
21171             DEFAULT_SERVICO_PORT on a non-matching destination \
21172             under the outer accessor's reference projection",
21173        );
21174
21175        // (3) Matching destination — the resolver's `map_or(…)` arm
21176        // returns the `:entrada :port` value under the outer
21177        // accessor's reference projection.
21178        let mut spec = three_member_spec();
21179        if let Some(e) = spec.entrada.as_mut() {
21180            e.para = "cart".into();
21181            e.port = 9443;
21182        }
21183        assert_eq!(
21184            spec.port_for_destination("cart"),
21185            9443,
21186            "the port-fallback resolver must return the \
21187             `:entrada :port` value on a matching destination \
21188             under the outer accessor's reference projection",
21189        );
21190    }
21191
21192    #[test]
21193    fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
21194        // The canonical per-`:politicas` `:mtls-required` mTLS-
21195        // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
21196        // must return the `:politicas :mtls-required` typed bool
21197        // verbatim as an `Option<bool>`, byte-equal to the raw field
21198        // access across every value in the three-way accept-set —
21199        // `None` (cluster default applies), `Some(true)` (mTLS
21200        // handshake enforced — the sandboxing-by-default arm the
21201        // MeshPolicy's docstring names), `Some(false)` (handshake
21202        // skipped — the explicit debug-edge opt-out).
21203        //
21204        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
21205        // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
21206        // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
21207        // shape — first `Option<Copy-T>`-return accessor on the M3
21208        // mesh-slot family. Pins against a future silent detour that
21209        // re-derived the toggle from a peer axis (an accidental
21210        // `.circuit_breaker.is_some()` collapse that assumed mTLS on
21211        // whenever a breaker is set), a `None` → `Some(false)` cluster-
21212        // default projection (the canonical `Option<bool>` → `bool`
21213        // collapse footgun the surrounding `is_empty()` predicate
21214        // guards on the peer emptiness axis), or a `Some(true)` /
21215        // `Some(false)` variant swap that landed on one consumer
21216        // without the other.
21217        for required in [None, Some(true), Some(false)] {
21218            let p = MeshPolicy {
21219                mtls_required: required,
21220                ..MeshPolicy::default()
21221            };
21222            assert_eq!(
21223                p.mtls_required(),
21224                required,
21225                "MeshPolicy::mtls_required must return :politicas \
21226                 :mtls-required verbatim (got {:?}, expected {required:?})",
21227                p.mtls_required(),
21228            );
21229            assert_eq!(
21230                p.mtls_required(),
21231                p.mtls_required,
21232                "MeshPolicy::mtls_required must byte-equal the raw \
21233                 .mtls_required field access across every value in the \
21234                 three-way accept-set",
21235            );
21236        }
21237    }
21238
21239    #[test]
21240    fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
21241        // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
21242        // arm must key off [`MeshPolicy::mtls_required`], not the raw
21243        // `.mtls_required` field access. Structurally: toggling ONLY
21244        // the `mtls_required` slot on an otherwise-default MeshPolicy
21245        // must flip `is_empty()` from `true` (all-`None`) to `false`
21246        // (one axis carries a value); the flip must be observed for
21247        // both `Some(true)` and `Some(false)` since the emptiness
21248        // semantic reads "any axis carries a value" — not "any axis
21249        // carries a truthy value" — the same non-collapsing shape the
21250        // sibling M2 [`crate::LimitsSpec::is_empty`] /
21251        // [`crate::BehaviorSpec::is_empty`] predicates carry on their
21252        // peer `Option<T>`-typed slot surfaces.
21253        //
21254        // Pins against a future silent detour that re-derived the
21255        // emptiness predicate off a peer axis (an accidental
21256        // `.rate_limit.is_none()`-only chain that dropped the
21257        // `mtls_required` arm entirely), a `mtls_required == Some(_)`
21258        // collapse to a truthy-only check (which would silently
21259        // classify `Some(false)` as empty), or an accessor-side
21260        // detour that no longer names the substrate-primitive typed
21261        // dispatch (an accidental `self.mtls_required.unwrap_or(false)
21262        // == false` fallback in the accessor that would silently
21263        // classify both `None` and `Some(false)` as the same value).
21264        //
21265        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
21266        // (7cd2a28) accessor-composition pin on the sibling optional-
21267        // scalar axis — same "the emptiness / shape-gate predicate
21268        // must route through the substrate-primitive typed dispatch"
21269        // discipline extended onto the peer per-`:politicas` emptiness
21270        // predicate.
21271        let empty = MeshPolicy::default();
21272        assert!(
21273            empty.is_empty(),
21274            "MeshPolicy::default() must be is_empty() — every axis \
21275             defaults to None",
21276        );
21277        for required in [Some(true), Some(false)] {
21278            let p = MeshPolicy {
21279                mtls_required: required,
21280                ..MeshPolicy::default()
21281            };
21282            assert!(
21283                !p.is_empty(),
21284                "MeshPolicy::is_empty must return false when \
21285                 :mtls-required is {required:?} — the emptiness \
21286                 predicate reads \"any axis carries a value\", not \
21287                 \"any axis carries a truthy value\"",
21288            );
21289            assert_eq!(
21290                p.mtls_required().is_none(),
21291                p.is_empty(),
21292                "when :mtls-required is the only set axis, \
21293                 is_empty() must equal mtls_required().is_none() — \
21294                 the accessor and the emptiness predicate must \
21295                 route through the same substrate-primitive typed \
21296                 dispatch on the :mtls-required arm",
21297            );
21298        }
21299    }
21300
21301    #[test]
21302    fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
21303        // The by-copy pin: [`MeshPolicy::mtls_required`] returns
21304        // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
21305        // accessor must return by value, not by reference. Peer of the
21306        // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
21307        // borrow-invariant pin on the sibling `Option<String>` slot,
21308        // but extended onto the peer `Option<bool>` copy-invariant
21309        // shape — the accessor's returned `Option<bool>` must outlive
21310        // `&self` (multiple calls must return equal values from a
21311        // dropped-`&self` copy, since the returned Option carries no
21312        // borrow), and calling the accessor twice on the same
21313        // MeshPolicy must yield the same `Option<bool>` verbatim
21314        // (idempotent, no side effects on `&self`).
21315        //
21316        // Pins against a future silent detour that returned
21317        // `Option<&bool>` (which would type-check but silently break
21318        // every downstream caller — [`single_field_overlay`]'s first
21319        // parameter is `Option<T: Clone>`, and `&bool` would fold to a
21320        // detached copy at the call site), an accidental
21321        // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
21322        // would also type-check but return `Option<&bool>`), or a
21323        // one-arm-only accessor that reads `Some(*b)` in the Some arm
21324        // but reads a fresh Default::default() in the None arm.
21325        for required in [None, Some(true), Some(false)] {
21326            let p = MeshPolicy {
21327                mtls_required: required,
21328                ..MeshPolicy::default()
21329            };
21330            let first = p.mtls_required();
21331            let second = p.mtls_required();
21332            assert_eq!(
21333                first, second,
21334                "MeshPolicy::mtls_required must be idempotent — two \
21335                 successive calls on the same &self must return the \
21336                 same Option<bool>",
21337            );
21338            assert_eq!(
21339                first, required,
21340                "MeshPolicy::mtls_required must return :politicas \
21341                 :mtls-required verbatim by copy — got {first:?}, \
21342                 expected {required:?}",
21343            );
21344        }
21345    }
21346
21347    #[test]
21348    fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
21349        // The canonical per-`:politicas` `:retries` transient-failure-
21350        // retry-budget scalar pin: [`MeshPolicy::retries`] must return
21351        // the `:politicas :retries` typed `u32` verbatim as an
21352        // `Option<u32>`, byte-equal to the raw field access across every
21353        // representative value in the accept-set — `None` (cluster
21354        // default applies — typically "no retries beyond a single
21355        // dispatch attempt" the caixa-mesh `retry_overlay` builder
21356        // documents), `Some(1)` (the lower boundary of the
21357        // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
21358        // `AplicacaoSpec::validate_politicas` gate carves out on the
21359        // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
21360        // (the upper boundary the same gate carves out on the sibling
21361        // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
21362        // past-the-guard sentinel that pins the accessor doesn't perform
21363        // a silent bounds-collapse at the return path).
21364        //
21365        // Sibling of the peer per-`:politicas`
21366        // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
21367        // sibling `Option<Copy-T>` optional-scalar axis, extended to the
21368        // peer per-`:politicas` `Option<u32>` shape — second
21369        // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
21370        // Pins against a future silent detour that re-derived the retry
21371        // cap from a peer axis (an accidental `.circuit_breaker
21372        // .as_ref().map(|b| b.max_failures)` collapse that read the
21373        // breaker's max-failure count as a retry budget), a
21374        // `None → Some(0)` cluster-default projection (which would
21375        // silently re-introduce the `PolicyRetriesZero` refusal case at
21376        // the emit boundary), or a bounds-collapsing accessor that
21377        // clamped the return through `POLICY_RETRIES_MAX` (the
21378        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
21379        // must ship the raw slot verbatim so a validate-time gate
21380        // regression surfaces at the emit boundary rather than being
21381        // silently absorbed).
21382        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
21383            let p = MeshPolicy {
21384                retries,
21385                ..MeshPolicy::default()
21386            };
21387            assert_eq!(
21388                p.retries(),
21389                retries,
21390                "MeshPolicy::retries must return :politicas :retries \
21391                 verbatim (got {:?}, expected {retries:?})",
21392                p.retries(),
21393            );
21394            assert_eq!(
21395                p.retries(),
21396                p.retries,
21397                "MeshPolicy::retries must byte-equal the raw .retries \
21398                 field access across every value in the accept-set",
21399            );
21400        }
21401    }
21402
21403    #[test]
21404    fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
21405        // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
21406        // must key off [`MeshPolicy::retries`], not the raw `.retries`
21407        // field access. Structurally: toggling ONLY the `retries` slot
21408        // on an otherwise-default MeshPolicy must flip `is_empty()`
21409        // from `true` (all-`None`) to `false` (one axis carries a
21410        // value); the flip must be observed for every value in the
21411        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
21412        // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
21413        // the emptiness semantic reads "any axis carries a value" —
21414        // not "any axis carries a value the validate gate accepts" —
21415        // the same non-collapsing shape the peer M2
21416        // [`crate::LimitsSpec::is_empty`] /
21417        // [`crate::BehaviorSpec::is_empty`] predicates carry.
21418        //
21419        // Pins against a future silent detour that re-derived the
21420        // emptiness predicate off a peer axis (an accidental
21421        // `.rate_limit.is_none()`-only chain that dropped the
21422        // `retries` arm entirely), a `retries == Some(_)` collapse
21423        // that key-off a validate-gate-clamped bounds check (which
21424        // would silently classify a past-the-guard `Some(u32::MAX)`
21425        // as empty because it fails the `1..=POLICY_RETRIES_MAX`
21426        // check), or an accessor-side detour that no longer names the
21427        // substrate-primitive typed dispatch.
21428        //
21429        // Sibling of the peer per-`:politicas`
21430        // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
21431        // pin on the sibling `Option<Copy-T>` optional-scalar axis —
21432        // same "the emptiness predicate must route through the
21433        // substrate-primitive typed dispatch" discipline extended onto
21434        // the peer per-`:politicas` `Option<u32>` axis.
21435        let empty = MeshPolicy::default();
21436        assert!(
21437            empty.is_empty(),
21438            "MeshPolicy::default() must be is_empty() — every axis \
21439             defaults to None",
21440        );
21441        for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
21442            let p = MeshPolicy {
21443                retries,
21444                ..MeshPolicy::default()
21445            };
21446            assert!(
21447                !p.is_empty(),
21448                "MeshPolicy::is_empty must return false when \
21449                 :retries is {retries:?} — the emptiness \
21450                 predicate reads \"any axis carries a value\", not \
21451                 \"any axis carries a value the validate gate \
21452                 accepts\"",
21453            );
21454            assert_eq!(
21455                p.retries().is_none(),
21456                p.is_empty(),
21457                "when :retries is the only set axis, is_empty() \
21458                 must equal retries().is_none() — the accessor and \
21459                 the emptiness predicate must route through the same \
21460                 substrate-primitive typed dispatch on the :retries \
21461                 arm",
21462            );
21463        }
21464    }
21465
21466    #[test]
21467    fn mesh_policy_retries_projects_option_u32_by_copy() {
21468        // The by-copy pin: [`MeshPolicy::retries`] returns
21469        // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
21470        // accessor must return by value, not by reference. Sibling of
21471        // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
21472        // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
21473        // extended onto the sibling `Option<u32>` copy-invariant
21474        // shape — the accessor's returned `Option<u32>` must outlive
21475        // `&self` (multiple calls must return equal values from a
21476        // dropped-`&self` copy, since the returned Option carries no
21477        // borrow), and calling the accessor twice on the same
21478        // MeshPolicy must yield the same `Option<u32>` verbatim
21479        // (idempotent, no side effects on `&self`).
21480        //
21481        // Pins against a future silent detour that returned
21482        // `Option<&u32>` (which would type-check but silently break
21483        // every downstream caller — [`crate::render::single_field_overlay`]'s
21484        // first parameter is `Option<T: Clone>`, and `&u32` would
21485        // fold to a detached copy at the call site), an accidental
21486        // `Option::as_ref()` projection (`self.retries.as_ref()` would
21487        // also type-check but return `Option<&u32>`), or a one-arm-
21488        // only accessor that reads `Some(*n)` in the Some arm but
21489        // reads a fresh `Default::default()` (`0_u32`) in the None
21490        // arm.
21491        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
21492            let p = MeshPolicy {
21493                retries,
21494                ..MeshPolicy::default()
21495            };
21496            let first = p.retries();
21497            let second = p.retries();
21498            assert_eq!(
21499                first, second,
21500                "MeshPolicy::retries must be idempotent — two \
21501                 successive calls on the same &self must return the \
21502                 same Option<u32>",
21503            );
21504            assert_eq!(
21505                first, retries,
21506                "MeshPolicy::retries must return :politicas :retries \
21507                 verbatim by copy — got {first:?}, expected {retries:?}",
21508            );
21509        }
21510    }
21511
21512    #[test]
21513    fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
21514        // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
21515        // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
21516        // return the `:politicas :timeout` typed [`Duration`] verbatim
21517        // as an `Option<Duration>`, byte-equal to the raw field access
21518        // across every representative value in the accept-set — `None`
21519        // (cluster default applies — typically the gateway class's
21520        // implementation-side per-request wall-clock cap the caixa-mesh
21521        // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
21522        // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
21523        // set the surrounding `AplicacaoSpec::validate_politicas` gate
21524        // carves out on the sibling `PolicyTimeoutZero` /
21525        // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
21526        // (the upper boundary the same gate carves out on the sibling
21527        // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
21528        // (a past-the-guard sentinel that pins the accessor doesn't
21529        // perform a silent bounds-collapse into `None` on the zero-
21530        // Duration arm — validate rejects zero but the accessor must
21531        // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
21532        // past-the-guard sentinel that pins the accessor doesn't
21533        // perform a silent bounds-collapse at the return path).
21534        //
21535        // Sibling of the peer per-`:politicas`
21536        // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
21537        // `Option<u32>` optional-scalar axis and the peer per-
21538        // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
21539        // pin on the sibling `Option<bool>` optional-scalar axis,
21540        // extended onto the peer per-`:politicas` `Option<Duration>`
21541        // shape — third `Option<Copy-T>`-return accessor on the M3
21542        // mesh-slot family. Pins against a future silent detour that
21543        // re-derived the per-call cap from a peer axis (an accidental
21544        // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
21545        // read the breaker's rolling-window duration as a per-call
21546        // deadline), a `None → Some(Duration::MAX)` cluster-default
21547        // projection (which would silently re-introduce the
21548        // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
21549        // blocking" arm at the emit boundary), or a bounds-collapsing
21550        // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
21551        // (the `AplicacaoSpec::validate` gate owns the bounds; the
21552        // accessor must ship the raw slot verbatim so a validate-time
21553        // gate regression surfaces at the emit boundary rather than
21554        // being silently absorbed).
21555        for timeout in [
21556            None,
21557            Some(Duration::from_millis(1)),
21558            Some(POLICY_TIMEOUT_MAX),
21559            Some(Duration::ZERO),
21560            Some(Duration::MAX),
21561        ] {
21562            let p = MeshPolicy {
21563                timeout,
21564                ..MeshPolicy::default()
21565            };
21566            assert_eq!(
21567                p.timeout(),
21568                timeout,
21569                "MeshPolicy::timeout must return :politicas :timeout \
21570                 verbatim (got {:?}, expected {timeout:?})",
21571                p.timeout(),
21572            );
21573            assert_eq!(
21574                p.timeout(),
21575                p.timeout,
21576                "MeshPolicy::timeout must byte-equal the raw .timeout \
21577                 field access across every value in the accept-set",
21578            );
21579        }
21580    }
21581
21582    #[test]
21583    fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
21584        // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
21585        // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
21586        // field access. Structurally: toggling ONLY the `timeout` slot
21587        // on an otherwise-default MeshPolicy must flip `is_empty()`
21588        // from `true` (all-`None`) to `false` (one axis carries a
21589        // value); the flip must be observed for every value in the
21590        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
21591        // gate accepts (`Some(Duration::from_millis(1))`,
21592        // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
21593        // reads "any axis carries a value" — not "any axis carries a
21594        // value the validate gate accepts" — the same non-collapsing
21595        // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
21596        // [`crate::BehaviorSpec::is_empty`] predicates carry.
21597        //
21598        // Pins against a future silent detour that re-derived the
21599        // emptiness predicate off a peer axis (an accidental
21600        // `.rate_limit.is_none()`-only chain that dropped the
21601        // `timeout` arm entirely), a `timeout == Some(_)` collapse
21602        // that key-off a validate-gate-clamped bounds check (which
21603        // would silently classify a past-the-guard `Some(Duration::MAX)`
21604        // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
21605        // check), or an accessor-side detour that no longer names the
21606        // substrate-primitive typed dispatch.
21607        //
21608        // Sibling of the peer per-`:politicas`
21609        // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
21610        // the sibling `Option<u32>` optional-scalar axis and the peer
21611        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
21612        // accessor-composition pin on the sibling `Option<bool>`
21613        // optional-scalar axis — same "the emptiness predicate must
21614        // route through the substrate-primitive typed dispatch"
21615        // discipline extended onto the peer per-`:politicas`
21616        // `Option<Duration>` axis.
21617        let empty = MeshPolicy::default();
21618        assert!(
21619            empty.is_empty(),
21620            "MeshPolicy::default() must be is_empty() — every axis \
21621             defaults to None",
21622        );
21623        for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
21624            let p = MeshPolicy {
21625                timeout,
21626                ..MeshPolicy::default()
21627            };
21628            assert!(
21629                !p.is_empty(),
21630                "MeshPolicy::is_empty must return false when \
21631                 :timeout is {timeout:?} — the emptiness \
21632                 predicate reads \"any axis carries a value\", not \
21633                 \"any axis carries a value the validate gate \
21634                 accepts\"",
21635            );
21636            assert_eq!(
21637                p.timeout().is_none(),
21638                p.is_empty(),
21639                "when :timeout is the only set axis, is_empty() \
21640                 must equal timeout().is_none() — the accessor and \
21641                 the emptiness predicate must route through the same \
21642                 substrate-primitive typed dispatch on the :timeout \
21643                 arm",
21644            );
21645        }
21646    }
21647
21648    #[test]
21649    fn mesh_policy_timeout_projects_option_duration_by_copy() {
21650        // The by-copy pin: [`MeshPolicy::timeout`] returns
21651        // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
21652        // and the accessor must return by value, not by reference.
21653        // Sibling of the peer per-`:politicas`
21654        // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
21655        // sibling `Option<u32>` optional-scalar axis and the peer
21656        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
21657        // by-copy pin on the sibling `Option<bool>` optional-scalar
21658        // axis, extended onto the peer per-`:politicas`
21659        // `Option<Duration>` copy-invariant shape — the accessor's
21660        // returned `Option<Duration>` must outlive `&self` (multiple
21661        // calls must return equal values from a dropped-`&self`
21662        // copy, since the returned Option carries no borrow), and
21663        // calling the accessor twice on the same MeshPolicy must
21664        // yield the same `Option<Duration>` verbatim (idempotent, no
21665        // side effects on `&self`).
21666        //
21667        // Pins against a future silent detour that returned
21668        // `Option<&Duration>` (which would type-check but silently
21669        // break every downstream caller — [`crate::render::single_field_overlay`]'s
21670        // first parameter is `Option<T: Clone>`, and `&Duration`
21671        // would fold to a detached copy at the call site), an
21672        // accidental `Option::as_ref()` projection
21673        // (`self.timeout.as_ref()` would also type-check but return
21674        // `Option<&Duration>`), or a one-arm-only accessor that
21675        // reads `Some(*d)` in the Some arm but reads a fresh
21676        // `Default::default()` (`Duration::ZERO`) in the None arm
21677        // (which would silently re-classify every unset `:timeout`
21678        // as the `PolicyTimeoutZero`-refused zero-Duration value at
21679        // the accessor boundary).
21680        for timeout in [
21681            None,
21682            Some(Duration::from_millis(1)),
21683            Some(POLICY_TIMEOUT_MAX),
21684            Some(Duration::ZERO),
21685            Some(Duration::MAX),
21686        ] {
21687            let p = MeshPolicy {
21688                timeout,
21689                ..MeshPolicy::default()
21690            };
21691            let first = p.timeout();
21692            let second = p.timeout();
21693            assert_eq!(
21694                first, second,
21695                "MeshPolicy::timeout must be idempotent — two \
21696                 successive calls on the same &self must return the \
21697                 same Option<Duration>",
21698            );
21699            assert_eq!(
21700                first, timeout,
21701                "MeshPolicy::timeout must return :politicas :timeout \
21702                 verbatim by copy — got {first:?}, expected {timeout:?}",
21703            );
21704        }
21705    }
21706
21707    #[test]
21708    fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
21709        // The canonical per-`:politicas` `:rate-limit` Envoy-
21710        // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
21711        // [`MeshPolicy::rate_limit`] must return the `:politicas
21712        // :rate-limit` typed [`RateLimit`] verbatim as an
21713        // `Option<RateLimit>`, byte-equal to the raw field access
21714        // across every representative value in the accept-set — `None`
21715        // (cluster default applies — no per-Aplicacao rate declaration,
21716        // the gateway-class per-listener default arm the future caixa-
21717        // mesh `local_rate_limit_overlay` emitter documents),
21718        // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
21719        // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
21720        // accept-set the surrounding
21721        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
21722        // sibling `PolicyRateLimitZero` refusal, paired with the
21723        // canonical-window "1 second" arm of the three-unit
21724        // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
21725        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
21726        // (the upper boundary the same gate carves out on the sibling
21727        // `PolicyRateLimitExceedsCap` refusal, paired with the
21728        // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
21729        // (a past-the-guard sentinel that pins the accessor doesn't
21730        // perform a silent bounds-collapse into `None` on the
21731        // zero-rate/zero-window arm — validate rejects zero but the
21732        // accessor must ship the raw slot verbatim so a validate-time
21733        // gate regression surfaces at the emit boundary rather than
21734        // being silently absorbed), and
21735        // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
21736        // (a past-the-guard sentinel that pins the accessor doesn't
21737        // perform a silent bounds-collapse at the return path).
21738        //
21739        // First `Option<Copy-composite-T>`-return accessor pin on the
21740        // M3 mesh-slot family (peer of the sibling per-`:politicas`
21741        // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
21742        // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
21743        // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
21744        // Copy accessor pins, extended onto the peer per-`:politicas`
21745        // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
21746        // and the accessor returns by value). Pins against a future
21747        // silent detour that re-derived the rate declaration from a
21748        // peer axis (an accidental
21749        // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
21750        // collapse that read the breaker's trip threshold + rolling
21751        // window as a rate declaration), a `None → Some(default())`
21752        // cluster-default projection (which would silently re-
21753        // introduce a "cluster default is 0/s" arm the emit boundary
21754        // would take as "declared but inert" — the canonical
21755        // declared-but-inert footgun the sibling
21756        // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
21757        // amplification-shape axis), a bounds-collapsing accessor
21758        // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
21759        // clamped `rl.window` through [`is_canonical_rate_limit_window`]
21760        // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
21761        // accessor must ship the raw slot verbatim), or a
21762        // by-reference detour (`Option<&RateLimit>`) that broke every
21763        // downstream consumer keying off `Option<RateLimit>` by-copy.
21764        for rl in [
21765            None,
21766            Some(RateLimit {
21767                rate: 1,
21768                window: Duration::from_secs(1),
21769            }),
21770            Some(RateLimit {
21771                rate: POLICY_RATE_LIMIT_MAX,
21772                window: Duration::from_secs(3600),
21773            }),
21774            Some(RateLimit {
21775                rate: 0,
21776                window: Duration::ZERO,
21777            }),
21778            Some(RateLimit {
21779                rate: u32::MAX,
21780                window: Duration::MAX,
21781            }),
21782        ] {
21783            let p = MeshPolicy {
21784                rate_limit: rl,
21785                ..MeshPolicy::default()
21786            };
21787            assert_eq!(
21788                p.rate_limit(),
21789                rl,
21790                "MeshPolicy::rate_limit must return :politicas :rate-limit \
21791                 verbatim (got {:?}, expected {rl:?})",
21792                p.rate_limit(),
21793            );
21794            assert_eq!(
21795                p.rate_limit(),
21796                p.rate_limit,
21797                "MeshPolicy::rate_limit must byte-equal the raw \
21798                 .rate_limit field access across every value in the \
21799                 accept-set",
21800            );
21801        }
21802    }
21803
21804    #[test]
21805    fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
21806        // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
21807        // must key off [`MeshPolicy::rate_limit`], not the raw
21808        // `.rate_limit` field access. Structurally: toggling ONLY the
21809        // `rate_limit` slot on an otherwise-default MeshPolicy must
21810        // flip `is_empty()` from `true` (all-`None`) to `false` (one
21811        // axis carries a value); the flip must be observed for every
21812        // representative value in the accept-set the surrounding
21813        // [`AplicacaoSpec::validate_politicas`] gate accepts
21814        // (`Some(RateLimit { rate: 1, window: 1s })`,
21815        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
21816        // since the emptiness semantic reads "any axis carries a
21817        // value" — not "any axis carries a value the validate gate
21818        // accepts" — the same non-collapsing shape the peer M2
21819        // [`crate::LimitsSpec::is_empty`] /
21820        // [`crate::BehaviorSpec::is_empty`] predicates carry.
21821        //
21822        // Pins against a future silent detour that re-derived the
21823        // emptiness predicate off a peer axis (an accidental
21824        // `.timeout.is_none()`-only chain that dropped the
21825        // `rate_limit` arm entirely — the last unlifted inline field
21826        // access on `is_empty` before this lift), a `rate_limit ==
21827        // Some(_)` collapse that key-off a validate-gate-clamped
21828        // bounds check (which would silently classify a past-the-
21829        // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
21830        // because it fails the value-shape gate), or an accessor-
21831        // side detour that no longer names the substrate-primitive
21832        // typed dispatch.
21833        //
21834        // Fourth "the emptiness predicate must route through the
21835        // substrate-primitive typed dispatch" composition pin on the
21836        // M3 mesh-slot family — closes the last unlifted composition
21837        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
21838        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
21839        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
21840        // 7073d0f is_empty-composition pins on the sibling primitive-
21841        // Copy axes, extended onto the peer per-`:politicas`
21842        // composite-Copy `Option<RateLimit>` axis).
21843        let empty = MeshPolicy::default();
21844        assert!(
21845            empty.is_empty(),
21846            "MeshPolicy::default() must be is_empty() — every axis \
21847             defaults to None",
21848        );
21849        for rl in [
21850            RateLimit {
21851                rate: 1,
21852                window: Duration::from_secs(1),
21853            },
21854            RateLimit {
21855                rate: POLICY_RATE_LIMIT_MAX,
21856                window: Duration::from_secs(3600),
21857            },
21858        ] {
21859            let p = MeshPolicy {
21860                rate_limit: Some(rl),
21861                ..MeshPolicy::default()
21862            };
21863            assert!(
21864                !p.is_empty(),
21865                "MeshPolicy::is_empty must return false when \
21866                 :rate-limit is {rl:?} — the emptiness predicate \
21867                 reads \"any axis carries a value\", not \"any axis \
21868                 carries a value the validate gate accepts\"",
21869            );
21870            assert_eq!(
21871                p.rate_limit().is_none(),
21872                p.is_empty(),
21873                "when :rate-limit is the only set axis, is_empty() \
21874                 must equal rate_limit().is_none() — the accessor \
21875                 and the emptiness predicate must route through the \
21876                 same substrate-primitive typed dispatch on the \
21877                 :rate-limit arm",
21878            );
21879        }
21880    }
21881
21882    #[test]
21883    fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
21884        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
21885        // `:rate-limit` value-shape gate must key off
21886        // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
21887        // field bind. Structurally: a `MeshPolicy` whose only set
21888        // axis is a `Some(RateLimit { rate: 0, .. })` must surface
21889        // the `PolicyRateLimitZero` refusal exactly, and the same
21890        // MeshPolicy with the rate at the canonical lower boundary
21891        // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
21892        // The pair jointly pins the accessor + validate-gate
21893        // composition: any future silent detour that had the accessor
21894        // omit the `Some(RateLimit { rate: 0, .. })` arm (a
21895        // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
21896        // silently absorb the `PolicyRateLimitZero` refusal at the
21897        // accessor boundary — the composition pin catches that at
21898        // caixa-core build time.
21899        //
21900        // Sibling of the peer [`validate_politicas`]
21901        // `:mtls-required` / `:retries` / `:timeout` composition pins
21902        // on the sibling primitive-Copy optional-scalar axes — same
21903        // "the validate / shape-gate predicate must route through the
21904        // substrate-primitive typed dispatch" discipline extended
21905        // onto the peer per-`:politicas` composite-Copy
21906        // `Option<RateLimit>` axis. Second composition-with-accessor
21907        // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
21908        // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
21909        let mut spec = three_member_spec();
21910        spec.politicas = MeshPolicy {
21911            rate_limit: Some(RateLimit {
21912                rate: 0,
21913                window: Duration::from_secs(1),
21914            }),
21915            ..MeshPolicy::default()
21916        };
21917        assert!(
21918            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
21919            "validate_politicas must reject rate == 0 with \
21920             PolicyRateLimitZero — the accessor and the validate gate \
21921             must route through the same substrate-primitive typed \
21922             dispatch on the :rate-limit zero-floor arm",
21923        );
21924        spec.politicas = MeshPolicy {
21925            rate_limit: Some(RateLimit {
21926                rate: 1,
21927                window: Duration::from_secs(1),
21928            }),
21929            ..MeshPolicy::default()
21930        };
21931        assert!(
21932            spec.validate().is_ok(),
21933            "validate_politicas must accept rate == 1 (the canonical \
21934             lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
21935             set) with a canonical 1s window",
21936        );
21937    }
21938
21939    #[test]
21940    fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
21941        // The canonical per-`:politicas` `:circuit-breaker` Envoy-
21942        // `outlier_detection`-mesh consecutive-failure-ejection scalar
21943        // pin: [`MeshPolicy::circuit_breaker`] must return the
21944        // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
21945        // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
21946        // raw field access across every representative value in the
21947        // accept-set — `None` (cluster default applies — no
21948        // per-Aplicacao breaker declaration, the gateway-class per-
21949        // listener default arm the future caixa-mesh
21950        // `outlier_detection_overlay` emitter documents),
21951        // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
21952        // (the lower boundary of the accept-set the surrounding
21953        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
21954        // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
21955        // refusals),
21956        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
21957        // (the upper boundary the same gate carves out on the sibling
21958        // `PolicyBreakerMaxFailuresExceedsCap` /
21959        // `PolicyBreakerWindowExceedsCap` refusals),
21960        // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
21961        // (a past-the-guard sentinel that pins the accessor doesn't
21962        // perform a silent bounds-collapse into `None` on the
21963        // zero-failures/zero-window arm — validate rejects zero but
21964        // the accessor must ship the raw slot verbatim so a validate-
21965        // time gate regression surfaces at the emit boundary rather
21966        // than being silently absorbed), and
21967        // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
21968        // (a past-the-guard sentinel that pins the accessor doesn't
21969        // perform a silent bounds-collapse at the return path).
21970        //
21971        // Second `Option<Copy-composite-T>`-return accessor pin on the
21972        // M3 mesh-slot family (peer of the sibling per-`:politicas`
21973        // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
21974        // composite-Copy accessor pin, and of the sibling per-
21975        // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
21976        // [`MeshPolicy::retries`] bdfb399 /
21977        // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
21978        // accessor pins). Pins against a future silent detour that
21979        // re-derived the breaker declaration from a peer axis (an
21980        // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
21981        // collapse that read the rate-limit's bucket capacity + refill
21982        // period as a breaker declaration), a `None → Some(default())`
21983        // cluster-default projection (which would silently re-
21984        // introduce the `PolicyBreakerZeroFailures` /
21985        // `PolicyBreakerZeroWindow` refusal cases at the emit
21986        // boundary), a bounds-collapsing accessor that clamped
21987        // `cb.max_failures` through
21988        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
21989        // through [`POLICY_BREAKER_WINDOW_MAX`] (the
21990        // [`AplicacaoSpec::validate`] gate owns the bounds; the
21991        // accessor must ship the raw slot verbatim), or a
21992        // by-reference detour (`Option<&CircuitBreaker>`) that broke
21993        // every downstream consumer keying off `Option<CircuitBreaker>`
21994        // by-copy.
21995        for cb in [
21996            None,
21997            Some(CircuitBreaker {
21998                max_failures: 1,
21999                window: Duration::from_millis(1),
22000            }),
22001            Some(CircuitBreaker {
22002                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
22003                window: POLICY_BREAKER_WINDOW_MAX,
22004            }),
22005            Some(CircuitBreaker {
22006                max_failures: 0,
22007                window: Duration::ZERO,
22008            }),
22009            Some(CircuitBreaker {
22010                max_failures: u32::MAX,
22011                window: Duration::MAX,
22012            }),
22013        ] {
22014            let p = MeshPolicy {
22015                circuit_breaker: cb,
22016                ..MeshPolicy::default()
22017            };
22018            assert_eq!(
22019                p.circuit_breaker(),
22020                cb,
22021                "MeshPolicy::circuit_breaker must return :politicas \
22022                 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
22023                p.circuit_breaker(),
22024            );
22025            assert_eq!(
22026                p.circuit_breaker(),
22027                p.circuit_breaker,
22028                "MeshPolicy::circuit_breaker must byte-equal the raw \
22029                 .circuit_breaker field access across every value in \
22030                 the accept-set",
22031            );
22032        }
22033    }
22034
22035    #[test]
22036    fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
22037        // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
22038        // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
22039        // `.circuit_breaker` field access. Structurally: toggling ONLY
22040        // the `circuit_breaker` slot on an otherwise-default MeshPolicy
22041        // must flip `is_empty()` from `true` (all-`None`) to `false`
22042        // (one axis carries a value); the flip must be observed for
22043        // every representative value in the accept-set the surrounding
22044        // [`AplicacaoSpec::validate_politicas`] gate accepts
22045        // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
22046        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
22047        // since the emptiness semantic reads "any axis carries a
22048        // value" — not "any axis carries a value the validate gate
22049        // accepts" — the same non-collapsing shape the peer M2
22050        // [`crate::LimitsSpec::is_empty`] /
22051        // [`crate::BehaviorSpec::is_empty`] predicates carry.
22052        //
22053        // Pins against a future silent detour that re-derived the
22054        // emptiness predicate off a peer axis (an accidental
22055        // `.rate_limit.is_none()`-only chain that dropped the
22056        // `circuit_breaker` arm entirely — the last unlifted inline
22057        // field access on `is_empty` before this lift), a
22058        // `circuit_breaker == Some(_)` collapse that key-off a
22059        // validate-gate-clamped bounds check (which would silently
22060        // classify a past-the-guard `Some(CircuitBreaker { max_failures:
22061        // 0, window: 0s })` as empty because it fails the value-shape
22062        // gate), or an accessor-side detour that no longer names the
22063        // substrate-primitive typed dispatch.
22064        //
22065        // Fifth "the emptiness predicate must route through the
22066        // substrate-primitive typed dispatch" composition pin on the
22067        // M3 mesh-slot family — closes the last unlifted composition
22068        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
22069        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
22070        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
22071        // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
22072        // composition pins on the sibling primitive-Copy + composite-
22073        // Copy axes, extended onto the peer per-`:politicas`
22074        // composite-Copy `Option<CircuitBreaker>` axis).
22075        let empty = MeshPolicy::default();
22076        assert!(
22077            empty.is_empty(),
22078            "MeshPolicy::default() must be is_empty() — every axis \
22079             defaults to None",
22080        );
22081        for cb in [
22082            CircuitBreaker {
22083                max_failures: 1,
22084                window: Duration::from_millis(1),
22085            },
22086            CircuitBreaker {
22087                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
22088                window: POLICY_BREAKER_WINDOW_MAX,
22089            },
22090        ] {
22091            let p = MeshPolicy {
22092                circuit_breaker: Some(cb),
22093                ..MeshPolicy::default()
22094            };
22095            assert!(
22096                !p.is_empty(),
22097                "MeshPolicy::is_empty must return false when \
22098                 :circuit-breaker is {cb:?} — the emptiness predicate \
22099                 reads \"any axis carries a value\", not \"any axis \
22100                 carries a value the validate gate accepts\"",
22101            );
22102            assert_eq!(
22103                p.circuit_breaker().is_none(),
22104                p.is_empty(),
22105                "when :circuit-breaker is the only set axis, \
22106                 is_empty() must equal circuit_breaker().is_none() — \
22107                 the accessor and the emptiness predicate must route \
22108                 through the same substrate-primitive typed dispatch \
22109                 on the :circuit-breaker arm",
22110            );
22111        }
22112    }
22113
22114    #[test]
22115    fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
22116        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
22117        // `:circuit-breaker` value-shape gate must key off
22118        // [`MeshPolicy::circuit_breaker`], not the raw
22119        // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
22120        // whose only set axis is a `Some(CircuitBreaker { max_failures:
22121        // 0, .. })` must surface the `PolicyBreakerZeroFailures`
22122        // refusal exactly, and the same MeshPolicy with the breaker at
22123        // the canonical lower boundary
22124        // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
22125        // pass validate. The pair jointly pins the accessor +
22126        // validate-gate composition: any future silent detour that had
22127        // the accessor omit the `Some(CircuitBreaker { max_failures:
22128        // 0, .. })` arm (a
22129        // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
22130        // collapse) would silently absorb the
22131        // `PolicyBreakerZeroFailures` refusal at the accessor
22132        // boundary — the composition pin catches that at caixa-core
22133        // build time.
22134        //
22135        // Sibling of the peer [`validate_politicas`]
22136        // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
22137        // composition pins on the sibling primitive-Copy + composite-
22138        // Copy optional-scalar axes — same "the validate / shape-gate
22139        // predicate must route through the substrate-primitive typed
22140        // dispatch" discipline extended onto the peer per-`:politicas`
22141        // composite-Copy `Option<CircuitBreaker>` axis. Second
22142        // composition-with-accessor pin on the M3 mesh-slot
22143        // `Option<CircuitBreaker>` arm alongside the
22144        // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
22145        let mut spec = three_member_spec();
22146        spec.politicas = MeshPolicy {
22147            circuit_breaker: Some(CircuitBreaker {
22148                max_failures: 0,
22149                window: Duration::from_millis(1),
22150            }),
22151            ..MeshPolicy::default()
22152        };
22153        assert!(
22154            matches!(
22155                spec.validate(),
22156                Err(AplicacaoError::PolicyBreakerZeroFailures)
22157            ),
22158            "validate_politicas must reject max_failures == 0 with \
22159             PolicyBreakerZeroFailures — the accessor and the validate \
22160             gate must route through the same substrate-primitive \
22161             typed dispatch on the :circuit-breaker zero-floor arm",
22162        );
22163        spec.politicas = MeshPolicy {
22164            circuit_breaker: Some(CircuitBreaker {
22165                max_failures: 1,
22166                window: Duration::from_millis(1),
22167            }),
22168            ..MeshPolicy::default()
22169        };
22170        assert!(
22171            spec.validate().is_ok(),
22172            "validate_politicas must accept a CircuitBreaker at the \
22173             canonical lower boundary (max_failures = 1, window = \
22174             1ms) — the accessor and the validate gate must route \
22175             through the same substrate-primitive typed dispatch on \
22176             the :circuit-breaker arm",
22177        );
22178    }
22179
22180    #[test]
22181    fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
22182        // The canonical per-`:politicas :circuit-breaker` `:max-failures`
22183        // Envoy-outlier-detection trip-threshold scalar pin:
22184        // [`CircuitBreaker::max_failures`] must return the
22185        // `:politicas :circuit-breaker :max-failures` typed `u32`
22186        // verbatim, byte-equal to the raw field access across every
22187        // representative value in the accept-set — `1` (the lower
22188        // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
22189        // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
22190        // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
22191        // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
22192        // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
22193        // refusal), `0` (a past-the-guard sentinel that pins the accessor
22194        // doesn't perform a silent bounds-collapse into `1` on the zero
22195        // arm — validate rejects zero but the accessor must ship the
22196        // raw slot verbatim so a validate-time gate regression surfaces
22197        // at the emit boundary rather than being silently absorbed),
22198        // `u32::MAX` (a past-the-guard sentinel that pins the accessor
22199        // doesn't perform a silent bounds-collapse through
22200        // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
22201        //
22202        // First sub-struct required-scalar accessor pin on the M3
22203        // mesh-slot family — sibling in shape to the peer per-`:membros`
22204        // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
22205        // (a40b0e3) required-`String`-carry accessor pins and the peer
22206        // per-`:contratos` [`WitContract::source`] /
22207        // [`WitContract::destination`] (7f0fd43) required-`String`-carry
22208        // accessor pins, extended onto the peer per-`CircuitBreaker`
22209        // required-`u32` scalar-value axis. Pins against a future silent
22210        // detour that re-derived the trip threshold from a peer axis (an
22211        // accidental `self.window.as_secs() as u32` collapse that read
22212        // the breaker's rolling-window duration as a failure count), a
22213        // `0 → 1` cluster-default projection (which would silently absorb
22214        // the `PolicyBreakerZeroFailures` refusal case at the accessor
22215        // boundary), or a bounds-collapsing accessor that clamped the
22216        // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
22217        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
22218        // must ship the raw slot verbatim).
22219        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
22220            let cb = CircuitBreaker {
22221                max_failures,
22222                window: Duration::from_secs(60),
22223            };
22224            assert_eq!(
22225                cb.max_failures(),
22226                max_failures,
22227                "CircuitBreaker::max_failures must return :politicas \
22228                 :circuit-breaker :max-failures verbatim (got {}, \
22229                 expected {max_failures})",
22230                cb.max_failures(),
22231            );
22232            assert_eq!(
22233                cb.max_failures(),
22234                cb.max_failures,
22235                "CircuitBreaker::max_failures must byte-equal the raw \
22236                 .max_failures field access across every value in the \
22237                 u32 accept-set",
22238            );
22239        }
22240    }
22241
22242    #[test]
22243    fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
22244        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
22245        // `:circuit-breaker :max-failures` zero-floor arm must key off
22246        // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
22247        // field access. Structurally: a `CircuitBreaker { max_failures:
22248        // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
22249        // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
22250        // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
22251        // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
22252        // pass validate. The pair jointly pins the accessor +
22253        // validate-gate composition: any future silent detour that had
22254        // the accessor return a fresh `1` on the zero arm (a
22255        // `.max_failures().max(1)` collapse) would silently absorb the
22256        // `PolicyBreakerZeroFailures` refusal at the accessor boundary
22257        // and the validate gate would accept a struct-literal
22258        // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
22259        // catches that at caixa-core build time.
22260        //
22261        // Peer of the sibling per-`:politicas`
22262        // [`MeshPolicy::mtls_required`] (c0110f1) /
22263        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
22264        // (7073d0f) accessor-composition pins on the sibling optional-
22265        // scalar axes — same "the validate / shape-gate predicate must
22266        // route through the substrate-primitive typed dispatch"
22267        // discipline extended onto the peer per-`CircuitBreaker`
22268        // required-scalar composition axis.
22269        let mut spec = three_member_spec();
22270        spec.politicas = MeshPolicy {
22271            circuit_breaker: Some(CircuitBreaker {
22272                max_failures: 0,
22273                window: Duration::from_secs(60),
22274            }),
22275            ..MeshPolicy::default()
22276        };
22277        assert!(
22278            matches!(
22279                spec.validate(),
22280                Err(AplicacaoError::PolicyBreakerZeroFailures)
22281            ),
22282            "validate_politicas must reject max_failures == 0 with \
22283             PolicyBreakerZeroFailures — the accessor and the validate \
22284             gate must route through the same substrate-primitive typed \
22285             dispatch on the :max-failures zero-floor arm",
22286        );
22287        spec.politicas = MeshPolicy {
22288            circuit_breaker: Some(CircuitBreaker {
22289                max_failures: 1,
22290                window: Duration::from_secs(60),
22291            }),
22292            ..MeshPolicy::default()
22293        };
22294        assert!(
22295            spec.validate().is_ok(),
22296            "validate_politicas must accept max_failures == 1 (the \
22297             lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
22298             accept-set)",
22299        );
22300    }
22301
22302    #[test]
22303    fn circuit_breaker_max_failures_projects_u32_by_copy() {
22304        // The by-copy pin: [`CircuitBreaker::max_failures`] returns
22305        // `u32` by copy — `u32` is `Copy` and the accessor must return
22306        // by value, not by reference. Peer of the sibling
22307        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
22308        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
22309        // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
22310        // optional-scalar axes, extended onto the peer
22311        // per-`CircuitBreaker` required-`u32` copy-invariant shape —
22312        // the accessor's returned `u32` must outlive `&self` (multiple
22313        // calls must return equal values from a dropped-`&self` copy,
22314        // since the returned scalar carries no borrow), and calling
22315        // the accessor twice on the same CircuitBreaker must yield the
22316        // same `u32` verbatim (idempotent, no side effects on `&self`).
22317        //
22318        // Pins against a future silent detour that returned `&u32`
22319        // (which would type-check but silently break every downstream
22320        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
22321        // first parameter is `u32`, and `&u32` would fold to a detached
22322        // copy at the call site with a `*` deref the sibling accessors
22323        // don't need), an accidental `.max_failures.wrapping_add(0)`
22324        // detour that returned a fresh copy through an arithmetic
22325        // no-op (breaking a future `const fn` regression), or a
22326        // one-arm-only accessor that returned a saturating value on
22327        // some sentinel input (breaking the pass-through invariant the
22328        // sibling required-scalar accessors carry).
22329        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
22330            let cb = CircuitBreaker {
22331                max_failures,
22332                window: Duration::from_secs(60),
22333            };
22334            let first = cb.max_failures();
22335            let second = cb.max_failures();
22336            assert_eq!(
22337                first, second,
22338                "CircuitBreaker::max_failures must be idempotent — two \
22339                 successive calls on the same &self must return the \
22340                 same u32",
22341            );
22342            assert_eq!(
22343                first, max_failures,
22344                "CircuitBreaker::max_failures must return :politicas \
22345                 :circuit-breaker :max-failures verbatim by copy — \
22346                 got {first}, expected {max_failures}",
22347            );
22348        }
22349    }
22350
22351    #[test]
22352    fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
22353        // The canonical per-`:politicas :circuit-breaker` `:window`
22354        // Envoy-outlier-detection rolling-observation-interval scalar
22355        // pin: [`CircuitBreaker::window`] must return the
22356        // `:politicas :circuit-breaker :window` typed `Duration`
22357        // verbatim, byte-equal to the raw field access across every
22358        // representative value in the accept-set — `Duration::from_millis(1)`
22359        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
22360        // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
22361        // gate carves out on the sibling `PolicyBreakerZeroWindow`
22362        // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
22363        // same gate carves out on the sibling
22364        // `PolicyBreakerWindowExceedsCap` refusal),
22365        // `Duration::ZERO` (a past-the-guard sentinel that pins the
22366        // accessor doesn't perform a silent bounds-collapse into
22367        // `Duration::from_millis(1)` on the zero arm — validate rejects
22368        // zero but the accessor must ship the raw slot verbatim so a
22369        // validate-time gate regression surfaces at the emit boundary
22370        // rather than being silently absorbed),
22371        // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
22372        // far above the 1h cap — that pins the accessor doesn't perform
22373        // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
22374        // at the return path).
22375        //
22376        // Second sub-struct required-scalar accessor pin on the M3
22377        // mesh-slot family — sibling in shape to the just-landed
22378        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
22379        // (3a74062) required-`u32` accessor pin on the peer
22380        // per-`CircuitBreaker` required-axis, extended onto the
22381        // per-sub-struct required-`Duration` axis. Pins against a
22382        // future silent detour that re-derived the observation window
22383        // from a peer axis (an accidental
22384        // `Duration::from_secs(self.max_failures as u64)` collapse that
22385        // read the breaker's trip count as an observation-interval
22386        // duration), a `Duration::ZERO → Duration::from_millis(1)`
22387        // cluster-default projection (which would silently absorb the
22388        // `PolicyBreakerZeroWindow` refusal case at the accessor
22389        // boundary), or a bounds-collapsing accessor that clamped the
22390        // return through `POLICY_BREAKER_WINDOW_MAX` (the
22391        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
22392        // must ship the raw slot verbatim).
22393        for window in [
22394            Duration::from_millis(1),
22395            POLICY_BREAKER_WINDOW_MAX,
22396            Duration::ZERO,
22397            Duration::from_secs(86_400),
22398        ] {
22399            let cb = CircuitBreaker {
22400                max_failures: 5,
22401                window,
22402            };
22403            assert_eq!(
22404                cb.window(),
22405                window,
22406                "CircuitBreaker::window must return :politicas \
22407                 :circuit-breaker :window verbatim (got {:?}, \
22408                 expected {window:?})",
22409                cb.window(),
22410            );
22411            assert_eq!(
22412                cb.window(),
22413                cb.window,
22414                "CircuitBreaker::window must byte-equal the raw \
22415                 .window field access across every value in the \
22416                 Duration accept-set",
22417            );
22418        }
22419    }
22420
22421    #[test]
22422    fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
22423        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
22424        // `:circuit-breaker :window` zero-floor arm must key off
22425        // [`CircuitBreaker::window`], not the raw `.window` field
22426        // access. Structurally: a `CircuitBreaker { window:
22427        // Duration::ZERO, .. }` embedded in a
22428        // `:politicas :circuit-breaker` slot must surface the
22429        // `PolicyBreakerZeroWindow` refusal exactly, and a
22430        // `CircuitBreaker { window: Duration::from_millis(1), .. }`
22431        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
22432        // accept-set) must pass validate. The pair jointly pins the
22433        // accessor + validate-gate composition: any future silent
22434        // detour that had the accessor return a fresh
22435        // `Duration::from_millis(1)` on the zero arm (a
22436        // `.window().max(Duration::from_millis(1))` collapse) would
22437        // silently absorb the `PolicyBreakerZeroWindow` refusal at the
22438        // accessor boundary and the validate gate would accept a
22439        // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
22440        // — the composition pin catches that at caixa-core build time.
22441        //
22442        // Peer of the sibling per-`CircuitBreaker`
22443        // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
22444        // pin on the peer required-scalar `:max-failures` axis — same
22445        // "the validate / shape-gate predicate must route through the
22446        // substrate-primitive typed dispatch" discipline extended onto
22447        // the peer per-`CircuitBreaker` required-`Duration` composition
22448        // axis.
22449        let mut spec = three_member_spec();
22450        spec.politicas = MeshPolicy {
22451            circuit_breaker: Some(CircuitBreaker {
22452                max_failures: 5,
22453                window: Duration::ZERO,
22454            }),
22455            ..MeshPolicy::default()
22456        };
22457        assert!(
22458            matches!(
22459                spec.validate(),
22460                Err(AplicacaoError::PolicyBreakerZeroWindow)
22461            ),
22462            "validate_politicas must reject window == Duration::ZERO \
22463             with PolicyBreakerZeroWindow — the accessor and the \
22464             validate gate must route through the same substrate-\
22465             primitive typed dispatch on the :window zero-floor arm",
22466        );
22467        spec.politicas = MeshPolicy {
22468            circuit_breaker: Some(CircuitBreaker {
22469                max_failures: 5,
22470                window: Duration::from_millis(1),
22471            }),
22472            ..MeshPolicy::default()
22473        };
22474        assert!(
22475            spec.validate().is_ok(),
22476            "validate_politicas must accept window == \
22477             Duration::from_millis(1) (the lower boundary of the \
22478             1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
22479        );
22480    }
22481
22482    #[test]
22483    fn circuit_breaker_window_projects_duration_by_copy() {
22484        // The by-copy pin: [`CircuitBreaker::window`] returns
22485        // `Duration` by copy — `Duration` is `Copy` and the accessor
22486        // must return by value, not by reference. Peer of the sibling
22487        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
22488        // (3a74062) by-copy pin on the peer required-scalar
22489        // `:max-failures` axis, extended onto the peer
22490        // per-`CircuitBreaker` required-`Duration` copy-invariant shape
22491        // — the accessor's returned `Duration` must outlive `&self`
22492        // (multiple calls must return equal values from a
22493        // dropped-`&self` copy, since the returned scalar carries no
22494        // borrow), and calling the accessor twice on the same
22495        // CircuitBreaker must yield the same `Duration` verbatim
22496        // (idempotent, no side effects on `&self`).
22497        //
22498        // Pins against a future silent detour that returned
22499        // `&Duration` (which would type-check but silently break every
22500        // downstream `Duration`-by-value consumer —
22501        // [`crate::render::require_positive_canonical_bounded_duration`]'s
22502        // first parameter is `Duration`, and `&Duration` would fold to
22503        // a detached copy at the call site with a `*` deref the sibling
22504        // accessors don't need), an accidental `.window + Duration::ZERO`
22505        // detour that returned a fresh copy through an arithmetic
22506        // no-op (breaking a future `const fn` regression), or a
22507        // one-arm-only accessor that returned a saturating value on
22508        // some sentinel input (breaking the pass-through invariant the
22509        // sibling required-scalar accessors carry).
22510        for window in [
22511            Duration::from_millis(1),
22512            POLICY_BREAKER_WINDOW_MAX,
22513            Duration::ZERO,
22514            Duration::from_secs(86_400),
22515        ] {
22516            let cb = CircuitBreaker {
22517                max_failures: 5,
22518                window,
22519            };
22520            let first = cb.window();
22521            let second = cb.window();
22522            assert_eq!(
22523                first, second,
22524                "CircuitBreaker::window must be idempotent — two \
22525                 successive calls on the same &self must return the \
22526                 same Duration",
22527            );
22528            assert_eq!(
22529                first, window,
22530                "CircuitBreaker::window must return :politicas \
22531                 :circuit-breaker :window verbatim by copy — \
22532                 got {first:?}, expected {window:?}",
22533            );
22534        }
22535    }
22536
22537    #[test]
22538    fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
22539        // Apex-identity pair-invariant pin composing both substrate-
22540        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
22541        // and [`WitContract::destination`] — at the emit-side call shape
22542        // every per-`(:de, :para)` CNP L4 port reader now takes. The
22543        // invariant, evaluated per-edge:
22544        //
22545        //   spec.port_for_destination(c.destination()) == expected_port
22546        //
22547        // where `expected_port` is `entrada.port` when
22548        // `c.destination() == entrada.destination()` and
22549        // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
22550        // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
22551        // pin on the per-`:entrada` axis — that pin encodes the apex
22552        // ingress L4 identity via `entrada.destination()`; this pin
22553        // encodes the per-edge L4 identity via `c.destination()`, and
22554        // both compose on the same substrate-primitive resolver so a
22555        // future refactor that silently split either accessor's apex
22556        // behavior surfaces at caixa-core build time.
22557        let mut spec = three_member_spec();
22558        if let Some(e) = spec.entrada.as_mut() {
22559            e.para = "cart".into();
22560            e.port = 8443;
22561        }
22562        let apex_contract = WitContract {
22563            de: "checkout".into(),
22564            para: "cart".into(),
22565            wit: "wasi:http/proxy".into(),
22566            endpoint: Some("/hello".into()),
22567            subject: None,
22568            slot: None,
22569        };
22570        assert_eq!(
22571            spec.port_for_destination(apex_contract.destination()),
22572            8443,
22573            "`spec.port_for_destination(c.destination())` must equal \
22574             `entrada.port` when the contract callee names the ingress \
22575             apex — the CNP per-edge L4 port and the HTTPRoute apex \
22576             backendRef port share this substrate-primitive resolver.",
22577        );
22578        let non_apex_contract = WitContract {
22579            de: "cart".into(),
22580            para: "payment".into(),
22581            wit: "wasi:http/proxy".into(),
22582            endpoint: Some("/charge".into()),
22583            subject: None,
22584            slot: None,
22585        };
22586        assert_eq!(
22587            spec.port_for_destination(non_apex_contract.destination()),
22588            DEFAULT_SERVICO_PORT,
22589            "`spec.port_for_destination(c.destination())` must fall back \
22590             to the substrate-canonical port floor when the contract \
22591             callee is not the ingress apex — the resolver's non-apex \
22592             arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
22593        );
22594    }
22595
22596    #[test]
22597    fn membro_key_consts_are_lower_camel_case_shape() {
22598        // Shape-pin: every `MEMBRO_KEY_*` const must be a
22599        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
22600        // `kebab-case` hyphens, no leading colon, no `PascalCase`
22601        // leading capital, no whitespace / dots) — the canonical shape
22602        // the `#[serde(rename_all = "camelCase")]` derive produces on
22603        // [`Membro`]. A future flip to a non-camelCase attribute at
22604        // the derive surfaces both here (this test fails on the
22605        // stale-constant shape) and at
22606        // `membro_serde_keys_match_lifted_membro_key_consts` (that test
22607        // fails on the mismatch between const and derive). Peer with
22608        // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
22609        // on the sibling `SupervisorSpec` top-level axis.
22610        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
22611            assert!(
22612                !key.is_empty(),
22613                "MEMBRO_KEY_* must be non-empty (got {key:?})"
22614            );
22615            let first = key.chars().next().unwrap();
22616            assert!(
22617                first.is_ascii_lowercase(),
22618                "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
22619                 (got {key:?}, leads with {first:?})",
22620            );
22621            assert!(
22622                key.chars().all(|c| c.is_ascii_alphanumeric()),
22623                "MEMBRO_KEY_* must be ASCII-alphanumeric only \
22624                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
22625            );
22626        }
22627    }
22628
22629    // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
22630
22631    #[test]
22632    fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
22633        // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
22634        // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
22635        // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
22636        // keys the `#[serde(rename_all = "camelCase")]` attribute on
22637        // [`WitContract`] emits for the required-triad. The three
22638        // sibling payload-arm keys already pin under
22639        // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
22640        // `STORE_FIELD_NAME` — pin all six alongside so a future
22641        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
22642        // verbatim-field-name flip at the derive attribute (any of which
22643        // would silently break every downstream JSON consumer that
22644        // reaches for one of the six via `Value::get(...)`) surfaces
22645        // here as a build-time test failure at `aplicacao.rs`, not as an
22646        // apply-time `.get(<stale-canonical-const>)` returning `None`
22647        // far from the derive-attr drift's commit. Peer with the sibling
22648        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
22649        // pin on the M3 `:membros` per-entry axis — same discipline the
22650        // `Membro` per-entry lift established, extended here to the
22651        // sibling M3 `WitContract` per-`:contratos` entry axis, the last
22652        // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
22653        // axis on the Aplicacao surface without a lifted serde-key peer.
22654        let c = WitContract {
22655            de: "cart".into(),
22656            para: "catalog".into(),
22657            wit: "wasi:http/proxy".into(),
22658            endpoint: Some("/lookup".into()),
22659            subject: None,
22660            slot: None,
22661        };
22662        let json = serde_json::to_string(&c).unwrap();
22663        for key in [
22664            crate::CONTRATO_KEY_DE,
22665            crate::CONTRATO_KEY_PARA,
22666            crate::CONTRATO_KEY_WIT,
22667            WitTarget::HTTP_FIELD_NAME,
22668        ] {
22669            let quoted = format!("\"{key}\"");
22670            assert!(
22671                json.contains(&quoted),
22672                "serialized WitContract must carry the lifted \
22673                 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
22674                 {quoted} verbatim in the JSON emission (got: {json})",
22675            );
22676        }
22677
22678        // Pin the two remaining payload-arm keys by round-tripping a
22679        // `WitContract` under each payload-shape (pub-sub, store) — the
22680        // required-triad appears on every emission but the payload arms
22681        // only surface when their `Option<String>` field is `Some`.
22682        let pubsub = WitContract {
22683            de: "cart".into(),
22684            para: "events".into(),
22685            wit: "nats:pub-sub".into(),
22686            endpoint: None,
22687            subject: Some("orders.placed".into()),
22688            slot: None,
22689        };
22690        let pubsub_json = serde_json::to_string(&pubsub).unwrap();
22691        let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
22692        assert!(
22693            pubsub_json.contains(&pubsub_quoted),
22694            "serialized pub-sub WitContract must carry the lifted \
22695             WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
22696             verbatim in the JSON emission (got: {pubsub_json})",
22697        );
22698        let store = WitContract {
22699            de: "cart".into(),
22700            para: "sessions".into(),
22701            wit: "wasi:keyvalue/store".into(),
22702            endpoint: None,
22703            subject: None,
22704            slot: Some("cart/$id".into()),
22705        };
22706        let store_json = serde_json::to_string(&store).unwrap();
22707        let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
22708        assert!(
22709            store_json.contains(&store_quoted),
22710            "serialized store WitContract must carry the lifted \
22711             WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
22712             verbatim in the JSON emission (got: {store_json})",
22713        );
22714    }
22715
22716    #[test]
22717    fn contrato_key_consts_are_pairwise_distinct() {
22718        // Cross-axis drift-detection pin: a future collapse of the six
22719        // canonical [`WitContract`] per-entry byte-strings onto the same
22720        // value (e.g. an accidental copy-paste flip of
22721        // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
22722        // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
22723        // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
22724        // every downstream probe on one axis onto the sibling axis's
22725        // overlay entry and pass every propagation-probe test that
22726        // expected only the stale axis's value. Peer of the sibling
22727        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
22728        // widened here to the six-way axis the `WitContract`
22729        // required-triad + `WitTarget` payload-triad jointly cover.
22730        let all = [
22731            crate::CONTRATO_KEY_DE,
22732            crate::CONTRATO_KEY_PARA,
22733            crate::CONTRATO_KEY_WIT,
22734            WitTarget::HTTP_FIELD_NAME,
22735            WitTarget::PUBSUB_FIELD_NAME,
22736            WitTarget::STORE_FIELD_NAME,
22737        ];
22738        for (i, a) in all.iter().enumerate() {
22739            for b in all.iter().skip(i + 1) {
22740                assert_ne!(
22741                    a, b,
22742                    "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
22743                     must be pairwise-distinct canonical byte-sequences \
22744                     — got `{a}` == `{b}`",
22745                );
22746            }
22747        }
22748    }
22749
22750    #[test]
22751    fn contrato_key_consts_are_lower_camel_case_shape() {
22752        // Shape-pin: every `CONTRATO_KEY_*` (and every peer
22753        // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
22754        // byte-sequence (no `snake_case` underscores, no `kebab-case`
22755        // hyphens, no leading colon, no `PascalCase` leading capital, no
22756        // whitespace / dots) — the canonical shape the
22757        // `#[serde(rename_all = "camelCase")]` derive produces on
22758        // [`WitContract`]. A future flip to a non-camelCase attribute at
22759        // the derive surfaces both here (this test fails on the
22760        // stale-constant shape) and at
22761        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
22762        // (that test fails on the mismatch between const and derive).
22763        // Peer with `membro_key_consts_are_lower_camel_case_shape`
22764        // (ce80ca0) on the sibling `Membro` per-entry axis.
22765        for key in [
22766            crate::CONTRATO_KEY_DE,
22767            crate::CONTRATO_KEY_PARA,
22768            crate::CONTRATO_KEY_WIT,
22769            WitTarget::HTTP_FIELD_NAME,
22770            WitTarget::PUBSUB_FIELD_NAME,
22771            WitTarget::STORE_FIELD_NAME,
22772        ] {
22773            assert!(
22774                !key.is_empty(),
22775                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
22776                 non-empty (got {key:?})"
22777            );
22778            let first = key.chars().next().unwrap();
22779            assert!(
22780                first.is_ascii_lowercase(),
22781                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
22782                 with an ASCII-lowercase byte (got {key:?}, leads with \
22783                 {first:?})",
22784            );
22785            assert!(
22786                key.chars().all(|c| c.is_ascii_alphanumeric()),
22787                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
22788                 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
22789                 whitespace (got {key:?})",
22790            );
22791        }
22792    }
22793
22794    // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
22795
22796    #[test]
22797    fn entrada_serde_keys_match_lifted_entrada_key_consts() {
22798        // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
22799        // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
22800        // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
22801        // name the exact camelCase JSON keys the
22802        // `#[serde(rename_all = "camelCase")]` attribute on
22803        // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
22804        // pin that each canonical byte-sequence appears verbatim in the
22805        // JSON — a future accidental `rename_all = "snake_case"` /
22806        // `"kebab-case"` / verbatim-field-name flip at the derive
22807        // attribute (any of which would silently break every downstream
22808        // JSON consumer that reaches for one of the four consts via
22809        // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
22810        // emitter's per-Aplicacao hostname/paths/port projection, the
22811        // future `app-operator` reconciler's per-Aplicacao ingress
22812        // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
22813        // materializer's admission-time cross-check) surfaces here as
22814        // a build-time test failure at `aplicacao.rs`, not as an
22815        // apply-time `.get(<stale-canonical-const>)` returning `None`
22816        // far from the derive-attr drift's commit. Peer with the
22817        // sibling
22818        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
22819        // (ca463a4) and
22820        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
22821        // pins on the M3 collection-slot atom axes — same discipline
22822        // both collection-slot lifts established, extended here to the
22823        // singleton `:entrada` mesh-slot atom axis, the last M3
22824        // typed-struct top-level `#[serde(rename_all = "camelCase")]`
22825        // axis on the Aplicacao surface without a lifted serde-key
22826        // peer.
22827        let e = Entrada {
22828            host: "checkout.quero.cloud".into(),
22829            para: "cart".into(),
22830            paths: vec!["/cart".into()],
22831            port: 8080,
22832        };
22833        let json = serde_json::to_string(&e).unwrap();
22834        for key in [
22835            crate::ENTRADA_KEY_HOST,
22836            crate::ENTRADA_KEY_PARA,
22837            crate::ENTRADA_KEY_PATHS,
22838            crate::ENTRADA_KEY_PORT,
22839        ] {
22840            let quoted = format!("\"{key}\"");
22841            assert!(
22842                json.contains(&quoted),
22843                "serialized Entrada must carry the lifted ENTRADA_KEY_* \
22844                 byte-sequence {quoted} verbatim in the JSON emission \
22845                 (got: {json})",
22846            );
22847        }
22848    }
22849
22850    #[test]
22851    fn entrada_key_consts_are_pairwise_distinct() {
22852        // Cross-axis drift-detection pin: a future collapse of the four
22853        // canonical [`Entrada`] singleton byte-strings onto the same
22854        // value (e.g. an accidental copy-paste flip of
22855        // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
22856        // silently reroute every downstream probe on one axis onto the
22857        // sibling axis's overlay entry and pass every propagation-probe
22858        // test that expected only the stale axis's value — the
22859        // Gateway/HTTPRoute emitter would read the hostname string
22860        // where the destination-Servico name was expected (or vice
22861        // versa), the admission-webhook cross-check would compare the
22862        // wrong pair of values, and the resulting Gateway resource
22863        // would either be admitted with garbage or rejected at the
22864        // controller far from the rebrand commit's source. Peer of the
22865        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
22866        // tetrad (40cc4e5), the two-way distinct pin on the
22867        // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
22868        // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
22869        // triad (ca463a4).
22870        let all = [
22871            crate::ENTRADA_KEY_HOST,
22872            crate::ENTRADA_KEY_PARA,
22873            crate::ENTRADA_KEY_PATHS,
22874            crate::ENTRADA_KEY_PORT,
22875        ];
22876        for (i, a) in all.iter().enumerate() {
22877            for b in all.iter().skip(i + 1) {
22878                assert_ne!(
22879                    a, b,
22880                    "ENTRADA_KEY_* consts must be pairwise-distinct \
22881                     canonical byte-sequences — got `{a}` == `{b}`",
22882                );
22883            }
22884        }
22885    }
22886
22887    #[test]
22888    fn entrada_key_consts_are_lower_camel_case_shape() {
22889        // Shape-pin: every `ENTRADA_KEY_*` const must be a
22890        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
22891        // `kebab-case` hyphens, no leading colon, no `PascalCase`
22892        // leading capital, no whitespace / dots) — the canonical shape
22893        // the `#[serde(rename_all = "camelCase")]` derive produces on
22894        // [`Entrada`]. A future flip to a non-camelCase attribute at
22895        // the derive surfaces both here (this test fails on the
22896        // stale-constant shape) and at
22897        // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
22898        // test fails on the mismatch between const and derive). Peer
22899        // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
22900        // and `contrato_key_consts_are_lower_camel_case_shape`
22901        // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
22902        // entry axes.
22903        for key in [
22904            crate::ENTRADA_KEY_HOST,
22905            crate::ENTRADA_KEY_PARA,
22906            crate::ENTRADA_KEY_PATHS,
22907            crate::ENTRADA_KEY_PORT,
22908        ] {
22909            assert!(
22910                !key.is_empty(),
22911                "ENTRADA_KEY_* must be non-empty (got {key:?})"
22912            );
22913            let first = key.chars().next().unwrap();
22914            assert!(
22915                first.is_ascii_lowercase(),
22916                "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
22917                 (got {key:?}, leads with {first:?})",
22918            );
22919            assert!(
22920                key.chars().all(|c| c.is_ascii_alphanumeric()),
22921                "ENTRADA_KEY_* must be ASCII-alphanumeric only \
22922                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
22923            );
22924        }
22925    }
22926
22927    // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
22928
22929    #[test]
22930    fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
22931        // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
22932        // ([`crate::POLITICAS_KEY_TIMEOUT`] /
22933        // [`crate::POLITICAS_KEY_RETRIES`] /
22934        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
22935        // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
22936        // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
22937        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
22938        // on [`MeshPolicy`] emits. Three of the five axes
22939        // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
22940        // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
22941        // camelCase transforms — the derive-attribute is load-bearing
22942        // on those, unlike the sibling `Entrada` / `Membro` /
22943        // `WitContract` structs whose fields are all lowercase-single-
22944        // word and where the derive is a no-op on every axis.
22945        // Serialize a fully-populated [`MeshPolicy`] (every axis
22946        // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
22947        // on none of the five slots) and pin that each canonical
22948        // byte-sequence appears verbatim in the JSON — a future
22949        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
22950        // verbatim-field-name flip at the derive attribute (any of
22951        // which would silently break every downstream JSON consumer
22952        // that reaches for one of the five consts via
22953        // `Value::get(...)` — the future M4 per-edge `:politicas`
22954        // overlay projection onto Cilium `L7Rules` and Gateway API
22955        // `HTTPRoute` backend timeouts, the future
22956        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
22957        // admission-time mesh-policy cross-check, the future
22958        // `feira lint` per-`:politicas` bound-check gate) surfaces here
22959        // as a build-time test failure at `aplicacao.rs`, not as an
22960        // apply-time `.get(<stale-canonical-const>)` returning `None`
22961        // far from the derive-attr drift's commit. Peer with the
22962        // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
22963        // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
22964        // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
22965        // (ce80ca0) pins on the M3 collection-slot / singleton-slot
22966        // atom axes — same discipline every M3 sibling lift
22967        // established, extended here to the singleton `:politicas`
22968        // mesh-slot atom axis, closing the last M3 typed-struct
22969        // top-level `#[serde(rename_all = "camelCase")]` axis on the
22970        // Aplicacao surface without a lifted serde-key peer.
22971        let p = MeshPolicy {
22972            timeout: Some(Duration::from_secs(30)),
22973            retries: Some(3),
22974            circuit_breaker: Some(CircuitBreaker {
22975                max_failures: 5,
22976                window: Duration::from_secs(60),
22977            }),
22978            mtls_required: Some(true),
22979            rate_limit: Some(RateLimit {
22980                rate: 100,
22981                window: Duration::from_secs(1),
22982            }),
22983        };
22984        let json = serde_json::to_string(&p).unwrap();
22985        for key in [
22986            crate::POLITICAS_KEY_TIMEOUT,
22987            crate::POLITICAS_KEY_RETRIES,
22988            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
22989            crate::POLITICAS_KEY_MTLS_REQUIRED,
22990            crate::POLITICAS_KEY_RATE_LIMIT,
22991        ] {
22992            let quoted = format!("\"{key}\"");
22993            assert!(
22994                json.contains(&quoted),
22995                "serialized MeshPolicy must carry the lifted \
22996                 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
22997                 JSON emission (got: {json})",
22998            );
22999        }
23000    }
23001
23002    #[test]
23003    fn politicas_key_consts_are_pairwise_distinct() {
23004        // Cross-axis drift-detection pin: a future collapse of the five
23005        // canonical [`MeshPolicy`] singleton byte-strings onto the same
23006        // value (e.g. an accidental copy-paste flip of
23007        // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
23008        // would silently reroute every downstream probe on one axis
23009        // onto the sibling axis's overlay entry and pass every
23010        // propagation-probe test that expected only the stale axis's
23011        // value — the M4 per-edge `:politicas` overlay projection would
23012        // read the retry-count string where the timeout duration was
23013        // expected (or vice versa), the CR materializer's admission
23014        // cross-check would compare the wrong pair of values, and the
23015        // resulting mesh reconciler would either bind the wrong axis
23016        // or reject the resource at reconcile far from the rebrand
23017        // commit's source. Peer of the sibling four-way distinct pin
23018        // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
23019        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
23020        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
23021        // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
23022        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
23023        let all = [
23024            crate::POLITICAS_KEY_TIMEOUT,
23025            crate::POLITICAS_KEY_RETRIES,
23026            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
23027            crate::POLITICAS_KEY_MTLS_REQUIRED,
23028            crate::POLITICAS_KEY_RATE_LIMIT,
23029        ];
23030        for (i, a) in all.iter().enumerate() {
23031            for b in all.iter().skip(i + 1) {
23032                assert_ne!(
23033                    a, b,
23034                    "POLITICAS_KEY_* consts must be pairwise-distinct \
23035                     canonical byte-sequences — got `{a}` == `{b}`",
23036                );
23037            }
23038        }
23039    }
23040
23041    #[test]
23042    fn politicas_key_consts_are_lower_camel_case_shape() {
23043        // Shape-pin: every `POLITICAS_KEY_*` const must be a
23044        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
23045        // `kebab-case` hyphens, no leading colon, no `PascalCase`
23046        // leading capital, no whitespace / dots) — the canonical shape
23047        // the `#[serde(rename_all = "camelCase")]` derive produces on
23048        // [`MeshPolicy`]. A future flip to a non-camelCase attribute
23049        // at the derive surfaces both here (this test fails on the
23050        // stale-constant shape) and at
23051        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
23052        // (that test fails on the mismatch between const and derive).
23053        // Peer with `entrada_key_consts_are_lower_camel_case_shape`
23054        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
23055        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
23056        // (ca463a4) on the sibling M3 typed-struct axes.
23057        for key in [
23058            crate::POLITICAS_KEY_TIMEOUT,
23059            crate::POLITICAS_KEY_RETRIES,
23060            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
23061            crate::POLITICAS_KEY_MTLS_REQUIRED,
23062            crate::POLITICAS_KEY_RATE_LIMIT,
23063        ] {
23064            assert!(
23065                !key.is_empty(),
23066                "POLITICAS_KEY_* must be non-empty (got {key:?})"
23067            );
23068            let first = key.chars().next().unwrap();
23069            assert!(
23070                first.is_ascii_lowercase(),
23071                "POLITICAS_KEY_* must lead with an ASCII-lowercase \
23072                 byte (got {key:?}, leads with {first:?})",
23073            );
23074            assert!(
23075                key.chars().all(|c| c.is_ascii_alphanumeric()),
23076                "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
23077                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
23078            );
23079        }
23080    }
23081
23082    // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
23083
23084    #[test]
23085    fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
23086        // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
23087        // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
23088        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
23089        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
23090        // [`CircuitBreaker`] emits inside the
23091        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
23092        // two axes (`max_failures` → `maxFailures`) is a non-trivial
23093        // camelCase transform — the derive-attribute is load-bearing on
23094        // that axis, unlike the sibling `window` field where the derive
23095        // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
23096        // pin that each canonical byte-sequence appears verbatim in the
23097        // JSON — a future accidental `rename_all = "snake_case"` /
23098        // `"kebab-case"` / verbatim-field-name flip at the derive
23099        // attribute (any of which would silently break every downstream
23100        // JSON consumer that reaches for one of the two consts via
23101        // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
23102        // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
23103        // per-edge `:politicas` overlay projection onto the mesh's
23104        // per-backend consecutive-failure-counter tripping threshold, the
23105        // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
23106        // admission-time breaker cross-check, the future `feira lint`
23107        // per-`:politicas :circuit-breaker` bound-check gate) surfaces
23108        // here as a build-time test failure at `aplicacao.rs`, not as an
23109        // apply-time `.get(<stale-canonical-const>)` returning `None`
23110        // far from the derive-attr drift's commit. Peer with the sibling
23111        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
23112        // (b55cca7) parent-axis pin — that test pins the outer
23113        // sub-block key the derive on [`MeshPolicy`] emits, this test
23114        // pins the inner keys the derive on the payload type emits, so
23115        // the two together lock the whole [`MeshPolicy`] breaker-tuning
23116        // shape end-to-end at build time.
23117        let cb = CircuitBreaker {
23118            max_failures: 5,
23119            window: Duration::from_secs(60),
23120        };
23121        let json = serde_json::to_string(&cb).unwrap();
23122        for key in [
23123            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
23124            crate::CIRCUIT_BREAKER_KEY_WINDOW,
23125        ] {
23126            let quoted = format!("\"{key}\"");
23127            assert!(
23128                json.contains(&quoted),
23129                "serialized CircuitBreaker must carry the lifted \
23130                 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
23131                 in the JSON emission (got: {json})",
23132            );
23133        }
23134    }
23135
23136    #[test]
23137    fn circuit_breaker_key_consts_are_pairwise_distinct() {
23138        // Cross-axis drift-detection pin: a future collapse of the two
23139        // canonical [`CircuitBreaker`] sub-block byte-strings onto the
23140        // same value (e.g. an accidental copy-paste flip of
23141        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
23142        // `"maxFailures"`) would silently reroute every downstream
23143        // probe on one axis onto the sibling axis's overlay entry and
23144        // pass every propagation-probe test that expected only the
23145        // stale axis's value — the M4 per-edge `:politicas` overlay
23146        // projection would read the failure-count where the window
23147        // duration was expected (or vice versa), the CR materializer's
23148        // admission cross-check would compare the wrong pair of values,
23149        // and the resulting mesh reconciler would either bind the wrong
23150        // axis or reject the resource at reconcile far from the rebrand
23151        // commit's source. Peer of the sibling five-way distinct pin on
23152        // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
23153        // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
23154        // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
23155        // six-way distinct pin on the `CONTRATO_KEY_*` triad +
23156        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
23157        let all = [
23158            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
23159            crate::CIRCUIT_BREAKER_KEY_WINDOW,
23160        ];
23161        for (i, a) in all.iter().enumerate() {
23162            for b in all.iter().skip(i + 1) {
23163                assert_ne!(
23164                    a, b,
23165                    "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
23166                     canonical byte-sequences — got `{a}` == `{b}`",
23167                );
23168            }
23169        }
23170    }
23171
23172    #[test]
23173    fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
23174        // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
23175        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
23176        // `kebab-case` hyphens, no leading colon, no `PascalCase`
23177        // leading capital, no whitespace / dots) — the canonical shape
23178        // the `#[serde(rename_all = "camelCase")]` derive produces on
23179        // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
23180        // at the derive surfaces both here (this test fails on the
23181        // stale-constant shape) and at
23182        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
23183        // (that test fails on the mismatch between const and derive).
23184        // Peer with `politicas_key_consts_are_lower_camel_case_shape`
23185        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
23186        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
23187        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
23188        // (ca463a4) on the sibling M3 typed-struct axes.
23189        for key in [
23190            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
23191            crate::CIRCUIT_BREAKER_KEY_WINDOW,
23192        ] {
23193            assert!(
23194                !key.is_empty(),
23195                "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
23196            );
23197            let first = key.chars().next().unwrap();
23198            assert!(
23199                first.is_ascii_lowercase(),
23200                "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
23201                 byte (got {key:?}, leads with {first:?})",
23202            );
23203            assert!(
23204                key.chars().all(|c| c.is_ascii_alphanumeric()),
23205                "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
23206                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
23207            );
23208        }
23209    }
23210
23211    // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
23212
23213    #[test]
23214    fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
23215        // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
23216        // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
23217        // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
23218        // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
23219        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
23220        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
23221        // [`Placement`] emits. One of the four axes (`shard_key` →
23222        // `shardKey`) is a non-trivial camelCase transform — the
23223        // derive-attribute is load-bearing on that axis, unlike the
23224        // sibling `estrategia` / `clusters` / `affinity` axes whose
23225        // source-side field names carry no `_` and where the derive is a
23226        // no-op. Serialize a fully-populated [`Placement`] (both
23227        // `Option`-carrying axes `Some(_)` so
23228        // `skip_serializing_if = "Option::is_none"` fires on neither of
23229        // the two optional slots) and pin that each canonical
23230        // byte-sequence appears verbatim in the JSON — a future
23231        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
23232        // verbatim-field-name flip at the derive attribute (any of which
23233        // would silently break every downstream consumer that reaches
23234        // for one of the four consts via
23235        // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
23236        // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
23237        // aggregator's per-cluster fanout filter keying off
23238        // `placement.clusters`, the M3 shard-pool dispatch materializer
23239        // keying off `placement.shardKey`, the M3 Adaptive compression
23240        // pass weighting off `placement.affinity`, every downstream
23241        // dispatcher branching on `placement.estrategia`, the future
23242        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
23243        // admission-time placement cross-check, the future `feira lint`
23244        // per-`:placement` bound-check gate) surfaces here as a
23245        // build-time test failure at `aplicacao.rs`, not as an
23246        // apply-time `.get(<stale-canonical-const>)` returning `None`
23247        // far from the derive-attr drift's commit. Peer with the sibling
23248        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
23249        // (b55cca7),
23250        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
23251        // (468e959),
23252        // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
23253        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
23254        // (ca463a4), and
23255        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
23256        // pins on the M3 collection-slot / singleton-slot atom axes —
23257        // closes the last M3 typed-struct top-level
23258        // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
23259        // surface without a drift-detection pin.
23260        let p = Placement {
23261            estrategia: PlacementStrategy::Sharded,
23262            clusters: vec!["rio".into(), "mar".into()],
23263            affinity: Some("data-locality".into()),
23264            shard_key: Some("$tenantId".into()),
23265        };
23266        let json = serde_json::to_string(&p).unwrap();
23267        for key in [
23268            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
23269            crate::M3_PLACEMENT_KEY_CLUSTERS,
23270            crate::M3_PLACEMENT_KEY_AFFINITY,
23271            crate::M3_PLACEMENT_KEY_SHARD_KEY,
23272        ] {
23273            let quoted = format!("\"{key}\"");
23274            assert!(
23275                json.contains(&quoted),
23276                "serialized Placement must carry the lifted \
23277                 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
23278                 the JSON emission (got: {json})",
23279            );
23280        }
23281    }
23282
23283    #[test]
23284    fn m3_placement_key_consts_are_pairwise_distinct() {
23285        // Cross-axis drift-detection pin: a future collapse of the four
23286        // canonical [`Placement`] sub-block byte-strings onto the same
23287        // value (e.g. an accidental copy-paste flip of
23288        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
23289        // `"affinity"`) would silently reroute every downstream probe on
23290        // one axis onto the sibling axis's overlay entry and pass every
23291        // propagation-probe test that expected only the stale axis's
23292        // value — the M3 shard-pool dispatch materializer would read the
23293        // affinity placement-hint where the shard-selection template was
23294        // expected (or vice versa), the M3 Adaptive compression pass's
23295        // cross-check would compare the wrong pair of values, and the
23296        // resulting placement engine would either bind the wrong axis or
23297        // reject the resource at reconcile far from the rebrand commit's
23298        // source. Peer of the sibling two-way distinct pin on the
23299        // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
23300        // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
23301        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
23302        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
23303        // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
23304        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
23305        let all = [
23306            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
23307            crate::M3_PLACEMENT_KEY_CLUSTERS,
23308            crate::M3_PLACEMENT_KEY_AFFINITY,
23309            crate::M3_PLACEMENT_KEY_SHARD_KEY,
23310        ];
23311        for (i, a) in all.iter().enumerate() {
23312            for b in all.iter().skip(i + 1) {
23313                assert_ne!(
23314                    a, b,
23315                    "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
23316                     canonical byte-sequences — got `{a}` == `{b}`",
23317                );
23318            }
23319        }
23320    }
23321
23322    #[test]
23323    fn m3_placement_key_consts_are_lower_camel_case_shape() {
23324        // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
23325        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
23326        // `kebab-case` hyphens, no leading colon, no `PascalCase`
23327        // leading capital, no whitespace / dots) — the canonical shape
23328        // the `#[serde(rename_all = "camelCase")]` derive produces on
23329        // [`Placement`]. A future flip to a non-camelCase attribute at
23330        // the derive surfaces both here (this test fails on the stale-
23331        // constant shape) and at
23332        // `placement_serde_keys_match_lifted_m3_placement_key_consts`
23333        // (that test fails on the mismatch between const and derive).
23334        // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
23335        // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
23336        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
23337        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
23338        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
23339        // (ca463a4) on the sibling M3 typed-struct axes.
23340        for key in [
23341            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
23342            crate::M3_PLACEMENT_KEY_CLUSTERS,
23343            crate::M3_PLACEMENT_KEY_AFFINITY,
23344            crate::M3_PLACEMENT_KEY_SHARD_KEY,
23345        ] {
23346            assert!(
23347                !key.is_empty(),
23348                "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
23349            );
23350            let first = key.chars().next().unwrap();
23351            assert!(
23352                first.is_ascii_lowercase(),
23353                "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
23354                 byte (got {key:?}, leads with {first:?})",
23355            );
23356            assert!(
23357                key.chars().all(|c| c.is_ascii_alphanumeric()),
23358                "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
23359                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
23360            );
23361        }
23362    }
23363
23364    // ── AplicacaoSpec::port_for_destination — the substrate-canonical
23365    //    destination-facing L4 port resolver every per-Aplicacao renderer
23366    //    reaching for a per-destination Servico TCP port axis routes
23367    //    through. The four pin tests below fix the four-way accept-set
23368    //    the resolver must always honor: (:entrada-para-matches,
23369    //    :entrada-para-mismatches, :entrada-none-so-fallback,
23370    //    :entrada-port-non-default-honored) — drift on any arm surfaces
23371    //    at caixa-core build time rather than at cluster-apply time.
23372
23373    #[test]
23374    fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
23375        // The typed `:entrada` block's `:para "cart"` matches the
23376        // queried destination, so the resolver returns the author-
23377        // declared `:port` scalar verbatim — the canonical "the
23378        // destination Servico IS the ingress apex, honor the typed
23379        // listener port" arm of the port-resolution dispatch.
23380        let mut spec = three_member_spec();
23381        if let Some(e) = spec.entrada.as_mut() {
23382            e.para = "cart".into();
23383            e.port = 9090;
23384        }
23385        assert_eq!(
23386            spec.port_for_destination("cart"),
23387            9090,
23388            "port_for_destination(entrada.para) must return entrada.port \
23389             verbatim, not the DEFAULT_SERVICO_PORT fallback"
23390        );
23391    }
23392
23393    #[test]
23394    fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
23395        // The typed `:entrada` block names `:para "cart"`, but the
23396        // queried destination is `"payment"` — a Servico that
23397        // participates in the mesh graph but is not the ingress apex.
23398        // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
23399        // canonical port floor, closing the "non-apex destination reads
23400        // the substrate default" arm. Same fixture the peer
23401        // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
23402        // pin at caixa-mesh exercises through the CNP emit-side path;
23403        // this pin exercises the shared underlying resolver directly.
23404        let spec = three_member_spec();
23405        assert_eq!(
23406            spec.port_for_destination("payment"),
23407            DEFAULT_SERVICO_PORT,
23408            "port_for_destination(non-apex-destination) must route \
23409             through the lifted DEFAULT_SERVICO_PORT canonical port floor"
23410        );
23411    }
23412
23413    #[test]
23414    fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
23415        // Internal-only Aplicacao — no `:entrada` block declared. Every
23416        // per-destination port query falls back to the lifted
23417        // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
23418        // the Aplicacao surface admits `:entrada None` (internal mesh
23419        // with no external gateway); every downstream renderer's per-
23420        // destination port axis must still resolve to a well-defined
23421        // scalar even without an ingress apex.
23422        let mut spec = three_member_spec();
23423        spec.entrada = None;
23424        assert_eq!(
23425            spec.port_for_destination("cart"),
23426            DEFAULT_SERVICO_PORT,
23427            "port_for_destination on an internal-only Aplicacao must \
23428             fall back to the lifted DEFAULT_SERVICO_PORT floor for \
23429             every destination"
23430        );
23431        assert_eq!(
23432            spec.port_for_destination("payment"),
23433            DEFAULT_SERVICO_PORT,
23434            "port_for_destination on an internal-only Aplicacao must \
23435             fall back uniformly across every destination — the fallback \
23436             is not entrada-shape-conditional"
23437        );
23438    }
23439
23440    #[test]
23441    fn port_for_destination_honors_non_default_entrada_port_verbatim() {
23442        // Structural pin against a hypothetical future refactor that
23443        // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
23444        // the resolver (a "normalize to the default when the author's
23445        // port matches the substrate default" collapse) — that would
23446        // break renderer sites that carry meaning on the emitted port
23447        // value beyond bare equality (a future per-cluster listener-
23448        // audit that keys off the author-declared port, not the
23449        // resolved-with-fallback port). Pin that a non-default
23450        // entrada.port is returned verbatim so drift here surfaces at
23451        // caixa-core build time.
23452        let mut spec = three_member_spec();
23453        if let Some(e) = spec.entrada.as_mut() {
23454            e.para = "cart".into();
23455            e.port = 8443;
23456        }
23457        assert_ne!(
23458            8443, DEFAULT_SERVICO_PORT,
23459            "test fixture must probe a port distinct from \
23460             DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
23461        );
23462        assert_eq!(
23463            spec.port_for_destination("cart"),
23464            8443,
23465            "port_for_destination(entrada.para) must return entrada.port \
23466             verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
23467        );
23468    }
23469
23470    #[test]
23471    fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
23472        // Apex-identity pair-invariant pin composing both substrate-
23473        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
23474        // and [`Entrada::destination`] — at the emit-side call shape
23475        // every per-Aplicacao renderer's ingress-apex L4 port reader
23476        // now takes. The invariant:
23477        //
23478        //   spec.port_for_destination(entrada.destination()) == entrada.port
23479        //
23480        // holds by construction under today's single-destination
23481        // `:entrada` slot (`destination()` returns `entrada.para`, and
23482        // the resolver's apex arm matches `para == destination` and
23483        // returns `entrada.port`), and every downstream consumer that
23484        // composes the two accessors at the ingress apex — the
23485        // `caixa_mesh::gateway_routes` HTTPRoute per-rule
23486        // `backendRefs[0].port` emit-site path, the peer future M4 CR
23487        // materializer's admission-webhook that promotes the scalar to
23488        // a per-CR override overlay, every future per-Aplicacao snapshot
23489        // renderer's apex-facing L4 port reader — reaches through the
23490        // same composition. Pin the identity across four permutations
23491        // (`:para` × `:port` including a non-default port to exercise
23492        // the honor-verbatim arm and a non-cart `:para` to exercise
23493        // destination-agnostic identity) so a future refactor that
23494        // silently split either accessor's apex behavior surfaces at
23495        // caixa-core build time — a subtle `destination()` renaming
23496        // that returned `entrada.host.as_str()` instead of
23497        // `entrada.para.as_str()` would blow this pin loudly, closing
23498        // the last quiet failure mode the two lifts admit in composition.
23499        //
23500        // Peer discipline with the sibling caixa-mesh cross-crate pin
23501        // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
23502        // on the two-renderer pair-invariant axis; this pin encodes the
23503        // same two-consumer coherence rule at the substrate-primitive
23504        // level so the invariant survives even if every renderer is
23505        // deleted.
23506        for (para, port) in [
23507            ("cart", DEFAULT_SERVICO_PORT),
23508            ("cart", 8443u16),
23509            ("payment", 9090u16),
23510            ("catalog", 443u16),
23511        ] {
23512            let mut spec = three_member_spec();
23513            if let Some(e) = spec.entrada.as_mut() {
23514                e.para = para.into();
23515                e.port = port;
23516            }
23517            let expected_port = spec
23518                .entrada
23519                .as_ref()
23520                .expect("three_member_spec carries a typed `:entrada` block")
23521                .port;
23522            let composed_port = {
23523                let entrada = spec.entrada.as_ref().expect("entrada present");
23524                spec.port_for_destination(entrada.destination())
23525            };
23526            assert_eq!(
23527                composed_port, expected_port,
23528                "`spec.port_for_destination(entrada.destination())` must \
23529                 equal `entrada.port` under today's single-destination \
23530                 `:entrada` slot — this is the apex-identity contract \
23531                 every downstream ingress-apex L4 port reader relies on. \
23532                 Input :entrada :para: {para:?}, :entrada :port: {port}"
23533            );
23534        }
23535    }
23536
23537    #[test]
23538    fn port_for_destination_apex_arm_routes_through_destination_accessor() {
23539        // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
23540        // per-`:entrada` apex-arm membership probe must key off
23541        // [`Entrada::destination`], not the raw `.para` field access.
23542        // Structurally: setting ONLY the `:entrada :para` field to a
23543        // fresh non-cart destination on an otherwise-well-formed
23544        // Aplicacao must (1) leave `e.destination()` byte-equal to
23545        // `e.para.as_str()` (the accessor is byte-projective by
23546        // definition), and (2) cause the resolver's apex arm to fire
23547        // and return `entrada.port` at exactly that new destination
23548        // while every other destination string falls through to
23549        // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
23550        // membership check. Pins against a future silent detour that
23551        // (a) re-derived the apex-arm membership probe off
23552        // `e.para == destination` in `port_for_destination` instead of
23553        // `e.destination() == destination`, silently disagreeing with
23554        // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
23555        // consumers (`entrada.destination()` at
23556        // caixa-mesh/src/lib.rs:3173, `c.destination()` at
23557        // caixa-mesh/src/lib.rs:2739) that already reach through the
23558        // accessor, (b) accessor-side introduced a per-tenant alias
23559        // arm the caller was unaware of, silently rewriting an
23560        // author-declared `:para "cart"` value to a canary-aliased
23561        // form — the raw-field-access resolver would fall through to
23562        // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
23563        // while the peer emit-site consumers landed on the aliased
23564        // destination, splitting the ingress-apex L4 port at
23565        // cluster-apply time.
23566        //
23567        // Peer of the sibling
23568        // [`validate_membros_empty_gate_routes_through_nome_accessor`]
23569        // (d0de220) composition pin on the per-`:membros` refusal-arm
23570        // axis — same "the shape-gate predicate must route through the
23571        // substrate-primitive typed dispatch" discipline extended onto
23572        // the per-`:entrada` apex-arm membership-probe axis. Closes
23573        // the last unlifted `.para` production-code read site on
23574        // `Entrada` in `caixa-core` — after this converge every
23575        // `caixa-core` `.para` field access outside the accessor's own
23576        // body and outside the `WitContract` per-`:contratos` sibling
23577        // axis is either a test-side field-setter or a doc-comment
23578        // reference.
23579        for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
23580            let mut spec = three_member_spec();
23581            if let Some(e) = spec.entrada.as_mut() {
23582                e.para = para.into();
23583                e.port = port;
23584            }
23585            let e = spec
23586                .entrada
23587                .as_ref()
23588                .expect("three_member_spec carries a typed `:entrada` block");
23589            assert_eq!(
23590                e.destination(),
23591                e.para.as_str(),
23592                "Entrada::destination must byte-equal the .para field \
23593                 access — an accessor-side detour that no longer \
23594                 projects the raw field would silently split this \
23595                 drift-detection test from the port_for_destination \
23596                 apex-arm membership probe",
23597            );
23598            assert_eq!(
23599                spec.port_for_destination(para),
23600                port,
23601                "port_for_destination must key off the accessor-projected \
23602                 destination and return `entrada.port` on the apex arm — \
23603                 input :entrada :para: {para:?}, :entrada :port: {port}",
23604            );
23605            assert_eq!(
23606                spec.port_for_destination("ghost-destination-never-a-member"),
23607                DEFAULT_SERVICO_PORT,
23608                "port_for_destination must fall through to \
23609                 DEFAULT_SERVICO_PORT on a non-matching destination \
23610                 under the accessor-projected membership check — input \
23611                 :entrada :para: {para:?}, :entrada :port: {port}",
23612            );
23613        }
23614    }
23615
23616    #[test]
23617    fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
23618        // The canonical per-`:politicas :rate-limit` `:rate`
23619        // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
23620        // [`RateLimit::rate`] must return the `:politicas :rate-limit`
23621        // typed `u32` verbatim, byte-equal to the raw field access
23622        // across every representative value in the accept-set — `1` (the
23623        // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
23624        // the surrounding [`AplicacaoSpec::validate_politicas`] gate
23625        // carves out on the sibling `PolicyRateLimitZero` refusal),
23626        // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
23627        // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
23628        // `0` (a past-the-guard sentinel that pins the accessor doesn't
23629        // perform a silent bounds-collapse into `1` on the zero arm —
23630        // validate rejects zero but the accessor must ship the raw slot
23631        // verbatim so a validate-time gate regression surfaces at the
23632        // emit boundary rather than being silently absorbed), `u32::MAX`
23633        // (a past-the-guard sentinel that pins the accessor doesn't
23634        // perform a silent bounds-collapse through
23635        // `POLICY_RATE_LIMIT_MAX` at the return path).
23636        //
23637        // First sub-struct required-scalar accessor pin on the
23638        // `RateLimit` axis — sibling in shape to the peer
23639        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
23640        // required-`u32` accessor pin on the peer per-sub-struct
23641        // required-axis. Pins against a future silent detour that
23642        // re-derived the token capacity from a peer axis (an accidental
23643        // `self.window.as_secs() as u32` collapse that read the
23644        // rate-limit window duration as a token count), a `0 → 1`
23645        // cluster-default projection (which would silently absorb the
23646        // `PolicyRateLimitZero` refusal case at the accessor boundary),
23647        // or a bounds-collapsing accessor that clamped the return
23648        // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
23649        // gate owns the bounds; the accessor must ship the raw slot
23650        // verbatim).
23651        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
23652            let rl = RateLimit {
23653                rate,
23654                window: Duration::from_secs(1),
23655            };
23656            assert_eq!(
23657                rl.rate(),
23658                rate,
23659                "RateLimit::rate must return :politicas :rate-limit :rate \
23660                 verbatim (got {}, expected {rate})",
23661                rl.rate(),
23662            );
23663            assert_eq!(
23664                rl.rate(),
23665                rl.rate,
23666                "RateLimit::rate must byte-equal the raw .rate field \
23667                 access across every value in the u32 accept-set",
23668            );
23669        }
23670    }
23671
23672    #[test]
23673    fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
23674        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
23675        // `:rate-limit :rate` zero-floor arm must key off
23676        // [`RateLimit::rate`], not the raw `.rate` field access.
23677        // Structurally: a `RateLimit { rate: 0, window:
23678        // Duration::from_secs(1) }` embedded in a `:politicas
23679        // :rate-limit` slot must surface the `PolicyRateLimitZero`
23680        // refusal exactly, and a `RateLimit { rate: 1, window:
23681        // Duration::from_secs(1) }` (the lower boundary of the
23682        // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
23683        // The pair jointly pins the accessor + validate-gate composition:
23684        // any future silent detour that had the accessor return a fresh
23685        // `1` on the zero arm (a `.rate().max(1)` collapse) would
23686        // silently absorb the `PolicyRateLimitZero` refusal at the
23687        // accessor boundary and the validate gate would accept a
23688        // struct-literal `RateLimit { rate: 0, .. }` — the composition
23689        // pin catches that at caixa-core build time.
23690        //
23691        // Peer of the sibling per-`CircuitBreaker`
23692        // [`CircuitBreaker::max_failures`] (3a74062) /
23693        // [`CircuitBreaker::window`] (373957f) accessor-composition
23694        // pins on the peer required-scalar axes — same "the validate /
23695        // shape-gate predicate must route through the substrate-primitive
23696        // typed dispatch" discipline extended onto the peer
23697        // per-`RateLimit` required-`u32` composition axis.
23698        let mut spec = three_member_spec();
23699        spec.politicas = MeshPolicy {
23700            rate_limit: Some(RateLimit {
23701                rate: 0,
23702                window: Duration::from_secs(1),
23703            }),
23704            ..MeshPolicy::default()
23705        };
23706        assert!(
23707            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
23708            "validate_politicas must reject rate == 0 with \
23709             PolicyRateLimitZero — the accessor and the validate gate \
23710             must route through the same substrate-primitive typed \
23711             dispatch on the :rate zero-floor arm",
23712        );
23713        spec.politicas = MeshPolicy {
23714            rate_limit: Some(RateLimit {
23715                rate: 1,
23716                window: Duration::from_secs(1),
23717            }),
23718            ..MeshPolicy::default()
23719        };
23720        assert!(
23721            spec.validate().is_ok(),
23722            "validate_politicas must accept rate == 1 (the lower \
23723             boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
23724        );
23725    }
23726
23727    #[test]
23728    fn rate_limit_rate_projects_u32_by_copy() {
23729        // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
23730        // `u32` is `Copy` and the accessor must return by value, not by
23731        // reference. Peer of the sibling per-`CircuitBreaker`
23732        // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
23733        // peer required-scalar `:max-failures` axis, extended onto the
23734        // peer per-`RateLimit` required-`u32` copy-invariant shape —
23735        // the accessor's returned `u32` must outlive `&self` (multiple
23736        // calls must return equal values from a dropped-`&self` copy,
23737        // since the returned scalar carries no borrow), and calling the
23738        // accessor twice on the same RateLimit must yield the same
23739        // `u32` verbatim (idempotent, no side effects on `&self`).
23740        //
23741        // Pins against a future silent detour that returned `&u32`
23742        // (which would type-check but silently break every downstream
23743        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
23744        // first parameter is `u32`, and `&u32` would fold to a detached
23745        // copy at the call site with a `*` deref the sibling accessors
23746        // don't need), an accidental `.rate.wrapping_add(0)` detour that
23747        // returned a fresh copy through an arithmetic no-op (breaking a
23748        // future `const fn` regression), or a one-arm-only accessor
23749        // that returned a saturating value on some sentinel input
23750        // (breaking the pass-through invariant the sibling required-
23751        // scalar accessors carry).
23752        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
23753            let rl = RateLimit {
23754                rate,
23755                window: Duration::from_secs(1),
23756            };
23757            let first = rl.rate();
23758            let second = rl.rate();
23759            assert_eq!(
23760                first, second,
23761                "RateLimit::rate must be idempotent — two successive \
23762                 calls on the same &self must return the same u32",
23763            );
23764            assert_eq!(
23765                first, rate,
23766                "RateLimit::rate must return :politicas :rate-limit :rate \
23767                 verbatim by copy — got {first}, expected {rate}",
23768            );
23769        }
23770    }
23771
23772    #[test]
23773    fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
23774        // The canonical per-`:politicas :rate-limit` `:window`
23775        // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
23776        // pin: [`RateLimit::window`] must return the
23777        // `:politicas :rate-limit :window` typed `Duration` verbatim,
23778        // byte-equal to the raw field access across every
23779        // representative value in the accept-set — `Duration::from_secs(1)`
23780        // (the `"s"` canonical window, the lower row of
23781        // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
23782        // [`AplicacaoSpec::validate_politicas`] gate accepts via
23783        // [`is_canonical_rate_limit_window`]),
23784        // `Duration::from_secs(60)` (the `"m"` canonical window, the
23785        // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
23786        // window, the upper row), `Duration::ZERO` (a past-the-guard
23787        // sentinel that pins the accessor doesn't perform a silent
23788        // bounds-collapse into `Duration::from_secs(1)` on the zero
23789        // arm — validate rejects an off-set window through
23790        // `PolicyRateLimitWindowNotCanonical` but the accessor must
23791        // ship the raw slot verbatim so a validate-time gate
23792        // regression surfaces at the emit boundary rather than being
23793        // silently absorbed), `Duration::from_millis(500)` (a
23794        // sub-canonical past-the-guard sentinel that pins the accessor
23795        // doesn't silently normalize a non-canonical fractional
23796        // magnitude onto the nearest canonical row).
23797        //
23798        // Second sub-struct required-scalar accessor pin on the
23799        // `RateLimit` axis — sibling in shape to the just-landed
23800        // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
23801        // accessor pin on the peer per-sub-struct required-axis,
23802        // extended onto the per-`RateLimit` required-`Duration` axis.
23803        // Pins against a future silent detour that re-derived the
23804        // refill period from a peer axis (an accidental
23805        // `Duration::from_secs(self.rate as u64)` collapse that read
23806        // the rate-limit token capacity as a refill-interval
23807        // duration), a `Duration::ZERO → Duration::from_secs(1)`
23808        // canonical-default projection (which would silently absorb
23809        // the `PolicyRateLimitWindowNotCanonical` refusal case at the
23810        // accessor boundary), or a canonical-set-collapsing accessor
23811        // that clamped the return through [`rate_limit_window_unit`]
23812        // (the `AplicacaoSpec::validate` gate owns the canonical-set
23813        // membership; the accessor must ship the raw slot verbatim).
23814        for window in [
23815            Duration::from_secs(1),
23816            Duration::from_secs(60),
23817            Duration::from_secs(3600),
23818            Duration::ZERO,
23819            Duration::from_millis(500),
23820        ] {
23821            let rl = RateLimit { rate: 100, window };
23822            assert_eq!(
23823                rl.window(),
23824                window,
23825                "RateLimit::window must return :politicas :rate-limit :window \
23826                 verbatim (got {:?}, expected {window:?})",
23827                rl.window(),
23828            );
23829            assert_eq!(
23830                rl.window(),
23831                rl.window,
23832                "RateLimit::window must byte-equal the raw .window field \
23833                 access across every value in the Duration accept-set",
23834            );
23835        }
23836    }
23837
23838    #[test]
23839    fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
23840        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
23841        // `:rate-limit :window` canonical-set arm must key off
23842        // [`RateLimit::window`], not the raw `.window` field access.
23843        // Structurally: a `RateLimit { window: Duration::from_millis(500),
23844        // .. }` embedded in a `:politicas :rate-limit` slot must
23845        // surface the `PolicyRateLimitWindowNotCanonical` refusal
23846        // exactly (with the sub-canonical `Duration::from_millis(500)`
23847        // magnitude carried through verbatim), and a `RateLimit
23848        // { window: Duration::from_secs(1), .. }` (the lower row of
23849        // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
23850        // The pair jointly pins the accessor + validate-gate
23851        // composition: any future silent detour that had the accessor
23852        // normalize the off-set window to the nearest canonical row
23853        // (a `.window().max(Duration::from_secs(1))` collapse, or a
23854        // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
23855        // collapse) would silently absorb the
23856        // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
23857        // boundary — including a drift in the error's `window` payload
23858        // (the emit-side diagnostic reader keys off the offending
23859        // magnitude verbatim, so a normalization at the accessor
23860        // boundary would silently pin the wrong magnitude in the
23861        // refusal). The composition pin catches that at caixa-core
23862        // build time.
23863        //
23864        // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
23865        // (7f81a60) accessor-composition pin on the peer required-
23866        // scalar `:rate` axis — same "the validate / shape-gate
23867        // predicate must route through the substrate-primitive typed
23868        // dispatch, and the error payload must project through the
23869        // same accessor" discipline extended onto the peer
23870        // per-`RateLimit` required-`Duration` composition axis.
23871        let mut spec = three_member_spec();
23872        spec.politicas = MeshPolicy {
23873            rate_limit: Some(RateLimit {
23874                rate: 100,
23875                window: Duration::from_millis(500),
23876            }),
23877            ..MeshPolicy::default()
23878        };
23879        match spec.validate() {
23880            Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
23881                assert_eq!(
23882                    window,
23883                    Duration::from_millis(500),
23884                    "PolicyRateLimitWindowNotCanonical must carry the \
23885                     offending :window magnitude verbatim through the \
23886                     accessor — got {window:?}, expected 500ms",
23887                );
23888            }
23889            other => panic!(
23890                "validate_politicas must reject non-canonical :window \
23891                 with PolicyRateLimitWindowNotCanonical — the accessor \
23892                 and the validate gate must route through the same \
23893                 substrate-primitive typed dispatch on the :window \
23894                 canonical-set arm; got {other:?}",
23895            ),
23896        }
23897        spec.politicas = MeshPolicy {
23898            rate_limit: Some(RateLimit {
23899                rate: 100,
23900                window: Duration::from_secs(1),
23901            }),
23902            ..MeshPolicy::default()
23903        };
23904        assert!(
23905            spec.validate().is_ok(),
23906            "validate_politicas must accept window == Duration::from_secs(1) \
23907             (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
23908        );
23909    }
23910
23911    #[test]
23912    fn rate_limit_window_projects_duration_by_copy() {
23913        // The by-copy pin: [`RateLimit::window`] returns `Duration`
23914        // by copy — `Duration` is `Copy` and the accessor must return
23915        // by value, not by reference. Peer of the sibling per-`RateLimit`
23916        // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
23917        // required-scalar `:rate` axis, extended onto the peer
23918        // per-`RateLimit` required-`Duration` copy-invariant shape —
23919        // the accessor's returned `Duration` must outlive `&self`
23920        // (multiple calls must return equal values from a
23921        // dropped-`&self` copy, since the returned scalar carries no
23922        // borrow), and calling the accessor twice on the same
23923        // RateLimit must yield the same `Duration` verbatim
23924        // (idempotent, no side effects on `&self`).
23925        //
23926        // Pins against a future silent detour that returned
23927        // `&Duration` (which would type-check but silently break every
23928        // downstream `Duration`-by-value consumer —
23929        // [`is_canonical_rate_limit_window`]'s first parameter is
23930        // `Duration`, and `&Duration` would fold to a detached copy at
23931        // the call site with a `*` deref the sibling accessors don't
23932        // need), an accidental `.window + Duration::ZERO` detour that
23933        // returned a fresh copy through an arithmetic no-op (breaking
23934        // a future `const fn` regression), or a one-arm-only accessor
23935        // that returned a canonical fallback on some sentinel input
23936        // (breaking the pass-through invariant the sibling required-
23937        // scalar accessors carry).
23938        for window in [
23939            Duration::from_secs(1),
23940            Duration::from_secs(60),
23941            Duration::from_secs(3600),
23942            Duration::ZERO,
23943            Duration::from_millis(500),
23944        ] {
23945            let rl = RateLimit { rate: 100, window };
23946            let first = rl.window();
23947            let second = rl.window();
23948            assert_eq!(
23949                first, second,
23950                "RateLimit::window must be idempotent — two successive \
23951                 calls on the same &self must return the same Duration",
23952            );
23953            assert_eq!(
23954                first, window,
23955                "RateLimit::window must return :politicas :rate-limit :window \
23956                 verbatim by copy — got {first:?}, expected {window:?}",
23957            );
23958        }
23959    }
23960}