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    /// Canonical `feira app graph` per-`:contratos`-edge payload-column
1298    /// byte-string the payload-less [`WitTarget::Capability`] arm renders
1299    /// as under [`Self::graph_label`] — the sibling
1300    /// [`WitTarget::CAPABILITY_LABEL`] scalar on the peer graph-verb
1301    /// payload-column axis (the graph verb spells payload-less as
1302    /// `(capability-only)`, distinct from the duplicate-`:contratos`
1303    /// diagnostic's `(capability — no payload)` on the human-readable
1304    /// [`Self::label`] axis). Peer of [`Self::CAPABILITY_LABEL`] /
1305    /// [`Self::CAPABILITY_EXPECTED`] on the payload-less-arm scalar-const
1306    /// family — extends the "one canonical declaration per arm, next to
1307    /// the variant, so a future rename lands in one place" discipline
1308    /// onto the third payload-less-arm consumer axis (`feira app graph`
1309    /// payload column, joining the [`Self::label`] duplicate-`:contratos`
1310    /// diagnostic axis and the [`Self::target`] wrong-target diagnostic
1311    /// axis).
1312    ///
1313    /// Until this lift landed the byte-string sat inline in
1314    /// [`caixa-feira`]'s `cmd::app::GraphArgs::run` per-`:contratos` payload-
1315    /// column match at `caixa-feira/src/cmd/app.rs:111` as a raw
1316    /// `"(capability-only)".to_string()` literal, with no compile-time link
1317    /// back to the [`WitTarget::Capability`] variant declaration nor to
1318    /// the sibling [`Self::CAPABILITY_LABEL`] / [`Self::CAPABILITY_EXPECTED`]
1319    /// peer consts already carrying the "one canonical declaration per
1320    /// payload-less-arm consumer axis" discipline. A rebrand on either
1321    /// side (the graph verb's operator-facing vocabulary tightening from
1322    /// `"(capability-only)"` to `"capability"` / `"(capability edge)"` as
1323    /// the WIT registry vocabulary sharpens, an M4 split of
1324    /// [`Self::Capability`] into per-shape peers) would silently
1325    /// desynchronize the graph-verb byte-string from the paired
1326    /// per-arm-adjacent const and land two spellings of the same axis in
1327    /// two spots.
1328    pub const CAPABILITY_GRAPH_LABEL: &'static str = "(capability-only)";
1329
1330    /// The `(author-facing field name, payload)` pair this typed target
1331    /// arm carries — `Some((HTTP_FIELD_NAME, endpoint))` for
1332    /// [`Self::Http`], `Some((PUBSUB_FIELD_NAME, subject))` for
1333    /// [`Self::PubSub`], `Some((STORE_FIELD_NAME, slot))` for
1334    /// [`Self::Store`], `None` for the payload-less
1335    /// [`Self::Capability`] arm.
1336    ///
1337    /// Lifted as the single 4-arm dispatch that both [`Self::label`]
1338    /// (formats `":{field} {payload:?}"` on `Some`, falls to
1339    /// [`Self::CAPABILITY_LABEL`] on `None`) and [`Self::field_name`]
1340    /// (returns the first component) route through, so a future
1341    /// [`WitTarget`] variant addition — the M4-and-later per-edge WIT
1342    /// registry may split [`Self::Http`] into `Rest` / `Grpc` peers,
1343    /// or extend [`Self::Store`] with a `Queue`-shaped peer — becomes
1344    /// exactly one new match-arm here (a compile-time exhaustiveness
1345    /// error otherwise), not a coordinated three-way rewrite of the
1346    /// prior [`Self::label`] template + [`Self::field_name`] dispatch
1347    /// + every downstream consumer that reaches for the pair.
1348    ///
1349    /// Until this lift landed the three payload arms sat in
1350    /// [`Self::label`] as three near-identical `format!(":{} {…:?}", …)`
1351    /// invocations (one per variant, each hand-quoting the paired
1352    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1353    /// [`Self::STORE_FIELD_NAME`] const) — the canonical
1354    /// "same shape, written N times" duplication THEORY.md §I.3.5
1355    /// ("Generation first, composition second, hand-authoring last;
1356    /// the duplication budget is zero") promotes to a build-time
1357    /// concern, with each per-arm site paired to its own const with no
1358    /// compile-time link between the format template and the arm's
1359    /// payload extraction.
1360    #[must_use]
1361    pub const fn payload_pair(&self) -> Option<(&'static str, &'a str)> {
1362        match *self {
1363            WitTarget::Http { endpoint } => Some((Self::HTTP_FIELD_NAME, endpoint)),
1364            WitTarget::PubSub { subject } => Some((Self::PUBSUB_FIELD_NAME, subject)),
1365            WitTarget::Store { slot } => Some((Self::STORE_FIELD_NAME, slot)),
1366            WitTarget::Capability => None,
1367        }
1368    }
1369
1370    /// The canonical author-facing `:contratos` payload field name
1371    /// this typed target arm carries (`Http` → `Some("endpoint")`,
1372    /// `PubSub` → `Some("subject")`, `Store` → `Some("slot")`), or
1373    /// `None` for the payload-less `Capability` arm.
1374    ///
1375    /// Routes through [`Self::payload_pair`] — the single 4-arm
1376    /// dispatch [`Self::label`] also reads — so a future variant
1377    /// addition is one match-arm edit at [`Self::payload_pair`], not a
1378    /// per-consumer rewrite. Same "exhaustive-match at one canonical
1379    /// dispatch, thin projections at each consumer" trajectory the
1380    /// peer [`PlacementStrategy::as_str`] / [`std::fmt::Display`]
1381    /// pair (0a2f653) landed on the sibling M3 typed-enum axis.
1382    #[must_use]
1383    pub const fn field_name(&self) -> Option<&'static str> {
1384        match self.payload_pair() {
1385            Some((f, _)) => Some(f),
1386            None => None,
1387        }
1388    }
1389
1390    /// Render this typed target as a stable human-readable label
1391    /// (`:endpoint "/charge"`, `:subject "events.x"`,
1392    /// `:slot "checkout/$order"`, or `(capability — no payload)` when
1393    /// the WIT world is a pure capability edge).
1394    ///
1395    /// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
1396    /// gate so the diagnostic names *which* identical edge was
1397    /// declared twice (not just which `(de, para, wit)` triple).
1398    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
1399    /// on the payload-carrying arms (`Some((field, payload)) →
1400    /// format!(":{field} {payload:?}")`) and through the lifted
1401    /// [`Self::CAPABILITY_LABEL`] const on the payload-less
1402    /// [`Self::Capability`] arm — so a future variant addition (the
1403    /// M4-and-later per-edge WIT registry may split [`Self::Http`]
1404    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
1405    /// `Queue`-shaped peer) becomes a single new match-arm on
1406    /// [`Self::payload_pair`] rather than a rewrite of this template
1407    /// (and every downstream consumer that reaches for the label
1408    /// shape: the per-edge policy resolver in M4, the `feira app
1409    /// graph` view, the operator's mesh-graph audit). Until this
1410    /// lift landed the three payload arms carried three near-identical
1411    /// per-arm `format!(":{} {…:?}", …)` invocations, and the
1412    /// [`Self::Capability`] arm carried the payload-less byte-string
1413    /// twice (once inline here, once in the pin test) — closing the
1414    /// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
1415    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
1416    /// / 4a1e490) peer-const lifts already established for the
1417    /// payload-carrying arms.
1418    #[must_use]
1419    pub fn label(&self) -> String {
1420        match self.payload_pair() {
1421            Some((field, payload)) => format!(":{field} {payload:?}"),
1422            None => Self::CAPABILITY_LABEL.to_string(),
1423        }
1424    }
1425
1426    /// Render this typed target as the `feira app graph` per-`:contratos`
1427    /// payload-column byte-string (`endpoint=/charge`, `subject=events.x`,
1428    /// `slot=checkout/$order`, or [`Self::CAPABILITY_GRAPH_LABEL`] on the
1429    /// payload-less arm).
1430    ///
1431    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
1432    /// on the payload-carrying arms (`Some((field, payload)) →
1433    /// format!("{field}={payload}")`) and through the lifted
1434    /// [`Self::CAPABILITY_GRAPH_LABEL`] const on the payload-less
1435    /// [`Self::Capability`] arm — so a future variant addition
1436    /// (the M4-and-later per-edge WIT registry may split [`Self::Http`]
1437    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
1438    /// `Queue`-shaped peer) becomes one match-arm edit at
1439    /// [`Self::payload_pair`], propagating through this graph-verb
1440    /// projection at zero call-site cost, sibling to the peer
1441    /// [`Self::label`] duplicate-`:contratos` diagnostic emission on the
1442    /// same 4-arm dispatch.
1443    ///
1444    /// Until this lift landed the [`caixa-feira`]
1445    /// `cmd::app::GraphArgs::run` per-`:contratos` payload column
1446    /// (`caixa-feira/src/cmd/app.rs:101-112`) hand-rolled the same 4-arm
1447    /// dispatch inline, re-projecting `HTTP_FIELD_NAME` /
1448    /// `PUBSUB_FIELD_NAME` / `STORE_FIELD_NAME` under a per-arm
1449    /// `format!("{}={endpoint}", ...)` template and hard-coding
1450    /// `"(capability-only)"` as a fifth payload-less scalar with no link
1451    /// back to the paired [`WitTarget::Capability`] variant declaration.
1452    /// A future variant addition would have had to be threaded through
1453    /// both [`Self::label`] (via [`Self::payload_pair`]) *and* the graph
1454    /// verb's inline match in lockstep or the two projections would
1455    /// silently disagree on the arm-set the graph verb prints — the
1456    /// duplicate-`:contratos` diagnostic reading one shape while the
1457    /// graph verb's payload column silently dropped the new arm to
1458    /// `(capability-only)`. Lifting the graph-verb projection onto the
1459    /// same substrate-primitive [`Self::payload_pair`] dispatch closes
1460    /// the axis: both projections migrate as a unit.
1461    ///
1462    /// The `field=payload` (no colon prefix, `=` separator, no `Debug`
1463    /// quoting) shape is graph-verb-canonical — distinct from the
1464    /// sibling [`Self::label`] `":{field} {payload:?}"` shape the
1465    /// duplicate-`:contratos` diagnostic seeds (see
1466    /// [`Self::CAPABILITY_LABEL`] vs. [`Self::CAPABILITY_GRAPH_LABEL`]
1467    /// on the payload-less axis for the paired distinction).
1468    #[must_use]
1469    pub fn graph_label(&self) -> String {
1470        match self.payload_pair() {
1471            Some((field, payload)) => format!("{field}={payload}"),
1472            None => Self::CAPABILITY_GRAPH_LABEL.to_string(),
1473        }
1474    }
1475}
1476
1477/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
1478/// pretty-printed byte-string every consumer that formats a typed
1479/// payload target as user-facing text lands on (the
1480/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
1481/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
1482/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
1483/// graph` per-`:contratos`-edge payload column that reaches the graph
1484/// verb through `format!("{target}")`, the future M4 per-edge policy
1485/// resolver's per-edge audit-log line, the operator's mesh-graph
1486/// per-edge inspection view) reaches for the same lifted
1487/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
1488/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
1489/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
1490/// routes through — extending the three-path-convergence
1491/// (`Debug` for structural inspection, `Display` for user-facing text,
1492/// per-arm typed accessor for the canonical byte-string) discipline the
1493/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
1494/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
1495/// onto the fourth (and only remaining) typed-shape-discriminator axis
1496/// on the caixa surface.
1497///
1498/// Pre-lift the two paths were structurally independent — every consumer
1499/// reaching for a payload byte-string past the [`WitTarget::label`]
1500/// helper had to pick between three paths ([`WitTarget::label`],
1501/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
1502/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
1503/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
1504/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
1505/// that reached for `format!("{target}")` — the canonical shape every
1506/// user-facing pretty-print site on the sibling typed-enum axes already
1507/// uses — would silently land on the `Debug` derive's structural output
1508/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
1509/// than the `label()` helper's stable byte-string (`:endpoint
1510/// "/charge"` — the author-facing `:contratos` keyword form) the
1511/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
1512/// already threads through. The two spellings would diverge silently in
1513/// every downstream diagnostic / graph / audit line reached through
1514/// `format!` rather than through the `label()` helper. Routing
1515/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
1516/// path: every `format!("{v}")` call reaches the same
1517/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
1518/// and the duplicate-`:contratos` gate already route through, so a
1519/// future variant addition (the M4-and-later per-edge WIT registry may
1520/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
1521/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
1522/// consumer at exactly one place — the [`WitTarget::payload_pair`]
1523/// match — rather than fanning out through hand-rolled per-arm
1524/// [`std::fmt::Display`] arms.
1525///
1526/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
1527/// is the typed view returned by [`WitContract::target`], not a
1528/// closed-set discriminator enum with a gen-platform Discriminant
1529/// registration, so the `Debug` derive's structural output (which every
1530/// `{v:?}` consumer still reaches) stays distinct from the `Display`
1531/// helper's stable pretty-printed byte-string. `Debug` reveals variant
1532/// shape for structural inspection; `Display` (via `label`) reveals the
1533/// stable author-facing payload projection.
1534///
1535/// Pin tests
1536/// [`tests::wit_target_display_routes_through_label_helper`] and
1537/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
1538/// assert the two paths agree byte-for-byte on every variant, so a
1539/// future variant addition or `label()` reimplementation that hand-rolls
1540/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
1541/// build error visible at caixa-core test time, not a silent
1542/// per-consumer dispatch miss at diagnostic / audit / graph time.
1543impl std::fmt::Display for WitTarget<'_> {
1544    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1545        f.write_str(&self.label())
1546    }
1547}
1548
1549// ── one Aplicacao member ─────────────────────────────────────────────
1550
1551/// A Servico participating in the Aplicacao. Same shape as
1552/// `crate::supervisor::ChildSpec` but without a restart policy —
1553/// supervision is per-Servico (each member has its own
1554/// `:supervisor`), the Aplicacao orchestrates *placement*.
1555#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1556#[serde(rename_all = "camelCase")]
1557pub struct Membro {
1558    /// Member caixa's `:nome`. Resolves through the same dep
1559    /// resolution path as `crate::dep::Dep`.
1560    pub caixa: String,
1561
1562    /// Semver constraint.
1563    pub versao: String,
1564}
1565
1566impl Membro {
1567    /// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
1568    /// accessor every consumer that reads the member's Servico identity
1569    /// keys off — returns the author-declared `:membros :caixa`
1570    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
1571    /// own [`String`] storage.
1572    ///
1573    /// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
1574    /// participating in the Aplicacao — validated by
1575    /// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
1576    /// (via [`validate_membro_caixa`]), unique across the Aplicacao's
1577    /// `:membros` list, distinct from the Aplicacao's own `:nome` (via
1578    /// [`validate_no_self_membership`]) — and every downstream consumer
1579    /// that fans on the member's identity keys off this scalar (the
1580    /// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
1581    /// lookup, the per-`:membros` duplicate gate's dedup key, the
1582    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
1583    /// identity, the self-membership gate, the
1584    /// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
1585    /// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
1586    /// CR materializer's per-member resolver).
1587    ///
1588    /// Prior to this lift the `.caixa` byte-string was read inline at
1589    /// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
1590    /// set collector at
1591    /// `self.membros.iter().map(|m| m.caixa.as_str())`, the
1592    /// [`validate_membros`] validation-side member-caixa gate at
1593    /// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
1594    /// per-member duplicate-gate dedup key at
1595    /// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
1596    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
1597    /// `adj.entry(m.caixa.as_str()).or_default()`, and the
1598    /// [`validate_no_self_membership`] self-loop gate at
1599    /// `m.caixa == parent_nome`) — five open-coded field-accesses that
1600    /// expressed no compile-time link back to the typed slot. Every
1601    /// caixa-mesh `metadata.name` derived from a `:membros :caixa`
1602    /// value flows through the [`caixa_mesh::fleet_programs`] per-entry
1603    /// `name:` axis, so a future extension of the `:membros :caixa`
1604    /// axis to a richer author surface — a per-cluster alias table the
1605    /// operator pins through a future `:placement`-scoped slot, a
1606    /// namespace-qualified rewrite the M4 CR materializer applies
1607    /// per-CR, a per-member overlay from the future `:membros
1608    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
1609    /// acknowledges — would have had to be threaded through every
1610    /// open-coded copy in lockstep or one consumer would silently
1611    /// disagree with the peers on which caixa a given member resolves
1612    /// to. A member-set lookup that treated the name as `"cart"` while
1613    /// the peer adjacency map treated it as `"tenant-a/cart"` would
1614    /// silently split the `:contratos` membership-lookup diagnostic from
1615    /// the cycle-detector's node identity — a two-consumer split at the
1616    /// validator far from the source `caixa.lisp` with no field naming
1617    /// the identity-drift root cause. Lifting the resolution rule to a
1618    /// typed method on the substrate primitive means every downstream
1619    /// consumer of the Aplicacao's per-`:membros` identity surface
1620    /// reaches for exactly one typed dispatch — the resolver's
1621    /// accept-set migrates as a unit on any future axis addition.
1622    ///
1623    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
1624    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
1625    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
1626    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
1627    /// destination-Servico scalar accessors — same "one typed dispatch
1628    /// on the substrate primitive, thin projections at each consumer"
1629    /// discipline extended onto the per-`:membros` member-caixa `:nome`
1630    /// byte-string axis. Named `nome()` to match the tatara-lisp
1631    /// author-surface term the field's docstring already reaches for
1632    /// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
1633    /// [`crate::dep::Dep::nome`] field-name discipline the substrate
1634    /// already carries — the accessor's name maps directly onto the
1635    /// canonical caixa-identity vocabulary rather than shadowing the
1636    /// field's storage-side `caixa` label.
1637    #[must_use]
1638    pub fn nome(&self) -> &str {
1639        self.caixa.as_str()
1640    }
1641
1642    /// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
1643    /// requirement scalar accessor every consumer that reads the
1644    /// member's version pin keys off — returns the author-declared
1645    /// `:membros :versao` byte-string verbatim as a `&str`, borrowed
1646    /// from the typed slot's own [`String`] storage.
1647    ///
1648    /// The `:membros :versao` slot carries the Cargo-shaped semver
1649    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
1650    /// pins which release of the member-caixa the Aplicacao composes
1651    /// against — the same requirement grammar the peer `:deps :versao`
1652    /// / `:children :versao` axes carry, resolved through the shared
1653    /// [`crate::render::require_valid_versao_requirement`] cascade and
1654    /// the shared [`crate::version::parse_requirement`] parser. Every
1655    /// downstream consumer that fans on the member's version pin keys
1656    /// off this scalar (the [`validate_membros`] per-member requirement
1657    /// gate at `require_valid_versao_requirement(m.versao_requirement(),
1658    /// …)`, the [`feira app graph`] per-member `println!("    - {} {}",
1659    /// m.nome(), m.versao_requirement())` line, every future per-cluster
1660    /// version-lock overlay the operator pins through a future
1661    /// `:placement`-scoped slot, the future
1662    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
1663    /// version resolver, the future `feira app deploy` pipeline's
1664    /// per-member lacre BLAKE3-closure lookup).
1665    ///
1666    /// Prior to this lift the `.versao` byte-string was accessed inline
1667    /// at two `&str`-shaped sites — the [`validate_membros`]
1668    /// requirement-gate call `require_valid_versao_requirement(&m.versao,
1669    /// …)` and the `feira app graph` per-member printer's `println!(
1670    /// "    - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
1671    /// prior to this lift) — two open-coded field-accesses that expressed
1672    /// no compile-time link back to the typed slot. A future extension of
1673    /// the `:membros :versao` axis to a richer author surface (a
1674    /// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
1675    /// flow, a lacre-projected concrete-version rewrite the operator
1676    /// materializes at CR-admission time, a future `:membros :versao-lock`
1677    /// per-cluster override slot) would have had to be threaded through
1678    /// every open-coded copy in lockstep or one consumer would silently
1679    /// disagree with the peers on which release constraint a given
1680    /// member resolves to. Lifting the resolution rule to a typed method
1681    /// on the substrate primitive means every downstream requirement-
1682    /// facing consumer reaches for exactly one typed dispatch — the
1683    /// resolver's accept-set migrates as a unit on any future axis
1684    /// addition.
1685    ///
1686    /// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
1687    /// member-caixa `:nome` scalar accessor — the pair
1688    /// `(nome(), versao_requirement())` jointly projects the
1689    /// `(caixa, versao)` field pair every renderer that fans on
1690    /// per-member identity + version pin keys off, closing the last
1691    /// unlifted per-`:membros` scalar axis so every downstream
1692    /// per-`:membros` reader now routes through a typed dispatch on the
1693    /// substrate primitive. Named `versao_requirement()` rather than
1694    /// `versao()` because the field's storage-side `.versao` label is
1695    /// already the author-surface term (`:versao`); the accessor's name
1696    /// carries the semantic role — the semver *requirement* string the
1697    /// shared [`crate::version::parse_requirement`] entry-point consumes
1698    /// — so a raw field access and a typed dispatch read differently at
1699    /// every consumer site.
1700    ///
1701    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
1702    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
1703    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
1704    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
1705    /// destination-Servico scalar accessors — same "one typed dispatch
1706    /// on the substrate primitive, thin projections at each consumer"
1707    /// discipline extended onto the per-`:membros` member-`:versao`
1708    /// semver-requirement byte-string axis.
1709    #[must_use]
1710    pub fn versao_requirement(&self) -> &str {
1711        self.versao.as_str()
1712    }
1713}
1714
1715// ── mesh-level policies ──────────────────────────────────────────────
1716
1717/// Mesh policies that apply to every `:contratos` edge unless
1718/// overridden per-edge in M4. V0 is a single global policy block.
1719#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
1720#[serde(rename_all = "camelCase")]
1721pub struct MeshPolicy {
1722    /// Per-call timeout. Authored as a duration string (`"30s"`).
1723    #[serde(
1724        default,
1725        skip_serializing_if = "Option::is_none",
1726        with = "supervisor::duration_codec"
1727    )]
1728    pub timeout: Option<Duration>,
1729
1730    /// Number of retries on transient failure. None = no retries.
1731    #[serde(default, skip_serializing_if = "Option::is_none")]
1732    pub retries: Option<u32>,
1733
1734    /// Circuit breaker config. Trips after N failures within W
1735    /// duration; closes after a cooldown.
1736    #[serde(default, skip_serializing_if = "Option::is_none")]
1737    pub circuit_breaker: Option<CircuitBreaker>,
1738
1739    /// Whether mTLS is required for every contrato. Default: true
1740    /// (sandboxing-by-default; explicit opt-out only).
1741    #[serde(default, skip_serializing_if = "Option::is_none")]
1742    pub mtls_required: Option<bool>,
1743
1744    /// Token-bucket rate limit. Authored as `"100/s"` or
1745    /// `"5000/m"`; stored as `(rate, window)`.
1746    #[serde(
1747        default,
1748        skip_serializing_if = "Option::is_none",
1749        with = "rate_limit_codec"
1750    )]
1751    pub rate_limit: Option<RateLimit>,
1752}
1753
1754impl MeshPolicy {
1755    /// True when no `:politicas` axis carries a value — every field is
1756    /// `None`. The same emptiness contract every other M2/M3 typed
1757    /// surface carries ([`crate::LimitsSpec::is_empty`],
1758    /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
1759    /// typed slot onto a cluster artifact key off this predicate to
1760    /// decide "emit the slot" vs "skip the slot entirely", so an
1761    /// authored-but-unset `:politicas (())` round-trips to a rendered
1762    /// artifact that's structurally identical to one that omits the
1763    /// slot. Lifted as a typed predicate (rather than per-renderer
1764    /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
1765    /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
1766    /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
1767    /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
1768    /// not a coordinated rewrite of every consumer that's reaching
1769    /// for the emptiness semantic.
1770    #[must_use]
1771    pub const fn is_empty(&self) -> bool {
1772        self.timeout().is_none()
1773            && self.retries().is_none()
1774            && self.circuit_breaker().is_none()
1775            && self.mtls_required().is_none()
1776            && self.rate_limit().is_none()
1777    }
1778
1779    /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
1780    /// per-call-deadline scalar accessor every consumer of the
1781    /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
1782    /// returns the author-declared `:politicas :timeout` typed
1783    /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
1784    /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
1785    /// is `Copy`, so the accessor returns by value; no borrow of
1786    /// `&self` past the call). `None` when the slot is absent (the
1787    /// "cluster default applies — typically the gateway class's
1788    /// implementation-side per-request wall-clock cap" arm caixa-mesh's
1789    /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
1790    /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
1791    /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
1792    /// round-trips to a rendered `HTTPRoute` structurally identical to
1793    /// one that omits the slot).
1794    ///
1795    /// The `:politicas :timeout` slot carries the "no infinite blocking"
1796    /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
1797    /// the typed slot's `Option<Duration>` accept-set (zero-floor
1798    /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
1799    /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
1800    /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
1801    /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
1802    /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
1803    /// Every downstream consumer that reads the per-call cap keys off
1804    /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
1805    /// renderers key off to decide "emit :politicas overlay" vs "skip
1806    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
1807    /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
1808    /// fans the deadline into every rule via
1809    /// [`crate::render::single_field_overlay`], the future M4 per-
1810    /// Aplicacao Gateway API reconciler materialization pass, the
1811    /// future per-`:contratos`-edge timeout-override overlay the
1812    /// MESH-COMPOSITION §III.2 roadmap acknowledges).
1813    ///
1814    /// Prior to this lift the `.timeout` field was accessed inline at
1815    /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
1816    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
1817    /// …)` call — two open-coded field-accesses that expressed no
1818    /// compile-time link back to the typed slot. A future extension of
1819    /// the `:politicas :timeout` axis to a richer author surface — a
1820    /// per-`:contratos`-edge timeout override the operator pins through
1821    /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
1822    /// roadmap acknowledges, a per-cluster timeout-default overlay the
1823    /// M4 CR materializer resolves per-CR, a split of the single
1824    /// per-call `Duration` into a richer `{request, backendRequest}`
1825    /// pair once the Gateway API's per-rule `timeouts` block grows the
1826    /// upstream-facing backendRequest arm alongside the client-facing
1827    /// request arm — would have had to be threaded through both open-
1828    /// coded copies in lockstep or the emptiness predicate and the
1829    /// caixa-mesh emit path would silently disagree on which per-call
1830    /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
1831    /// whose only axis is a `Some :timeout` would satisfy `is_empty()
1832    /// == false` while the renderer's overlay-emit path silently read
1833    /// a drifted other value, or vice versa: an author's `:timeout
1834    /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
1835    /// the emptiness predicate still classified the policy as non-
1836    /// empty, and every `kubectl -n tatara-system get httproute -o yaml
1837    /// | grep -A2 timeouts` audit would land on a route whose author's
1838    /// typed slot value silently vanished at the renderer layer).
1839    /// Lifting the resolution to a typed method on the substrate
1840    /// primitive means every downstream consumer of the Aplicacao's
1841    /// per-`:politicas` deadline surface reaches for exactly one typed
1842    /// dispatch — the resolver's accept-set migrates as a unit on any
1843    /// future axis addition.
1844    ///
1845    /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
1846    /// family (sibling of the peer per-`:politicas`
1847    /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
1848    /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
1849    /// `Option<bool>` accessor — same "one typed dispatch on the
1850    /// substrate primitive, thin projections at each consumer"
1851    /// discipline extended onto the peer per-`:politicas` typed-
1852    /// [`Duration`] optional-scalar axis; closes the "optional per-slot
1853    /// numeric-Copy-T scalar" projection pattern the sibling
1854    /// `Option<u32>` / `Option<bool>` lifts opened, since every
1855    /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
1856    /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
1857    /// than a scalar). Named `timeout()` to match the storage field's
1858    /// name; the accessor's identity maps onto the canonical MESH-
1859    /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
1860    #[must_use]
1861    pub const fn timeout(&self) -> Option<Duration> {
1862        self.timeout
1863    }
1864
1865    /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
1866    /// retry-budget scalar accessor every consumer of the Aplicacao's
1867    /// Gateway API v1.x per-rule retry-cap keys off — returns the
1868    /// author-declared `:politicas :retries` typed `u32` verbatim as an
1869    /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
1870    /// storage (`Option<u32>` is `Copy`, so the accessor returns by
1871    /// value; no borrow of `&self` past the call). `None` when the slot
1872    /// is absent (the "cluster default applies — typically 'no retries
1873    /// beyond a single dispatch attempt'" arm the caixa-mesh
1874    /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
1875    /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
1876    /// this predicate too, so an authored-but-unset `:politicas
1877    /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
1878    /// identical to one that omits the slot).
1879    ///
1880    /// The `:politicas :retries` slot carries the "transient failure
1881    /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
1882    /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
1883    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
1884    /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
1885    /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
1886    /// count scalar the caixa-mesh `retry_overlay` builder writes.
1887    /// Every downstream consumer that reads the retry cap keys off this
1888    /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
1889    /// renderers key off to decide "emit :politicas overlay" vs "skip
1890    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
1891    /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
1892    /// the value into every rule via [`crate::render::single_field_overlay`],
1893    /// the future M4 per-Aplicacao Gateway API reconciler
1894    /// materialization pass, the future per-`:contratos`-edge retry-
1895    /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
1896    /// acknowledges).
1897    ///
1898    /// Prior to this lift the `.retries` field was accessed inline at
1899    /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
1900    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
1901    /// …)` call — two open-coded field-accesses that expressed no
1902    /// compile-time link back to the typed slot. A future extension of
1903    /// the `:politicas :retries` axis to a richer author surface — a
1904    /// per-`:contratos`-edge retry override the operator pins through a
1905    /// future `:contratos :retries` slot, a per-cluster retry-default
1906    /// overlay the M4 CR materializer resolves per-CR, a promotion of
1907    /// the plain `u32` attempt-count to a richer `{attempts, codes,
1908    /// backoff}` sub-block once the Gateway API grows the peer
1909    /// `retry.codes` / `retry.backoff` axes — would have had to be
1910    /// threaded through both open-coded copies in lockstep or the
1911    /// emptiness predicate and the caixa-mesh emit path would silently
1912    /// disagree on which retry budget a given [`MeshPolicy`] resolves to
1913    /// (a `:politicas` block whose only axis is a `Some :retries` would
1914    /// satisfy `is_empty() == false` while the renderer's overlay-emit
1915    /// path silently read a drifted other value, or vice versa: an
1916    /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
1917    /// block while the emptiness predicate still classified the policy
1918    /// as non-empty). Lifting the resolution to a typed method on the
1919    /// substrate primitive means every downstream consumer of the
1920    /// Aplicacao's per-`:politicas` retry surface reaches for exactly
1921    /// one typed dispatch — the resolver's accept-set migrates as a
1922    /// unit on any future axis addition.
1923    ///
1924    /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
1925    /// family (sibling of the peer per-`:politicas`
1926    /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
1927    /// same "one typed dispatch on the substrate primitive, thin
1928    /// projections at each consumer" discipline extended onto the
1929    /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
1930    /// the "optional per-slot numeric-Copy-T scalar" projection pattern
1931    /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
1932    /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
1933    /// fold on). Named `retries()` to match the storage field's name;
1934    /// the accessor's identity maps onto the canonical MESH-COMPOSITION
1935    /// §III.2 vocabulary the slot's docstring already carries.
1936    #[must_use]
1937    pub const fn retries(&self) -> Option<u32> {
1938        self.retries
1939    }
1940
1941    /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
1942    /// enforcement-toggle scalar accessor every consumer of the
1943    /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
1944    /// — returns the author-declared `:politicas :mtls-required` typed
1945    /// bool verbatim as an `Option<bool>`, copied out of the typed
1946    /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
1947    /// the accessor returns by value; no borrow of `&self` past the
1948    /// call). `None` when the slot is absent (the "cluster default
1949    /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
1950    /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
1951    /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
1952    /// this predicate too, so an authored-but-unset `:politicas
1953    /// (:mtls-required ())` round-trips to a rendered
1954    /// `CiliumNetworkPolicy` structurally identical to one that omits
1955    /// the slot).
1956    ///
1957    /// The `:politicas :mtls-required` slot carries the "explicit opt-
1958    /// out only, sandboxing-by-default" mTLS-enforcement toggle
1959    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
1960    /// `{None, Some(true), Some(false)}` accept-set maps onto the
1961    /// Cilium `authentication.mode` bijection through
1962    /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
1963    /// handshake enforced), `Some(false) → "disabled"` (handshake
1964    /// skipped — the debug-edge opt-out), `None` → omit the block
1965    /// (cluster default applies). Every downstream consumer that
1966    /// reads the toggle keys off this scalar (the
1967    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
1968    /// off to decide "emit :politicas overlay" vs "skip entirely", the
1969    /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
1970    /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
1971    /// ingress rule via [`crate::render::single_field_overlay`], the
1972    /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
1973    /// materialization pass, the future per-`:contratos`-edge mTLS
1974    /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
1975    ///
1976    /// Prior to this lift the `.mtls_required` field was accessed
1977    /// inline at two sites — [`MeshPolicy::is_empty`]'s
1978    /// `self.mtls_required.is_none()` arm and caixa-mesh's
1979    /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
1980    /// two open-coded field-accesses that expressed no compile-time
1981    /// link back to the typed slot. A future extension of the
1982    /// `:politicas :mtls-required` axis to a richer author surface —
1983    /// a per-`:contratos`-edge mTLS override the operator pins through
1984    /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
1985    /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
1986    /// M4 CR materializer resolves per-CR, a three-valued
1987    /// `{None, Some(true), Some(false), Some(Optional)}` promotion
1988    /// once Cilium's `authentication.mode` grows an `"optional"` arm —
1989    /// would have had to be threaded through both open-coded copies in
1990    /// lockstep or the emptiness predicate and the caixa-mesh emit
1991    /// path would silently disagree on which toggle a given
1992    /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
1993    /// axis is a `Some`
1994    /// `:mtls-required` would satisfy `is_empty() == false` while the
1995    /// renderer's overlay-emit path silently read a drifted other
1996    /// value, or vice versa). Lifting the resolution to a typed method
1997    /// on the substrate primitive means every downstream consumer of
1998    /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
1999    /// for exactly one typed dispatch — the resolver's accept-set
2000    /// migrates as a unit on any future axis addition.
2001    ///
2002    /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
2003    /// family (peer of the sibling per-`:placement`
2004    /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
2005    /// same "one typed dispatch on the substrate primitive, thin
2006    /// projections at each consumer" discipline extended onto the
2007    /// peer per-`:politicas` typed-bool optional-scalar axis; opens
2008    /// the "optional per-slot Copy-T scalar" projection pattern the
2009    /// sibling per-`:politicas` `:retries` (Option<u32>) /
2010    /// `:timeout` (Option<Duration>) future lifts fold on). Named
2011    /// `mtls_required()` to match the storage field's name; the
2012    /// accessor's identity maps onto the canonical MESH-COMPOSITION
2013    /// §III.2 vocabulary the slot's docstring already carries.
2014    #[must_use]
2015    pub const fn mtls_required(&self) -> Option<bool> {
2016        self.mtls_required
2017    }
2018
2019    /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
2020    /// `local_rate_limit`-mesh token-bucket-declaration scalar
2021    /// accessor every consumer of the Aplicacao's per-`:politicas`
2022    /// per-`(rate, window)` rate-limit surface keys off — returns the
2023    /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
2024    /// verbatim as an `Option<RateLimit>`, copied out of the typed
2025    /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
2026    /// `Copy`, so the accessor returns by value; no borrow of `&self`
2027    /// past the call). `None` when the slot is absent (the "cluster
2028    /// default applies — typically 'no per-Aplicacao rate declaration,
2029    /// gateway-class per-listener default applies'" arm the future
2030    /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
2031    /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
2032    /// `rate_limit().is_none()` arm reads this predicate too, so an
2033    /// authored-but-unset `:politicas (:rate-limit ())` round-trips
2034    /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
2035    /// identical to one that omits the slot).
2036    ///
2037    /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
2038    /// token-bucket rate declaration" contract (MESH-COMPOSITION
2039    /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
2040    /// (rate lower-bounded by 1 through
2041    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
2042    /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
2043    /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
2044    /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
2045    /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
2046    /// bijection the future `CiliumClusterwideEnvoyConfig` per-
2047    /// `:politicas` overlay emits. Every downstream consumer that
2048    /// reads the rate declaration keys off this scalar (the
2049    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2050    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2051    /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
2052    /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
2053    /// `rl.window` against [`is_canonical_rate_limit_window`], the
2054    /// future M4 per-Aplicacao Envoy reconciler materialization pass,
2055    /// the future per-`:contratos`-edge rate-limit override the
2056    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2057    ///
2058    /// Prior to this lift the `.rate_limit` field was accessed inline
2059    /// at two sites — [`MeshPolicy::is_empty`]'s
2060    /// `self.rate_limit.is_none()` arm and the `validate_politicas`
2061    /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
2062    /// field-accesses that expressed no compile-time link back to the
2063    /// typed slot. A future extension of the `:politicas :rate-limit`
2064    /// axis to a richer author surface — a per-`:contratos`-edge
2065    /// rate-limit override the operator pins through a future
2066    /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
2067    /// roadmap acknowledges, a per-cluster rate-limit-default overlay
2068    /// the M4 CR materializer resolves per-CR, a promotion of the
2069    /// plain `(rate, window)` scalar pair to a richer
2070    /// `{rate, window, burst, key}` sub-block once Envoy's
2071    /// `local_rate_limit` grows the peer `burst_size` /
2072    /// `descriptor_key` axes — would have had to be threaded through
2073    /// both open-coded copies in lockstep or the emptiness predicate
2074    /// and the validate gate would silently disagree on which rate
2075    /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
2076    /// block whose only axis is a `Some :rate-limit` would satisfy
2077    /// `is_empty() == false` while the validate path silently read a
2078    /// drifted other value, or vice versa: an author's
2079    /// `:rate-limit "100/s"` would omit the value-shape gate while the
2080    /// emptiness predicate still classified the policy as non-empty).
2081    /// Lifting the resolution to a typed method on the substrate
2082    /// primitive means every downstream consumer of the Aplicacao's
2083    /// per-`:politicas` rate-limit surface reaches for exactly one
2084    /// typed dispatch — the resolver's accept-set migrates as a unit
2085    /// on any future axis addition.
2086    ///
2087    /// First `Option<Copy-composite-T>`-return accessor on the M3
2088    /// mesh-slot family — closes the last un-lifted per-`:politicas`
2089    /// scalar-value axis. Peer of the sibling per-`:politicas`
2090    /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
2091    /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
2092    /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
2093    /// "one typed dispatch on the substrate primitive, thin
2094    /// projections at each consumer" discipline extended onto the
2095    /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
2096    /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
2097    /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
2098    /// sub-accessors rather than a top-level accessor because
2099    /// consumers reach for the axes not the aggregate). Named
2100    /// `rate_limit()` to match the storage field's name; the
2101    /// accessor's identity maps onto the canonical MESH-COMPOSITION
2102    /// §III.2 vocabulary the slot's docstring already carries.
2103    #[must_use]
2104    pub const fn rate_limit(&self) -> Option<RateLimit> {
2105        self.rate_limit
2106    }
2107
2108    /// Substrate-canonical per-`:politicas` `:circuit-breaker`
2109    /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
2110    /// declaration scalar accessor every consumer of the Aplicacao's
2111    /// per-`:politicas` breaker declaration keys off — returns the
2112    /// author-declared `:politicas :circuit-breaker` typed
2113    /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
2114    /// copied out of the typed slot's own `Option<CircuitBreaker>`
2115    /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
2116    /// by value; no borrow of `&self` past the call). `None` when the
2117    /// slot is absent (the "cluster default applies — typically 'no
2118    /// per-Aplicacao breaker declaration, gateway-class per-listener
2119    /// default applies'" arm the future caixa-mesh
2120    /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
2121    /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
2122    /// arm reads this predicate too, so an authored-but-unset
2123    /// `:politicas (:circuit-breaker ())` round-trips to a rendered
2124    /// `CiliumClusterwideEnvoyConfig` structurally identical to one
2125    /// that omits the slot).
2126    ///
2127    /// The `:politicas :circuit-breaker` slot carries the
2128    /// "per-Aplicacao consecutive-transient-failure trip declaration"
2129    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2130    /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
2131    /// zero-floor rejected through
2132    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2133    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
2134    /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
2135    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
2136    /// canonical-form pinned through
2137    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
2138    /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
2139    /// bijection the future `CiliumClusterwideEnvoyConfig`
2140    /// per-`:politicas` overlay emits. Every downstream consumer that
2141    /// reads the breaker declaration keys off this scalar (the
2142    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2143    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2144    /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
2145    /// that brackets `cb.max_failures()` against
2146    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
2147    /// [`POLICY_BREAKER_WINDOW_MAX`] via
2148    /// [`crate::render::require_positive_canonical_bounded_duration`],
2149    /// the future M4 per-Aplicacao Envoy reconciler materialization
2150    /// pass, the future per-`:contratos`-edge breaker override the
2151    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2152    ///
2153    /// Prior to this lift the `.circuit_breaker` field was accessed
2154    /// inline at two sites — [`MeshPolicy::is_empty`]'s
2155    /// `self.circuit_breaker.is_none()` arm and the
2156    /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
2157    /// bind — two open-coded field-accesses that expressed no
2158    /// compile-time link back to the typed slot. A future extension of
2159    /// the `:politicas :circuit-breaker` axis to a richer author
2160    /// surface — a per-`:contratos`-edge breaker override the operator
2161    /// pins through a future `:contratos :circuit-breaker` slot the
2162    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
2163    /// breaker-default overlay the M4 CR materializer resolves per-CR,
2164    /// a promotion of the plain `(max_failures, window)` scalar pair to
2165    /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
2166    /// sub-block once Envoy's `outlier_detection` grows the peer
2167    /// ejection-percentage / ejection-time axes — would have had to be
2168    /// threaded through both open-coded copies in lockstep or the
2169    /// emptiness predicate and the validate gate would silently
2170    /// disagree on which breaker declaration a given [`MeshPolicy`]
2171    /// resolves to (a `:politicas` block whose only axis is a
2172    /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
2173    /// the validate path silently read a drifted other value, or vice
2174    /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
2175    /// "60s"))` would omit the value-shape gate while the emptiness
2176    /// predicate still classified the policy as non-empty). Lifting
2177    /// the resolution to a typed method on the substrate primitive
2178    /// means every downstream consumer of the Aplicacao's
2179    /// per-`:politicas` breaker surface reaches for exactly one typed
2180    /// dispatch — the resolver's accept-set migrates as a unit on any
2181    /// future axis addition.
2182    ///
2183    /// Second `Option<Copy-composite-T>`-return accessor on the M3
2184    /// mesh-slot family (sibling of the peer per-`:politicas`
2185    /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
2186    /// on the same composite-Copy shape, and of the sibling per-
2187    /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
2188    /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
2189    /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
2190    /// `Option<bool>` accessors on the sibling primitive-Copy axes —
2191    /// same "one typed dispatch on the substrate primitive, thin
2192    /// projections at each consumer" discipline extended onto the last
2193    /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
2194    /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
2195    /// match the storage field's name; the accessor's identity maps
2196    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2197    /// docstring already carries. Closes the last unlifted
2198    /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
2199    /// reader now routes through a typed dispatch on the substrate
2200    /// primitive.
2201    #[must_use]
2202    pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
2203        self.circuit_breaker
2204    }
2205}
2206
2207#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2208#[serde(rename_all = "camelCase")]
2209pub struct CircuitBreaker {
2210    pub max_failures: u32,
2211    #[serde(with = "supervisor::duration_codec_required")]
2212    pub window: Duration,
2213}
2214
2215impl CircuitBreaker {
2216    /// Substrate-canonical per-`:politicas :circuit-breaker`
2217    /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
2218    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2219    /// breaker trip-count keys off — returns the author-declared
2220    /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
2221    /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
2222    /// so the accessor returns by value; no borrow of `&self` past the
2223    /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
2224    /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
2225    /// axis; a `CircuitBreaker` past pattern-match is definitionally
2226    /// present, and its `:max-failures` field carries the trip count as a
2227    /// required-axis scalar).
2228    ///
2229    /// The `:politicas :circuit-breaker :max-failures` axis carries the
2230    /// "consecutive-transient-failure trip threshold" contract
2231    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
2232    /// (zero-floor rejected through
2233    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2234    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
2235    /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
2236    /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
2237    /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
2238    /// Every downstream consumer that reads the trip threshold keys off
2239    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2240    /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
2241    /// canonical `require_positive_bounded_u32` helper, the future M4
2242    /// per-Aplicacao Envoy config reconciler materialization pass, the
2243    /// future per-`:contratos`-edge breaker-override overlay the
2244    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2245    ///
2246    /// Prior to this lift the `.max_failures` field was accessed inline
2247    /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
2248    /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
2249    /// open-coded field-access that expressed no compile-time link back
2250    /// to the typed sub-struct axis. A future extension of the
2251    /// `:max-failures` axis to a richer author surface — a
2252    /// per-`:contratos`-edge breaker override the operator pins through a
2253    /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
2254    /// #3 roadmap acknowledges, a per-cluster max-failures-default
2255    /// overlay the M4 CR materializer resolves per-CR, a promotion of the
2256    /// plain `u32` trip count to a richer
2257    /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
2258    /// tuple once Envoy's `outlier_detection` block's peer axes come into
2259    /// scope, a per-Envoy-cluster minimum-request-volume gate before the
2260    /// count arms — would have had to be threaded through every open-
2261    /// coded copy in lockstep or the validate gate and the future M4
2262    /// emit path would silently disagree on which trip threshold a given
2263    /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
2264    /// would satisfy validate while the emit path silently read a drifted
2265    /// other value, or vice versa: a validated typed slot would land at
2266    /// the emit boundary as a no-op breaker whose trip threshold is
2267    /// structurally never reached). Lifting the resolution to a typed
2268    /// method on the substrate primitive means every downstream consumer
2269    /// of the Aplicacao's per-`:politicas :circuit-breaker`
2270    /// trip-threshold surface reaches for exactly one typed dispatch —
2271    /// the resolver's accept-set migrates as a unit on any future axis
2272    /// addition.
2273    ///
2274    /// First sub-struct scalar accessor on the M3 mesh-slot family
2275    /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
2276    /// scalar" projection pattern the sibling `CircuitBreaker::window` /
2277    /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
2278    /// closes the last unlifted per-`:politicas` scalar-value axis after
2279    /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
2280    /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
2281    /// Same "one typed dispatch on the substrate primitive, thin
2282    /// projections at each consumer" discipline the peer
2283    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
2284    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
2285    /// [`Membro::versao_requirement`] (a40b0e3),
2286    /// [`Entrada::destination`] (6db982c) accessors carry on their
2287    /// respective per-mesh-slot-atom scalar-value axes, extended onto the
2288    /// per-sub-struct required-`u32` axis. Named `max_failures()` to
2289    /// match the storage field's name; the accessor's identity maps onto
2290    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2291    /// docstring already carries.
2292    #[must_use]
2293    pub const fn max_failures(&self) -> u32 {
2294        self.max_failures
2295    }
2296
2297    /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
2298    /// Envoy-outlier-detection rolling-observation-interval scalar
2299    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2300    /// breaker rolling-window duration keys off — returns the
2301    /// author-declared `:politicas :circuit-breaker :window` typed
2302    /// `Duration` verbatim, copied out of the typed slot's own
2303    /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
2304    /// by value; no borrow of `&self` past the call). Non-optional (the
2305    /// surrounding `Option<CircuitBreaker>` is the "slot present?"
2306    /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
2307    /// `CircuitBreaker` past pattern-match is definitionally present,
2308    /// and its `:window` field carries the rolling-observation interval
2309    /// as a required-axis scalar).
2310    ///
2311    /// The `:politicas :circuit-breaker :window` axis carries the
2312    /// "consecutive-transient-failure rolling-observation interval"
2313    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2314    /// `Duration` accept-set (zero-floor rejected through
2315    /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
2316    /// residue rejected through
2317    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
2318    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
2319    /// Envoy `outlier_detection.interval` per-cluster
2320    /// ejection-observation-interval scalar (equivalently the future
2321    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2322    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2323    /// consumer that reads the rolling-observation interval keys off
2324    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2325    /// integer-millisecond canonical-form + cap bracket at
2326    /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
2327    /// [`crate::render::require_positive_canonical_bounded_duration`]
2328    /// helper, the future M4 per-Aplicacao Envoy config reconciler
2329    /// materialization pass, the future per-`:contratos`-edge
2330    /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
2331    /// acknowledges).
2332    ///
2333    /// Prior to this lift the `.window` field was accessed inline at
2334    /// one production site — [`AplicacaoSpec::validate_politicas`]'s
2335    /// `require_positive_canonical_bounded_duration(cb.window, …)`
2336    /// call — one open-coded field-access that expressed no compile-
2337    /// time link back to the typed sub-struct axis. A future extension
2338    /// of the `:window` axis to a richer author surface — a
2339    /// per-`:contratos`-edge window override the operator pins through
2340    /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
2341    /// #3 roadmap acknowledges, a per-cluster window-default overlay
2342    /// the M4 CR materializer resolves per-CR, a promotion of the plain
2343    /// `Duration` observation interval to a richer
2344    /// `{interval, base_ejection_time, max_ejection_percent}` tuple
2345    /// once Envoy's `outlier_detection` block's peer axes come into
2346    /// scope, a per-Envoy-cluster minimum-request-volume gate before
2347    /// the window arms — would have had to be threaded through every
2348    /// open-coded copy in lockstep or the validate gate and the future
2349    /// M4 emit path would silently disagree on which observation
2350    /// interval a given [`CircuitBreaker`] resolves to (an author's
2351    /// `:window "60s"` would satisfy validate while the emit path
2352    /// silently read a drifted other value, or vice versa: a validated
2353    /// typed slot would land at the emit boundary as a breaker whose
2354    /// observation window is structurally so wide that no realistic
2355    /// failure-rate shape can trip it). Lifting the resolution to a
2356    /// typed method on the substrate primitive means every downstream
2357    /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
2358    /// observation-window surface reaches for exactly one typed
2359    /// dispatch — the resolver's accept-set migrates as a unit on any
2360    /// future axis addition.
2361    ///
2362    /// Second sub-struct scalar accessor on the M3 mesh-slot family —
2363    /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
2364    /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
2365    /// required-axis, extended onto the per-sub-struct required-`Duration`
2366    /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
2367    /// axis. Same "one typed dispatch on the substrate primitive, thin
2368    /// projections at each consumer" discipline the peer
2369    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
2370    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
2371    /// [`Membro::versao_requirement`] (a40b0e3),
2372    /// [`Entrada::destination`] (6db982c) accessors carry on their
2373    /// respective per-mesh-slot-atom scalar-value axes, extended onto
2374    /// the per-sub-struct required-`Duration` axis. Named `window()` to
2375    /// match the storage field's name; the accessor's identity maps onto
2376    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2377    /// docstring already carries.
2378    #[must_use]
2379    pub const fn window(&self) -> Duration {
2380        self.window
2381    }
2382}
2383
2384#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2385pub struct RateLimit {
2386    /// Requests per window.
2387    pub rate: u32,
2388    /// Window duration.
2389    pub window: Duration,
2390}
2391
2392impl RateLimit {
2393    /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
2394    /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
2395    /// every consumer of the Aplicacao's per-`:contratos`-edge
2396    /// rate-limit-bucket capacity keys off — returns the author-declared
2397    /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
2398    /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
2399    /// returns by value; no borrow of `&self` past the call). Non-optional
2400    /// (the surrounding `Option<RateLimit>` is the "slot present?"
2401    /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
2402    /// `RateLimit` past pattern-match is definitionally present, and its
2403    /// `:rate` field carries the token-bucket capacity as a required-axis
2404    /// scalar).
2405    ///
2406    /// The `:politicas :rate-limit` `:rate` axis carries the
2407    /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
2408    /// the typed slot's `u32` accept-set (zero-floor rejected through
2409    /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
2410    /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
2411    /// `local_rate_limit.token_bucket.max_tokens` per-cluster
2412    /// token-bucket-capacity scalar (equivalently the future
2413    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2414    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2415    /// consumer that reads the token-bucket capacity keys off this
2416    /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2417    /// cap bracket that gates on the canonical
2418    /// [`crate::render::require_positive_bounded_u32`] helper, the
2419    /// [`rate_limit_codec::render`] `Duration → unit` projection that
2420    /// emits the `<n>/<s|m|h>` author surface, the future M4
2421    /// per-Aplicacao Envoy config reconciler materialization pass, the
2422    /// future per-`:contratos`-edge rate-limit-override overlay the
2423    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2424    ///
2425    /// Prior to this lift the `.rate` field was accessed inline at three
2426    /// production sites — [`AplicacaoSpec::validate_politicas`]'s
2427    /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
2428    /// [`rate_limit_codec::render`] format-arm arms (canonical-window
2429    /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
2430    /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
2431    /// field-accesses that expressed no compile-time link back to the
2432    /// typed sub-struct axis. A future extension of the `:rate` axis
2433    /// to a richer author surface — a per-`:contratos`-edge rate
2434    /// override the operator pins through a future `:contratos :rate`
2435    /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
2436    /// per-cluster rate-default overlay the M4 CR materializer resolves
2437    /// per-CR, a promotion of the plain `u32` token capacity to a
2438    /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
2439    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
2440    /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
2441    /// before the token arms — would have had to be threaded through
2442    /// every open-coded copy in lockstep or the validate gate, the
2443    /// codec's render path, and the future M4 emit path would silently
2444    /// disagree on which token capacity a given [`RateLimit`] resolves
2445    /// to (an author's `:rate-limit "100/s"` would satisfy validate
2446    /// while the render / emit paths silently read a drifted other
2447    /// value, or vice versa: a validated typed slot would land at the
2448    /// emit boundary as a no-op limiter whose token capacity is
2449    /// structurally so high that no realistic per-edge traffic shape
2450    /// can drain it). Lifting the resolution to a typed method on the
2451    /// substrate primitive means every downstream consumer of the
2452    /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
2453    /// reaches for exactly one typed dispatch — the resolver's
2454    /// accept-set migrates as a unit on any future axis addition.
2455    ///
2456    /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
2457    /// in shape to the peer per-`CircuitBreaker`
2458    /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
2459    /// on the peer per-sub-struct required-axis, extended onto the
2460    /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
2461    /// required-axis scalar" projection pattern the sibling
2462    /// [`RateLimit::window`] future lift folds on. Same "one typed
2463    /// dispatch on the substrate primitive, thin projections at each
2464    /// consumer" discipline the peer [`WitContract::source`] /
2465    /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
2466    /// (0804823), [`Membro::nome`] (4a32abf),
2467    /// [`Membro::versao_requirement`] (a40b0e3),
2468    /// [`Entrada::destination`] (6db982c),
2469    /// [`CircuitBreaker::max_failures`] (3a74062),
2470    /// [`CircuitBreaker::window`] (373957f) accessors carry on their
2471    /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
2472    /// to match the storage field's name; the accessor's identity maps
2473    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2474    /// docstring already carries.
2475    #[must_use]
2476    pub const fn rate(&self) -> u32 {
2477        self.rate
2478    }
2479
2480    /// Substrate-canonical per-`:politicas :rate-limit` `:window`
2481    /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
2482    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2483    /// rate-limit-bucket refill period keys off — returns the
2484    /// author-declared `:politicas :rate-limit` typed `Duration`
2485    /// verbatim, copied out of the typed slot's own `Duration` storage
2486    /// (`Duration` is `Copy`, so the accessor returns by value; no
2487    /// borrow of `&self` past the call). Non-optional (the surrounding
2488    /// `Option<RateLimit>` is the "slot present?" projection at the
2489    /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
2490    /// pattern-match is definitionally present, and its `:window`
2491    /// field carries the token-bucket refill period as a required-axis
2492    /// scalar).
2493    ///
2494    /// The `:politicas :rate-limit` `:window` axis carries the
2495    /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
2496    /// — the typed slot's `Duration` accept-set (constrained to the
2497    /// three canonical windows `{1s, 60s, 3600s}` the
2498    /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
2499    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
2500    /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
2501    /// per-cluster token-bucket-refill-period scalar (equivalently the
2502    /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2503    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2504    /// consumer that reads the token-bucket refill period keys off
2505    /// this scalar (the [`AplicacaoSpec::validate_politicas`]
2506    /// canonical-window gate that keys off
2507    /// [`is_canonical_rate_limit_window`], the
2508    /// [`rate_limit_codec::render`] `Duration → unit` projection that
2509    /// emits the `<n>/<s|m|h>` author surface — canonical arm via
2510    /// [`rate_limit_window_unit`] and non-canonical fallback via
2511    /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
2512    /// reconciler materialization pass, the future per-`:contratos`-
2513    /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
2514    /// roadmap acknowledges).
2515    ///
2516    /// Prior to this lift the `.window` field was accessed inline at
2517    /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
2518    /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
2519    /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
2520    /// error-payload construction on refusal, and the two
2521    /// [`rate_limit_codec::render`] arms
2522    /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
2523    /// and non-canonical-window `rl.window.as_secs()` fallback). Three
2524    /// open-coded field-accesses that expressed no compile-time link
2525    /// back to the typed sub-struct axis. A future extension of the
2526    /// `:window` axis to a richer author surface — a per-`:contratos`-
2527    /// edge window override the operator pins through a future
2528    /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
2529    /// acknowledges, a per-cluster window-default overlay the M4 CR
2530    /// materializer resolves per-CR, a promotion of the plain
2531    /// `Duration` refill period to a richer
2532    /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
2533    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
2534    /// axis comes into scope, an addition of a `"d"` day suffix once
2535    /// Envoy's `rate_limit_action` grows daily-bucket support — would
2536    /// have had to be threaded through every open-coded copy in
2537    /// lockstep or the validate gate, the codec's render path, and
2538    /// the future M4 emit path would silently disagree on which
2539    /// refill period a given [`RateLimit`] resolves to (an author's
2540    /// `:rate-limit "100/s"` would satisfy validate while the render
2541    /// / emit paths silently read a drifted other value, or vice
2542    /// versa: a validated typed slot would land at the emit boundary
2543    /// as a limiter whose refill period is structurally so long that
2544    /// no realistic per-edge traffic shape stays inside the token
2545    /// budget). Lifting the resolution to a typed method on the
2546    /// substrate primitive means every downstream consumer of the
2547    /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
2548    /// reaches for exactly one typed dispatch — the resolver's
2549    /// accept-set migrates as a unit on any future axis addition.
2550    ///
2551    /// Second sub-struct scalar accessor on the `RateLimit` axis —
2552    /// sibling in shape to the just-landed [`RateLimit::rate`]
2553    /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
2554    /// required-axis, extended onto the per-sub-struct
2555    /// required-`Duration` axis; closes the last unlifted
2556    /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
2557    /// per-sub-struct accessor coverage is now complete across both
2558    /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
2559    /// the substrate primitive, thin projections at each consumer"
2560    /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
2561    /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
2562    /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
2563    /// (7f0fd43), [`WitContract::world_ref`] (0804823),
2564    /// [`Membro::nome`] (4a32abf),
2565    /// [`Membro::versao_requirement`] (a40b0e3),
2566    /// [`Entrada::destination`] (6db982c) accessors carry on their
2567    /// respective per-mesh-slot-atom scalar-value axes. Named
2568    /// `window()` to match the storage field's name; the accessor's
2569    /// identity maps onto the canonical MESH-COMPOSITION §III.2
2570    /// vocabulary the slot's docstring already carries.
2571    #[must_use]
2572    pub const fn window(&self) -> Duration {
2573        self.window
2574    }
2575
2576    /// Recognize this rate-limit's `:window` as a canonical
2577    /// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
2578    /// exactly matches one of the three closed-set arm-Durations
2579    /// (`1s` / `60s` / `3600s`), `None` when the window carries a
2580    /// non-canonical magnitude the codec's round-trip would break on
2581    /// (sub-second residue, or a second-magnitude outside the set
2582    /// [`RateLimitUnit::ALL`] enumerates).
2583    ///
2584    /// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
2585    /// returns `Some` here — the validate gate's
2586    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
2587    /// rejects every window this accessor returns `None` on. Downstream
2588    /// consumers past validate (the codec's [`rate_limit_codec::render`]
2589    /// path, the future M4 per-Aplicacao Envoy config reconciler's
2590    /// materialization pass, the future per-`:contratos`-edge rate-limit-
2591    /// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
2592    /// acknowledges) that read the typed unit off a validated slot can
2593    /// pattern-match on the returned `Some` without re-checking
2594    /// canonicality at the consumer layer — the typed enum surface is
2595    /// the load-bearing carrier of the canonicality invariant.
2596    ///
2597    /// Preferred over the free [`is_canonical_rate_limit_window`]
2598    /// module-private helper at any call site that has the typed
2599    /// [`RateLimit`] in hand (the codec's `render` arm at
2600    /// [`rate_limit_codec::render`], the validate gate's canonical-form
2601    /// arm in [`AplicacaoSpec::validate_politicas`], any future
2602    /// per-`:contratos` edge-override overlay resolver): those consumers
2603    /// reach for the typed enum without going through the
2604    /// `.window()` scalar-projection layer, and get the enum value
2605    /// directly (which the codec's render arm can then format via
2606    /// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
2607    /// "typed sub-struct scalar accessor, one dispatch on the substrate
2608    /// primitive" discipline the sibling [`RateLimit::rate`] and
2609    /// [`RateLimit::window`] accessors carry on the peer per-sub-struct
2610    /// scalar-value axes, extended onto the per-`RateLimit` typed-unit
2611    /// projection axis (the third scalar accessor on the [`RateLimit`]
2612    /// axis, first typed-enum-return projection).
2613    #[must_use]
2614    pub fn canonical_unit(&self) -> Option<RateLimitUnit> {
2615        RateLimitUnit::from_window(self.window)
2616    }
2617}
2618
2619/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
2620/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
2621/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
2622///
2623/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
2624/// the `:politicas :rate-limit` unit surface reads from
2625/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
2626/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
2627/// [`is_canonical_rate_limit_window`] predicate the
2628/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
2629/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
2630/// projection) now lives inside this typed enum's `match self` arms — a
2631/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
2632/// `rate_limit_action` grows daily-bucket support) is one new variant
2633/// plus the exhaustiveness arms on the four methods, so every consumer
2634/// picks it up by compile-time construction rather than a runtime
2635/// table-scan miss.
2636///
2637/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
2638/// scanned via `find_map` at every projection call — an untyped runtime
2639/// walk that carried no compile-time link between the parse arm's
2640/// accepted suffixes, the render arm's emitted suffixes, and the
2641/// validate gate's accepted windows. A future rate-limit-unit addition
2642/// that landed one row without threading through the other consumers
2643/// (or a copy-paste flip that collapsed two rows onto one suffix) would
2644/// silently split the accepted-set across the three consumers — the
2645/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
2646/// for a 24h window that parse can't round-trip, the validate gate
2647/// misses one canonical window. Lifting the pairs onto a typed
2648/// closed-set enum with exhaustive `match` arms makes any such
2649/// half-landed extension a caixa-core build error (the compiler enforces
2650/// arm coverage on every method), not a silent per-consumer drift
2651/// surfacing at apply time. Same "closed-set typed-enum discriminator"
2652/// discipline the sibling [`PlacementStrategy`] (cc8f749),
2653/// [`crate::supervisor::RestartStrategy`],
2654/// [`crate::supervisor::RestartPolicy`],
2655/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
2656/// closed-set typed enums carry on their respective closed-set axes —
2657/// extended onto the seventh closed-set typed-enum discriminator axis
2658/// on the caixa typed surface (the `:politicas :rate-limit :window`
2659/// canonical-unit axis).
2660#[derive(
2661    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
2662)]
2663pub enum RateLimitUnit {
2664    /// 1-second window — canonical author-surface suffix `"s"`
2665    /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
2666    /// with a 1s magnitude.
2667    Second,
2668    /// 1-minute window — canonical author-surface suffix `"m"`
2669    /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
2670    /// with a 60s magnitude.
2671    Minute,
2672    /// 1-hour window — canonical author-surface suffix `"h"`
2673    /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
2674    /// with a 3600s magnitude.
2675    Hour,
2676}
2677
2678impl RateLimitUnit {
2679    /// Exhaustive iteration surface for every consumer that reads the
2680    /// full canonical-unit set (the byte-parity witness against the
2681    /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
2682    /// webhook's accepted-suffix listing in its rejection body, any
2683    /// future round-trip fuzz harness). A future variant addition to
2684    /// [`RateLimitUnit`] extends this slice as a single edit and every
2685    /// consumer picks up the new entry by construction — the compiler-
2686    /// checked exhaustiveness on the sibling method `match` arms is the
2687    /// build-time guarantee that no arm forgets to grow.
2688    pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
2689
2690    /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
2691    /// string every `<n>/<unit>` rate-limit shape carries after its
2692    /// `/` separator. The single source of truth the codec's parse and
2693    /// render arms both dispatch on: the parse arm matches an incoming
2694    /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
2695    /// output; the render arm emits the entry's `as_suffix` verbatim
2696    /// after the rate magnitude.
2697    #[must_use]
2698    pub const fn as_suffix(self) -> &'static str {
2699        match self {
2700            Self::Second => "s",
2701            Self::Minute => "m",
2702            Self::Hour => "h",
2703        }
2704    }
2705
2706    /// Canonical `Duration` for this unit — the token-bucket refill
2707    /// period the [`RateLimit::window`] axis carries when the surrounding
2708    /// slot's `:rate-limit` author surface named this unit.
2709    #[must_use]
2710    pub const fn window(self) -> Duration {
2711        Duration::from_secs(match self {
2712            Self::Second => 1,
2713            Self::Minute => 60,
2714            Self::Hour => 3_600,
2715        })
2716    }
2717
2718    /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
2719    /// `None` when `suffix` is outside the closed-set arm-string set
2720    /// [`Self::as_suffix`] emits. The single `str → Self` projection
2721    /// [`rate_limit_codec::parse`] consumes.
2722    #[must_use]
2723    pub fn from_suffix(suffix: &str) -> Option<Self> {
2724        Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
2725    }
2726
2727    /// Recognize a canonical rate-limit `Duration` as one of the three
2728    /// arms, or `None` when `window` carries sub-second residue or a
2729    /// second-magnitude outside the closed-set arm-window set
2730    /// [`Self::window`] emits. The single `Duration → Self` projection
2731    /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
2732    /// both consume.
2733    #[must_use]
2734    pub fn from_window(window: Duration) -> Option<Self> {
2735        if window.subsec_nanos() != 0 {
2736            return None;
2737        }
2738        Self::ALL.iter().copied().find(|u| u.window() == window)
2739    }
2740
2741    /// Canonical rate-limit `Duration` for a unit suffix, or `None` when
2742    /// `suffix` is outside the closed-set arm-string set [`Self::as_suffix`]
2743    /// emits. Composes [`Self::from_suffix`] with [`Self::window`] — the
2744    /// single `&str → Duration` projection [`rate_limit_codec::parse`]
2745    /// consumes.
2746    ///
2747    /// The peer `Duration → &'static str` axis folded onto the substrate
2748    /// primitive [`RateLimit::canonical_unit`] typed accessor once both
2749    /// production consumers ([`rate_limit_codec::render`] and
2750    /// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
2751    /// migrated (61421a6): the free helper's `Duration → &str` projection
2752    /// is now the two-step composition
2753    /// `rl.canonical_unit().map(RateLimitUnit::as_suffix)` every consumer
2754    /// reads through the typed accessor. This lift closes the peer
2755    /// `&str → Duration` axis by folding the vestigial module-private
2756    /// `rate_limit_window_from_unit` delegate onto this associated method
2757    /// — the codec's parse arm and every future wire-side consumer of the
2758    /// `&str → Duration` projection (a future admission-webhook that
2759    /// reads a `:rate-limit` shape off a CR spec's `raw string` value
2760    /// before it's promoted to a validated typed slot, a future
2761    /// `feira lint` shape-probe that reads the author-surface bytes
2762    /// verbatim) now reach for exactly one typed dispatch on the
2763    /// substrate primitive.
2764    ///
2765    /// Same "closed-set typed-enum discriminator with canonical
2766    /// projections per axis" discipline the sibling [`Self::as_suffix`]
2767    /// / [`Self::window`] / [`Self::from_suffix`] / [`Self::from_window`]
2768    /// methods carry — this associated method closes the fifth (and last
2769    /// unlifted) projection axis on the arm-table, so the closed-set enum
2770    /// now owns every `str ↔ Duration ↔ Self` typed dispatch every
2771    /// consumer of the `:politicas :rate-limit :window` axis reaches
2772    /// through. A future rate-limit-unit addition (a `"d"` day suffix
2773    /// once Envoy's `rate_limit_action` grows daily-bucket support, a
2774    /// `"ms"` sub-second window once high-throughput per-edge policies
2775    /// come into scope per MESH-COMPOSITION §III.2 #3) is one new
2776    /// variant plus one arm per method — the compiler enforces
2777    /// exhaustiveness on every consumer's `match self` arms and picks
2778    /// the new unit up by construction across all five projections.
2779    #[must_use]
2780    pub fn window_from_suffix(suffix: &str) -> Option<Duration> {
2781        Self::from_suffix(suffix).map(Self::window)
2782    }
2783}
2784
2785/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
2786/// every consumer that formats a canonical rate-limit unit as user-
2787/// facing text (future M4 admission-webhook rejection bodies naming
2788/// the accepted-suffix set, future `feira app graph` per-`:politicas`
2789/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
2790/// codec's parse arm accepts and the render arm emits. Same
2791/// as_str-through-Display convergence discipline the sibling
2792/// [`PlacementStrategy`], [`crate::CaixaKind`],
2793/// [`crate::supervisor::RestartStrategy`], and
2794/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
2795impl std::fmt::Display for RateLimitUnit {
2796    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2797        f.write_str(self.as_suffix())
2798    }
2799}
2800
2801/// Upper-bound ceiling on the `:politicas :timeout` axis — every
2802/// validated [`MeshPolicy::timeout`] past
2803/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
2804/// (inclusive on both ends, integer-millisecond magnitudes by the
2805/// canonical-form gate immediately preceding).
2806///
2807/// The typed field is `Option<Duration>` (the zero-floor arm
2808/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
2809/// `Duration::ZERO`, and the canonical-form arm
2810/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
2811/// sub-millisecond residue), so a programmatic struct literal
2812/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
2813/// 24h) and the equivalent author-surface form
2814/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
2815/// integer-hour magnitude) both round-trip cleanly through serde — a
2816/// structurally unbounded `Duration` ceiling. A `:timeout` value far
2817/// above the documented production-playbook band (Envoy default `15s`,
2818/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
2819/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
2820/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
2821/// at `~3600s`) silently degenerates the mesh-policy contract: the
2822/// per-call deadline is structurally so long that no realistic
2823/// synchronous-`:contratos` traversal can reach it, so the typed slot
2824/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
2825/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
2826/// blocking" degenerates to a nominal-only contract on the
2827/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
2828/// the sibling `:politicas :retries` axis and the
2829/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
2830/// `:politicas :circuit-breaker :max-failures` axis — all three close
2831/// the "structurally unbounded ceiling on a typed `:politicas` axis"
2832/// footgun the prior zero-floor-and-canonical-form-only checks left
2833/// open.
2834///
2835/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
2836/// shared duration codec emits (`"<n>h"` for any integer-hour
2837/// magnitude) — every value in the canonical authoring form's
2838/// `<integer><unit>` grammar at or below this cap renders to a clean
2839/// canonical string. The cap sits an order of magnitude above every
2840/// documented production-playbook recommendation band (Envoy default
2841/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
2842/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
2843/// configured maximum (`proxy_read_timeout` typical max `3600s`),
2844/// below the clearly-pathological "effectively no timeout" floor
2845/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
2846/// want for a long-running synchronous workflow, but a hard wall above
2847/// which the mesh-level deadline is structurally a non-deadline.
2848/// Lifted as a typed `pub const` so the bound has exactly one source
2849/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
2850/// materializer's admission webhook and the caixa-mesh-side
2851/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2852/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
2853/// other typed upper bound in this crate carries
2854/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
2855/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2856/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2857/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2858pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
2859
2860/// Upper-bound ceiling on the `:politicas :retries` axis — every
2861/// validated [`MeshPolicy::retries`] past
2862/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
2863///
2864/// The typed slot is `Option<u32>` (`None` = no retries on transient
2865/// failure; `Some(0)` already rejected by the
2866/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
2867/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
2868/// .. }`) and the equivalent author-surface form
2869/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
2870/// serde / the codec — a structurally unbounded `u32` ceiling. The
2871/// runtime substrate that consumes the value (Envoy's
2872/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
2873/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
2874/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
2875/// admission cap is 10) translates a four-billion-retry policy into a
2876/// thundering-herd amplification vector on transient failure — the
2877/// caller's one request fans out to `retries` server-side calls per
2878/// edge per traversal, multiplying load by `(retries+1)^depth` across
2879/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
2880/// invariant "no infinite blocking" pairs with a no-runaway-amplification
2881/// invariant on the retry axis; both belong at the typed-slot layer.
2882///
2883/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
2884/// upstream mesh-policy schema that documents one) and sits above the
2885/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
2886/// every documented production playbook): a value the author can
2887/// plausibly want, but a hard wall above which the policy is
2888/// structurally a footgun. Lifted as a typed `pub const` so the bound
2889/// has exactly one source of truth — a future axis reaching for the
2890/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
2891/// materializer's admission webhook, the caixa-mesh-side
2892/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
2893/// one place. Same shape every other typed upper bound in this crate
2894/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2895/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2896/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
2897/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2898pub const POLICY_RETRIES_MAX: u32 = 10;
2899
2900/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
2901/// axis — every validated [`CircuitBreaker::max_failures`] past
2902/// [`AplicacaoSpec::validate_politicas`] lies in
2903/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
2904///
2905/// The typed field is `u32` (the zero-floor arm
2906/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
2907/// `0` — a breaker that trips on the first call), so a programmatic
2908/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
2909/// and the equivalent author-surface form
2910/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
2911/// cleanly through serde — a structurally unbounded `u32` ceiling. A
2912/// `max_failures` value far above the documented production-playbook
2913/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
2914/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
2915/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
2916/// typical 5–50) silently disables the breaker's protection role:
2917/// the threshold is structurally so high that no realistic
2918/// failures-per-`:window` traffic shape can reach it, so the breaker
2919/// never trips and the typed slot becomes a no-op carried on every
2920/// emitted Envoy / Cilium L7 overlay. Pairs with the
2921/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
2922/// axis — both close the "structurally unbounded `u32` ceiling on a
2923/// typed policy axis" footgun the prior zero-floor-only checks left
2924/// open.
2925///
2926/// The `1000` ceiling sits an order of magnitude above every
2927/// documented upstream production-playbook recommendation band (the
2928/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
2929/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
2930/// the clearly-pathological "effectively no protection"
2931/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
2932/// plausibly want at hyperscale, but a hard wall above which the
2933/// policy is structurally a no-op. Lifted as a typed `pub const` so
2934/// the bound has exactly one source of truth — the future M4
2935/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
2936/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
2937/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
2938/// one place. Same shape every other typed upper bound in this crate
2939/// carries ([`POLICY_RETRIES_MAX`],
2940/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2941/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2942/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2943pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
2944
2945/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
2946/// every validated [`CircuitBreaker::window`] past
2947/// [`AplicacaoSpec::validate_politicas`] lies in
2948/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
2949/// integer-millisecond magnitudes by the canonical-form gate
2950/// immediately preceding).
2951///
2952/// The typed field is `Duration` (the zero-floor arm
2953/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
2954/// `Duration::ZERO`, and the canonical-form arm
2955/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
2956/// sub-millisecond residue), so a programmatic struct literal
2957/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
2958/// and the equivalent author-surface form
2959/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
2960/// integer-hour magnitude) both round-trip cleanly through serde — a
2961/// structurally unbounded `Duration` ceiling. A `:window` value far
2962/// above the documented production-playbook band (Hystrix
2963/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
2964/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
2965/// Istio `outlierDetection.interval` default `10s`, Envoy
2966/// `outlier_detection.interval` default `10s`, AWS App Mesh
2967/// circuit-breaker time-window typical `30s..=300s`) degenerates the
2968/// breaker's role: a rolling-window failure counter whose window is
2969/// hours long is operationally a lifetime counter, the breaker's
2970/// "recent failures" memory is structurally so long that transient
2971/// failures are never forgotten, and the typed slot becomes a no-op
2972/// trigger that trips once and stays tripped for the lifetime of the
2973/// component carried on every emitted Envoy / Cilium L7 overlay.
2974///
2975/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
2976/// shared duration codec emits (`"<n>h"` for any integer-hour
2977/// magnitude) — every value in the canonical authoring form's
2978/// `<integer><unit>` grammar at or below this cap renders to a clean
2979/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
2980/// cap on the first typed-`Duration` `:politicas` axis: the two
2981/// duration-typed `:politicas` axes now share a single uniform top
2982/// edge so the next typed-slot wiring (the future caixa-mesh
2983/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
2984/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
2985/// admission webhook) reaches for either field knowing the value is
2986/// in `1ms..=1h` without re-validating at the renderer layer. The cap
2987/// sits two orders of magnitude above every documented upstream
2988/// production-playbook recommendation band (Hystrix / resilience4j /
2989/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
2990/// and below the clearly-pathological "rolling window degenerates to
2991/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
2992/// author can plausibly want for a very-low-traffic long-tail
2993/// failure-detection window, but a hard wall above which the breaker's
2994/// rolling-window contract is structurally a lifetime-counter contract.
2995/// Lifted as a typed `pub const` so the bound has exactly one source
2996/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
2997/// materializer's admission webhook and the caixa-mesh-side
2998/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2999/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3000/// other typed upper bound in this crate carries
3001/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3002/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3003/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3004/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3005/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3006pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
3007
3008/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
3009/// every validated [`RateLimit::rate`] past
3010/// [`AplicacaoSpec::validate_politicas`] lies in
3011/// `1..=POLICY_RATE_LIMIT_MAX`.
3012///
3013/// The typed field is `u32` (the zero-floor arm
3014/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
3015/// zero-rate limit denies every request, the canonical "I forgot
3016/// that 0 means deny-everything" footgun), so a programmatic struct
3017/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
3018/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
3019/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
3020/// round-trip cleanly through serde — a structurally unbounded `u32`
3021/// ceiling. The runtime substrate consuming the value (Envoy's
3022/// `local_rate_limit.token_bucket.max_tokens`, the future
3023/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3024/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
3025/// rate-limit into a no-op rate-limiter: the bucket capacity is
3026/// structurally so high no realistic per-edge traffic shape can
3027/// drain it, the limiter never trips, and the typed slot becomes a
3028/// "rate-limit declared, no enforcement" footgun — the canonical
3029/// declared-but-inert shape every other `:politicas` cap arm
3030/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
3031/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
3032///
3033/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
3034/// above every documented upstream production-playbook recommendation
3035/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
3036/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
3037/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
3038/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
3039/// `limit_req_zone` typical `1..=1_000` RPS) and below the
3040/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
3041/// `u32::MAX`): a value the author can plausibly want at hyperscale
3042/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
3043/// /h-window arm), but a hard wall above which the policy is
3044/// structurally a no-op carried verbatim on every emitted Envoy /
3045/// Cilium L7 overlay. The cap brackets all three canonical windows
3046/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
3047/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
3048/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
3049/// per-endpoint API band). Lifted as a typed `pub const` so the bound
3050/// has exactly one source of truth — the future M4
3051/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3052/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3053/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3054/// one place. Same shape every other typed upper bound in this crate
3055/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3056/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
3057/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3058/// [`crate::LIMITS_WALL_CLOCK_MAX`],
3059/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3060/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3061pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
3062
3063// `:entrada :host` total-length and per-label cap axes route through
3064// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
3065// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
3066// pair of aplicacao-private aliases the previous `validate_entrada_host`
3067// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
3068// = 63`) were structurally the same K8s Gateway API v1 Hostname
3069// admission-schema bounds — the total-length cap on the OpenAPI
3070// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
3071// same regex — that the peer axes at the caixa-core::render level pin,
3072// so hoisting both readers onto the shared lifted constants closes the
3073// third-occurrence duplication threshold structurally: the M4
3074// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
3075// label validator, the future per-`Certificate` SAN emitter, and every
3076// other per-Gateway-API-Hostname landing site reach the same one place
3077// as the `:entrada :host` gate does — no per-axis alias drift surface
3078// between them, by construction.
3079
3080/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
3081/// extractor expression — the upper bound `validate_placement_shard_key`
3082/// enforces on every well-shaped shard-key past validate. The realistic
3083/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
3084/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
3085/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
3086/// `:placement :affinity` / `:placement :clusters` identifier-shaped
3087/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
3088/// in `:shard-key`" footgun at validate time rather than at the future
3089/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
3090const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
3091
3092/// Reject `:membros :caixa` values the K8s apiserver would refuse at
3093/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3094/// that maps the shared parser-shaped reason into the
3095/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
3096/// is self-locating (the offending `caixa:` is named verbatim) and
3097/// the author can grep their caixa.lisp for `:caixa "<name>"` and
3098/// fix it in one edit. Same diagnostic shape as
3099/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
3100/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
3101fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
3102    // Empty is already gated by `MembroCaixaEmpty` at the call site;
3103    // re-checking here keeps the predicate usable from any future
3104    // call site (the M4 CR materializer) without an empty-check
3105    // footgun. The shared
3106    // [`crate::render::require_valid_dns_1123_label`] helper brackets
3107    // the empty-first + shape cascade every peer name axis
3108    // (`:placement :clusters`, `:placement :affinity`, `:contratos
3109    // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
3110    // `:upgrade-from :module`) routes through, so drift between the
3111    // eight axes' accepted DNS-1123-label sets is structurally
3112    // impossible.
3113    crate::render::require_valid_dns_1123_label(
3114        caixa,
3115        || AplicacaoError::MembroCaixaEmpty,
3116        |reason| AplicacaoError::MembroCaixaInvalid {
3117            caixa: caixa.to_string(),
3118            reason,
3119        },
3120    )
3121}
3122
3123/// Reject `:placement :clusters` entries the K8s apiserver would refuse
3124/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3125/// that maps the shared parser-shaped reason into the
3126/// [`AplicacaoError::PlacementClusterInvalid`] variant.
3127///
3128/// Cluster names land in DNS-1123-label territory across every consumer:
3129/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
3130/// the `lareira-fleet-programs` aggregator applies to scope programs to
3131/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
3132/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
3133/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
3134/// cluster identity the M4 CR materializer round-trips. Each apiserver-
3135/// side schema enforces the DNS-1123 label rule on admission; a
3136/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
3137/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
3138/// mistaken-identity slug) silently passes the prior empty-/duplicate-
3139/// only gate and the failure surfaces as a no-match at filter time —
3140/// the workload doesn't land in the named cluster, with no diagnostic
3141/// naming the offending `:clusters` entry. Lifting the gate to caixa-
3142/// build time mirrors the `:membros :caixa` value-shape trajectory
3143/// (3f9d7a0) on the peer name axis.
3144///
3145/// The diagnostic carries the offending `cluster:` verbatim plus a
3146/// parser-shaped `reason:` naming the specific violation, so the
3147/// author can grep their caixa.lisp for `:clusters` and fix it in
3148/// one edit. Same diagnostic shape as
3149/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
3150fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
3151    // Empty is already gated by `PlacementClusterEmpty` at the call
3152    // site; re-checking here keeps the predicate usable from any
3153    // future call site (the M4 CR materializer's per-cluster validator)
3154    // without an empty-check footgun. Routes through the shared
3155    // [`crate::render::require_valid_dns_1123_label`] gate the peer
3156    // name axes each land on.
3157    crate::render::require_valid_dns_1123_label(
3158        cluster,
3159        || AplicacaoError::PlacementClusterEmpty,
3160        |reason| AplicacaoError::PlacementClusterInvalid {
3161            cluster: cluster.to_string(),
3162            reason,
3163        },
3164    )
3165}
3166
3167/// Reject `:placement :affinity` hints whose shape can never legitimately
3168/// land in any downstream selector or label-keyed routing axis. Thin
3169/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
3170/// shared parser-shaped reason into the
3171/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
3172/// diagnostic is self-locating (the offending `:affinity` is named
3173/// verbatim) and the author can grep their caixa.lisp for
3174/// `:affinity "<hint>"` and fix it in one edit.
3175///
3176/// The `:affinity` slot carries a placement-engine hint — canonical
3177/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
3178/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
3179/// compression overlay and the future M4 placement-engine's per-hint
3180/// routing axis. Each downstream consumer (caixa-mesh's
3181/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
3182/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3183/// `spec.placement.affinity` admission rule, the future M4 per-hint
3184/// node-affinity / pod-affinity rule generator keying off the same
3185/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
3186/// selector) requires the value to be a DNS-1123 label — K8s label
3187/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
3188/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
3189/// admission rule the apiserver enforces.
3190///
3191/// Until this gate landed an `:affinity "DataLocality"` (the canonical
3192/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
3193/// Python-module-name leak), `:affinity "data.locality"` (the
3194/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
3195/// `:affinity "data-locality-"` (boundary-hyphen violation),
3196/// `:affinity "data locality"` (paste-from-doc whitespace),
3197/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
3198/// 64-byte over-cap slug silently passed the empty-only check and the
3199/// failure surfaced as a no-match at the M3 Adaptive compression
3200/// overlay's filter time (`placement.affinity` carried a malformed
3201/// value, no node matched, the workload landed on the default
3202/// heuristic) — the canonical "declared-but-inert" footgun mirroring
3203/// the empty-:affinity / empty-shard-key / zero-:politicas /
3204/// empty-:contratos-target gates already close on every other
3205/// declare-but-no-opinion axis. Lifting the rejection to a build-time
3206/// gate closes the fifth typed slot on the Aplicacao surface to land
3207/// on the canonical DNS-1123 label floor (after the four Servico-name
3208/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
3209/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
3210/// b0e8748).
3211///
3212/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
3213/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
3214/// validated values are guaranteed-accepted by the apiserver without
3215/// re-validation at any downstream renderer or admission layer.
3216fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
3217    // Empty is gated separately at the call site for a self-locating
3218    // diagnostic; re-checking here keeps the predicate usable from any
3219    // future call site (the M4 CR materializer's per-affinity
3220    // validator) without an empty-check footgun. Routes through the
3221    // shared [`crate::render::require_valid_dns_1123_label`] gate the
3222    // peer name axes each land on.
3223    crate::render::require_valid_dns_1123_label(
3224        affinity,
3225        || AplicacaoError::PlacementAffinityEmpty,
3226        |reason| AplicacaoError::PlacementAffinityInvalid {
3227            affinity: affinity.to_string(),
3228            reason,
3229        },
3230    )
3231}
3232
3233/// Reject `:placement :shard-key` extractor expressions whose shape can
3234/// never legitimately drive the future M4 Akka-style cluster-sharding
3235/// reconciler's hash-extractor pass. Maps the per-byte / length checks
3236/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
3237/// diagnostic is self-locating (the offending `:shard-key` value is
3238/// named verbatim alongside the parser-shaped reason) and the author can
3239/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
3240/// edit.
3241///
3242/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
3243/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
3244/// expression naming the message property to hash on. The realistic
3245/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
3246/// property name; `$tenantId` — Akka entity-id placeholder;
3247/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
3248/// `${tenant}` — interpolation-style template) all sit in the printable
3249/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
3250/// multi-line blob landing in `:shard-key`, an embedded space from a
3251/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
3252/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
3253/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
3254/// check and the failure surfaces at the future M4 reconciler's hash
3255/// pass as a runtime extractor-evaluation error far from the source
3256/// `caixa.lisp`, with no field naming which member's `:shard-key`
3257/// carried the offending value.
3258///
3259/// The contract — the printable ASCII single-token intersection-floor
3260/// every Akka-style entity-id extractor implementation admits:
3261///
3262///   - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
3263///     peer DNS-1123-label-shaped `:placement :affinity` /
3264///     `:placement :clusters` identifier axes; realistic shard-keys sit
3265///     well under 32 bytes, the cap surfaces paste-from-doc multi-line
3266///     blob footguns at validate time;
3267///   - every byte in the printable ASCII range `0x21..=0x7E` —
3268///     rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
3269///     `"$tenantId\n"` from paste-from-aligned-doc /
3270///     paste-from-shell-heredoc), control characters (`\x00..\x1F`,
3271///     `\x7F` — the canonical "embedded null from a copy-paste-binary
3272///     footgun"), and non-ASCII bytes (`"$tenàntId"` —
3273///     un-Punycode-encoded IDN that round-trips inconsistently across
3274///     NFC/NFD normalization).
3275///
3276/// The accepted set is broader than the DNS-1123 label floor the peer
3277/// `:placement :clusters` / `:placement :affinity` axes use because the
3278/// `:shard-key` value is not a K8s `metadata.name` / label-selector
3279/// landing site; it's an extractor expression the future Akka-style
3280/// reconciler reads as a property reference. The realistic forms
3281/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
3282/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
3283/// but every Akka-style entity-id extractor parses. The
3284/// printable-ASCII-token floor accepts every shape any such extractor
3285/// would accept while rejecting the cross-implementation footguns
3286/// (whitespace breaks token boundaries; non-ASCII round-trips
3287/// inconsistently across YAML emitters and NFC/NFD normalization;
3288/// control characters silently corrupt the next read).
3289///
3290/// Until this gate landed `validate_placement` only refused the
3291/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
3292/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
3293/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
3294/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
3295/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
3296/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
3297/// control character from paste-from-binary, the 64-byte over-cap
3298/// paste-from-doc multi-line slug) silently passed validate. The future
3299/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
3300/// would then surface the malformed value either as a runtime
3301/// extractor-evaluation error (whitespace breaks the extractor's token
3302/// boundary, no match) or as a silently-different shard assignment
3303/// across YAML emitters (non-ASCII normalizes differently between the
3304/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
3305/// parser, the same entity ID maps to two distinct shards on a
3306/// re-render). Lifting the shape gate to caixa-build time makes the
3307/// extractor-floor invariant a structural property of every validated
3308/// `Placement`: every `Sharded` placement past `validate_placement` has
3309/// a `:shard-key` the future M4 reconciler can hash without
3310/// re-validating at the runtime layer.
3311///
3312/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
3313/// [`AplicacaoError::ContratoSubjectInvalid`] /
3314/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
3315/// on the peer `:contratos` payload axes — each lifts the
3316/// runtime-side parser's intersection-floor to a caixa-build-time gate,
3317/// closing the canonical "this passed validate but the runtime parser
3318/// rejected it" surprise.
3319fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
3320    // Empty is gated separately at the call site via the more
3321    // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
3322    // re-checking here keeps the predicate usable from any future call
3323    // site (the M4 CR materializer's per-shard-key validator) without
3324    // an empty-check footgun.
3325    if key.is_empty() {
3326        return Err(AplicacaoError::ShardedKeyEmpty);
3327    }
3328    if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
3329        return Err(AplicacaoError::ShardKeyInvalid {
3330            shard_key: key.to_string(),
3331            reason: format!(
3332                "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
3333                 (got {} bytes; realistic Akka-style entity-id extractor expressions \
3334                 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
3335                 well under 32 bytes, this length suggests a paste-from-doc \
3336                 multi-line blob landed in `:shard-key` instead of a single-token \
3337                 extractor expression)",
3338                key.len()
3339            ),
3340        });
3341    }
3342    for &b in key.as_bytes() {
3343        if (0x21..=0x7E).contains(&b) {
3344            continue;
3345        }
3346        let reason = if b == b' ' {
3347            "contains a space (Akka-style entity-id extractor expressions are \
3348             single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
3349             whitespace breaks the extractor's token boundary at the runtime layer, \
3350             and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
3351             a multi-token blob in one `:shard-key` slot)"
3352                .to_string()
3353        } else if b == b'\t' {
3354            "contains a tab character (paste-from-aligned-doc footgun; the \
3355             Akka-style entity-id extractor reads `:shard-key` as a single-token \
3356             reference, embedded whitespace breaks the token boundary at the \
3357             runtime hash-extractor pass)"
3358                .to_string()
3359        } else if b == b'\n' || b == b'\r' {
3360            format!(
3361                "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
3362                 paste-from-multiline-doc footgun; the Akka-style entity-id \
3363                 extractor reads `:shard-key` as a single-token reference, embedded \
3364                 newlines either truncate the value at the YAML emitter layer or \
3365                 break the token boundary at the runtime hash-extractor pass)"
3366            )
3367        } else if b < 0x20 || b == 0x7F {
3368            format!(
3369                "contains control character 0x{b:02x} (the canonical \
3370                 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
3371                 control characters silently corrupt round-trip serialization \
3372                 across YAML emitters and break the runtime hash-extractor's \
3373                 single-token parser)"
3374            )
3375        } else {
3376            format!(
3377                "contains non-ASCII byte 0x{b:02x} (the canonical \
3378                 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
3379                 inconsistently across NFC/NFD normalization on APFS / ext4 / \
3380                 across YAML emitter implementations — the same entity ID can \
3381                 silently map to two distinct shards on a re-render. Use a \
3382                 printable-ASCII extractor expression like `tenantId`, \
3383                 `$tenantId`, or `metadata.tenantId`)"
3384            )
3385        };
3386        return Err(AplicacaoError::ShardKeyInvalid {
3387            shard_key: key.to_string(),
3388            reason,
3389        });
3390    }
3391    Ok(())
3392}
3393
3394/// Reject `:contratos :de` / `:contratos :para` values whose shape
3395/// can never legitimately match a validated `:membros :caixa`. Thin
3396/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
3397/// shared parser-shaped reason into the
3398/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
3399/// diagnostic is self-locating (which slot — `:de` or `:para` — and
3400/// the offending value verbatim) and the author can grep their
3401/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
3402/// one edit.
3403///
3404/// Until this gate landed an empty or DNS-1123-malformed `:de` /
3405/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
3406/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
3407/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
3408/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
3409/// un-Punycode-encoded IDN) silently passed the per-axis check and
3410/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
3411/// membership lookup — diagnostic-framed as "this caixa is not in
3412/// `:membros`" when the root cause is "this `:de` value is not a
3413/// well-shaped Servico-name identifier and could never legitimately
3414/// match any validated member". Because every `:membros :caixa` is
3415/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
3416/// `names` HashSet structurally never contains an empty / malformed
3417/// string, so the membership lookup arm misframes every empty /
3418/// malformed input. Lifting the shape arm ahead of the lookup
3419/// preserves the legitimate `ContratoMemberMissing` arm (a
3420/// well-shaped `:de` that simply isn't in `:membros` — a phantom
3421/// reference) while routing every structurally-impossible-to-match
3422/// input through the narrower self-locating shape diagnostic.
3423///
3424/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
3425/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
3426/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
3427/// to land on the canonical [`crate::render::is_dns_1123_label`]
3428/// floor. The `slot: &'static str` field carries the kebab-case
3429/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
3430/// per-callback-slot diagnostic shape and the
3431/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
3432/// (85f102c) cross-list-tag pattern.
3433fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
3434    // Routes through the shared
3435    // [`crate::render::require_valid_dns_1123_label`] gate the peer
3436    // name axes each land on. The `slot: &'static str` field flows
3437    // through both error variants so the diagnostic names which
3438    // per-edge axis (`:de` vs `:para`) the offending value came from.
3439    crate::render::require_valid_dns_1123_label(
3440        caixa,
3441        || AplicacaoError::ContratoCaixaEmpty { slot },
3442        |reason| AplicacaoError::ContratoCaixaInvalid {
3443            slot,
3444            caixa: caixa.to_string(),
3445            reason,
3446        },
3447    )
3448}
3449
3450/// Reject `:entrada :para` values whose shape can never legitimately
3451/// match a validated `:membros :caixa`. Thin wrapper around
3452/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
3453/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
3454/// variant, so the diagnostic is self-locating (the offending
3455/// `:entrada :para` value is named verbatim) and the author can grep
3456/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
3457///
3458/// Until this gate landed an empty or DNS-1123-malformed `:entrada
3459/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
3460/// ADR typo, `:para "my_cart"` the Python-module-name leak,
3461/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
3462/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
3463/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
3464/// silently passed the per-axis check and surfaced as
3465/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
3466/// — diagnostic-framed as "this caixa is not in `:membros`" when the
3467/// root cause is "this `:entrada :para` value is not a well-shaped
3468/// Servico-name identifier and could never legitimately match any
3469/// validated member". Because every `:membros :caixa` is shape-
3470/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
3471/// `HashSet` structurally never contains an empty / malformed string,
3472/// so the membership lookup arm misframes every empty / malformed
3473/// input. Lifting the shape arm ahead of the lookup preserves the
3474/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
3475/// simply isn't in `:membros` — a phantom reference) while routing
3476/// every structurally-impossible-to-match input through the narrower
3477/// self-locating shape diagnostic.
3478///
3479/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
3480/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
3481/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
3482/// fourth and last Aplicacao-level Servico-name reference axis to
3483/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
3484/// No `slot: &'static str` field because there is only one axis
3485/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
3486/// the simpler shape mirrors [`validate_membro_caixa`] and
3487/// [`validate_placement_cluster`].
3488fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
3489    // Empty is gated separately at the call site for a self-locating
3490    // diagnostic; re-checking here keeps the predicate usable from any
3491    // future call site (the M4 CR materializer's per-`:entrada`
3492    // validator) without an empty-check footgun. Routes through the
3493    // shared [`crate::render::require_valid_dns_1123_label`] gate the
3494    // peer name axes each land on.
3495    crate::render::require_valid_dns_1123_label(
3496        para,
3497        || AplicacaoError::EntradaParaEmpty,
3498        |reason| AplicacaoError::EntradaParaInvalid {
3499            para: para.to_string(),
3500            reason,
3501        },
3502    )
3503}
3504
3505/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
3506/// would refuse at admission time. The contract — exactly the regex
3507/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
3508/// and `HTTPRoute.spec.hostnames[]`,
3509/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
3510/// (max length 253; per-label max length 63):
3511///
3512///   - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
3513///     uppercase, no underscore, no Unicode/IDN — IDN must be
3514///     pre-encoded as Punycode `xn--…` by the author);
3515///   - exactly one optional leading wildcard label (`*.`); a wildcard
3516///     in any non-leading label position is rejected;
3517///   - each `.`-separated label is 1..=63 bytes, with non-hyphen
3518///     alphanumeric at both boundaries (no `-foo`, no `foo-`);
3519///   - total length 1..=253 bytes;
3520///   - no IPv4 literal (Gateway API forbids IP literals);
3521///   - no scheme (`https://`, `http://`), no port (`:8080`), no
3522///     whitespace, no path (`/`).
3523///
3524/// Lifted as a typed gate (rather than an inline cascade in
3525/// `validate()`) so the contract lives in one place — every future
3526/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3527/// materializer's host validator, the future per-`:entrada` SAN
3528/// emission for cert-manager Certificates, the multi-`:entrada`
3529/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
3530/// for the same predicate, not its own. Same compounding shape as
3531/// `is_canonical_rate_limit_window` (808017c) and
3532/// [`WitTarget::label`] (previously the free `contrato_target_label`
3533/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
3534/// per-variant label match is compiler-checked-exhaustive).
3535///
3536/// The diagnostic carries the offending `host:` verbatim plus a
3537/// parser-shaped `reason:` naming the specific violation, so the
3538/// author can grep their caixa.lisp for `:host "<host>"` and fix it
3539/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
3540/// (9888b13).
3541fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
3542    // Empty is already gated by `EmptyEntradaHost` at the call site;
3543    // re-checking here keeps the predicate usable from any future
3544    // call site (M4 CR materializer) without an empty-check footgun.
3545    if host.is_empty() {
3546        return Err(AplicacaoError::EmptyEntradaHost);
3547    }
3548    if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
3549        return Err(AplicacaoError::EntradaHostInvalid {
3550            host: host.to_string(),
3551            reason: format!(
3552                "exceeds Gateway API v1 Hostname max length of {cap} bytes \
3553                 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
3554                host.len(),
3555                cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
3556            ),
3557        });
3558    }
3559    if host.contains("://") {
3560        return Err(AplicacaoError::EntradaHostInvalid {
3561            host: host.to_string(),
3562            reason: "must not carry a scheme (drop the `https://` or `http://` prefix; \
3563                     Gateway API takes the bare hostname)"
3564                .to_string(),
3565        });
3566    }
3567    if host.contains('/') {
3568        return Err(AplicacaoError::EntradaHostInvalid {
3569            host: host.to_string(),
3570            reason: "must not carry a path (drop the `/…` suffix; Gateway API path \
3571                     matching is in `:entrada :paths`)"
3572                .to_string(),
3573        });
3574    }
3575    // After the `://` scheme-prefix and `/` path arms have ruled out the
3576    // two `:`-bearing shapes the Gateway API actively rejects with
3577    // location-shaped diagnostics, any remaining `:` in the host body is
3578    // either the canonical "I put the port in the `:host` slot"
3579    // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
3580    // slot lives one axis away on the same `:entrada` block) or an
3581    // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
3582    // Hostname forbids identically to the IPv4-literal arm below. Both
3583    // shapes silently fell through the `://` and `/` arms before this
3584    // lift and surfaced as a deep `label "<rest>:<port>" contains
3585    // invalid character ':'` diagnostic from the per-byte loop near the
3586    // bottom of this predicate, which named the offending byte but not
3587    // the canonical authoring fix — for the port case the author has to
3588    // know the `:entrada` block carries a separate `:port u16` slot
3589    // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
3590    // move the value over; for the IPv6 case the author has to know
3591    // Gateway API v1 forbids IP literals across the board. The contract
3592    // doc-comment above already promises "no port (`:8080`)" verbatim
3593    // in the rejected-shape enumeration but the predicate's
3594    // implementation refused the `:` only as a side-effect of the
3595    // per-label `[a-z0-9-]` character-class loop; this arm brings the
3596    // implementation in line with the documented contract by surfacing
3597    // the canonical fix at the top-level shape gate, peer with how the
3598    // `://` arm names the scheme prefix and the `/` arm names the
3599    // `:entrada :paths` axis. Same compounding trajectory the recent
3600    // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
3601    // — the typed slot's rejected set matches the apiserver's rejected
3602    // set, structurally, with a self-locating diagnostic at the
3603    // offending axis instead of a deep parser-shape leak.
3604    if host.contains(':') {
3605        return Err(AplicacaoError::EntradaHostInvalid {
3606            host: host.to_string(),
3607            reason: "must not contain `:` (the port belongs in the `:entrada :port` \
3608                     slot — a separate `u16` axis on the same `:entrada` block, \
3609                     defaulting to 8080 — not in the host body; drop the `:<port>` \
3610                     suffix and author the bare hostname. If you intended an IPv6 \
3611                     literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
3612                     Hostname forbids IP literals identically to the IPv4-literal \
3613                     arm — use a DNS name)"
3614                .to_string(),
3615        });
3616    }
3617    // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
3618    // predicate — the same single source of truth every peer
3619    // ASCII-whitespace scan in caixa-core flows through: the four
3620    // typed-magnitude codec sites (`limits::parse_byte_size` backing
3621    // `:limits :memory`, `limits::parse_duration` backing `:limits
3622    // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
3623    // `aplicacao::rate_limit_codec::parse` backing `:politicas
3624    // :rate-limit`) and the shared duration codec
3625    // (`supervisor::duration_codec::parse`) backing `:supervisor
3626    // :restart-window` / `:politicas :timeout` / `:politicas
3627    // :circuit-breaker :window`. This landing closes the last string-typed
3628    // slot in caixa-core still calling `.bytes().any(|b|
3629    // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
3630    // across every typed slot now shares one predicate, so a future
3631    // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
3632    // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
3633    // deliberately excluded from the peer non-ASCII predicate) can
3634    // extend at this shared site in one edit rather than seven
3635    // independent scans diverging over time. Naming the offending byte
3636    // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
3637    // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
3638    // the offending byte verbatim" discipline every peer codec site
3639    // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
3640    // / `supervisor.rs:823` / `aplicacao.rs:1640`).
3641    if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
3642        return Err(AplicacaoError::EntradaHostInvalid {
3643            host: host.to_string(),
3644            reason: format!(
3645                "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
3646                 Hostname is a single-token DNS name — leading, trailing, \
3647                 or embedded whitespace breaks the K8s apiserver's Hostname \
3648                 regex at admission time; the paste-from-aligned-doc / \
3649                 paste-from-shell-history / paste-from-CSV footgun silently \
3650                 lands a multi-token blob in `:entrada :host`. Strip every \
3651                 whitespace byte and author the bare hostname — space \
3652                 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
3653                 refuse identically)"
3654            ),
3655        });
3656    }
3657    // Peer of the ASCII-whitespace scan above: route the non-ASCII
3658    // subset of Unicode `White_Space` through the shared
3659    // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
3660    // single source of truth every peer non-ASCII-whitespace scan in
3661    // caixa-core flows through: `limits::parse_byte_size` (`:limits
3662    // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
3663    // `limits::parse_millicores` (`:limits :cpu`),
3664    // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
3665    // and `supervisor::duration_codec::parse` (`:supervisor
3666    // :restart-window` / `:politicas :timeout` / `:politicas
3667    // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
3668    // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
3669    // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
3670    // paste-from-web-doc), or an EM-SPACE-split host
3671    // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
3672    // survived this predicate's ASCII byte-scan (none of the UTF-8
3673    // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
3674    // `u8::is_ascii_whitespace`), then landed on the per-label
3675    // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
3676    // predicate with the generic `label "…" must start and end with an
3677    // alphanumeric` diagnostic — a "far from source at build-time"
3678    // leak that names the label-shape violation but not the
3679    // paste-from-typography origin the author actually needs to fix.
3680    // Peer with the four codec sites the 1b75b38 landing pinned: the
3681    // typed slot's diagnostic axis names the offending codepoint
3682    // (`U+XXXX`) verbatim rather than laundering the value through a
3683    // downstream label-shape arm, so the author can grep their
3684    // caixa.lisp for the invisible codepoint at the surfaced position
3685    // rather than eyeball a multi-byte host for embedded NBSP / LINE
3686    // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
3687    // discipline the peer ASCII-whitespace arm (720ac3b) carries:
3688    // drift between any two typed-slot sites' non-ASCII-whitespace
3689    // rejection set becomes a single-edit fix at the shared predicate
3690    // rather than N independent inline scans diverging over time, and
3691    // a future stricter classification (BOM `\u{FEFF}` / ZWSP
3692    // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
3693    // `char::is_whitespace`" class the peer non-ASCII predicate's
3694    // doc-comment names as the follow-up trajectory) extends at the
3695    // shared predicate in one edit rather than seven.
3696    if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
3697        return Err(AplicacaoError::EntradaHostInvalid {
3698            host: host.to_string(),
3699            reason: format!(
3700                "contains non-ASCII Unicode whitespace character {ch:?} \
3701                 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
3702                 single-token DNS name limited to `[a-z0-9-]` labels; \
3703                 the paste-from-typography footgun silently lands an \
3704                 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
3705                 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
3706                 `U+3000`, and every other member of the Unicode \
3707                 `White_Space` property outside the ASCII byte range) \
3708                 in `:entrada :host`, which the K8s apiserver's \
3709                 Hostname regex refuses at admission time far from the \
3710                 caixa.lisp source line. Strip every non-ASCII \
3711                 whitespace character and author the bare hostname \
3712                 with only ASCII bytes (write \"checkout.quero.cloud\" \
3713                 verbatim)",
3714                codepoint = ch as u32,
3715            ),
3716        });
3717    }
3718
3719    // Strip the optional single leading wildcard label *before* the
3720    // trailing-dot check so the bare `"*."` form surfaces the more
3721    // self-locating "wildcard without domain" diagnostic instead of
3722    // the generic "trailing dot" one.
3723    let (had_wildcard, rest) = match host.strip_prefix("*.") {
3724        Some(r) => (true, r),
3725        None => (false, host),
3726    };
3727    if had_wildcard && rest.is_empty() {
3728        return Err(AplicacaoError::EntradaHostInvalid {
3729            host: host.to_string(),
3730            reason: "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)".to_string(),
3731        });
3732    }
3733    if rest.contains('*') {
3734        return Err(AplicacaoError::EntradaHostInvalid {
3735            host: host.to_string(),
3736            reason: "wildcard `*` is allowed only as the first label (`*.example.com`); \
3737                     no inner or trailing `*` labels"
3738                .to_string(),
3739        });
3740    }
3741    if rest.ends_with('.') {
3742        return Err(AplicacaoError::EntradaHostInvalid {
3743            host: host.to_string(),
3744            reason: "must not have a trailing `.` (Gateway API hostnames are not \
3745                     fully-qualified with a root dot; the apiserver regex rejects \
3746                     trailing dots)"
3747                .to_string(),
3748        });
3749    }
3750
3751    // Reject pure IPv4 literals: four dot-separated labels, every
3752    // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
3753    // literals as Hostnames.
3754    let labels: Vec<&str> = rest.split('.').collect();
3755    if labels.len() == 4
3756        && labels
3757            .iter()
3758            .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
3759    {
3760        return Err(AplicacaoError::EntradaHostInvalid {
3761            host: host.to_string(),
3762            reason: "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
3763                     literals; use a DNS name)"
3764                .to_string(),
3765        });
3766    }
3767
3768    // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
3769    // hyphen, with non-hyphen at both boundaries.
3770    for label in &labels {
3771        if label.is_empty() {
3772            return Err(AplicacaoError::EntradaHostInvalid {
3773                host: host.to_string(),
3774                reason: "has an empty label (consecutive `..` or a leading `.`)".to_string(),
3775            });
3776        }
3777        if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
3778            return Err(AplicacaoError::EntradaHostInvalid {
3779                host: host.to_string(),
3780                reason: format!(
3781                    "label {label:?} exceeds DNS-1123 label max length of \
3782                     {cap} bytes (got {} bytes)",
3783                    label.len(),
3784                    cap = crate::render::DNS_1123_LABEL_MAX_LEN,
3785                ),
3786            });
3787        }
3788        let bytes = label.as_bytes();
3789        if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
3790            return Err(AplicacaoError::EntradaHostInvalid {
3791                host: host.to_string(),
3792                reason: format!(
3793                    "label {label:?} must start and end with an alphanumeric \
3794                     (no leading or trailing `-`)"
3795                ),
3796            });
3797        }
3798        for &b in bytes {
3799            let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
3800            if !valid {
3801                let msg = if b.is_ascii_uppercase() {
3802                    format!(
3803                        "label {label:?} contains uppercase character {ch:?} \
3804                         (Gateway API hostnames are lowercase-only; use {lower:?})",
3805                        ch = b as char,
3806                        lower = label.to_ascii_lowercase()
3807                    )
3808                } else if b == b'_' {
3809                    format!(
3810                        "label {label:?} contains `_` (Gateway API hostnames \
3811                         allow only `[a-z0-9-]`; use `-` instead)"
3812                    )
3813                } else {
3814                    format!(
3815                        "label {label:?} contains invalid character {ch:?} \
3816                         (Gateway API hostnames allow only `[a-z0-9-]`)",
3817                        ch = b as char
3818                    )
3819                };
3820                return Err(AplicacaoError::EntradaHostInvalid {
3821                    host: host.to_string(),
3822                    reason: msg,
3823                });
3824            }
3825        }
3826    }
3827    Ok(())
3828}
3829
3830/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
3831/// would refuse at admission time. Thin wrapper around
3832/// [`crate::render::is_gateway_api_http_path`] that maps the shared
3833/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
3834/// variant, preserving the more self-locating
3835/// [`AplicacaoError::EntradaPathEmpty`] /
3836/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
3837/// path fails those narrower invariants first.
3838///
3839/// The contract is the canonical HTTP-path grammar — `1..=
3840/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
3841/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
3842/// whitespace/control/non-ASCII bytes — shared with the
3843/// `:contratos :endpoint` axis through the lifted predicate so drift
3844/// between either landing site and the K8s apiserver-side
3845/// HTTPPathMatch.value OpenAPI schema is a build error visible at
3846/// the predicate, not a per-renderer "this passed validate but failed
3847/// admission" surprise. The diagnostic carries the offending `path:`
3848/// verbatim plus a parser-shaped `reason:` naming the specific
3849/// violation, so the author can grep their caixa.lisp for `:paths`
3850/// and fix it in one edit. Same diagnostic shape as
3851/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
3852/// axis.
3853fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
3854    // Empty and missing-leading-`/` are already gated at the call
3855    // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
3856    // checking here keeps the per-axis narrower diagnostics in force
3857    // when the predicate is reached directly (and `is_gateway_api_http_path`
3858    // itself defends against `bytes[0]`-style indexing on empty
3859    // input).
3860    if path.is_empty() {
3861        return Err(AplicacaoError::EntradaPathEmpty);
3862    }
3863    if !path.starts_with('/') {
3864        return Err(AplicacaoError::EntradaPathNotAbsolute {
3865            path: path.to_string(),
3866        });
3867    }
3868    crate::render::is_gateway_api_http_path(path).map_err(|reason| {
3869        AplicacaoError::EntradaPathInvalid {
3870            path: path.to_string(),
3871            reason,
3872        }
3873    })
3874}
3875
3876mod rate_limit_codec {
3877    // `Duration` is no longer named here — the codec routes through
3878    // the substrate primitive [`super::RateLimitUnit::window_from_suffix`]
3879    // (parse arm, `&str → Duration`) and [`super::RateLimit::canonical_unit`]
3880    // (render arm, `Duration → RateLimitUnit`) typed dispatches that carry
3881    // the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection on the
3882    // closed-set enum's arm-table rather than through vestigial free-helper
3883    // delegates.
3884    use super::{RateLimit, RateLimitUnit};
3885    use serde::{Deserialize, Deserializer, Serializer};
3886
3887    pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
3888        match v {
3889            Some(rl) => s.serialize_str(&render(*rl)),
3890            None => s.serialize_none(),
3891        }
3892    }
3893
3894    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
3895        let opt: Option<String> = Option::deserialize(d)?;
3896        match opt {
3897            None => Ok(None),
3898            Some(s) => parse(&s).map(Some).map_err(serde::de::Error::custom),
3899        }
3900    }
3901
3902    fn parse(s: &str) -> Result<RateLimit, String> {
3903        // Whitespace-rejection arm — peer with the leading-`+`
3904        // (`"+100/s"`) and leading-zero (`"0100/s"`) arms below on the
3905        // same canonical-form render-determinism axis. Until this gate
3906        // landed the parser silently tolerated leading / trailing /
3907        // internal whitespace via the top-level `s.trim()` and the
3908        // per-part `rate_str.trim()` / `unit.trim()` calls, so every
3909        // whitespace-carrying shape (`" 100/s"`, `"100/s "`,
3910        // `"100 /s"`, `"100/ s"`, `"100 / s"`, `"100/s\n"`,
3911        // `"\t100/s"`) parsed to the same `RateLimit { 100, 1s }` and
3912        // serde silently round-tripped to `"100/s"` on the next emit
3913        // (a *different* canonical string) — breaking the THEORY.md
3914        // Part V render-determinism contract on the same
3915        // canonical-form-drift axis the leading-`+` arm below (the
3916        // 4eeae98 predecessor) and the leading-zero arm below (the
3917        // 4f46830 predecessor) already close.
3918        //
3919        // The canonical author shape is `<integer>/<s|m|h>` with no
3920        // whitespace bytes anywhere — every string [`render`] emits
3921        // carries none, so the parser's accepted set must match for
3922        // serialize / deserialize to round-trip losslessly. This gate
3923        // makes the pre-existing `s.trim()` / `rate_str.trim()` /
3924        // `unit.trim()` calls below strict no-ops on the accepted set
3925        // (every byte-position match they would perform is now already
3926        // trimmed away by the accepted set itself), while the arm
3927        // surfaces every rejected whitespace-carrying shape with a
3928        // self-locating diagnostic naming the offending byte and the
3929        // canonical form the author intended, peer with every prior
3930        // canonical-form-drift arm on this codec.
3931        //
3932        // Routed through the lifted
3933        // [`crate::render::find_ascii_whitespace_byte`] predicate — the
3934        // same source of truth the four peer typed-magnitude codec
3935        // sites (`limits::parse_byte_size`, `limits::parse_duration`,
3936        // `limits::parse_millicores`, `supervisor::duration_codec`)
3937        // share. `u8::is_ascii_whitespace()` at the predicate covers
3938        // the five WhatWG-conformant ASCII whitespace bytes (space,
3939        // tab, LF, FF, CR); the "single lifted predicate" discipline
3940        // the peer non-ASCII arm below carries on the strictly-
3941        // complementary Unicode `White_Space` class extends here to
3942        // the ASCII byte set as well.
3943        if let Some(b) = crate::render::find_ascii_whitespace_byte(s) {
3944            return Err(format!(
3945                "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
3946                 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
3947                 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
3948                 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
3949                 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
3950                 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
3951                 on first serialize — breaking the THEORY.md Part V render-determinism \
3952                 contract every typed slot carries. Strip every whitespace byte (write \
3953                 `\"100/s\"` verbatim)"
3954            ));
3955        }
3956        // Non-ASCII Unicode `White_Space` arm — the strictly-
3957        // complementary class the ASCII arm above cannot see.
3958        // `str::trim` at the top of every peer codec uses
3959        // `char::is_whitespace` (Unicode `White_Space`, strictly
3960        // wider than the ASCII byte set), so an NBSP (`\u{00A0}`) /
3961        // LINE SEPARATOR (`\u{2028}`) / EM-SPACE (`\u{2003}`)
3962        // survives the byte-scan (its UTF-8 bytes are not in
3963        // `is_ascii_whitespace`), gets silently stripped by the
3964        // top-level `s.trim()` below, and the value round-trips
3965        // through `render` to a *different* canonical form
3966        // (`\"100/s\"`) on next emit — breaking the THEORY.md Part V
3967        // render-determinism contract every typed slot carries.
3968        // Closed here (`:politicas :rate-limit`) and at the three
3969        // peer codec sites (`limits::parse_byte_size`,
3970        // `limits::parse_duration`, `supervisor::duration_codec`)
3971        // through the shared
3972        // [`crate::render::find_non_ascii_whitespace_char`] predicate
3973        // — the "single lifted predicate across all four codec sites
3974        // in one follow-up run" the 24a8ad4 commit body's `Forward
3975        // compounding` bullet named as the next compounding step.
3976        if let Some(ch) = crate::render::find_non_ascii_whitespace_char(s) {
3977            return Err(format!(
3978                "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
3979                 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
3980                 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
3981                 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
3982                 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
3983                 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
3984                 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
3985                 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
3986                 silently strips it at parse entry, and the value round-trips through \
3987                 `render` to a *different* canonical form (`\"100/s\"`) on first \
3988                 serialize — breaking the THEORY.md Part V render-determinism contract \
3989                 every typed slot carries. Strip every non-ASCII whitespace character \
3990                 (write `\"100/s\"` verbatim with only ASCII bytes)",
3991                cp = ch as u32
3992            ));
3993        }
3994        let s = s.trim();
3995        let (rate_str, unit) = s
3996            .split_once('/')
3997            .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
3998        let rate_trim = rate_str.trim();
3999        // The canonical authoring form for `:politicas :rate-limit` is
4000        // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
4001        // non-negative integer with no decimal point and no leading
4002        // sign, so the parser's accepted set must match for
4003        // serialize/deserialize to round-trip without canonical-form
4004        // drift. Until this gate landed the parser accepted any
4005        // `u32::from_str`-shaped magnitude — and current Rust
4006        // `u32::from_str` permissively accepts a leading `+` (`"+100"`
4007        // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
4008        // serde silently round-tripped to `"100/s"` on the next emit
4009        // (a *different* canonical string) — breaking the THEORY.md
4010        // Part V render-determinism contract on the fifth typed-codec
4011        // surface in caixa-core (peer with the four duration codecs the
4012        // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
4013        // already covered: `supervisor::duration_codec` backing three
4014        // typed-duration slots, `limits::parse_duration` backing
4015        // `:limits :wall-clock`, `limits::parse_byte_size` backing
4016        // `:limits :memory`). The fractional / decimal-shaped sibling
4017        // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
4018        // existing rejection arm, but the diagnostic is value-laundered
4019        // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
4020        // doesn't name the canonical-form remediation or the round-trip
4021        // drift the next emit would produce); this gate lifts the
4022        // fractional arm onto the same canonical-form diagnostic the
4023        // peer codecs carry.
4024        //
4025        // Strict canonical form: every byte of the magnitude is an
4026        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
4027        // inputs the gate distinguishes "non-canonical-but-numeric"
4028        // (parses as f64 or i64 — surfaced with a self-locating
4029        // diagnostic naming the canonical authoring form and the
4030        // round-trip drift the rejected shape would produce on first
4031        // serialize) from "garbage" (parses as neither — surfaced with
4032        // the existing narrower `"not a u32"` wording so its
4033        // diagnostic shape remains stable for the parser-shape footgun
4034        // case).
4035        //
4036        // Routed through the lifted
4037        // [`crate::render::is_digit_only_magnitude`] predicate — the
4038        // same source of truth the four peer typed-magnitude codec
4039        // sites share.
4040        let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
4041        if !digit_only {
4042            let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
4043            if numeric {
4044                return Err(format!(
4045                    "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
4046                     canonical authoring form for `:politicas :rate-limit` is \
4047                     `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4048                     with no decimal point and no leading `+` / `-` sign. A fractional / \
4049                     signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
4050                     through `render` to a *different* canonical form (`\"1/s\"`, \
4051                     `\"100/s\"`, parser-reject) on first serialize — breaking the \
4052                     THEORY.md Part V render-determinism contract every typed slot \
4053                     carries. Pick an integer rate that fits the desired window \
4054                     (write `\"6000/m\"` instead of `\"1.66/s\"`)"
4055                ));
4056            }
4057            return Err(format!("rate-limit rate {rate_str:?} not a u32"));
4058        }
4059        // Leading-zero arm — peer with the prior `"+100/s"` arm above
4060        // (4eeae98's predecessor) on the same canonical-form
4061        // render-determinism axis. The digit-only gate accepts
4062        // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
4063        // them losslessly (= 100, 0, 7), but `render` emits the
4064        // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
4065        // a *different* canonical string on the next emit, breaking
4066        // the THEORY.md Part V render-determinism contract the same
4067        // way `"+100/s"` did before the leading-`+` arm landed. The
4068        // single-byte magnitude `"0"` itself round-trips losslessly
4069        // through `render` (`render(0)` emits `"0/s"`) — the
4070        // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
4071        // what refuses rate-zero authoring, so `"0/s"` stays in the
4072        // accepted set at this codec layer and the diagnostic
4073        // partitioning between canonical-form drift (this arm) and
4074        // semantic-zero (the downstream gate) remains stable.
4075        // Peer with the future leading-zero arms on the three peer
4076        // typed-magnitude codecs the trajectory acknowledges:
4077        // `supervisor::duration_codec`, `limits::parse_duration`,
4078        // `limits::parse_byte_size` — each carries the same
4079        // canonical-form-drift class today; this gate lands the
4080        // discipline on the fourth typed-magnitude codec in
4081        // caixa-core first because the peer `"+100/s"` arm above is
4082        // the closest predecessor on the trajectory.
4083        //
4084        // Routed through the lifted
4085        // [`crate::render::is_leading_zero_padded_magnitude`]
4086        // predicate — the same source of truth the four peer
4087        // typed-magnitude codec sites share.
4088        if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
4089            return Err(format!(
4090                "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
4091                 canonical authoring form for `:politicas :rate-limit` is \
4092                 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4093                 with no leading-zero padding on the magnitude. A leading-zero magnitude \
4094                 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
4095                 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
4096                 first serialize — breaking the THEORY.md Part V render-determinism \
4097                 contract every typed slot carries. Strip the leading zeros (write \
4098                 `\"100/s\"` instead of `\"0100/s\"`)"
4099            ));
4100        }
4101        // The digit-only gate guarantees every byte is `[0-9]`, and
4102        // the leading-zero arm above guarantees the magnitude is
4103        // either the single byte `"0"` or starts with `[1-9]`, so
4104        // the only way `u32::from_str` can fail here is overflow
4105        // (the magnitude exceeds `u32::MAX`). Surface that with an
4106        // overflow-shaped wording so the diagnostic names the
4107        // offending magnitude verbatim rather than collapsing onto
4108        // the non-canonical arm. Same shape
4109        // `supervisor::duration_codec` (1c55a2a) carries on the peer
4110        // duration-codec axis.
4111        let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
4112            format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
4113        })?;
4114        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives on
4115        // the closed-set typed enum [`super::RateLimitUnit`]; this parse
4116        // arm reads the `&str → Duration` projection through the
4117        // substrate primitive [`super::RateLimitUnit::window_from_suffix`]
4118        // (a two-step typed dispatch composing [`super::RateLimitUnit::from_suffix`]
4119        // with [`super::RateLimitUnit::window`]) rather than the vestigial
4120        // module-private `rate_limit_window_from_unit` free helper the
4121        // predecessor 61421a6 left as the last unlifted delegate on this
4122        // axis. One typed dispatch on the substrate primitive instead of
4123        // one runtime call through the free-helper delegate; the sole
4124        // production consumer of the `&str → Duration` axis (this parse
4125        // arm) now reaches for exactly one typed method on the closed-set
4126        // enum, sibling to the codec's render arm's
4127        // [`super::RateLimit::canonical_unit`] dispatch on the paired
4128        // `Duration → RateLimitUnit` axis and to the validate gate's
4129        // [`super::RateLimit::canonical_unit`] shape-probe on the
4130        // canonical-window axis. A future rate-limit-unit addition (a
4131        // `"d"` day suffix once Envoy's `rate_limit_action` grows
4132        // daily-bucket support, a `"ms"` sub-second window once
4133        // high-throughput per-edge policies come into scope per
4134        // MESH-COMPOSITION §III.2 #3) is one variant + one arm per method
4135        // on the closed-set enum, and the compiler enforces exhaustiveness
4136        // on every consumer's `match self` arms — this parse arm's
4137        // accepted-suffix set, the render arm's emitted-suffix set, the
4138        // validate gate's canonical-window set, and every future
4139        // per-`:contratos`-edge rate-limit-override overlay all pick it up
4140        // by construction.
4141        let unit = unit.trim();
4142        let window = RateLimitUnit::window_from_suffix(unit)
4143            .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
4144        Ok(RateLimit { rate, window })
4145    }
4146
4147    fn render(rl: RateLimit) -> String {
4148        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
4149        // module scope on the closed-set typed enum [`super::RateLimitUnit`];
4150        // this render arm reads the `Duration → RateLimitUnit` projection
4151        // through the substrate primitive [`super::RateLimit::canonical_unit`]
4152        // (returns `None` on every non-canonical window — the sub-second /
4153        // non-`{1, 60, 3600}` shapes the validate gate rejects), then
4154        // formats the returned typed enum through its
4155        // [`std::fmt::Display`] impl (which routes through
4156        // [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
4157        // the substrate primitive instead of one runtime `find_map`
4158        // walk through the free-helper delegate chain
4159        // [`super::rate_limit_window_unit`] (the vestigial free helper's
4160        // sole production consumer was this arm; every other consumer of
4161        // the `Duration → unit` axis — the validate gate below and the
4162        // future M4 per-Aplicacao Envoy config reconciler — now reads
4163        // the same typed method).
4164        //
4165        // A future rate-limit-unit addition (a `"d"` day suffix once
4166        // Envoy's `rate_limit_action` grows daily-bucket support) is
4167        // one variant + one arm per method on the closed-set enum, and
4168        // the compiler enforces exhaustiveness on every consumer's
4169        // `match self` arms — the codec's `parse` accepted-suffix set,
4170        // this render arm's emitted-suffix set, the validate gate's
4171        // canonical-window set, and every future per-`:contratos`-edge
4172        // rate-limit-override overlay all pick it up by construction.
4173        if let Some(unit) = rl.canonical_unit() {
4174            format!("{}/{unit}", rl.rate())
4175        } else {
4176            // Defensive fallback for non-canonical windows. Note:
4177            // [`AplicacaoSpec::validate_politicas`] rejects any
4178            // non-canonical `:rate-limit :window` via
4179            // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
4180            // a validated `RateLimit` never reaches this branch. The
4181            // emitted `<n>/<k>s` form is *not* round-trippable through
4182            // [`parse`] (which accepts only the closed-set
4183            // [`super::RateLimitUnit`] suffixes, not `<k>s` with an
4184            // explicit count) — the validate gate is what makes the
4185            // round-trip a structural property; this branch exists only
4186            // so a programmatic non-validated serialize doesn't panic.
4187            format!("{}/{}s", rl.rate(), rl.window().as_secs())
4188        }
4189    }
4190}
4191
4192// ── placement strategy ───────────────────────────────────────────────
4193
4194/// How the Aplicacao distributes across clusters. Three options:
4195///
4196/// - `SingleNode` — one cluster runs the app at a time; takeover on
4197///   death (Erlang/OTP distributed-app semantics).
4198/// - `Replicated` — every named cluster runs an instance (active-active).
4199/// - `Sharded` — entities distribute by hash key across clusters
4200///   (Akka cluster sharding).
4201#[derive(
4202    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
4203)]
4204pub enum PlacementStrategy {
4205    SingleNode,
4206    Replicated,
4207    Sharded,
4208}
4209
4210impl Default for PlacementStrategy {
4211    fn default() -> Self {
4212        Self::Replicated
4213    }
4214}
4215
4216impl PlacementStrategy {
4217    /// Exhaustive iteration surface for every consumer that reads the
4218    /// full closed-set (the future M4 admission-webhook's accepted-
4219    /// strategy listing in its rejection body, a future `feira app
4220    /// placement --list` CLI-side surfacing of the accepted arm-set,
4221    /// any future round-trip fuzz harness). A future variant addition
4222    /// (an `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint
4223    /// names as a trajectory item) extends this slice as a single edit
4224    /// and every consumer picks up the new entry by construction — the
4225    /// compiler-checked exhaustiveness on the sibling method `match`
4226    /// arms is the build-time guarantee that no arm forgets to grow.
4227    /// Same shape as the sibling closed-set typed enums'
4228    /// [`RateLimitUnit::ALL`] (6bce03d) and
4229    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
4230    /// surfaces — the third closed-set typed enum on the caixa surface
4231    /// to converge onto the same discipline.
4232    pub const ALL: &'static [Self] = &[Self::SingleNode, Self::Replicated, Self::Sharded];
4233
4234    /// Canonical camelCase-schema discriminator scalar this variant
4235    /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
4236    /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
4237    /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4238    /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
4239    /// every substrate consumer that dispatches on the strategy (the
4240    /// `lareira-fleet-programs` aggregator, the future `app-operator`
4241    /// reconciler, the M3 Adaptive compression pass) reads the same
4242    /// byte-string the `Serialize` derive emits — the pin test in
4243    /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
4244    /// asserts the two paths agree.
4245    #[must_use]
4246    pub const fn as_str(self) -> &'static str {
4247        match self {
4248            Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
4249            Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
4250            Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
4251        }
4252    }
4253
4254    /// Substrate-canonical reverse projection on the `:placement
4255    /// :estrategia` closed-set axis — parses the camelCase-schema
4256    /// discriminator scalar back to the typed variant, or `None` when
4257    /// `s` is outside the closed-set arm-string set [`Self::as_str`]
4258    /// emits. Dispatches on the same lifted
4259    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
4260    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4261    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] constants the
4262    /// [`Self::as_str`] emitter walks, so the parse and emit halves of
4263    /// the round-trip migrate through one caixa-core edit on any future
4264    /// arm addition (an `Anycast` mesh-anycast arm the MESH-COMPOSITION
4265    /// §II.5 hint names as a trajectory item lands one variant + one
4266    /// arm per method and the compiler enforces exhaustiveness on every
4267    /// consumer's `match self` arms).
4268    ///
4269    /// Prior to this lift the substrate carried only the forward
4270    /// `Self → &str` projection (the [`Self::as_str`] emitter, the
4271    /// [`std::fmt::Display`] impl routed through it, the `Serialize`
4272    /// derive that emits the same byte-string under
4273    /// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]) — every non-serde
4274    /// consumer that wanted to parse a wire-form strategy scalar had to
4275    /// re-inline a three-arm `match s { "SingleNode" => …, "Replicated"
4276    /// => …, "Sharded" => …, _ => … }` cascade that expressed no
4277    /// compile-time link back to the typed variant's canonical lifted
4278    /// constant. A future variant rename or a per-arm serde-attribute
4279    /// drift would silently split the wire byte-string one non-serde
4280    /// consumer parsed from the one the emitter wrote, with the
4281    /// failure surfacing at parse time far from the rebrand commit.
4282    ///
4283    /// Same closed-set-reverse-projection discipline the sibling
4284    /// [`crate::CaixaKind::from_wire`] (2aa6d23) and
4285    /// [`RateLimitUnit::from_suffix`] typed enums carry on the peer
4286    /// wire-side `str → Self` axes — extended onto the M3 mesh-primitive-
4287    /// defining `:placement :estrategia` closed-set axis, the third
4288    /// substrate-side closed-set typed enum to converge on the two-way
4289    /// `str ↔ Self` round-trip. Method-named `from_wire` (not `from_str`)
4290    /// to match the peer [`crate::CaixaKind::from_wire`] shape verbatim
4291    /// and side-step the [`std::str::FromStr`]-collision clippy
4292    /// (`clippy::should_implement_trait`) the plain `from_str` name
4293    /// carries; a future explicit [`std::str::FromStr`] impl can layer
4294    /// on top by delegating to this canonical arm-dispatch method.
4295    ///
4296    /// Returns `Option<Self>` (rather than `Result<Self, _>`) to match
4297    /// the sibling [`crate::CaixaKind::from_wire`] shape: the caller
4298    /// picks the diagnostic form appropriate for its use site — a
4299    /// future `feira app placement --set` CLI-side arg-parse that wants
4300    /// an `"unknown strategy: {s} (accepted: SingleNode, Replicated,
4301    /// Sharded)"` diagnostic builds one on top by iterating
4302    /// [`Self::ALL`], while the future M4 admission-webhook's rejection
4303    /// path folds `None` onto its per-CR structured refusal body.
4304    #[must_use]
4305    pub fn from_wire(s: &str) -> Option<Self> {
4306        match s {
4307            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE => Some(Self::SingleNode),
4308            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED => Some(Self::Replicated),
4309            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED => Some(Self::Sharded),
4310            _ => None,
4311        }
4312    }
4313}
4314
4315/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
4316/// the pretty-printed byte-string every consumer that formats the strategy
4317/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
4318/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
4319/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
4320/// per-Aplicacao strategy line, the future M4 CR materializer's per-
4321/// admission-webhook rejection body) reaches for the same lifted
4322/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
4323/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4324/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
4325/// `Serialize` derive already emits under
4326/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
4327/// [`PlacementStrategy::as_str`] helper already returns.
4328///
4329/// Until this lift landed the sibling OTP-shape typed enums —
4330/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
4331/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
4332/// so [`std::fmt::Display`] routes through the same discriminant string
4333/// the wire format emits) — carried a stable [`std::fmt::Display`]
4334/// surface but [`PlacementStrategy`] did not; every consumer reaching
4335/// for a strategy byte-string past the wire format had to pick between
4336/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
4337/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
4338/// derive), any two of which a future variant rename or
4339/// `#[serde(rename_all = "kebab-case")]` attribute would silently
4340/// desynchronize — with the failure surfacing as a downstream renderer /
4341/// operator's per-strategy dispatch reading one spelling while the wire
4342/// format emitted another, far from the source rebrand commit and with
4343/// no field naming the drift. Routing `Display` through
4344/// [`PlacementStrategy::as_str`] makes the three paths
4345/// (`Debug` for structural inspection, `Display` for user-facing text,
4346/// `Serialize` for the wire format) converge on the same lifted
4347/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
4348/// the diagnostic byte-string, and the pretty-printed byte-string move
4349/// as a single unit through one canonical declaration each, by
4350/// construction. Same trajectory as [`PlacementStrategy::as_str`]
4351/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
4352/// closes the third path.
4353///
4354/// Pin tests
4355/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
4356/// and
4357/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
4358/// assert the three paths agree byte-for-byte on every variant, so a
4359/// future variant rename or per-arm serde attribute drift is a build
4360/// error visible at caixa-core test time, not a silent per-consumer
4361/// dispatch miss at apply / reconcile time.
4362impl std::fmt::Display for PlacementStrategy {
4363    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4364        f.write_str(self.as_str())
4365    }
4366}
4367
4368/// Where the Aplicacao runs.
4369#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
4370#[serde(rename_all = "camelCase")]
4371pub struct Placement {
4372    /// Distribution strategy.
4373    #[serde(default)]
4374    pub estrategia: PlacementStrategy,
4375
4376    /// Named clusters that host this Aplicacao. Required for
4377    /// `Replicated` and `SingleNode`; for `Sharded` declares the
4378    /// shard pool.
4379    #[serde(default)]
4380    pub clusters: Vec<String>,
4381
4382    /// Optional hint to the placement engine: `"data-locality"`,
4383    /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
4384    #[serde(default, skip_serializing_if = "Option::is_none")]
4385    pub affinity: Option<String>,
4386
4387    /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
4388    #[serde(default, skip_serializing_if = "Option::is_none")]
4389    pub shard_key: Option<String>,
4390}
4391
4392impl Placement {
4393    /// Substrate-canonical per-`:placement` Akka-cluster-sharding
4394    /// `:shard-key` extractor-expression scalar accessor every consumer
4395    /// of the Aplicacao's hash-keyed distribution routing keys off —
4396    /// returns the author-declared `:placement :shard-key` byte-string
4397    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
4398    /// own `Option<String>` storage; `None` when the slot is absent
4399    /// (the canonical shape under `:estrategia Replicated` /
4400    /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
4401    /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
4402    /// partition — `validate` refuses any `Placement` past this call
4403    /// that lands `Some` on a non-`Sharded` strategy or `None` on
4404    /// `Sharded`).
4405    ///
4406    /// The `:placement :shard-key` slot carries the Akka-style
4407    /// cluster-sharding entity-id extractor expression
4408    /// (MESH-COMPOSITION §II.4) — validated by
4409    /// [`validate_placement_shard_key`] to be a non-empty printable-
4410    /// ASCII single-token reference (`tenantId`, `$tenantId`,
4411    /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
4412    /// future M4 Akka-style cluster-sharding reconciler hashes without
4413    /// re-validating at the runtime layer), and every downstream
4414    /// consumer that reads the key keys off this scalar (the
4415    /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
4416    /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
4417    /// declared-but-inert refusal diagnostic, the caixa-mesh
4418    /// per-Aplicacao `placement.shardKey` emit path the substrate
4419    /// operator's per-entity hash-routing reader consumes, the future
4420    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4421    /// per-shard-key resolver).
4422    ///
4423    /// Prior to this lift the `.shard_key` field was accessed inline at
4424    /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
4425    /// `Sharded` arm's `match &self.placement.shard_key { None => …,
4426    /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
4427    /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
4428    /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
4429    /// — two open-coded field-accesses that expressed no compile-time
4430    /// link back to the typed slot. A future extension of the
4431    /// `:placement :shard-key` axis to a richer author surface — a
4432    /// per-cluster override the operator pins through a future
4433    /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
4434    /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
4435    /// alias table the M4 CR materializer resolves per-CR, a
4436    /// per-Aplicacao dynamic `:shard-key` derivation the future
4437    /// adaptive placement engine computes from `:affinity` weights —
4438    /// would have had to be threaded through both open-coded copies in
4439    /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
4440    /// arm refusal would silently disagree on which extractor
4441    /// expression a given Placement resolves to. Lifting the resolution
4442    /// rule to a typed method on the substrate primitive means every
4443    /// downstream consumer of the Aplicacao's per-`:placement`
4444    /// hash-key surface reaches for exactly one typed dispatch — the
4445    /// resolver's accept-set migrates as a unit on any future axis
4446    /// addition.
4447    ///
4448    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
4449    /// [`WitContract::destination`] / [`WitContract::world_ref`]
4450    /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
4451    /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
4452    /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
4453    /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
4454    /// typed dispatch on the substrate primitive, thin projections at
4455    /// each consumer" discipline extended onto the per-`:placement`
4456    /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
4457    /// First `Option<&str>`-return accessor on the M3 mesh-slot family
4458    /// — opens the "optional per-slot scalar" projection pattern the
4459    /// sibling per-`:placement` `:affinity`, per-`:politicas`
4460    /// `:rate-limit` future lifts fold on. Named `shard_key()` to
4461    /// match the storage field's name; the accessor's identity name
4462    /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
4463    /// slot's docstring already carries.
4464    #[must_use]
4465    pub fn shard_key(&self) -> Option<&str> {
4466        self.shard_key.as_deref()
4467    }
4468
4469    /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
4470    /// compression-hint scalar accessor every weighting-consumer of the
4471    /// Aplicacao's per-hint routing surface keys off — returns the
4472    /// author-declared `:placement :affinity` byte-string verbatim as
4473    /// an `Option<&str>`, borrowed from the typed slot's own
4474    /// `Option<String>` storage; `None` when the slot is absent (the
4475    /// canonical shape of an Aplicacao that leaves the compression
4476    /// weighting up to the placement engine's cluster-default arm — no
4477    /// author-authored `data-locality` / `low-latency` / etc. hint
4478    /// biases the routing).
4479    ///
4480    /// The `:placement :affinity` slot carries the M3 Adaptive-
4481    /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
4482    /// by [`validate_placement_affinity`] to be a DNS-1123 label
4483    /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
4484    /// K8s-conformant label-selector shape every apiserver-side pod-
4485    /// affinity / node-affinity materializer already gates on
4486    /// admission), and every downstream consumer that reads the hint
4487    /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
4488    /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
4489    /// `placement.affinity` overlay emit path the substrate operator's
4490    /// per-hint weighting-consumer reads, the future M4
4491    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
4492    /// pod-affinity / node-affinity selector resolver).
4493    ///
4494    /// Prior to this lift the `.affinity` field was accessed inline at
4495    /// the sole caixa-core site — the
4496    /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
4497    /// `if let Some(a) = &self.placement.affinity { …
4498    /// validate_placement_affinity(a)? … }` cascade — one open-coded
4499    /// field-access that expressed no compile-time link back to the
4500    /// typed slot. A future extension of the `:placement :affinity`
4501    /// axis to a richer author surface — a per-cluster override the
4502    /// operator pins through a future `:placement :affinity-overrides`
4503    /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
4504    /// tenant hint alias table the M4 CR materializer resolves per-CR,
4505    /// a per-Aplicacao dynamic `:affinity` derivation the future
4506    /// adaptive placement engine computes from `:clusters` topology —
4507    /// would have had to be threaded through the open-coded copy in
4508    /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
4509    /// materializer reader that landed on the axis, or the per-hint
4510    /// value-shape gate and its downstream weighting consumers would
4511    /// silently disagree on which hint a given Placement resolves to.
4512    /// Lifting the resolution rule to a typed method on the substrate
4513    /// primitive means every downstream consumer of the Aplicacao's
4514    /// per-`:placement` compression-hint surface reaches for exactly
4515    /// one typed dispatch — the resolver's accept-set migrates as a
4516    /// unit on any future axis addition.
4517    ///
4518    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
4519    /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
4520    /// optional-scalar axis — same "one typed dispatch on the substrate
4521    /// primitive, thin projections at each consumer" discipline extended
4522    /// onto the per-`:placement` M3-Adaptive-compression-hint
4523    /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
4524    /// return accessor on the M3 mesh-slot family; closes the last
4525    /// un-lifted per-`:placement` `Option<String>` axis. Named
4526    /// `affinity()` to match the storage field's name; the accessor's
4527    /// identity name maps onto the canonical MESH-COMPOSITION §II.4
4528    /// vocabulary the slot's docstring already carries.
4529    #[must_use]
4530    pub fn affinity(&self) -> Option<&str> {
4531        self.affinity.as_deref()
4532    }
4533
4534    /// Substrate-canonical per-`:placement` `:estrategia` distribution-
4535    /// strategy scalar accessor every consumer that dispatches on the
4536    /// Aplicacao's per-cluster distribution shape keys off — returns the
4537    /// author-declared `:placement :estrategia` variant verbatim as a
4538    /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
4539    /// `PlacementStrategy` storage.
4540    ///
4541    /// The `:placement :estrategia` slot carries the closed-set
4542    /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
4543    /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
4544    /// `Replicated` — active-active across every named cluster; `Sharded`
4545    /// — Akka-style hash-keyed entity distribution across the cluster pool
4546    /// per §II.4) that every downstream consumer of the Aplicacao's
4547    /// per-cluster fan-out shape keys off. Validated by
4548    /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
4549    /// the sibling `:shard-key` axis (`shard_key.is_some() ==
4550    /// matches!(estrategia, Sharded)` — the cross-slot partition the
4551    /// [`Placement::shard_key`] accessor's docstring pins), and every
4552    /// downstream consumer that reads the strategy keys off this scalar
4553    /// (the [`AplicacaoSpec::validate_placement`]
4554    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
4555    /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
4556    /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
4557    /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
4558    /// declared-but-inert refusal's
4559    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
4560    /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
4561    /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
4562    /// emit path the substrate operator's per-strategy fan-out reader
4563    /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4564    /// materializer's per-strategy admission-webhook resolver).
4565    ///
4566    /// Prior to this lift the `.estrategia` field was accessed inline at
4567    /// four sites — the [`AplicacaoSpec::validate_placement`]
4568    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
4569    /// `estrategia: self.placement.estrategia`, the same method's
4570    /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
4571    /// partition dispatch, the non-`Sharded`-arm
4572    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
4573    /// `estrategia: self.placement.estrategia`, and the `feira app graph`
4574    /// per-Aplicacao strategy print line at
4575    /// `println!("… {} …", spec.placement.estrategia, …)`
4576    /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
4577    /// expressed no compile-time link back to the typed slot. A future
4578    /// extension of the `:placement :estrategia` axis to a richer author
4579    /// surface (a per-cluster override the operator pins through a future
4580    /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
4581    /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
4582    /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
4583    /// derivation the future adaptive placement engine computes from
4584    /// `:affinity` + `:clusters` topology) would have had to be threaded
4585    /// through every open-coded copy in lockstep — one consumer reading
4586    /// the raw variant while a peer read the operator-resolved variant
4587    /// would silently split the `PlacementWithoutClusters` /
4588    /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
4589    /// partition-dispatch input, a two-consumer split at the validator
4590    /// far from the source `caixa.lisp` with no field naming the
4591    /// strategy-drift root cause. Lifting the resolution rule to a typed
4592    /// method on the substrate primitive means every downstream consumer
4593    /// of the Aplicacao's per-`:placement` distribution-strategy surface
4594    /// reaches for exactly one typed dispatch — the resolver's accept-set
4595    /// migrates as a unit on any future axis addition.
4596    ///
4597    /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
4598    /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
4599    /// same "one typed dispatch on the substrate primitive, thin
4600    /// projections at each consumer" discipline extended onto the
4601    /// per-`:placement` distribution-strategy `Copy`-composite-enum
4602    /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
4603    /// family; first `Copy`-return accessor on the M3 mesh-slot
4604    /// `Placement` type — companion to the sibling per-`:placement`
4605    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
4606    /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
4607    /// optional-scalar axes, closing the last unlifted per-`:placement`
4608    /// scalar-value axis (the closed-set `PlacementStrategy`
4609    /// distribution-strategy discriminator) so every downstream
4610    /// per-`:placement` reader now routes through a typed dispatch on
4611    /// the substrate primitive. Named `estrategia()` to match the storage
4612    /// field's name; the accessor's identity name maps onto the
4613    /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
4614    /// already carries.
4615    #[must_use]
4616    pub fn estrategia(&self) -> PlacementStrategy {
4617        self.estrategia
4618    }
4619
4620    /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
4621    /// per-cluster distribution-target slice accessor every consumer that
4622    /// walks the Aplicacao's declared cluster-pool keys off — returns the
4623    /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
4624    /// `&[String]` slice-view, borrowed from the typed slot's own
4625    /// `Vec<String>` storage (a zero-copy slice-view over the same
4626    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
4627    /// through). Non-optional: the empty slice is the load-bearing
4628    /// pre-validation sentinel every downstream consumer of the paired
4629    /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
4630    /// off — every strategy in the closed
4631    /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
4632    /// requires a non-empty list (`SingleNode` / `Replicated` use the
4633    /// list as hosting / takeover candidates per Erlang/OTP distributed-
4634    /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
4635    /// shard pool per Akka cluster-sharding convention, §II.4), so the
4636    /// `.is_empty()` probe is the shared pre-condition every
4637    /// [`AplicacaoSpec::validate_placement`] arm heads on.
4638    ///
4639    /// The `:placement :clusters` slot carries the K8s-conformant DNS-
4640    /// 1123-label per-cluster distribution-target list — the same
4641    /// set-not-multiset shape the sibling `:membros :caixa` /
4642    /// `:children :caixa` axes carry (`validate_placement`'s per-entry
4643    /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
4644    /// pins the shape). Every downstream consumer that fans on the list
4645    /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
4646    /// pre-flight `.is_empty()` probe that trips
4647    /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
4648    /// per-cluster value-shape + duplicate-detection fan-out loop, the
4649    /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
4650    /// that materializes the list verbatim onto every
4651    /// programs.yaml entry the substrate operator's per-cluster
4652    /// `placement.clusters | contains .Values.cluster` filter reads,
4653    /// the `feira app graph` per-Aplicacao cluster print line, the
4654    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4655    /// per-cluster admission-webhook fan-out, the future M5 adaptive-
4656    /// placement engine's cluster-topology reader).
4657    ///
4658    /// Prior to this lift the `.clusters` `Vec<String>` was accessed
4659    /// inline at three production sites — the
4660    /// [`AplicacaoSpec::validate_placement`] pre-flight
4661    /// `self.placement.clusters.is_empty()` refusal probe, the same
4662    /// method's per-cluster validate loop's
4663    /// `for c in &self.placement.clusters` traversal head, and the
4664    /// `feira app graph` per-Aplicacao print line's
4665    /// `spec.placement.clusters` `{:?}` formatter argument
4666    /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
4667    /// that expressed no compile-time link back to the typed slot. A
4668    /// future extension of the `:placement :clusters` axis to a richer
4669    /// author surface (a per-tenant cluster-pool overlay the operator
4670    /// pins through a future `:placement :clusters-overrides` slot the
4671    /// MESH-COMPOSITION §V cross-cluster-federation roadmap
4672    /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
4673    /// the future M5 adaptive-placement engine computes from
4674    /// `:affinity` weights + live cluster-topology probes, a promotion
4675    /// of the plain `Vec<String>` to a richer `{static, dynamic}`
4676    /// partition once the substrate operator's cluster-membership
4677    /// reconciler comes into typed scope) would have had to be threaded
4678    /// through all three open-coded copies in lockstep or one consumer
4679    /// would silently disagree with the peers on which cluster-pool a
4680    /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
4681    /// reading the raw slot while the peer per-cluster validate loop
4682    /// read an operator-resolved slot would silently split the paired
4683    /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
4684    /// `PlacementClusterDuplicate` refusal cascade's actual traversal
4685    /// input from the pre-flight input, a three-consumer split at the
4686    /// validator and formatter far from the source `caixa.lisp` with
4687    /// no field naming the cluster-pool-drift root cause. Lifting the
4688    /// resolution rule to a typed method on the substrate primitive
4689    /// means every downstream consumer of the Aplicacao's
4690    /// per-`:placement` cluster-pool surface reaches for exactly one
4691    /// typed dispatch — the resolver's accept-set migrates as a unit
4692    /// on any future axis addition.
4693    ///
4694    /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
4695    /// slot — sibling to the seed M2
4696    /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
4697    /// slice-return accessor on the peer per-`:supervisor` static-
4698    /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
4699    /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
4700    /// primitive, thin projections at each consumer" discipline. The
4701    /// three peer `Vec`-carry axes still unlifted at the time of this
4702    /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
4703    /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
4704    /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
4705    /// [`crate::UpgradeFromEntry::instructions`]
4706    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
4707    /// — inherit this accessor's discipline as future compounding runs
4708    /// migrate their consumers onto the shared slice-return shape.
4709    /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
4710    /// type, sibling to the two `Option<&str>`-return
4711    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
4712    /// (74ec2d3) accessors and the `Copy`-return
4713    /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
4714    /// unlifted per-`:placement` field axis (the `Vec<String>`
4715    /// distribution-target-list carrier) so every downstream
4716    /// per-`:placement` reader now routes through a typed dispatch on
4717    /// the substrate primitive. Named `clusters()` to match the storage
4718    /// field's name verbatim and the tatara-lisp author-surface term
4719    /// (`:clusters`) the field's own docstring already carries; the
4720    /// accessor's identity maps onto the canonical MESH-COMPOSITION
4721    /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
4722    /// for. Returns `&[String]` (not `&Vec<String>`) because every
4723    /// downstream consumer of the cluster list treats it as a read-only
4724    /// sequence — the slice-view is the narrowest borrow that supports
4725    /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
4726    /// `.len()`) without leaking the backing `Vec`'s
4727    /// grow/push/reserve surface that no consumer of the typed view
4728    /// reaches for (the storage-side `Vec` remains reachable through
4729    /// the `pub clusters` field for the mutation-carrying serde
4730    /// round-trip and per-test fixture-mutation paths).
4731    #[must_use]
4732    pub fn clusters(&self) -> &[String] {
4733        self.clusters.as_slice()
4734    }
4735}
4736
4737impl Default for Placement {
4738    fn default() -> Self {
4739        Self {
4740            estrategia: PlacementStrategy::default(),
4741            clusters: Vec::new(),
4742            affinity: None,
4743            shard_key: None,
4744        }
4745    }
4746}
4747
4748// ── external entry point ─────────────────────────────────────────────
4749
4750/// External entry point — what an outside caller sees. Renders to a
4751/// Gateway / Ingress + a route to the named member Servico.
4752#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
4753#[serde(rename_all = "camelCase")]
4754pub struct Entrada {
4755    /// Public hostname (e.g. `"checkout.quero.cloud"`).
4756    pub host: String,
4757
4758    /// Member Servico the gateway routes to. Must be in `:membros`.
4759    pub para: String,
4760
4761    /// Optional path filter — if set, only matching paths route to
4762    /// this Aplicacao (the rest fall through to other route rules).
4763    #[serde(default)]
4764    pub paths: Vec<String>,
4765
4766    /// Default port on the destination Servico (the trigger.service.port).
4767    #[serde(default = "default_port")]
4768    pub port: u16,
4769}
4770
4771impl Entrada {
4772    /// Substrate-canonical per-`:entrada` URL-path fallback resolver
4773    /// every HTTPRoute-aware renderer keys off — returns the author-
4774    /// declared `:entrada :paths` list verbatim when non-empty, and the
4775    /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
4776    /// all fallback otherwise (so an Aplicacao author who declares an
4777    /// external `:entrada` block but no per-path rule surface still
4778    /// gets a route whose sole `HTTPPathMatch` matches every incoming
4779    /// request under the paired
4780    /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
4781    ///
4782    /// Prior to this lift the "if `:entrada :paths` is empty use the
4783    /// substrate catch-all; else return each declared path verbatim"
4784    /// cascade lived inline at
4785    /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
4786    /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
4787    /// per-Aplicacao HTTPRoute per-rule path-list emit site the
4788    /// substrate ships today, with no typed method on the substrate
4789    /// primitive that named the rule. A future path-resolution axis
4790    /// addition — a per-cluster `:entrada :default-path` override the
4791    /// operator pins through a future `:placement`-scoped slot, an
4792    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
4793    /// admission-webhook floor that materializes the catch-all before
4794    /// the CR lands, a future per-`:entrada :paths` overlay from a
4795    /// per-cluster policy the future `feira app deploy` pipeline
4796    /// consumes — would have to be threaded through every renderer's
4797    /// inline copy of the cascade in lockstep or one consumer would
4798    /// silently disagree with the peers on which path list a given
4799    /// `:entrada` block resolves to. Lifting the rule to a typed
4800    /// method on the substrate primitive means every downstream
4801    /// HTTPRoute-aware consumer (the M4 CR materializer, the future
4802    /// per-cluster overlay resolver, every future per-Aplicacao
4803    /// snapshot renderer) reaches for exactly one typed dispatch —
4804    /// the resolver's accept-set moves as a unit on any future axis
4805    /// addition.
4806    ///
4807    /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
4808    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
4809    /// per-`:entrada` scalar-value axes — extends the "one typed
4810    /// dispatch on the substrate primitive, thin projections at each
4811    /// consumer" discipline onto the per-`:entrada` path-list
4812    /// resolution axis every HTTPRoute-aware renderer consumes. Same
4813    /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
4814    /// sibling `:politicas` primitive — one typed method on the
4815    /// substrate primitive that names the cascade every renderer
4816    /// otherwise re-inlines.
4817    #[must_use]
4818    pub fn resolved_paths(&self) -> Vec<&str> {
4819        // Route the internal cascade-head + per-entry projection reads
4820        // through the lifted [`Self::paths`] slice accessor rather than
4821        // the raw `self.paths` field access — the substrate-primitive
4822        // per-`:entrada` path-list resolver's two internal reads now
4823        // key off the canonical raw-slot surface every downstream
4824        // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
4825        // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
4826        // entrada summary line's `{:?}` Debug print) routes through, so
4827        // any future rebrand on the typed slot's raw-slot reader lands
4828        // at exactly one place. Same two-consumer coherence discipline
4829        // the sibling `Placement::clusters` (a6e18d7) accessor pins on
4830        // the peer M3 mesh-slot `Vec<String>`-carry axis.
4831        if self.paths().is_empty() {
4832            vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
4833        } else {
4834            self.paths().iter().map(String::as_str).collect()
4835        }
4836    }
4837
4838    /// Substrate-canonical per-`:entrada` DNS-hostname singular
4839    /// accessor every Gateway-API `Listener.hostname` reader keys off
4840    /// — returns the author-declared `:entrada :host` byte-string
4841    /// verbatim as a `&str`, borrowed from the typed slot's own
4842    /// [`String`] storage.
4843    ///
4844    /// Named the "singular" half of the DNS-hostname resolver pair on
4845    /// the substrate primitive: the parent-Gateway per-listener
4846    /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
4847    /// (`Listener.hostname: Option<PreciseHostname>` — at most one
4848    /// hostname per listener), and this accessor is the typed dispatch
4849    /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
4850    /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
4851    /// the per-HTTPRoute `spec.hostnames[]` list axis the same
4852    /// per-Aplicacao ingress-hostname surface projects onto.
4853    ///
4854    /// Prior to this lift the `entrada.host.clone()` byte-string was
4855    /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
4856    /// per-listener singular `hostname:` axis
4857    /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
4858    /// per-HTTPRoute plural `spec.hostnames[]` axis
4859    /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
4860    /// consumers read the same `entrada.host` field but the two-site
4861    /// duplication expressed no compile-time contract that the singular
4862    /// Gateway-listener filter and the plural `HTTPRoute` filter list
4863    /// stay in lockstep on future extensions of the `:entrada` slot to
4864    /// a multi-hostname author surface (an `:entrada :alt-hosts` list
4865    /// overlay, a per-cluster SNI fan-out the operator pins through a
4866    /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
4867    /// Aplicacao` CR materializer's per-listener virtual-host filter
4868    /// admission-webhook overlay). Any such extension would have to be
4869    /// threaded through every renderer's inline copy of the resolution
4870    /// in lockstep or the Gateway listener's `hostname:` filter would
4871    /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
4872    /// — a Gateway-API-conformance divergence whose apply-time symptom
4873    /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
4874    /// `NoMatchingParent` — the API server rejects the route because
4875    /// its `hostnames[]` filter doesn't intersect the parent listener's
4876    /// `hostname` filter) is far from the source `caixa.lisp` and never
4877    /// surfaces in the emitted YAML. Lifting the singular and plural
4878    /// resolvers to typed methods on the substrate primitive means
4879    /// every consumer of the Aplicacao's ingress-hostname surface
4880    /// reaches for exactly one typed dispatch, and the pair-invariant
4881    /// `hostnames() == vec![hostname()]` pinned by the sibling
4882    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
4883    /// keeps the two axes in lockstep by construction.
4884    ///
4885    /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
4886    /// (1449891) path-list resolver on the per-HTTPRoute per-rule
4887    /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
4888    /// the substrate primitive, thin projections at each consumer"
4889    /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
4890    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
4891    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
4892    /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
4893    /// `:entrada` scalar-value + list-value axes.
4894    #[must_use]
4895    pub fn hostname(&self) -> &str {
4896        self.host.as_str()
4897    }
4898
4899    /// Substrate-canonical per-`:entrada` DNS-hostname plural
4900    /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
4901    /// keys off — returns the singleton `[hostname()]` list under
4902    /// today's single-hostname-per-Aplicacao author surface, and the
4903    /// authoritative multi-hostname list under a future
4904    /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
4905    ///
4906    /// Plural half of the DNS-hostname resolver pair — see the
4907    /// companion [`Entrada::hostname`] docstring for the two-consumer
4908    /// lift + pair-invariant discipline (`hostnames() ==
4909    /// vec![hostname()]`, pinned load-bearing by the sibling
4910    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
4911    /// test).
4912    ///
4913    /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
4914    /// per-`:entrada` plural-list resolver on the per-HTTPRoute
4915    /// per-rule path-list axis — same `Vec<&str>` shape, same
4916    /// substrate-primitive-owns-the-resolver discipline extended to
4917    /// the per-HTTPRoute virtual-host filter-list axis.
4918    #[must_use]
4919    pub fn hostnames(&self) -> Vec<&str> {
4920        vec![self.hostname()]
4921    }
4922
4923    /// Substrate-canonical per-`:entrada` destination-Servico scalar
4924    /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
4925    /// the author-declared `:entrada :para` byte-string verbatim as a
4926    /// `&str`, borrowed from the typed slot's own [`String`] storage.
4927    ///
4928    /// The `:entrada :para` slot names the single member Servico the
4929    /// external Gateway routes to (validated by
4930    /// [`AplicacaoSpec::validate`] to be a
4931    /// [`Membro::caixa`] the Aplicacao declares — a stray
4932    /// `:para` that doesn't name a member is
4933    /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
4934    /// backend-attachment miss at cluster-apply time). Under today's
4935    /// single-destination author surface `:entrada :para` is the ingress
4936    /// apex Servico's canonical identity; under a hypothetical
4937    /// future multi-backend author surface (a `:entrada
4938    /// :split :backends` weighted-fan-out overlay for canary /
4939    /// blue-green traffic-split rollouts, per-path override for
4940    /// path-based per-Servico routing beyond the single-apex model,
4941    /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4942    /// per-CR admission-webhook that promotes the scalar to a
4943    /// weighted list) this accessor is the substrate primitive's typed
4944    /// dispatch every downstream `HTTPRoute`-aware consumer routes
4945    /// through, so the resolution shape migrates as a unit on one
4946    /// caixa-core edit rather than a coordinated rewrite across every
4947    /// renderer's inline field-access.
4948    ///
4949    /// Prior to this lift the `entrada.para` byte-string was accessed
4950    /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
4951    /// `metadata.name` composer's per-destination discriminator arg
4952    /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
4953    /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
4954    /// per-HTTPRoute per-rule `backendRefs[0].name` axis
4955    /// (`entrada.para.clone()`,
4956    /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
4957    /// consumers read the same `entrada.para` field but the two-site
4958    /// duplication expressed no compile-time contract that the HTTPRoute
4959    /// name-discriminator and the per-rule backend name stay in
4960    /// lockstep on future extensions of the `:entrada` slot to a
4961    /// multi-destination author surface. Any such extension would have
4962    /// to be threaded through every renderer's inline copy of the
4963    /// destination projection in lockstep or the HTTPRoute
4964    /// `metadata.name` would silently reference a different destination
4965    /// than its own `backendRefs[]` — an operator-side
4966    /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
4967    /// grep-by-name lookup would land on a route whose `backendRefs[]`
4968    /// silently point at a peer Servico, dropping every external
4969    /// `:entrada` flow at the gateway with the destination-drift root
4970    /// cause invisible in the emitted YAML.
4971    ///
4972    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
4973    /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
4974    /// the per-listener singular / per-HTTPRoute plural filter axes and
4975    /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
4976    /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
4977    /// typed dispatch on the substrate primitive, thin projections at
4978    /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
4979    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
4980    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
4981    /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
4982    /// sibling per-`:entrada` scalar-value + list-value axes — this
4983    /// accessor closes the last unlifted per-`:entrada` scalar axis
4984    /// (the destination-Servico byte-string) so every downstream
4985    /// per-`:entrada` reader now routes through a typed dispatch on
4986    /// the substrate primitive.
4987    #[must_use]
4988    pub fn destination(&self) -> &str {
4989        self.para.as_str()
4990    }
4991
4992    /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
4993    /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
4994    /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
4995    /// reader keys off — returns the author-declared `:entrada :port`
4996    /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
4997    /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
4998    /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
4999    /// [`AplicacaoError::EntradaPortZero`], not a silent
5000    /// admission-webhook rejection at cluster-apply time).
5001    ///
5002    /// The `:entrada :port` slot carries the destination Servico's
5003    /// canonical in-cluster L4 listener port (`trigger.service.port` on
5004    /// the `pleme-computeunit` library chart), and every downstream
5005    /// consumer that reads the port keys off this scalar (the
5006    /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
5007    /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
5008    /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
5009    /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5010    /// CR materializer's per-Aplicacao gateway port resolver).
5011    ///
5012    /// Prior to this lift the `.port` field was accessed inline at two
5013    /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
5014    /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
5015    /// the [`AplicacaoSpec::port_for_destination`] resolver's
5016    /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
5017    /// open-coded field-accesses that expressed no compile-time link
5018    /// back to the typed slot. A future extension of the `:entrada :port`
5019    /// axis to a richer author surface — a per-cluster override the
5020    /// operator pins through a future `:placement :default-port` slot the
5021    /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
5022    /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
5023    /// heterogeneous listener ports, an M4
5024    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
5025    /// admission-webhook floor that promotes the scalar to a
5026    /// per-destination map — would have had to be threaded through both
5027    /// open-coded copies in lockstep or the structural-floor validator
5028    /// and the [`AplicacaoSpec::port_for_destination`] resolver would
5029    /// silently disagree on which port a given [`Entrada`] resolves to.
5030    /// Lifting the resolution rule to a typed method on the substrate
5031    /// primitive means every downstream consumer of the Aplicacao's
5032    /// per-`:entrada` L4-port surface reaches for exactly one typed
5033    /// dispatch — the resolver's accept-set migrates as a unit on any
5034    /// future axis addition.
5035    ///
5036    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
5037    /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
5038    /// accessors on the per-`:entrada` scalar-value axis — same "one
5039    /// typed dispatch on the substrate primitive, thin projections at
5040    /// each consumer" discipline extended onto the per-`:entrada`
5041    /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
5042    /// the M3 mesh-slot `Entrada` type — closes the last unlifted
5043    /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
5044    /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
5045    /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
5046    /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
5047    /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
5048    /// storage field's name; the accessor's identity name maps onto the
5049    /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
5050    /// already carries.
5051    #[must_use]
5052    pub fn port(&self) -> u16 {
5053        self.port
5054    }
5055
5056    /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
5057    /// slice accessor every HTTPRoute-aware renderer keys off when it
5058    /// wants the raw author-declared path-list (not the fallback-
5059    /// applied projection [`Self::resolved_paths`] returns) — returns
5060    /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
5061    /// borrowed from the typed slot's own [`Vec<String>`] storage.
5062    ///
5063    /// Named the "raw slot" half of the per-`:entrada` path-list resolver
5064    /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
5065    /// (1449891) closes the fallback-applying arm every per-Aplicacao
5066    /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
5067    /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
5068    /// catch-all; non-empty slot → per-entry verbatim projection); this
5069    /// accessor closes the raw-slot arm every consumer that must see the
5070    /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
5071    /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
5072    /// not `Err(EntradaPathEmpty)`, so it cannot route through the
5073    /// fallback-applying sibling; the `feira app graph` per-Aplicacao
5074    /// external-gateway summary line's `{:?}` Debug print — which must
5075    /// name the author's declaration, not the substrate's fallback, so
5076    /// an author reading their graph output can grep their caixa.lisp
5077    /// for the exact list they authored) routes through.
5078    ///
5079    /// Prior to this lift the `.paths` field was accessed inline at four
5080    /// production sites: the two internal reads in [`Self::resolved_paths`]
5081    /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
5082    /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
5083    /// value-shape gate's `for p in &e.paths` traversal head, and the
5084    /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
5085    /// Debug print — four open-coded field-accesses that expressed no
5086    /// compile-time link back to the typed slot. A future extension of
5087    /// the `:entrada :paths` axis to a richer author surface — a
5088    /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
5089    /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
5090    /// spec supports through `matches[].method`), a per-path per-header
5091    /// filter overlay (`matches[].headers[]`), a per-cluster override
5092    /// the operator pins through a future `:placement :path-overlay`
5093    /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5094    /// per-CR admission-webhook that normalized the list at admission
5095    /// time — would have had to be threaded through every open-coded
5096    /// copy in lockstep or the validator's per-entry gate would silently
5097    /// disagree with the renderer's per-entry emit on which list a given
5098    /// `:entrada` block resolves to. Lifting the resolution to a typed
5099    /// method on the substrate primitive means every downstream consumer
5100    /// of the Aplicacao's per-`:entrada` path-list surface reaches for
5101    /// exactly one typed dispatch — the resolver's accept-set migrates
5102    /// as a unit on any future axis addition.
5103    ///
5104    /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
5105    /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
5106    /// carry axis — same "one typed dispatch on the substrate primitive,
5107    /// thin projections at each consumer" discipline extended onto the
5108    /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
5109    /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
5110    /// carrier) so every downstream per-`:entrada` reader now routes
5111    /// through a typed dispatch on the substrate primitive. Returns
5112    /// `&[String]` (not `&Vec<String>`) because every downstream consumer
5113    /// treats the list as a read-only sequence — the slice-view is the
5114    /// narrowest borrow that supports every present + roadmapped consumer
5115    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
5116    /// `Vec`'s grow/push/reserve surface that no consumer of the typed
5117    /// view reaches for (the storage-side `Vec` remains reachable through
5118    /// the `pub paths` field for the mutation-carrying serde round-trip
5119    /// and per-test fixture-mutation paths).
5120    #[must_use]
5121    pub fn paths(&self) -> &[String] {
5122        self.paths.as_slice()
5123    }
5124}
5125
5126/// Canonical default L4 port every typed Servico exposes on its
5127/// in-cluster K8s Service (the `trigger.service.port` axis the
5128/// `pleme-computeunit` library chart emits, the `:entrada :port` author
5129/// surface defaults to when the author omits the slot, and the
5130/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
5131/// `:entrada` block matches the per-`:contratos` destination Servico).
5132/// The single source of truth all three typed-port consumers reach for:
5133///
5134///   - [`Entrada::port`]'s serde default (via the
5135///     [`default_port`] helper this constant feeds); the author surface
5136///     `(:entrada (:host … :para …))` without an explicit `:port` slot
5137///     reads back as a typed [`Entrada`] carrying this exact value;
5138///   - the
5139///     [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
5140///     emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
5141///     fallback, fired when the typed `:entrada` block doesn't name
5142///     the per-`:contratos` destination Servico — the typed
5143///     `:contratos` graph carries no per-destination port axis (the
5144///     destination port is the destination Servico's
5145///     `lareira-<nome>` chart's `trigger.service.port`, which the
5146///     Aplicacao-level renderer has no visibility into without a
5147///     resolver round-trip), so the renderer falls back to the
5148///     substrate's canonical Servico-port assumption — by
5149///     construction the same value the destination's own
5150///     `pleme-computeunit` chart emits, the same value the
5151///     destination's own typed `:entrada :port` slot defaults to;
5152///   - every future per-Servico renderer the absorption-roadmap
5153///     acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5154///     CR materializer's per-edge port resolver, the future
5155///     per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
5156///     emitter's per-route bucket key, the future caixa-otel
5157///     collector-pipeline emitter's per-Servico scrape port).
5158///
5159/// Until this lift landed the value `8080` lived at two production-code
5160/// call-sites: the [`default_port`] helper at
5161/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
5162/// and the `.unwrap_or(8080)` literal at
5163/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
5164/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
5165/// resolver). A future Servico-port rebrand — the substrate moving the
5166/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
5167/// gateway grows direct `:80` listeners, to `8443` once the substrate
5168/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
5169/// override the operator pins through a future
5170/// `:placement :default-port` slot — without a coordinated edit on
5171/// both sides would silently emit Servicos listening on one port and
5172/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
5173/// The CNP's apply-time symptom (the policy is admitted but every L4
5174/// flow on the destination Servico's actual port silently drops because
5175/// it doesn't match the whitelisted port) is far from the rebrand
5176/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
5177/// in hubble traces, not in `kubectl describe`. Lifting the literal to
5178/// a shared constant closes the drift footgun structurally — both
5179/// consumers read from the same `u16`, so any rebrand reaches both
5180/// sites by construction.
5181///
5182/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
5183/// per-renderer canonical-K8s-axis constant — the namespace string
5184/// and the canonical Servico port both lived as duplicated literals
5185/// across caixa-core / caixa-mesh / caixa-flux before their respective
5186/// lifts. Same "the typed constant lives in one place" discipline the
5187/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
5188/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
5189/// shared-string axes.
5190///
5191/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
5192pub const DEFAULT_SERVICO_PORT: u16 = 8080;
5193
5194/// Structural floor for the typed `:entrada :port` axis — every
5195/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
5196/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
5197///
5198/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
5199/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
5200/// interprets as "let the kernel pick a free port at bind time", not a
5201/// well-defined destination the substrate's per-`:entrada` Gateway API
5202/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
5203/// carrying `port: 0` degenerates to a nominal-only routing target: the
5204/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
5205/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
5206/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
5207/// at build time rather than at `kubectl apply` time), and the
5208/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
5209/// (caixa-mesh/src/lib.rs:2657 through
5210/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
5211/// [`Entrada::port`] typed value — silently emits a policy whose
5212/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
5213/// actual listener, dropping every L4 flow at the eBPF data plane far
5214/// from the source caixa.lisp with no field naming the port-zero-drift
5215/// root cause.
5216///
5217/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
5218/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
5219/// on the top edge (unlike the peer capped-`u32` `:politicas` /
5220/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
5221/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
5222/// well below `u32::MAX` and therefore need explicit typed caps).
5223///
5224/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
5225/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
5226/// scalar every `(:entrada (:host … :para …))` slot without an explicit
5227/// `:port` inherits through the serde default hook; this constant names
5228/// the accept-set floor every declared port must satisfy. The pair is
5229/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
5230/// substrate's default must satisfy its own accept-set floor by
5231/// construction) — a future rebrand that accidentally moved
5232/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
5233/// negative-cast typo, a per-cluster override the operator pins through
5234/// a future `:placement :default-port` slot that lands out-of-range)
5235/// would silently invalidate the serde-default emission at every
5236/// author-side `(:entrada (:host … :para …))` slot — the compile-time
5237/// invariant pin
5238/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
5239/// closes the drift footgun at caixa-core build time.
5240///
5241/// Lifted as a typed `pub const` (rather than an inline `0` literal at
5242/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
5243/// has exactly one source of truth — the future M4
5244/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
5245/// gateway resolver, the future per-Servico
5246/// `computeunit.trigger.service.port` renderer's per-CR port-value
5247/// validator, and every downstream test-fixture navigator asserting
5248/// the accept-set floor all read from one place. Same shape every
5249/// other typed bracket-floor / bracket-ceiling in this crate carries
5250/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
5251/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
5252/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
5253/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
5254/// [`POLICY_RATE_LIMIT_MAX`]).
5255pub const SERVICO_PORT_MIN: u16 = 1;
5256
5257const fn default_port() -> u16 {
5258    DEFAULT_SERVICO_PORT
5259}
5260
5261// ── the typed view ───────────────────────────────────────────────────
5262
5263/// Typed composition view of the flat Aplicacao slots on
5264/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
5265/// validation + downstream renderer consumption.
5266#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5267#[serde(rename_all = "camelCase")]
5268pub struct AplicacaoSpec {
5269    pub membros: Vec<Membro>,
5270    pub contratos: Vec<WitContract>,
5271    pub politicas: MeshPolicy,
5272    pub placement: Placement,
5273    pub entrada: Option<Entrada>,
5274}
5275
5276impl AplicacaoSpec {
5277    /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
5278    /// per-Aplicacao member-list slice-return accessor every
5279    /// per-Aplicacao member-list reader keys off — returns the author-
5280    /// declared `:membros` list verbatim as a `&[Membro]` slice-view
5281    /// over the same backing buffer the raw `self.membros.as_slice()`
5282    /// field access borrows from.
5283    ///
5284    /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
5285    /// member list — the load-bearing identity of the application graph
5286    /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
5287    /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
5288    /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
5289    /// accessor) with a `:versao` semver-requirement string (through
5290    /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
5291    /// and every downstream consumer that fans on the member-set keys
5292    /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
5293    /// membership-lookup `HashSet<&str>` seed's collect input, the
5294    /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
5295    /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
5296    /// per-member DNS-1123 / semver-requirement / duplicate-detection
5297    /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
5298    /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
5299    /// programs.yaml per-`:membros` fan-out emitter's per-entry
5300    /// mapping-composition loop, the `feira app graph` per-Aplicacao
5301    /// member-count print line and per-member tree traversal,
5302    /// every future wasm-operator (M4) per-Aplicacao CR materializer's
5303    /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
5304    /// placement engine's per-member weight-topology reader).
5305    ///
5306    /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
5307    /// inline at six production sites — the [`AplicacaoSpec::validate`]
5308    /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
5309    /// [`AplicacaoSpec::validate_membros`]'s pre-flight
5310    /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
5311    /// probe, the same method's per-member `for m in &self.membros`
5312    /// validate-loop traversal head, the
5313    /// [`AplicacaoSpec::detect_sync_cycles`]'s
5314    /// `for m in &self.membros` adjacency-list seed, the
5315    /// [`caixa_mesh::programs_for_aplicacao`] emitter's
5316    /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
5317    /// paired with the peer `for m in &spec.membros` per-entry fan-out
5318    /// loop, and the `feira app graph` per-Aplicacao print line's
5319    /// `spec.membros.len()` count formatter argument paired with the
5320    /// peer `for m in &spec.membros` per-member tree traversal — six
5321    /// open-coded field-accesses that expressed no compile-time link
5322    /// back to the typed slot. A future extension of the `:membros`
5323    /// axis to a richer author surface (a per-cluster member-set
5324    /// overlay the operator pins through a future
5325    /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
5326    /// roadmap acknowledges, a per-tenant member-alias table the M4
5327    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
5328    /// CR at admission time, a per-Aplicacao dynamic member-set
5329    /// derivation the future adaptive-placement engine computes from
5330    /// weighted membership topology, a promotion of the plain
5331    /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
5332    /// Orleans-style virtual-actor dynamic-membership comes into typed
5333    /// scope) would have had to be threaded through all six open-coded
5334    /// copies in lockstep or one consumer would silently disagree with
5335    /// the peers on which member-set a given Aplicacao resolves to —
5336    /// the `HashSet<&str>` name-set seed reading the raw slot while
5337    /// the peer `.is_empty()` refusal probe read an operator-resolved
5338    /// slot would silently split the `:contratos` membership-lookup
5339    /// input from the pre-flight-refusal input, a six-consumer split
5340    /// at the validator + programs.yaml emitter + graph printer far
5341    /// from the source `caixa.lisp` with no field naming the member-
5342    /// set-drift root cause. Lifting the resolution rule to a typed
5343    /// method on the substrate primitive means every downstream
5344    /// consumer of the Aplicacao's per-`:membros` member-list surface
5345    /// reaches for exactly one typed dispatch — the resolver's accept-
5346    /// set migrates as a unit on any future axis addition.
5347    ///
5348    /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
5349    /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
5350    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
5351    /// static-child-list `Vec`-carry axis, and to the M3
5352    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
5353    /// on the peer per-`:placement` distribution-target-list `Vec`-
5354    /// carry axis. Same "one typed dispatch on the substrate primitive,
5355    /// thin projections at each consumer" discipline. The two peer
5356    /// `Vec`-carry axes still unlifted at the time of this lift —
5357    /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
5358    /// WIT-typed edge list) and
5359    /// [`crate::UpgradeFromEntry::instructions`]
5360    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
5361    /// — inherit this accessor's discipline as future compounding runs
5362    /// migrate their consumers onto the shared slice-return shape.
5363    /// First `&[T]`-return accessor on the top-level M3 mesh-slot
5364    /// `AplicacaoSpec` type itself, extending the discipline beyond
5365    /// the inner per-slot types ([`crate::Placement`],
5366    /// [`crate::SupervisorSpec`]) onto the outermost typed composition
5367    /// view every renderer consumes. Named `membros()` to match the
5368    /// storage field's name verbatim and the tatara-lisp author-
5369    /// surface term (`:membros`) the field's own docstring already
5370    /// carries; the accessor's identity maps onto the canonical
5371    /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
5372    /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
5373    /// every downstream consumer of the member list treats it as a
5374    /// read-only sequence — the slice-view is the narrowest borrow
5375    /// that supports every present + roadmapped consumer
5376    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
5377    /// backing `Vec`'s grow/push/reserve surface that no consumer of
5378    /// the typed view reaches for (the storage-side `Vec` remains
5379    /// reachable through the `pub membros` field for the mutation-
5380    /// carrying serde round-trip and per-test fixture-mutation paths).
5381    #[must_use]
5382    pub fn membros(&self) -> &[Membro] {
5383        self.membros.as_slice()
5384    }
5385
5386    /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
5387    /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
5388    /// accessor every per-Aplicacao contract-list reader keys off —
5389    /// returns the author-declared `:contratos` list verbatim as a
5390    /// `&[WitContract]` slice-view over the same backing buffer the raw
5391    /// `self.contratos.as_slice()` field access borrows from.
5392    ///
5393    /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
5394    /// WIT-typed edge list — the load-bearing set of directed edges
5395    /// on the application graph whose nodes are the `:membros` entries
5396    /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
5397    /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
5398    /// six-tuple is the edge identity every downstream duplicate gate
5399    /// keys off). Every per-`:contratos` entry pairs a `:de` source-
5400    /// Servico caller name + a `:para` destination-Servico callee name
5401    /// (through the lifted [`WitContract::source`] +
5402    /// [`WitContract::destination`] (7f0fd43) accessor pair on the
5403    /// caller/callee-Servico axis) with a `:wit` world-reference
5404    /// (through the lifted [`WitContract::world_ref`] (0804823)
5405    /// accessor) and the target-shape-appropriate payload-carrier
5406    /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
5407    /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
5408    /// (ed22b66) accessor on the per-target-shape payload-carrier
5409    /// axis). Every downstream consumer that fans on the edge-set
5410    /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
5411    /// name-set / self-edge / target-shape / dedup fan-out loop, the
5412    /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
5413    /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
5414    /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
5415    /// grouping loop, the `feira app graph` per-Aplicacao contract-
5416    /// count print line and per-contract tree traversal, every future
5417    /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
5418    /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
5419    /// mesh-policy overlay resolver's per-contract typed-edge weight
5420    /// reader).
5421    ///
5422    /// Prior to this lift the `.contratos` `Vec<WitContract>` was
5423    /// accessed inline at four production sites — the
5424    /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
5425    /// per-edge validate-loop traversal head (which drives every
5426    /// per-edge name-set membership lookup, self-edge check,
5427    /// target-shape dispatch, and dedup `HashSet` insert), the
5428    /// [`AplicacaoSpec::detect_sync_cycles`]'s
5429    /// `for c in &self.contratos` adjacency-list seed head (which
5430    /// drives every per-edge sync-vs-pub-sub partition and per-edge
5431    /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
5432    /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
5433    /// `BTreeMap` grouping loop head (which drives every per-CNP
5434    /// fan-out emit), and the `feira app graph` per-Aplicacao print
5435    /// line's `spec.contratos.len()` count formatter argument paired
5436    /// with the peer `for c in &spec.contratos` per-contract tree
5437    /// traversal — four open-coded field-accesses that expressed no
5438    /// compile-time link back to the typed slot. A future extension
5439    /// of the `:contratos` axis to a richer author surface (a
5440    /// per-cluster contract overlay the operator pins through a
5441    /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
5442    /// federation roadmap acknowledges, a per-tenant edge-policy
5443    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5444    /// materializer resolves per-CR at admission time, a per-edge
5445    /// weight scalar the future adaptive-placement engine reads to
5446    /// bias sync-subgraph routing, a promotion of the plain
5447    /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
5448    /// once virtual-actor-style dynamic-edge composition comes into
5449    /// typed scope) would have had to be threaded through all four
5450    /// open-coded copies in lockstep or one consumer would silently
5451    /// disagree with the peers on which edge-set a given Aplicacao
5452    /// resolves to — the validator's per-edge dedup `HashSet` seed
5453    /// reading the raw slot while the peer sync-cycle adjacency-list
5454    /// seed read an operator-resolved slot would silently split the
5455    /// build-time edge-set gate from the runtime deadlock-detection
5456    /// gate, a four-consumer split at the validator, the cycle
5457    /// detector, the CNP emitter, and the graph printer far from
5458    /// the source `caixa.lisp` with no field naming the edge-set-
5459    /// drift root cause. Lifting the resolution rule to a typed method on the
5460    /// substrate primitive means every downstream consumer of the
5461    /// Aplicacao's per-`:contratos` edge-list surface reaches for
5462    /// exactly one typed dispatch — the resolver's accept-set
5463    /// migrates as a unit on any future axis addition.
5464    ///
5465    /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
5466    /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
5467    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
5468    /// static-child-list `Vec`-carry axis, to the M3
5469    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
5470    /// on the peer per-`:placement` distribution-target-list `Vec`-
5471    /// carry axis, and to the immediately-adjacent sibling M3
5472    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
5473    /// the peer per-`:membros` node-list `Vec`-carry axis — the
5474    /// per-`:contratos` edge-list accessor is the natural pair of
5475    /// the per-`:membros` node-list accessor (graph edges over graph
5476    /// nodes; every graph-shaped consumer reads both). Same "one
5477    /// typed dispatch on the substrate primitive, thin projections
5478    /// at each consumer" discipline. The last remaining `Vec`-carry
5479    /// axis still unlifted at the time of this lift —
5480    /// [`crate::UpgradeFromEntry::instructions`]
5481    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
5482    /// list) — inherits this accessor's discipline as future
5483    /// compounding runs migrate its consumers onto the shared slice-
5484    /// return shape. Second `&[T]`-return accessor on the top-level
5485    /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
5486    /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
5487    /// `:contratos` are the two `Vec` fields on the outer typed
5488    /// composition view — `:politicas`, `:placement`, `:entrada` are
5489    /// scalar/option-shaped and already route through their per-slot
5490    /// accessor families). Named `contratos()` to match the storage
5491    /// field's name verbatim and the tatara-lisp author-surface term
5492    /// (`:contratos`) the field's own docstring already carries; the
5493    /// accessor's identity maps onto the canonical MESH-COMPOSITION
5494    /// §III.1 vocabulary the slot's docstring already reaches for.
5495    /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
5496    /// every downstream consumer of the contract list treats it as a
5497    /// read-only sequence — the slice-view is the narrowest borrow
5498    /// that supports every present + roadmapped consumer
5499    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
5500    /// backing `Vec`'s grow/push/reserve surface that no consumer of
5501    /// the typed view reaches for (the storage-side `Vec` remains
5502    /// reachable through the `pub contratos` field for the mutation-
5503    /// carrying serde round-trip and per-test fixture-mutation paths).
5504    #[must_use]
5505    pub fn contratos(&self) -> &[WitContract] {
5506        self.contratos.as_slice()
5507    }
5508
5509    /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
5510    /// per-Aplicacao mesh-policy composite-reference accessor every
5511    /// per-Aplicacao policy-block reader keys off — returns the author-
5512    /// declared `:politicas` composite verbatim as a `&MeshPolicy`
5513    /// reference over the same backing storage the raw `&self.politicas`
5514    /// field access borrows from.
5515    ///
5516    /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
5517    /// mesh-policy composite — the load-bearing container of every
5518    /// mesh-level operational-policy axis every downstream mesh-artifact
5519    /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
5520    /// mesh-policy overlay is the single typed surface a
5521    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
5522    /// from). Every per-`:politicas` axis threads through a lifted
5523    /// per-slot accessor on the [`MeshPolicy`] type: the
5524    /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
5525    /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
5526    /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
5527    /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
5528    /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
5529    /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
5530    /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
5531    /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
5532    /// accessor. Every downstream consumer that reaches for a policy
5533    /// axis first passes through this outer accessor onto the composite
5534    /// and then dispatches onto the per-axis accessor — the two-level
5535    /// dispatch means every per-`:politicas` reader now routes through
5536    /// a typed dispatch on the substrate primitive at both altitudes.
5537    ///
5538    /// Prior to this lift the `.politicas` `MeshPolicy` composite was
5539    /// accessed inline at four production sites — the
5540    /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
5541    /// &self.politicas;` traversal seed (which drives every per-axis
5542    /// zero-floor + upper-cap + canonical-form bracket dispatch through
5543    /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
5544    /// `p.rate_limit()` on the axis-level lifted accessors), the
5545    /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
5546    /// emitter's `spec.politicas.mtls_required()` field-then-accessor
5547    /// chain (which drives every per-`(:de, :para)` CNP
5548    /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
5549    /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
5550    /// timeout + retry overlay emitter's paired
5551    /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
5552    /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
5553    /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
5554    /// open-coded outer-field accesses that expressed no compile-time
5555    /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
5556    /// future extension of the `:politicas` outer axis to a richer
5557    /// author surface (a per-cluster policy overlay the operator pins
5558    /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
5559    /// §V federation roadmap acknowledges, a per-tenant policy-alias
5560    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
5561    /// resolves per-CR at admission time, a per-Aplicacao dynamic
5562    /// policy-composite derivation the future adaptive-placement engine
5563    /// computes from a per-cluster load-topology reader, a promotion of
5564    /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
5565    /// partition once virtual-actor-style dynamic-mesh-policy
5566    /// composition comes into typed scope) would have had to be threaded
5567    /// through all four open-coded copies in lockstep or one consumer
5568    /// would silently disagree with the peers on which mesh-policy
5569    /// composite a given Aplicacao resolves to — the validator's
5570    /// per-axis bracket-dispatch seed reading the raw slot while the
5571    /// peer CNP mTLS-overlay emitter read an operator-resolved slot
5572    /// would silently split the build-time policy-shape gate from the
5573    /// runtime CNP-emission gate, a four-consumer split at the
5574    /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
5575    /// the source `caixa.lisp` with no field naming the policy-drift
5576    /// root cause. Lifting the resolution rule to a typed method on the
5577    /// substrate primitive means every downstream consumer of the
5578    /// Aplicacao's per-`:politicas` mesh-policy composite surface
5579    /// reaches for exactly one typed dispatch — the resolver's accept-
5580    /// set migrates as a unit on any future axis addition.
5581    ///
5582    /// First `&Composite`-return accessor on the top-level M3 mesh-slot
5583    /// `AplicacaoSpec` type itself — sibling to the seed slice-return
5584    /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
5585    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
5586    /// close the two `Vec`-carry axes on the outer typed composition
5587    /// view; the outer `:politicas` composite-reference axis is the
5588    /// natural pair to the paired outer `Vec`-carry accessors on the
5589    /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
5590    /// emitter reads all four axes as one unit (graph nodes + graph
5591    /// edges + mesh policy + placement pool). Peer to the same
5592    /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
5593    /// slot: every M2 `SupervisorSpec`-scoped composite reader
5594    /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
5595    /// `restart_window`, `children`) already routes through the M2
5596    /// `SupervisorSpec` accessor family — this lift extends the same
5597    /// "one typed dispatch on the substrate primitive at the outer
5598    /// composition altitude" discipline to the M3 mesh-slot
5599    /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
5600    /// remaining peer outer-composite axes still unlifted at the time
5601    /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
5602    /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
5603    /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
5604    /// inherit this accessor's discipline as future compounding runs
5605    /// migrate their consumers onto the shared reference-return shape.
5606    /// Named `politicas()` to match the storage field's name verbatim
5607    /// and the tatara-lisp author-surface term (`:politicas`) the
5608    /// field's own docstring already carries; the accessor's identity
5609    /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
5610    /// slot's docstring already reaches for. Returns `&MeshPolicy`
5611    /// (not the owning composite by copy or clone) because every
5612    /// downstream consumer of the mesh-policy composite treats it as a
5613    /// read-only per-axis dispatch source — the reference-view is the
5614    /// narrowest borrow that supports every present + roadmapped
5615    /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
5616    /// emptiness probe) without cloning the composite through every
5617    /// consumer's fast path.
5618    #[must_use]
5619    pub fn politicas(&self) -> &MeshPolicy {
5620        &self.politicas
5621    }
5622
5623    /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
5624    /// per-Aplicacao distribution-composite composite-reference accessor
5625    /// every per-Aplicacao placement-block reader keys off — returns the
5626    /// author-declared `:placement` composite verbatim as a `&Placement`
5627    /// reference over the same backing storage the raw `&self.placement`
5628    /// field access borrows from.
5629    ///
5630    /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
5631    /// distribution composite — the load-bearing container of every
5632    /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
5633    /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
5634    /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
5635    /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
5636    /// hosting-pool identity, §V for the `M3-Adaptive`-compression
5637    /// `:affinity` hint). Every per-`:placement` axis threads through a
5638    /// lifted per-slot accessor on the [`Placement`] type: the
5639    /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
5640    /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
5641    /// per-cluster distribution-target slice-return accessor, the
5642    /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
5643    /// optional-scalar accessor, and the [`Placement::shard_key`]
5644    /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
5645    /// downstream consumer that reaches for a placement axis first passes
5646    /// through this outer accessor onto the composite and then dispatches
5647    /// onto the per-axis accessor — the two-level dispatch means every
5648    /// per-`:placement` reader now routes through a typed dispatch on the
5649    /// substrate primitive at both altitudes.
5650    ///
5651    /// Prior to this lift the `.placement` `Placement` composite was
5652    /// accessed inline at three production sites — the
5653    /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
5654    /// seed (six `self.placement.<axis>()` field-then-inner-accessor
5655    /// chains: the pre-flight `.clusters().is_empty()` refusal probe
5656    /// paired with the `.estrategia()` diagnostic-carry copy, the per-
5657    /// cluster `.clusters()` validate-loop traversal head, the per-
5658    /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
5659    /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
5660    /// paired with the shape-gate cascade's `.shard_key()` /
5661    /// `.estrategia()` diagnostic-carry pair), the
5662    /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
5663    /// per-entry placement-block emitter's outer
5664    /// `serde_yaml::to_value(&spec.placement)` composite-serialization
5665    /// seed (which fans onto every per-cluster `programs[]` entry as a
5666    /// self-describing distribution overlay the aggregator filters by),
5667    /// and the `feira app graph` per-Aplicacao print line's paired
5668    /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
5669    /// then-inner-accessor chains (which drive the human-readable
5670    /// distribution summary of the typed Aplicacao view) — three open-
5671    /// coded outer-field accesses that expressed no compile-time link
5672    /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
5673    /// extension of the `:placement` outer axis to a richer author surface
5674    /// (a per-cluster placement overlay the operator pins through a
5675    /// future `:placement-overrides` slot the MESH-COMPOSITION §V
5676    /// federation roadmap acknowledges, a per-tenant placement-alias
5677    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
5678    /// resolves per-CR at admission time, a per-Aplicacao dynamic
5679    /// placement-composite derivation the future M5 adaptive-placement
5680    /// engine computes from a per-cluster load-topology reader, a
5681    /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
5682    /// partition once Orleans-style virtual-actor dynamic-placement comes
5683    /// into typed scope) would have had to be threaded through all three
5684    /// open-coded copies in lockstep or one consumer would silently
5685    /// disagree with the peers on which placement composite a given
5686    /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
5687    /// seed reading the raw slot while the peer
5688    /// `programs_for_aplicacao` emitter read an operator-resolved slot
5689    /// would silently split the build-time distribution-shape gate from
5690    /// the runtime programs.yaml distribution-annotation gate, a three-
5691    /// consumer split at the validator, the programs.yaml emitter, and
5692    /// the `feira app graph` printer far from the source `caixa.lisp`
5693    /// with no field naming the placement-drift root cause. Lifting the
5694    /// resolution rule to a typed method on the substrate primitive
5695    /// means every downstream consumer of the Aplicacao's per-
5696    /// `:placement` distribution composite surface reaches for exactly
5697    /// one typed dispatch — the resolver's accept-set migrates as a unit
5698    /// on any future axis addition.
5699    ///
5700    /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
5701    /// `AplicacaoSpec` type itself — sibling to the seed
5702    /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
5703    /// composite-reference accessor on the peer per-`:politicas` outer-
5704    /// composite axis, and to the paired slice-return accessors
5705    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
5706    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
5707    /// the two `Vec`-carry axes on the outer typed composition view; the
5708    /// outer `:placement` composite-reference axis is the natural pair
5709    /// to the peer `:politicas` composite-reference axis on the two
5710    /// operationally-symmetric M3 mesh slots (`:politicas` carries the
5711    /// how-to-run policy overlay, `:placement` carries the where-to-run
5712    /// distribution composite — every whole-Aplicacao mesh-artifact
5713    /// emitter reads both as one unit). Same "one typed dispatch on the
5714    /// substrate primitive, thin projections at each consumer"
5715    /// discipline the peer per-`:politicas` composite-reference axis
5716    /// already routes through. The one remaining outer-composite axis
5717    /// still unlifted at the time of this lift —
5718    /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
5719    /// external-gateway composite) — inherits this accessor's discipline
5720    /// as the next compounding run migrates its consumers onto the shared
5721    /// reference-return shape, closing the outer-composite altitude on
5722    /// every M3 mesh-slot axis. Named `placement()` to match the storage
5723    /// field's name verbatim and the tatara-lisp author-surface term
5724    /// (`:placement`) the field's own docstring already carries; the
5725    /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
5726    /// vocabulary the slot's docstring already reaches for. Returns
5727    /// `&Placement` (not the owning composite by copy or clone) because
5728    /// every downstream consumer of the placement composite treats it as
5729    /// a read-only per-axis dispatch source — the reference-view is the
5730    /// narrowest borrow that supports every present + roadmapped consumer
5731    /// (per-axis accessor dispatch, serde composite-serialization) without
5732    /// cloning the composite through every consumer's fast path.
5733    #[must_use]
5734    pub fn placement(&self) -> &Placement {
5735        &self.placement
5736    }
5737
5738    /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
5739    /// per-Aplicacao external-gateway composite optional-composite-
5740    /// reference accessor every per-Aplicacao gateway-block reader
5741    /// keys off — returns the author-declared `:entrada` composite
5742    /// verbatim as an `Option<&Entrada>` reference over the same
5743    /// backing storage the raw `self.entrada.as_ref()` field access
5744    /// borrows from, with `None` naming the internal-only mesh shape
5745    /// (the author-omitted `:entrada` slot the K8s Gateway API v1
5746    /// gateway_routes emitter treats as "emit nothing" and the peer
5747    /// `feira app graph` printer treats as "internal-only mesh").
5748    ///
5749    /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
5750    /// external-gateway composite — the load-bearing container of
5751    /// every does-this-Aplicacao-expose-a-public-endpoint axis every
5752    /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
5753    /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
5754    /// hostname axis, §III.4 for the `:para` destination-Servico
5755    /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
5756    /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
5757    /// axis threads through a lifted per-slot accessor on the
5758    /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
5759    /// Gateway-API `Listener.hostname` scalar accessor, the paired
5760    /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
5761    /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
5762    /// backendRefs destination-Servico scalar accessor, the
5763    /// [`Entrada::resolved_paths`] path-fallback resolver, and the
5764    /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
5765    /// scalar accessor. Every downstream consumer that reaches for
5766    /// an entrada axis first passes through this outer accessor onto
5767    /// the composite and then dispatches onto the per-axis accessor
5768    /// — the two-level dispatch means every per-`:entrada` reader
5769    /// now routes through a typed dispatch on the substrate primitive
5770    /// at both altitudes.
5771    ///
5772    /// Prior to this lift the `.entrada` `Option<Entrada>` composite
5773    /// was accessed inline at four production sites — the
5774    /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
5775    /// gate's `if let Some(e) = &self.entrada { … }` traversal head
5776    /// (which drives every per-axis refusal on the composite: the
5777    /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
5778    /// `EntradaMemberMissing` membership lookup against the
5779    /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
5780    /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
5781    /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
5782    /// per-path shape gate on each entry of `e.paths`), the
5783    /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
5784    /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
5785    /// composite-projection seed (which drives the destination-
5786    /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
5787    /// backendRefs port emitter fans on), the
5788    /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
5789    /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
5790    /// early-return seed (which drives the "no `:entrada` ⇒ no
5791    /// external artifacts" partition on the whole-Aplicacao Gateway-
5792    /// API emitter's fan-out), and the `feira app graph` per-
5793    /// Aplicacao print line's `if let Some(e) = &spec.entrada`
5794    /// external-gateway summary emitter (which drives the human-
5795    /// readable `entrada: host → para (paths=…, port=…)` /
5796    /// `entrada: (internal-only mesh)` partition on the typed
5797    /// Aplicacao view) — four open-coded outer-field accesses that
5798    /// expressed no compile-time link back to the typed slot at the
5799    /// [`AplicacaoSpec`] altitude. A future extension of the
5800    /// `:entrada` outer axis to a richer author surface (a
5801    /// multi-`:entrada` list the M4 CR materializer resolves per-CR
5802    /// at admission time so an Aplicacao can expose a public-web +
5803    /// admin-web pair, a per-cluster `:entrada-overrides` slot the
5804    /// MESH-COMPOSITION §V federation roadmap acknowledges so an
5805    /// operator can pin a per-cluster hostname override without
5806    /// re-authoring the `caixa.lisp`, a promotion of the plain
5807    /// `Option<Entrada>` to a richer `{single, multi}` partition once
5808    /// the multi-`:entrada` roadmap lands) would have had to be
5809    /// threaded through all four open-coded copies in lockstep or one
5810    /// consumer would silently disagree with the peers on which
5811    /// entrada composite a given Aplicacao resolves to — the
5812    /// validator's per-axis bracket-dispatch seed reading the raw
5813    /// slot while the peer `gateway_routes` emitter read an
5814    /// operator-resolved slot would silently split the build-time
5815    /// gateway-shape gate from the runtime Gateway + HTTPRoute
5816    /// emission gate, a four-consumer split at the validator, the
5817    /// `port_for_destination` L4-port resolver, the `gateway_routes`
5818    /// emitter, and the `feira app graph` printer far from the
5819    /// source `caixa.lisp` with no field naming the entrada-drift
5820    /// root cause. Lifting the resolution rule to a typed method on
5821    /// the substrate primitive means every downstream consumer of
5822    /// the Aplicacao's per-`:entrada` external-gateway composite
5823    /// surface reaches for exactly one typed dispatch — the
5824    /// resolver's accept-set migrates as a unit on any future axis
5825    /// addition.
5826    ///
5827    /// Third and final `&Composite`-return accessor on the top-level
5828    /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
5829    /// unlifted outer-composite axis on the outer typed composition
5830    /// view, sibling to the seed [`AplicacaoSpec::politicas`]
5831    /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
5832    /// accessor on the per-`:politicas` outer-composite axis and to
5833    /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
5834    /// distribution-composite composite-reference accessor on the
5835    /// per-`:placement` outer-composite axis; extends the outer-
5836    /// composite reference-return discipline the two peers already
5837    /// route through onto the last unlifted per-`AplicacaoSpec`
5838    /// outer-composite axis. The `:entrada` outer-composite axis is
5839    /// the natural pair to the two peer outer-composite axes on the
5840    /// three operationally-symmetric M3 mesh-slot outer composites
5841    /// (`:politicas` carries the how-to-run policy overlay,
5842    /// `:placement` carries the where-to-run distribution composite,
5843    /// `:entrada` carries the who-can-reach-it external-gateway
5844    /// composite — every whole-Aplicacao mesh-artifact emitter reads
5845    /// all three as one unit). Same "one typed dispatch on the
5846    /// substrate primitive, thin projections at each consumer"
5847    /// discipline the peer outer-composite axes already route through.
5848    /// Named `entrada()` to match the storage field's name verbatim
5849    /// and the tatara-lisp author-surface term (`:entrada`) the
5850    /// field's own docstring already carries; the accessor's
5851    /// identity maps onto the canonical MESH-COMPOSITION §III.4
5852    /// vocabulary the slot's docstring already reaches for. Returns
5853    /// `Option<&Entrada>` (not the owning composite by copy or
5854    /// clone) because every downstream consumer of the entrada
5855    /// composite treats it as a read-only per-axis dispatch source
5856    /// — the reference-view is the narrowest borrow that supports
5857    /// every present + roadmapped consumer (per-axis accessor
5858    /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
5859    /// port-fallback projection, early-return partition on the
5860    /// `None` arm) without cloning the composite through every
5861    /// consumer's fast path. The `Option` half of the return-type
5862    /// preserves the load-bearing "author-omitted `:entrada` ⇒
5863    /// internal-only mesh" partition (not a default composite the
5864    /// downstream must reject on emptiness) — the accessor projects
5865    /// the raw `Option<Entrada>` slot's presence bit through the
5866    /// reference-return unchanged.
5867    #[must_use]
5868    pub fn entrada(&self) -> Option<&Entrada> {
5869        self.entrada.as_ref()
5870    }
5871
5872    /// Validate the typed shape:
5873    ///   - `:membros` is non-empty; every entry has a non-empty `:caixa`
5874    ///     and a non-empty `:versao`; no two entries share the same
5875    ///     `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
5876    ///     not a multiset)
5877    ///   - every `:contratos` :de + :para must be in `:membros`
5878    ///   - no `:contratos` edge is a self-edge (`:de == :para`) — a
5879    ///     contract is an inter-Servico edge, so a Servico contracting
5880    ///     with itself is a build error under every WIT shape
5881    ///     (MESH-COMPOSITION §III.1)
5882    ///   - no two `:contratos` entries agree on
5883    ///     `(de, para, wit, endpoint, subject, slot)` — the typed-graph
5884    ///     edges are a set, not a multiset (peer of the `:membros` /
5885    ///     `:placement :clusters` / `:entrada :paths` duplicate gates)
5886    ///   - `:entrada :para` must be in `:membros`
5887    ///   - `:placement Sharded` must declare `:shard-key` (non-empty);
5888    ///     `:placement Replicated`/`SingleNode` must NOT declare
5889    ///     `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
5890    ///     consumes it (MESH-COMPOSITION §II.4), and the typed partition
5891    ///     between strategy and shard-key is symmetric: every validated
5892    ///     `Placement` has `shard_key.is_some()` iff `estrategia ==
5893    ///     Sharded`
5894    ///   - every `:placement` strategy must declare ≥1 `:clusters` entry —
5895    ///     `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
5896    ///     the shard pool (MESH-COMPOSITION §III.1)
5897    ///   - every `:clusters` entry is non-empty and unique
5898    ///   - `:placement :affinity`, when set, is non-empty
5899    ///   - the synchronous-`:contratos` subgraph is acyclic
5900    ///     (MESH-COMPOSITION §III.3)
5901    ///   - every declared `:politicas` value is operationally meaningful
5902    ///     (zero timeout, zero retries, zero breaker thresholds, zero rate
5903    ///     limit are all build errors — MESH-COMPOSITION §V CSE invariants;
5904    ///     omit the field instead to express "no policy on this axis")
5905    pub fn validate(&self) -> Result<(), AplicacaoError> {
5906        self.validate_membros()?;
5907        let names: std::collections::HashSet<&str> =
5908            self.membros().iter().map(Membro::nome).collect();
5909
5910        // Identity key for the typed-edge duplicate gate below: every
5911        // field that distinguishes one contract from another. Two
5912        // entries that agree on all six are *the same edge declared
5913        // twice*, the typed-graph analogue of duplicate `:membros` /
5914        // `:placement :clusters` / `:entrada :paths` entries (which
5915        // are already build errors at this layer). Rejecting it at the
5916        // validate gate closes a renderer-side footgun: caixa-mesh's
5917        // `cilium_network_policies` keys each emitted policy by
5918        // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
5919        // (de, para) and identical payload would land as two K8s
5920        // objects with colliding `metadata.name`, rejected at apply
5921        // time far from the source caixa.lisp.
5922        let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
5923            std::collections::HashSet::new();
5924        for c in self.contratos() {
5925            // Per-axis value-shape gate on every `:contratos` name
5926            // reference, before any graph-membership lookup. Empty +
5927            // DNS-1123-malformed `:de`/`:para` values silently fell
5928            // through to `ContratoMemberMissing` at the lookup arm
5929            // because every `:membros :caixa` is shape-validated
5930            // (3f9d7a0), so the `names` set structurally cannot contain
5931            // an empty / malformed string and the membership-lookup
5932            // diagnostic always misframed the root cause as
5933            // "this caixa is not in `:membros`". The shape gate runs
5934            // ahead of the lookup so structurally-impossible-to-match
5935            // inputs route through the narrower self-locating
5936            // diagnostic, preserving the legitimate "well-shaped
5937            // phantom reference" arm. `:de` runs before `:para` per
5938            // the canonical edge-direction order the existing
5939            // membership lookup, self-edge check, target dispatch,
5940            // and diagnostic strings already use.
5941            // Route the per-`:contratos` per-arm DNS-1123 shape-gate arg
5942            // + the paired [`AplicacaoError::ContratoMemberMissing`]
5943            // diagnostic's `caixa:` carrier through the lifted
5944            // [`WitContract::source`] / [`WitContract::destination`]
5945            // scalar accessors rather than the raw `&c.de` / `&c.para`
5946            // `&String`-borrow arg site + the raw `c.de.clone()` /
5947            // `c.para.clone()` field-access `String`-carry sites — the
5948            // last unlifted per-`:contratos` raw-field-access sites in
5949            // the M3 mesh-slot validator's per-edge per-arm shape-gate
5950            // arg + phantom-name diagnostic wrap-envelope emit surface.
5951            // `c.source()` is byte-identical to `&c.de` (pinned by the
5952            // sibling `wit_contract_source_returns_de_byte_equal_across_permutations`
5953            // + `wit_contract_source_borrows_from_de_storage` accessor
5954            // tests) and `c.destination()` is byte-identical to `&c.para`
5955            // (pinned by the sibling
5956            // `wit_contract_destination_returns_para_byte_equal_across_permutations`
5957            // + `wit_contract_destination_borrows_from_para_storage`
5958            // accessor tests) — so a future rebrand of either underlying
5959            // storage flows through the accessor's one body without a
5960            // coordinated per-consumer rewrite across the M3 mesh
5961            // validator's per-edge shape-gate + phantom-name refusal
5962            // arms. Peer of the sibling per-`:contratos` self-loop
5963            // arm's `.source().to_string()` / `.world_ref().to_string()`
5964            // `String`-carry sites the earlier convergence lifted onto
5965            // the same accessor pair.
5966            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
5967            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
5968            if !names.contains(c.source()) {
5969                return Err(AplicacaoError::ContratoMemberMissing {
5970                    caixa: c.source().to_string(),
5971                });
5972            }
5973            if !names.contains(c.destination()) {
5974                return Err(AplicacaoError::ContratoMemberMissing {
5975                    caixa: c.destination().to_string(),
5976                });
5977            }
5978            // A `:contratos` entry is an *inter*-Servico contract
5979            // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
5980            // typed edge between two distinct graph nodes. An edge whose
5981            // `:de` equals its `:para` is a Servico contracting with
5982            // itself — a degenerate edge under every WIT shape. The
5983            // synchronous shapes were caught only incidentally, and with
5984            // a misleading diagnostic: `detect_sync_cycles` reported
5985            // `cart → cart` as a `ContratoCycle` whose path is
5986            // `["cart", "cart"]` — framing a self-edge as a multi-node
5987            // deadlock. The pub-sub shape slipped through entirely
5988            // (`detect_sync_cycles` excludes `WitTarget::PubSub`, so a
5989            // `nats:pub-sub` edge from a member to itself silently
5990            // validated, then rendered a `CiliumNetworkPolicy` whose
5991            // endpointSelector and fromEndpoints both name the same
5992            // program — a self-allow rule that is a no-op, since
5993            // intra-pod traffic never traverses the mesh). A self-edge's
5994            // runtime meaning is an in-process call, which doesn't go
5995            // through the mesh at all, so no `:contratos` edge can carry
5996            // it. Firing the gate before the `:wit`/`target()` shape
5997            // checks means the structural "this edge can't exist" error
5998            // precedes the narrower payload-shape diagnostics, and shape-
5999            // agnostically covers all four `WitTarget` arms (HTTP / Store
6000            // / Capability / PubSub) at one point — closing the pub-sub
6001            // hole and replacing the misleading cycle diagnostic in one
6002            // gate. Peer of the duplicate-`:contratos` / duplicate-
6003            // `:membros` set gates: both reject a structurally
6004            // ill-formed graph at the typed surface, before the renderer
6005            // emits a K8s object that fails or no-ops far from the source
6006            // caixa.lisp.
6007            // Route the per-`:contratos` structural self-edge probe
6008            // through the lifted [`WitContract::is_self_loop`] typed
6009            // predicate rather than the raw `c.de == c.para` field-
6010            // equality check — the one production consumer of the per-
6011            // `:contratos` caller-equals-callee endpoint-equality axis
6012            // now keys off exactly one typed dispatch on the substrate
6013            // primitive, so any future rebrand of the axis (an M4-typed-
6014            // caller enum whose identity comparison rule the predicate
6015            // could route through, a per-cluster caller/callee-alias
6016            // table the M4 CR materializer resolves per-CR before the
6017            // equality probe) migrates as a single caixa-core edit
6018            // rather than a coordinated rewrite of the gate + every
6019            // downstream self-edge consumer. Peer of the sibling
6020            // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
6021            // [`WitContract::is_store`] shape-predicate routing on the
6022            // `:wit` world-ref axis, extended onto the per-edge
6023            // endpoint-equality axis.
6024            //
6025            // Route the paired [`AplicacaoError::ContratoSelfLoop`]
6026            // diagnostic's `caixa:` / `wit:` carriers through the
6027            // lifted [`WitContract::source`] / [`WitContract::world_ref`]
6028            // scalar accessors rather than the raw `c.de.clone()` /
6029            // `c.wit.clone()` field-access `String`-carry sites — the
6030            // last unlifted per-`:contratos` raw-field-access
6031            // `.clone()` sites in the M3 mesh-slot validator's self-
6032            // edge refusal arm. `.source().to_string()` is byte-
6033            // identical to `.de.clone()` (pinned by the sibling
6034            // `source_returns_de_byte_equal_across_permutations` accessor
6035            // test), and `.world_ref().to_string()` is byte-identical
6036            // to `.wit.clone()` (pinned by the sibling
6037            // `world_ref_returns_wit_byte_equal_across_permutations`
6038            // accessor test) — so a future rebrand of either underlying
6039            // storage flows through the accessor's one body without a
6040            // coordinated per-consumer rewrite across the M3 mesh
6041            // validator.
6042            if c.is_self_loop() {
6043                return Err(AplicacaoError::ContratoSelfLoop {
6044                    caixa: c.source().to_string(),
6045                    wit: c.world_ref().to_string(),
6046                });
6047            }
6048            if c.world_ref().is_empty() {
6049                let (de, para) = c.edge_pair();
6050                return Err(AplicacaoError::EmptyWit { de, para });
6051            }
6052            // Shape ↔ target consistency — surfaces "HTTP wit without
6053            // :endpoint", "NATS wit with :endpoint set", etc. as named
6054            // build errors instead of silent renderer drops. Threaded
6055            // through the duplicate-edge diagnostic below (via
6056            // [`WitTarget::label`]) so the "which typed target arm did
6057            // the duplicate carry" question is answered by the typed
6058            // enum's variant discriminator, not by re-probing the raw
6059            // `Option<String>` payload fields.
6060            let target_view = c.target()?;
6061            // Contract identity: (de, para, wit, endpoint, subject, slot).
6062            // Two contracts that match on all six are the same typed edge
6063            // declared twice — author error, not a legitimate variant of
6064            // "same caller-callee pair, different payload" (e.g.
6065            // cart→catalog at /products vs /search), which keeps distinct
6066            // identity keys via the differing endpoint payloads.
6067            //
6068            // Route the six-axis dedup key through the lifted
6069            // [`WitContract::identity`] composite-projection accessor
6070            // rather than the inline six-tuple builder — the two
6071            // substrate primitives on the per-`:contratos` identity axis
6072            // (the [`ContratoIdentity`] type alias's six axes, this
6073            // dedup-key's six tuple arms) now migrate as a unit on any
6074            // future axis addition. Peer of the sibling per-`:contratos`
6075            // composite-projection [`WitContract::edge_pair`] /
6076            // [`WitContract::edge_triple`] accessors on the
6077            // caller-callee / caller-callee-wit prefix axes; extends
6078            // the discipline onto the full-identity axis that carries
6079            // the three payload-shape arms too.
6080            let key = c.identity();
6081            crate::render::insert_first_seen(&mut seen_contracts, key, || {
6082                // Route the per-`:contratos` duplicate-gate diagnostic's
6083                // `(de, para, wit)` triple through the lifted
6084                // [`WitContract::edge_triple`] typed accessor rather
6085                // than pairing `edge_pair()` for the `(de, para)` prefix
6086                // with a raw `c.wit.clone()` for the `wit:` tail — the
6087                // paired-with-raw-field-access shape was the last
6088                // per-`:contratos` diagnostic constructor bypassing the
6089                // substrate-primitive composite projection, sibling to
6090                // the eight [`AplicacaoError::Contrato*`] triple-
6091                // carrying constructors [`WitContract::target`]'s edge
6092                // closure feeds through the same accessor.
6093                let (de, para, wit) = c.edge_triple();
6094                AplicacaoError::ContratoDuplicate {
6095                    de,
6096                    para,
6097                    wit,
6098                    target: target_view.label(),
6099                }
6100            })?;
6101        }
6102
6103        // Cycles in the synchronous-edge subgraph are build errors
6104        // (MESH-COMPOSITION §III.3). Pub-sub edges are excluded — they
6105        // are "acyclic by construction" because the publisher fires
6106        // and forgets, so no caller blocks on a downstream that loops
6107        // back to it.
6108        self.detect_sync_cycles()?;
6109
6110        if let Some(e) = self.entrada() {
6111            // Route the per-`:entrada` composite-reference read
6112            // through the lifted [`AplicacaoSpec::entrada`] accessor
6113            // rather than the raw `&self.entrada` field access — the
6114            // shape-and-membership gate's traversal head is now the
6115            // canonical read-side surface every per-Aplicacao entrada
6116            // consumer routes through, closing the fourth of four
6117            // open-coded outer-field accesses on the per-`:entrada`
6118            // outer-composite axis.
6119            //
6120            // Shape gate on `:entrada :para` runs ahead of the
6121            // membership lookup. Every `:membros :caixa` past
6122            // `validate_membro_caixa` is a valid DNS-1123 label
6123            // (3f9d7a0), so the `names` set structurally cannot
6124            // contain an empty / malformed string and the membership-
6125            // lookup diagnostic always misframed the root cause as
6126            // "this caixa is not in `:membros`". The shape gate
6127            // routes structurally-impossible-to-match inputs through
6128            // the narrower self-locating diagnostic, preserving the
6129            // legitimate "well-shaped phantom reference" arm — the
6130            // same trajectory the peer `:membros :caixa` (3f9d7a0),
6131            // `:placement :clusters` (6c8c00b), and `:contratos :de`
6132            // / `:para` (8d5af6b) axes already follow. This closes
6133            // the fourth and last Aplicacao-level Servico-name
6134            // reference axis on the canonical DNS-1123 floor.
6135            // Route the per-`:entrada :para` byte-string reads through
6136            // the lifted [`Entrada::destination`] accessor rather than
6137            // the raw `e.para` field access — the three
6138            // per-`AplicacaoSpec::validate` `:entrada :para` consumers
6139            // (shape-gate `validate_entrada_para` arg, membership
6140            // lookup, `EntradaMemberMissing` diagnostic carry) now key
6141            // off exactly one typed dispatch on the substrate
6142            // primitive, closing the last unlifted per-`:entrada :para`
6143            // raw-field-access axis on the M3 mesh-slot validator.
6144            // The `.destination().to_string()` at the diagnostic site
6145            // is byte-identical to `.para.clone()` — pinned by the
6146            // sibling `destination_returns_entrada_para_byte_equal` +
6147            // `destination_borrows_from_entrada_para_storage` accessor
6148            // tests — so a future rebrand of the underlying `:para`
6149            // storage (a lift from `String` to a typed
6150            // `ServicoName(String)` newtype, a per-Aplicacao interning
6151            // arena the M4 CR materializer authors, a
6152            // `smol_str::SmolStr` inline-buffer swap) flows through
6153            // the accessor's one body without a coordinated
6154            // per-consumer rewrite across the M3 mesh validator.
6155            validate_entrada_para(e.destination())?;
6156            if !names.contains(e.destination()) {
6157                return Err(AplicacaoError::EntradaMemberMissing {
6158                    para: e.destination().to_string(),
6159                });
6160            }
6161            // Route the per-`:entrada :host` byte-string reads through
6162            // the lifted [`Entrada::hostname`] accessor rather than
6163            // the raw `e.host` field access — the emptiness gate and
6164            // the shape-gate `validate_entrada_host` arg now key off
6165            // exactly one typed dispatch on the substrate primitive,
6166            // closing the last unlifted per-`:entrada :host` raw-
6167            // field-access axis on the M3 mesh-slot validator. Peer
6168            // of the sibling per-`:entrada :para` convergence above
6169            // and pinned by the existing
6170            // `hostname_returns_entrada_host_byte_equal` +
6171            // `hostnames_returns_singleton_of_hostname_accessor`
6172            // accessor tests, so any future
6173            // Gateway-API-shaped host renormalization (a wildcard-
6174            // label lift, a trailing-`.` FQDN substitution, an IDNA
6175            // Punycode round-trip the SNI fan-out overlay authors)
6176            // flows through the accessor's one body without a
6177            // coordinated per-consumer rewrite across the M3 mesh
6178            // validator.
6179            if e.hostname().is_empty() {
6180                return Err(AplicacaoError::EmptyEntradaHost);
6181            }
6182            // The `:host` lands verbatim as a K8s Gateway API v1
6183            // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
6184            // both apiserver-validated against the same restrictive
6185            // pattern: lowercase RFC 1123 DNS subdomain, optional
6186            // single leading wildcard label (`*.`), max length 253,
6187            // per-label max length 63, no IP literals, no scheme,
6188            // no port. Until this gate landed `validate()` only
6189            // refused the empty string (`EmptyEntradaHost`); a
6190            // structurally invalid hostname (`"https://example.com"`,
6191            // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
6192            // `"_underscored.example.com"`, `"FOO.example.com"`,
6193            // `"checkout.quero.cloud."`) silently passed validate
6194            // and the apiserver `field is invalid` error surfaced at
6195            // `kubectl apply` time, far from the source caixa.lisp.
6196            // Lifting the gate to caixa-build time mirrors the
6197            // `:entrada :paths` value-shape trajectory (eb3456d) and
6198            // closes the last unstructured `:entrada` axis.
6199            validate_entrada_host(e.hostname())?;
6200            // Structural-floor gate on `:entrada :port`: every
6201            // validated `Entrada::port` past this gate lies in
6202            // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
6203            // type-inferred ceiling closes the top edge, so no companion
6204            // upper-cap arm is needed here — unlike the peer capped-
6205            // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
6206            // `require_positive_bounded_u32` bracket covers both edges).
6207            // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
6208            // accept-set-floor const rather than the prior inline
6209            // `if e.port == 0` byte-check so a future rebrand of the
6210            // accept-set floor (a hypothetical unprivileged-only
6211            // migration lifting the floor to `1024`, a per-cluster
6212            // scoping the operator pins through a future
6213            // `:placement :port-floor` slot as the M4 typed-slot
6214            // trajectory adds it, the future
6215            // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6216            // per-Aplicacao gateway resolver reaching for the same
6217            // floor) is a one-line edit on the canonical
6218            // [`SERVICO_PORT_MIN`] declaration, not a coordinated
6219            // rewrite across the emit site + the pin test + every
6220            // future per-target renderer the substrate adds.
6221            if e.port() < SERVICO_PORT_MIN {
6222                return Err(AplicacaoError::EntradaPortZero);
6223            }
6224            // Each `:entrada :paths` entry becomes a K8s Gateway API
6225            // HTTPRoute `matches[].path.value`. The Gateway API rejects
6226            // values that don't start with `/` for `type: PathPrefix`,
6227            // and an empty value is meaningless. Surface those as build
6228            // errors (MESH-COMPOSITION §III.3) rather than apply-time
6229            // failures. Empty `:paths` itself is fine — caixa-mesh
6230            // falls back to a single `/` catch-all.
6231            let mut seen = std::collections::HashSet::new();
6232            // Route the per-entry value-shape gate's traversal head
6233            // through the lifted [`Entrada::paths`] slice accessor
6234            // rather than the raw `&e.paths` field access — the
6235            // per-Aplicacao `:entrada :paths` validate loop now keys
6236            // off the canonical raw-slot surface every downstream
6237            // per-`:entrada` path-list consumer (the sibling
6238            // [`Entrada::resolved_paths`] fallback-applying resolver
6239            // internal reads, `feira app graph`'s per-Aplicacao entrada
6240            // summary line's `{:?}` Debug print) routes through, so any
6241            // future rebrand on the typed slot's raw-slot reader lands
6242            // at exactly one place. Same convergence discipline as the
6243            // sibling [`Placement::clusters`] (a6e18d7) reader-site
6244            // convergences on the peer M3 mesh-slot `Vec<String>`-carry
6245            // axis.
6246            for p in e.paths() {
6247                if p.is_empty() {
6248                    return Err(AplicacaoError::EntradaPathEmpty);
6249                }
6250                if !p.starts_with('/') {
6251                    return Err(AplicacaoError::EntradaPathNotAbsolute { path: p.clone() });
6252                }
6253                // Per-entry value-shape gate: the path lands verbatim
6254                // as a K8s Gateway API HTTPRoute `matches[].path.value`
6255                // (caixa-mesh/src/lib.rs:498), apiserver-validated
6256                // against `maxLength: 1024` + the Gateway API webhook's
6257                // path-grammar rules (no `//`, no `/./`, no `/../`, no
6258                // query/fragment separators, no whitespace, no control
6259                // characters, no non-ASCII bytes). Until this gate
6260                // landed `validate` only refused the empty string and
6261                // missing-leading-slash (eb3456d); a structurally
6262                // invalid path (`"/api?q=1"`, `"/api#frag"`,
6263                // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
6264                // 1025-byte URL-shaped slug) silently passed validate
6265                // and the failure surfaced at `kubectl apply` time as
6266                // a Gateway API webhook rejection, far from the source
6267                // caixa.lisp, with no field naming the offending
6268                // `:paths` entry. Lifting the gate to caixa-build time
6269                // mirrors the `:entrada :host` value-shape trajectory
6270                // (c7d05ec) on the sibling axis — every author surface
6271                // that emits a Gateway API field now matches the
6272                // apiserver's accepted set at validate time.
6273                validate_entrada_path(p)?;
6274                crate::render::insert_first_seen(&mut seen, p.as_str(), || {
6275                    AplicacaoError::EntradaPathDuplicate { path: p.clone() }
6276                })?;
6277            }
6278        }
6279
6280        self.validate_placement()?;
6281
6282        self.validate_politicas()?;
6283
6284        Ok(())
6285    }
6286
6287    /// Reject `:membros` values that are operationally meaningless. The
6288    /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
6289    /// every entry names a Servico that participates in the Aplicacao,
6290    /// and the rendered programs.yaml fan-out emits one entry per
6291    /// `:membros`. Three authoring footguns are closed here:
6292    ///
6293    ///   - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
6294    ///     a `programs:` entry whose `name:` is the empty string, which
6295    ///     downstream `lareira-fleet-programs` rejects at template time
6296    ///     with a non-localized error;
6297    ///   - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
6298    ///     an empty semver constraint, so the failure surfaces far from
6299    ///     the source caixa.lisp;
6300    ///   - duplicate `:caixa` names — two entries with the same name
6301    ///     produce duplicate programs.yaml entries (one silently
6302    ///     overwrites the other in the cluster's HelmRelease values), and
6303    ///     contract membership lookups against `:contratos` collapse the
6304    ///     two onto one node, masking authoring mistakes.
6305    ///
6306    /// Same value-shape discipline as `:placement :clusters` (where empty
6307    /// + duplicate cluster names are rejected) and `:entrada :paths`
6308    /// (where empty + duplicate path entries are rejected). Lifting these
6309    /// invariants to the typed surface mirrors the MESH-COMPOSITION
6310    /// §III.3 promise that the `:membros` set — the load-bearing identity
6311    /// of the application graph — is well-formed by construction.
6312    fn validate_membros(&self) -> Result<(), AplicacaoError> {
6313        if self.membros().is_empty() {
6314            return Err(AplicacaoError::NoMembros);
6315        }
6316        let mut seen = std::collections::HashSet::new();
6317        for m in self.membros() {
6318            // Route the `MembroCaixaEmpty` refusal-arm's per-member
6319            // empty-`:caixa` shape-gate through the typed
6320            // [`Membro::nome`] accessor rather than the raw `.caixa`
6321            // field access — the last un-lifted `.caixa` production-
6322            // code read site on the per-`:membros` member-caixa `:nome`
6323            // axis, sibling to the six caixa-core validator read sites
6324            // (member-set collector, per-member value-shape gate,
6325            // duplicate dedup key, cycle-detector adjacency-map seed,
6326            // self-loop gate) the 4a32abf lift already routed through
6327            // the accessor and the peer 54bf2f3 caixa-mesh emit-side
6328            // per-`programs[]` entry-`name:` `String`-carry converge.
6329            // Prior to this converge the `MembroCaixaEmpty` refusal
6330            // arm was the solitary consumer bypassing the typed
6331            // dispatch — the same-loop iteration's very next call
6332            // `validate_membro_caixa(m.nome())` already routed through
6333            // the accessor, so an author landing an empty-`:caixa`
6334            // entry hit the accessor on the shape-gate line but
6335            // bypassed it on the emptiness line one line above. A
6336            // future extension of the `:membros :caixa` axis to a
6337            // richer author surface (a per-cluster alias table pinned
6338            // through a future `:placement`-scoped slot, a namespace-
6339            // qualified rewrite the M4 CR materializer applies per-CR,
6340            // a per-member overlay from the future `:membros
6341            // :nome-suffix` slot MESH-COMPOSITION §III.2 acknowledges)
6342            // that lands on the accessor would silently disagree
6343            // between the emptiness gate and every peer consumer —
6344            // an author-declared `:caixa "checkout"` value the
6345            // accessor rewrote to `""` under a future alias arm would
6346            // pass the raw `.is_empty()` gate here while the peer
6347            // `validate_membro_caixa(m.nome())` call one line below
6348            // (and every downstream emit-side consumer routing through
6349            // the accessor) tripped on the empty-value shape far from
6350            // this diagnostic. Pinned by the drift-detection test
6351            // [`validate_membros_empty_gate_routes_through_nome_accessor`]
6352            // below.
6353            if m.nome().is_empty() {
6354                return Err(AplicacaoError::MembroCaixaEmpty);
6355            }
6356            // Every emitted cluster artifact's `metadata.name` derives
6357            // from a `:membros :caixa` value verbatim — the rendered
6358            // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
6359            // the [`crate::LABEL_PROGRAM`] label value on every CNP
6360            // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
6361            // 272), the composed `CiliumNetworkPolicy` `metadata.name`
6362            // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
6363            // `metadata.name` when the member is the `:entrada :para`
6364            // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
6365            // schema enforces the DNS-1123 label rule on admission;
6366            // a structurally invalid member name (`"Cart"`, `"my_cart"`,
6367            // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
6368            // mistaken-identity slug) silently passes the prior empty-/
6369            // duplicate-only gate and the failure surfaces at `kubectl
6370            // apply` time as a `metadata.name: Invalid value` rejection,
6371            // far from the source caixa.lisp, with no field naming the
6372            // offending `:membros` entry. Lifting the gate to caixa-build
6373            // time mirrors the `:entrada :host` value-shape trajectory
6374            // (c7d05ec) on the peer axis — every author surface that
6375            // emits a K8s name now matches the apiserver's accepted set
6376            // at validate time.
6377            validate_membro_caixa(m.nome())?;
6378            // The author surface for `:versao` is the same Cargo-shaped
6379            // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
6380            // `"*"`) every `:deps` entry carries — and the lacre pipeline
6381            // resolves both axes through the same
6382            // [`crate::version::parse_requirement`] entry-point. The
6383            // shared [`crate::render::require_valid_versao_requirement`]
6384            // helper brackets the empty-first + parse cascade both peer
6385            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
6386            // [`crate::SupervisorSpec::validate`] on `:children :versao`)
6387            // route through, so drift between the three axes' accepted
6388            // requirement sets is structurally impossible and the parse-
6389            // side no-op the empty-first arm closes (semver's empty
6390            // parse yields an implicit `*`) lives in exactly one
6391            // predicate.
6392            crate::render::require_valid_versao_requirement(
6393                m.versao_requirement(),
6394                || AplicacaoError::MembroVersaoEmpty {
6395                    caixa: m.nome().to_string(),
6396                },
6397                |reason| AplicacaoError::MembroVersaoInvalid {
6398                    caixa: m.nome().to_string(),
6399                    versao: m.versao_requirement().to_string(),
6400                    reason,
6401                },
6402            )?;
6403            crate::render::insert_first_seen(&mut seen, m.nome(), || {
6404                AplicacaoError::MembroDuplicate {
6405                    caixa: m.nome().to_string(),
6406                }
6407            })?;
6408        }
6409        Ok(())
6410    }
6411
6412    /// Reject `:placement` values that are operationally meaningless or
6413    /// internally contradictory. Each strategy variant has the same
6414    /// invariants on `:clusters` (non-empty list, non-empty unique
6415    /// entries) — the §III.1 author surface is uniform on this axis,
6416    /// even though the *meaning* of the list differs by strategy
6417    /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
6418    /// shard pool).
6419    ///
6420    /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
6421    /// are the same authoring footgun closed for `:politicas` zero
6422    /// values and `:entrada` empty paths: the field is *declared* but
6423    /// carries no meaning, so downstream renderers either skip it
6424    /// silently (cluster-fanout drops the empty entry, no diagnostic)
6425    /// or apply it literally and fail at admission time. Lifting both
6426    /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
6427    /// violation is a build error" promise.
6428    ///
6429    /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
6430    /// is required exactly when `:estrategia Sharded` (hash-keyed
6431    /// distribution, Akka cluster-sharding convention, §II.4) and
6432    /// refused on `:estrategia Replicated`/`SingleNode` (where no
6433    /// hash-keyed routing axis consumes it). The partition closes the
6434    /// "I think I configured sharding" footgun where an author writes
6435    /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
6436    /// the typed slot's value silently vanishes at the renderer layer
6437    /// — every validated `Placement` past this call satisfies
6438    /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
6439    fn validate_placement(&self) -> Result<(), AplicacaoError> {
6440        // Every strategy needs at least one named cluster: `Replicated`
6441        // and `SingleNode` use the list as hosting/takeover candidates
6442        // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
6443        // §II.1), while `Sharded` uses it as the shard pool
6444        // (Akka cluster-sharding convention — §II.4). An empty list is
6445        // meaningless under any of the three.
6446        //
6447        // Route the paired pre-flight `.is_empty()` refusal probe and
6448        // the per-cluster validate loop's traversal head through the
6449        // lifted [`Placement::clusters`] slice-return accessor rather
6450        // than the raw `self.placement.clusters` field access — the
6451        // two production consumers of the per-`:placement` cluster-
6452        // pool `Vec`-carry now key off exactly one typed dispatch on
6453        // the substrate primitive, so any future rebrand on the axis
6454        // (a per-tenant cluster-pool overlay the operator pins through
6455        // a future `:placement :clusters-overrides` slot, a per-
6456        // Aplicacao dynamic cluster-pool derivation the future M5
6457        // adaptive-placement engine computes from `:affinity` weights)
6458        // migrates as a single caixa-core edit rather than a
6459        // coordinated rewrite of the paired arms — sibling of the
6460        // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
6461        // arm migration on the per-`:supervisor` static-child-list
6462        // `Vec`-carry axis.
6463        //
6464        // Route the per-`:placement` outer-composite reference read
6465        // through the lifted [`AplicacaoSpec::placement`] outer accessor
6466        // rather than the raw `&self.placement` field access — the
6467        // per-axis bracket-dispatch fan-out below (`p.clusters()`,
6468        // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
6469        // axis-level lifted accessor family) now routes through the
6470        // substrate-primitive typed dispatch at the outer composition
6471        // altitude, the same shape the peer caixa-mesh
6472        // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
6473        // and the sibling `feira app graph` per-Aplicacao print line
6474        // now key off after this accessor lift.
6475        let p = self.placement();
6476        if p.clusters().is_empty() {
6477            return Err(AplicacaoError::PlacementWithoutClusters {
6478                estrategia: p.estrategia(),
6479            });
6480        }
6481        let mut seen = std::collections::HashSet::new();
6482        for c in p.clusters() {
6483            // Per-entry value-shape gate: the cluster name lands in
6484            // every K8s context / `lareira-fleet-programs` aggregator
6485            // filter / future M4 CR materializer's per-cluster axis
6486            // a validated `:clusters` entry passes through, each
6487            // enforcing the DNS-1123 label rule on admission. Same
6488            // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
6489            // on the peer name axis — both axes' validated values
6490            // are guaranteed-accepted by the apiserver without
6491            // re-validation at any downstream renderer or admission
6492            // layer.
6493            validate_placement_cluster(c)?;
6494            crate::render::insert_first_seen(&mut seen, c.as_str(), || {
6495                AplicacaoError::PlacementClusterDuplicate { cluster: c.clone() }
6496            })?;
6497        }
6498        // Route the per-`:placement :affinity` per-hint value-shape
6499        // gate through the typed [`Placement::affinity`] accessor rather
6500        // than the raw `&self.placement.affinity` field access — the
6501        // sole open-coded field-access site on the per-`:placement`
6502        // M3-Adaptive-compression-hint axis the accessor lift now owns.
6503        // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
6504        // the accessor's `Option<&str>` return type;
6505        // [`validate_placement_affinity`]'s `&str` parameter accepts
6506        // the narrower borrow without a re-allocation, so the routing
6507        // change is byte-for-byte in the pass arm and remains
6508        // byte-for-byte in every failure diagnostic
6509        // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
6510        // String` field is populated inside
6511        // [`validate_placement_affinity`] via the peer `.to_string()`
6512        // path on the same borrowed slice). Peer of the sibling
6513        // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
6514        // routing through [`Placement::shard_key`] at the caixa-core
6515        // site above — extends the "read `:placement` optional-scalars
6516        // through the typed accessor" discipline to the second
6517        // `Option<String>`-shape slot on the M3 mesh-slot family.
6518        //
6519        // Per-hint value-shape gate: the `:affinity` value lands
6520        // verbatim in the M3 Adaptive compression overlay
6521        // (caixa-mesh's `placement.affinity` emission) and every
6522        // future M4 placement-engine routing axis keying off the
6523        // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
6524        // selector — each enforces the DNS-1123 label rule on
6525        // admission. Same typed-shape trajectory as `:placement
6526        // :clusters` (6c8c00b) on the sibling slot and the four
6527        // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
6528        // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
6529        // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
6530        // on the Aplicacao surface to land on the canonical
6531        // [`crate::render::is_dns_1123_label`] floor.
6532        if let Some(a) = p.affinity() {
6533            validate_placement_affinity(a)?;
6534        }
6535        match p.estrategia() {
6536            // Route the `Sharded`-arm shape-gate cascade through the
6537            // typed [`Placement::shard_key`] accessor rather than the
6538            // raw `&self.placement.shard_key` field access — one of the
6539            // two open-coded field-access sites on the per-`:placement`
6540            // Akka-cluster-sharding-key axis the accessor lift now
6541            // owns. The `Some(k)`-bound `k` narrows from `&String` to
6542            // `&str` under the accessor's `Option<&str>` return type;
6543            // `str::is_empty` and [`validate_placement_shard_key`]'s
6544            // `&str` parameter both accept the narrower borrow without
6545            // a re-allocation.
6546            PlacementStrategy::Sharded => match p.shard_key() {
6547                None => return Err(AplicacaoError::ShardedWithoutKey),
6548                Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
6549                // Per-axis value-shape gate on the Akka-cluster-sharding
6550                // `:shard-key` extractor expression. The shape gate runs
6551                // after the more self-locating `ShardedKeyEmpty` arm so
6552                // a `:shard-key ""` surfaces the narrower empty
6553                // diagnostic first; every non-empty `:shard-key` past
6554                // this call is guaranteed to be a printable-ASCII
6555                // single-token reference the future M4 Akka-style
6556                // cluster-sharding reconciler can hash without
6557                // re-validating at the runtime layer. Mirrors the
6558                // payload-axis shape gates on the peer `:contratos`
6559                // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
6560                // 63e18a0 / c4213a4) — each lifts the runtime parser's
6561                // intersection-floor to a caixa-build-time gate.
6562                Some(k) => validate_placement_shard_key(k)?,
6563            },
6564            // `:shard-key` is the Akka-cluster-sharding axis
6565            // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
6566            // across the cluster pool. `Replicated` (active-active across
6567            // every named cluster) and `SingleNode` (Erlang/OTP
6568            // distributed-app takeover/failover, §II.1) have no hash-keyed
6569            // routing axis to consume the slot; downstream renderers
6570            // (caixa-mesh's `placement.shardKey` overlay at
6571            // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
6572            // sharding reconciler) ignore `:shard-key` outside the
6573            // `Sharded` arm by construction. Until this gate landed an
6574            // author who wrote `:placement (:estrategia Replicated
6575            // :shard-key "tenantId")` (an off-by-one strategy typo, a
6576            // copy-paste from a Sharded sibling caixa, the "I think I
6577            // configured sharding" footgun) silently passed validate and
6578            // the typed slot's value vanished at the renderer layer with
6579            // no diagnostic — the canonical "declared-but-inert" footgun
6580            // the empty-:affinity / empty-shard-key / zero-:politicas /
6581            // empty-:contratos-target gates already close on every other
6582            // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
6583            // Lifting the rejection to a build-time gate closes the
6584            // Sharded ↔ non-Sharded partition over the typed
6585            // `:placement` slot: every validated `Placement` past this
6586            // call has `shard_key.is_some()` iff `estrategia ==
6587            // Sharded`, structurally — the future Akka reconciler can
6588            // reach for `placement.shard_key` knowing it's `Some` exactly
6589            // when the strategy consumes it, without re-deriving the
6590            // partition from inline strategy probes.
6591            PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
6592                // Route the non-`Sharded`-arm declared-but-inert refusal
6593                // through the typed [`Placement::shard_key`] accessor —
6594                // the second of the two open-coded field-access sites the
6595                // accessor lift now owns. The `Some(k)`-bound `k` narrows
6596                // from `&String` to `&str`; the `AplicacaoError::
6597                // ShardKeyOnNonSharded { shard_key: String }` diagnostic
6598                // materializes the owned `String` via `k.to_string()`
6599                // (peer to the sibling per-Membro `String`-carry sites
6600                // 4127bb6 routed through `m.nome().to_string()` /
6601                // `m.versao_requirement().to_string()`), so the whole
6602                // `Sharded` ↔ non-`Sharded` partition on the
6603                // `:shard-key` axis now flows through the same typed
6604                // dispatch as the sibling `Sharded`-arm shape gate.
6605                if let Some(k) = p.shard_key() {
6606                    return Err(AplicacaoError::ShardKeyOnNonSharded {
6607                        estrategia: p.estrategia(),
6608                        shard_key: k.to_string(),
6609                    });
6610                }
6611            }
6612        }
6613        Ok(())
6614    }
6615
6616    /// Reject `:politicas` values that are operationally meaningless.
6617    /// Each axis is optional — omitting it expresses "no policy on this
6618    /// axis". Carrying a *zero* value for a declared axis is the bug
6619    /// this function rejects: zero is either
6620    ///
6621    ///   - re-interpreted as "infinite" by downstream proxies (Envoy's
6622    ///     `RouteAction.timeout = 0s` disables the timeout entirely),
6623    ///     directly contradicting MESH-COMPOSITION §V CSE invariant
6624    ///     "every Aplicacao declares :politicas :timeout (no infinite
6625    ///     blocking)", or
6626    ///   - a renderer footgun (a 0-failure circuit breaker trips on the
6627    ///     first call; a 0-rate rate-limit denies every request).
6628    ///
6629    /// Lifting these "0 means the opposite of what you think" idioms to
6630    /// the typed Aplicacao surface as build errors mirrors the §III.3
6631    /// promise that contract drift, capability leaks, and cycles are all
6632    /// build errors — not runtime surprises.
6633    fn validate_politicas(&self) -> Result<(), AplicacaoError> {
6634        // Route the per-`:politicas` composite-reference read through
6635        // the lifted [`AplicacaoSpec::politicas`] outer accessor rather
6636        // than the raw `&self.politicas` field access — the per-axis
6637        // bracket-dispatch fan-out below (`p.timeout()`, `p.retries()`,
6638        // `p.circuit_breaker()`, `p.rate_limit()`) now routes through
6639        // the substrate-primitive typed dispatch at the outer
6640        // composition altitude AND at every per-axis altitude, matching
6641        // the peer caixa-mesh CNP mTLS-overlay + HTTPRoute
6642        // timeout/retry-overlay emitters that already key off the same
6643        // per-axis accessor family. The four-axis fan-out is now
6644        // uniformly `p.<axis>()` — the last two raw `p.timeout` /
6645        // `p.retries` field-access sites (co-resident with the peer
6646        // `p.circuit_breaker()` / `p.rate_limit()` accessor sites that
6647        // b0e741a / 21a6c3b already lifted) now route through
6648        // [`MeshPolicy::timeout`] / [`MeshPolicy::retries`], closing
6649        // the per-`:politicas` bracket-dispatch fan-out's raw-field-
6650        // access axis on the M3 mesh-slot family.
6651        let p = self.politicas();
6652        if let Some(t) = p.timeout() {
6653            // Zero-floor + integer-millisecond canonical-form +
6654            // upper-cap bracket on the typed `:timeout` axis. See
6655            // [`crate::render::require_positive_canonical_bounded_duration`]
6656            // for the full three-arm ordering discipline (zero-floor
6657            // strictly precedes the canonical-form arm so
6658            // `Duration::ZERO` surfaces the self-locating
6659            // `PolicyTimeoutZero` diagnostic naming the omit-axis
6660            // remediation; canonical-form strictly precedes the cap
6661            // arm so a sub-millisecond above-cap `Duration` surfaces
6662            // the more fundamental round-trip-shape diagnostic first)
6663            // and the four peer typed-`Duration` sites that now share
6664            // this canonical bracket. Every validated value lies in
6665            // `1ms..=POLICY_TIMEOUT_MAX` (1ms..=1h), integer-millisecond
6666            // granularity — the same top-and-bottom-edge discipline
6667            // [`POLICY_RETRIES_MAX`] and
6668            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] apply on the sibling
6669            // capped-`u32` `:politicas` axes.
6670            crate::render::require_positive_canonical_bounded_duration(
6671                t,
6672                POLICY_TIMEOUT_MAX,
6673                || AplicacaoError::PolicyTimeoutZero,
6674                |timeout| AplicacaoError::PolicyTimeoutNotCanonical { timeout },
6675                |timeout| AplicacaoError::PolicyTimeoutExceedsCap { timeout },
6676            )?;
6677        }
6678        if let Some(r) = p.retries() {
6679            // Zero-floor + upper-cap bracket on the typed `:retries`
6680            // axis. See [`crate::render::require_positive_bounded_u32`]
6681            // for the ordering discipline (zero-floor arm strictly
6682            // precedes cap arm so `Some(0)` surfaces the self-locating
6683            // `PolicyRetriesZero` diagnostic with its omit-axis
6684            // remediation directly named, not the misleading
6685            // `0 > POLICY_RETRIES_MAX == false` cap-arm miss). Until
6686            // this bracket landed the top edge ran all the way to
6687            // `u32::MAX` and a struct-literal `MeshPolicy { retries:
6688            // Some(100_000), .. }` (or the equivalent author-surface
6689            // `(:retries 100000)` / `(:retries 4294967295)` typo
6690            // landing in the slot) silently passed validate. The
6691            // runtime substrate consuming the value (Envoy's
6692            // `retry_policy.num_retries`, the future
6693            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
6694            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
6695            // policy into a thundering-herd amplification vector —
6696            // the caller's one request fans out to `retries`
6697            // server-side calls per edge per traversal, multiplying
6698            // load by `(retries+1)^depth` across the
6699            // synchronous-`:contratos` subgraph at the precise moment
6700            // the substrate is already failing (transient failure is
6701            // the trigger), exactly the failure mode AWS App Mesh's
6702            // explicit `maxRetries ≤ 10` schema cap exists to prevent.
6703            // The bracket set is `1..=POLICY_RETRIES_MAX`. Peer with
6704            // the sibling capped-`u32` `:politicas` axes
6705            // (`max_failures`, `rate_limit.rate`) and the peer capped-
6706            // `u32` axes in `:supervisor :max-restarts` +
6707            // `:limits :cpu`; all five now route through the same
6708            // canonical bracket helper.
6709            crate::render::require_positive_bounded_u32(
6710                r,
6711                POLICY_RETRIES_MAX,
6712                || AplicacaoError::PolicyRetriesZero,
6713                |retries| AplicacaoError::PolicyRetriesExceedsCap { retries },
6714            )?;
6715        }
6716        if let Some(cb) = p.circuit_breaker() {
6717            // Zero-floor + upper-cap bracket on the typed
6718            // `:max-failures` axis. See
6719            // [`crate::render::require_positive_bounded_u32`] for the
6720            // ordering discipline (zero-floor arm strictly precedes
6721            // cap arm so `max_failures == 0` surfaces the
6722            // self-locating `PolicyBreakerZeroFailures` diagnostic
6723            // with its omit-axis remediation directly named, not the
6724            // misleading `0 > POLICY_BREAKER_MAX_FAILURES_MAX ==
6725            // false` cap-arm miss). Until this bracket landed the top
6726            // edge ran all the way to `u32::MAX` and a struct-literal
6727            // `CircuitBreaker { max_failures: 100_000, .. }` (or the
6728            // equivalent author-surface `(:max-failures 100000)` /
6729            // `(:max-failures 4294967295)` typo landing in the slot)
6730            // silently passed validate. The runtime substrate
6731            // consuming the value (Envoy's
6732            // `outlier_detection.consecutive_5xx`, the future
6733            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
6734            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
6735            // breaker policy into a no-op — the trip threshold is
6736            // structurally so high that no realistic
6737            // failures-per-`:window` traffic shape can reach it, the
6738            // breaker never trips, and every typed-slot consumer
6739            // emits an Envoy / Cilium L7 overlay carrying a
6740            // protection that is structurally never enforced. The
6741            // bracket set is `1..=POLICY_BREAKER_MAX_FAILURES_MAX`;
6742            // peer with `retries` and `rate_limit.rate` on the same
6743            // helper.
6744            crate::render::require_positive_bounded_u32(
6745                cb.max_failures(),
6746                POLICY_BREAKER_MAX_FAILURES_MAX,
6747                || AplicacaoError::PolicyBreakerZeroFailures,
6748                |max_failures| AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
6749            )?;
6750            // Zero-floor + integer-millisecond canonical-form +
6751            // upper-cap bracket on the typed `:window` axis. See
6752            // [`crate::render::require_positive_canonical_bounded_duration`]
6753            // for the full three-arm ordering discipline (peer to the
6754            // `:timeout` site immediately above); every validated
6755            // value lies in `1ms..=POLICY_BREAKER_WINDOW_MAX`
6756            // (1ms..=1h), integer-millisecond granularity — the same
6757            // top-and-bottom-edge discipline
6758            // [`POLICY_TIMEOUT_MAX`] applies on the sibling
6759            // duration-typed `:politicas :timeout` axis.
6760            crate::render::require_positive_canonical_bounded_duration(
6761                cb.window(),
6762                POLICY_BREAKER_WINDOW_MAX,
6763                || AplicacaoError::PolicyBreakerZeroWindow,
6764                |window| AplicacaoError::PolicyBreakerWindowNotCanonical { window },
6765                |window| AplicacaoError::PolicyBreakerWindowExceedsCap { window },
6766            )?;
6767        }
6768        if let Some(rl) = p.rate_limit() {
6769            // Zero-floor + upper-cap bracket on the typed
6770            // `:rate-limit` rate axis. See
6771            // [`crate::render::require_positive_bounded_u32`] for the
6772            // ordering discipline (zero-floor arm strictly precedes
6773            // cap arm so `rl.rate == 0` surfaces the self-locating
6774            // `PolicyRateLimitZero` diagnostic with its omit-axis
6775            // remediation directly named, not the misleading
6776            // `0 > POLICY_RATE_LIMIT_MAX == false` cap-arm miss).
6777            // Until this bracket landed the top edge ran all the way
6778            // to `u32::MAX` and a struct-literal
6779            // `RateLimit { rate: u32::MAX, .. }` (or the equivalent
6780            // author-surface `(:rate-limit "4294967295/s")` /
6781            // `(:rate-limit "100000000/m")` typo landing in the slot)
6782            // silently passed validate. The runtime substrate
6783            // consuming the value (Envoy's
6784            // `local_rate_limit.token_bucket.max_tokens`, the future
6785            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
6786            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
6787            // rate-limit policy into a no-op limiter: the bucket
6788            // capacity is structurally so high that no realistic
6789            // per-edge traffic shape can drain it, the limiter never
6790            // trips, and every typed-slot consumer emits a "rate
6791            // declared" L7 overlay carrying enforcement that is
6792            // structurally never reached — the canonical
6793            // declared-but-inert footgun the sibling
6794            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap arm closes on
6795            // the peer no-op-breaker shape. The bracket set is
6796            // `1..=POLICY_RATE_LIMIT_MAX`; peer with `retries` and
6797            // `max_failures` on the same helper. The rate bracket
6798            // strictly precedes the window-canonical gate so a
6799            // structurally absurd rate magnitude surfaces the more
6800            // fundamental amplification-shape diagnostic before the
6801            // narrower codec-round-trip-shape diagnostic on `:window`.
6802            crate::render::require_positive_bounded_u32(
6803                rl.rate(),
6804                POLICY_RATE_LIMIT_MAX,
6805                || AplicacaoError::PolicyRateLimitZero,
6806                |rate| AplicacaoError::PolicyRateLimitExceedsCap { rate },
6807            )?;
6808            // The `:rate-limit` author surface is the canonical
6809            // `"<n>/<s|m|h>"` form, and the [`rate_limit_codec`] parser
6810            // accepts exactly the three-unit set (1s/60s/3600s) the
6811            // [`rate_limit_codec::render`] formatter emits the canonical
6812            // unit suffix for. A `RateLimit` whose `:window` is anything
6813            // else (zero, 30s, 45s, 120s, 86400s, …) is constructible
6814            // programmatically (struct literals in Rust + the typed
6815            // `Duration` field) but renders to a `<n>/<k>s` fragment
6816            // (the codec's fall-through) the parser then rejects on
6817            // round-trip — silently breaking the THEORY.md §V.2.7
6818            // render-determinism contract for any consumer that
6819            // serializes-then-deserializes the typed slot. Lifting the
6820            // canonical-window invariant to a build-time gate at
6821            // `validate_politicas` makes the codec's round-trip property
6822            // a structural property of the validated typed value:
6823            // every `RateLimit` past `AplicacaoSpec::validate` has a
6824            // window the codec round-trips losslessly, so the next
6825            // typed-slot wiring (the future `CiliumClusterwideEnvoyConfig`
6826            // emitter for `:politicas :rate-limit`, MESH-COMPOSITION
6827            // §III.2 #3) reaches for `rate_limit.window` knowing the
6828            // value is in the codec's accepted set without re-validating
6829            // at the renderer layer. Same trajectory as c4213a4 (typed
6830            // WitContract endpoint/subject/slot value-shape gates) and
6831            // the b0c8389 :behavior + :upgrade-from script-path lifts:
6832            // the typed slot's valid set matches its codec's accepted
6833            // set, structurally.
6834            // Route the canonical-window shape-gate through the substrate
6835            // primitive [`RateLimit::canonical_unit`] rather than the free
6836            // module-private [`is_canonical_rate_limit_window`] predicate:
6837            // both projections resolve `Duration → Option<RateLimitUnit>`
6838            // through [`RateLimitUnit::from_window`] (the sole `Duration → Self`
6839            // arm on the closed-set typed enum), but the accessor is the
6840            // typed method every downstream consumer of the validated slot
6841            // ([`rate_limit_codec::render`]'s canonical arm above, the
6842            // future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6843            // per-`:politicas :rate-limit` admission webhook, the future
6844            // per-`:contratos`-edge rate-limit-override overlay
6845            // MESH-COMPOSITION §III.2 #3 acknowledges) already reads. Two
6846            // production consumers of the canonical-unit axis (the codec
6847            // render and this validate gate) now key off exactly one typed
6848            // dispatch on the substrate primitive, so any future extension
6849            // to `canonical_unit` (a per-cluster canonical-window overlay
6850            // the operator pins through a future `:contratos :rate-limit
6851            // -unit-overrides` slot, a per-tenant unit-alias table the M4
6852            // CR materializer resolves per-CR) reaches both consumers by
6853            // construction rather than a coordinated rewrite of every
6854            // free-helper call site.
6855            if rl.canonical_unit().is_none() {
6856                return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical {
6857                    window: rl.window(),
6858                });
6859            }
6860        }
6861        Ok(())
6862    }
6863
6864    /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
6865    /// A synchronous edge is any contract whose typed [`WitTarget`] is
6866    /// `Http`, `Store`, or `Capability` — the caller blocks on the
6867    /// callee, so a cycle would deadlock at runtime. Pub-sub edges
6868    /// (`WitTarget::PubSub`) are skipped: an event publisher does not
6869    /// block on its subscribers, so they can never close a sync loop.
6870    ///
6871    /// Iterative DFS with three-coloring; the reported cycle is the
6872    /// path of caixa names traversed from the back-edge target around
6873    /// to itself, in declaration order. Adjacency lists and DFS roots
6874    /// are visited in `BTreeMap` key order so the diagnostic is
6875    /// deterministic across runs.
6876    fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
6877        use std::collections::{BTreeMap, BTreeSet};
6878
6879        #[derive(Clone, Copy, PartialEq, Eq)]
6880        enum Mark {
6881            White,
6882            Gray,
6883            Black,
6884        }
6885
6886        let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
6887        for m in self.membros() {
6888            adj.entry(m.nome()).or_default();
6889        }
6890        for c in self.contratos() {
6891            // target() was already called by validate(); re-running here
6892            // keeps detect_sync_cycles self-contained for callers that
6893            // reuse it (M4 per-edge policy resolver) without revalidating.
6894            //
6895            // The pub-sub-arm check routes through the lifted
6896            // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
6897            // arm-discriminator predicate rather than a raw `matches!(…,
6898            // WitTarget::PubSub { .. })` on the variant so a future
6899            // rebrand on the axis (an M4 per-edge WIT registry split of
6900            // [`WitTarget::PubSub`] into shape-specific peers, a
6901            // per-consumer rename that the accept-set already carries)
6902            // reaches this call site through the derive rather than a
6903            // scattered per-arm `matches!` rewrite — same
6904            // `IsVariant`-derived-arm-discriminator discipline the
6905            // peer closed-set typed enums ([`crate::CaixaKind`] via
6906            // f5bba80, [`PlacementStrategy`] via 766ec63,
6907            // [`crate::supervisor::RestartStrategy`] +
6908            // [`crate::supervisor::RestartPolicy`],
6909            // [`crate::upgrade::UpgradeInstruction`] via 915a934)
6910            // already route through on the substrate's other typed-enum
6911            // arm-discriminator axes.
6912            if c.target()?.is_pubsub() {
6913                continue;
6914            }
6915            adj.entry(c.source()).or_default().insert(c.destination());
6916        }
6917
6918        let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
6919        let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
6920
6921        // Stable DFS root order — BTreeMap iteration is sorted by key.
6922        let roots: Vec<&str> = adj.keys().copied().collect();
6923
6924        // Frame: (node, sorted-neighbours snapshot, next-edge index).
6925        for root in roots {
6926            if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
6927                continue;
6928            }
6929            let root_neighbors: Vec<&str> = adj
6930                .get(root)
6931                .map(|s| s.iter().copied().collect())
6932                .unwrap_or_default();
6933            let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
6934            color.insert(root, Mark::Gray);
6935
6936            loop {
6937                // Read+advance the top frame in one borrow scope so we
6938                // can later mutate the stack (push/pop) without holding
6939                // a borrow across.
6940                let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
6941                    let node = top.0;
6942                    if top.2 >= top.1.len() {
6943                        (node, None)
6944                    } else {
6945                        let nxt = top.1[top.2];
6946                        top.2 += 1;
6947                        (node, Some(nxt))
6948                    }
6949                });
6950                let Some((node, nxt_opt)) = step else { break };
6951                let Some(nxt) = nxt_opt else {
6952                    color.insert(node, Mark::Black);
6953                    stack.pop();
6954                    continue;
6955                };
6956                let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
6957                match nxt_color {
6958                    Mark::Gray => {
6959                        // Reconstruct the cycle from `node` back through
6960                        // the parent chain to `nxt`, then close.
6961                        let mut cycle = Vec::new();
6962                        let mut cur = node;
6963                        cycle.push(cur.to_string());
6964                        while cur != nxt {
6965                            match parent.get(cur).copied() {
6966                                Some(p) => {
6967                                    cur = p;
6968                                    cycle.push(cur.to_string());
6969                                }
6970                                None => break,
6971                            }
6972                        }
6973                        cycle.reverse();
6974                        cycle.push(nxt.to_string());
6975                        return Err(AplicacaoError::ContratoCycle { cycle });
6976                    }
6977                    Mark::White => {
6978                        parent.insert(nxt, node);
6979                        color.insert(nxt, Mark::Gray);
6980                        let nxt_neighbors: Vec<&str> = adj
6981                            .get(nxt)
6982                            .map(|s| s.iter().copied().collect())
6983                            .unwrap_or_default();
6984                        stack.push((nxt, nxt_neighbors, 0));
6985                    }
6986                    Mark::Black => {}
6987                }
6988            }
6989        }
6990        Ok(())
6991    }
6992
6993    /// Substrate-canonical destination-facing TCP port every emitted
6994    /// per-Aplicacao artifact must key `destination`-shaped port axes
6995    /// off. Returns the typed `:entrada :port` scalar when this
6996    /// Aplicacao's `:entrada` block names `destination` under its
6997    /// `:para` axis (the destination Servico *is* the ingress apex, so
6998    /// the substrate honors the author-declared listener port
6999    /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
7000    /// fallback otherwise (every non-apex destination — the internal
7001    /// mesh Servicos `:contratos` reach across, the future per-edge
7002    /// policy resolver's per-destination probe targets, the
7003    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
7004    /// L4 port resolver — reads the same substrate-canonical port floor
7005    /// by construction).
7006    ///
7007    /// Prior to this lift the "if :entrada matches this destination use
7008    /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
7009    /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
7010    /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
7011    /// prior to this lift), with no typed method on the substrate primitive
7012    /// that named the rule. A future per-destination port axis addition
7013    /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
7014    /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
7015    /// per-Servico listener ports land, a per-cluster override the operator
7016    /// pins through a future `:placement :default-port` slot — would have
7017    /// to be threaded through every renderer's inline cascade in lockstep
7018    /// or one consumer would silently disagree on which port a given
7019    /// destination Servico's ingress lands at. Lifting the rule to a
7020    /// typed method on the substrate primitive means the M4 CR
7021    /// materializer, the future per-edge policy resolver, and every
7022    /// downstream test-fixture navigator reach for exactly one typed
7023    /// dispatch — the resolver's accept-set moves as a unit on any
7024    /// future axis addition.
7025    ///
7026    /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
7027    /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
7028    /// the typed primitive, thin projections at each consumer"
7029    /// discipline lifts on the sibling `:contratos` payload / `:politicas
7030    /// :rate-limit` unit-suffix axes; extends the discipline onto the
7031    /// destination-facing port-resolution axis every per-Aplicacao
7032    /// L4-fallback renderer consumes.
7033    #[must_use]
7034    pub fn port_for_destination(&self, destination: &str) -> u16 {
7035        // Route the per-`:entrada` composite-reference read through
7036        // the lifted [`AplicacaoSpec::entrada`] accessor rather than
7037        // the raw `self.entrada.as_ref()` field access — the
7038        // per-destination L4-port fallback resolver's composite-
7039        // projection seed is now the canonical read-side surface
7040        // every per-Aplicacao entrada consumer routes through, peer
7041        // of the sibling `validate` per-`:entrada` shape-and-
7042        // membership gate migration on the same outer-composite
7043        // axis.
7044        // Route the per-`:entrada` apex-destination membership probe
7045        // through the lifted [`Entrada::destination`] accessor rather
7046        // than the raw `e.para == destination` field access — the last
7047        // un-lifted `.para` production-code read site on the per-
7048        // `:entrada` `:para` axis, sibling to the four caixa-core
7049        // consumer sites the peer 15ddd8c converge already routed
7050        // through the accessor (the three
7051        // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
7052        // membership gate sites: the `validate_entrada_para` DNS-1123
7053        // shape gate, the per-`:membros` membership lookup, and the
7054        // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
7055        // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
7056        // `entrada.para`-projection converge at
7057        // caixa-core/src/render.rs (the `gateway_api_http_route_name`
7058        // route-name projection site). Prior to this converge the
7059        // `port_for_destination` resolver was the solitary consumer
7060        // bypassing the typed dispatch on the `.para` axis — the two
7061        // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
7062        // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
7063        // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
7064        // reach through the same accessor family compose with this
7065        // resolver at the emit boundary via the apex-identity
7066        // invariant `spec.port_for_destination(entrada.destination())
7067        // == entrada.port` the sibling
7068        // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
7069        // pin pins across four permutations. A future extension of the
7070        // `:entrada :para` axis to a richer author surface (a per-
7071        // cluster alias overlay the operator pins through a future
7072        // `:placement`-scoped slot, a namespace-qualified rewrite the
7073        // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
7074        // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
7075        // §III.2 acknowledges) that lands on the accessor would silently
7076        // disagree between this resolver and the two `caixa-mesh` emit
7077        // sites — an author-declared `:para "cart"` value the accessor
7078        // rewrote to `"cart-v2"` under a future canary arm would leave
7079        // the resolver's membership arm falling through to
7080        // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
7081        // `.para`) while the peer emit-site consumers landed on the
7082        // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
7083        // silently disagreed on which destination port a given typed
7084        // `:entrada` resolves to at cluster-apply time. Pinned by the
7085        // drift-detection test
7086        // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
7087        // below.
7088        self.entrada()
7089            .filter(|e| e.destination() == destination)
7090            .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
7091    }
7092}
7093
7094/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
7095/// entry may name the Aplicacao's own `:nome`.
7096///
7097/// An Aplicacao that lists itself as a member is a degenerate self-edge in
7098/// the typed graph — the application graph is a DAG rooted at the Aplicacao
7099/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
7100/// Servicos that compose the app; an Aplicacao is never its own constituent),
7101/// and the lacre pipeline's closure-resolution would otherwise be handed a
7102/// node that is its own parent: a one-node cycle it either rejects far from
7103/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
7104/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
7105/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
7106/// label + lacre closure root), a member whose `:caixa` equals the
7107/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
7108/// peer.
7109///
7110/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
7111/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
7112/// gate `validate_upgrade_from_against_versao` and the supervision-tree
7113/// self-parent gate `crate::supervisor::validate_no_self_supervision`
7114/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
7115/// not a tree/mesh edge" discipline, here on the second typed-graph axis
7116/// (the Aplicacao :membros set; the supervision-tree :children list was the
7117/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
7118/// every validated Supervisor's children are distinct from its `:nome`,
7119/// every validated Aplicacao's membros are distinct from its `:nome`. The
7120/// transitive consequence is that `:entrada :para` and `:contratos`
7121/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
7122/// name the Aplicacao itself, without re-deriving the partition.
7123pub fn validate_no_self_membership(
7124    membros: &[Membro],
7125    parent_nome: &str,
7126) -> Result<(), AplicacaoError> {
7127    for m in membros {
7128        if m.nome() == parent_nome {
7129            return Err(AplicacaoError::MembroIsSelfAplicacao {
7130                caixa: parent_nome.to_string(),
7131            });
7132        }
7133    }
7134    Ok(())
7135}
7136
7137#[derive(Debug, Error, PartialEq, Eq)]
7138pub enum AplicacaoError {
7139    #[error("Aplicacao must declare at least one :membros entry")]
7140    NoMembros,
7141    #[error(
7142        ":membros entry has empty :caixa (every member must name a Servico; \
7143         omit the entry instead of carrying an empty name)"
7144    )]
7145    MembroCaixaEmpty,
7146    #[error(
7147        ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
7148         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
7149         name / label value the member name lands in; use a lowercase \
7150         alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
7151    )]
7152    MembroCaixaInvalid { caixa: String, reason: String },
7153    #[error(
7154        ":membros entry {caixa:?} has empty :versao (every member must pin a \
7155         semver constraint that resolves through the lacre pipeline)"
7156    )]
7157    MembroVersaoEmpty { caixa: String },
7158    #[error(
7159        ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
7160         requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
7161         `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
7162         carries; the lacre pipeline resolves both through the same parser)"
7163    )]
7164    MembroVersaoInvalid {
7165        caixa: String,
7166        versao: String,
7167        reason: String,
7168    },
7169    #[error(
7170        ":membros entry {caixa:?} appears more than once (the graph node set \
7171         is a set, not a multiset; duplicate members produce duplicate \
7172         programs.yaml entries and ambiguous :contratos membership lookups)"
7173    )]
7174    MembroDuplicate { caixa: String },
7175    #[error(
7176        "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
7177         never its own constituent Servico (the application graph is a DAG rooted \
7178         at the Aplicacao; :membros names the *other* caixas that compose the \
7179         app, not the app itself). Since every :nome is a globally-unique \
7180         substrate identity, a member naming the Aplicacao's own :nome is a \
7181         one-node lacre-closure recursion, not a coincidentally-named peer; \
7182         drop the self-referential :membros entry or rename it to the actual \
7183         constituent caixa."
7184    )]
7185    MembroIsSelfAplicacao { caixa: String },
7186    #[error(
7187        "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
7188         caixa declared in :membros; omit the contract or fill the {slot} field with a \
7189         member name)"
7190    )]
7191    ContratoCaixaEmpty { slot: &'static str },
7192    #[error(
7193        "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
7194         :contratos {slot} value names a member of :membros, which is itself a \
7195         DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
7196         object the member name lands in — Service, Pod, identity-based Cilium \
7197         selector; use a lowercase alphanumeric + hyphen identifier like \
7198         `\"checkout\"` or `\"cart-v2\"`)"
7199    )]
7200    ContratoCaixaInvalid {
7201        slot: &'static str,
7202        caixa: String,
7203        reason: String,
7204    },
7205    #[error("contrato references caixa {caixa:?} not declared in :membros")]
7206    ContratoMemberMissing { caixa: String },
7207    #[error(
7208        "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
7209         entry is an inter-Servico contract whose :de and :para must name distinct \
7210         :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
7211         the contract, or point :para at the member it actually calls)"
7212    )]
7213    ContratoSelfLoop { caixa: String, wit: String },
7214    #[error("contrato {de:?} → {para:?} has empty :wit")]
7215    EmptyWit { de: String, para: String },
7216    #[error(
7217        "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
7218         {reason} (the substrate dispatches `:wit` values on the canonical \
7219         lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
7220         `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
7221         demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
7222         kebab-case identifier per segment)"
7223    )]
7224    ContratoWitInvalid {
7225        de: String,
7226        para: String,
7227        wit: String,
7228        reason: String,
7229    },
7230    #[error(
7231        ":entrada :para is empty (every :entrada must route to a caixa declared in \
7232         :membros; fill the :para field with a member name)"
7233    )]
7234    EntradaParaEmpty,
7235    #[error(
7236        ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
7237         :entrada :para value names a member of :membros, which is itself a DNS-1123 \
7238         label per the K8s apiserver's `metadata.name` rule on every object the \
7239         member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
7240         Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
7241         `\"checkout\"` or `\"cart-v2\"`)"
7242    )]
7243    EntradaParaInvalid { para: String, reason: String },
7244    #[error(":entrada routes to caixa {para:?} not declared in :membros")]
7245    EntradaMemberMissing { para: String },
7246    #[error(":entrada must declare a non-empty :host")]
7247    EmptyEntradaHost,
7248    #[error(
7249        ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
7250         (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
7251         `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
7252         like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
7253    )]
7254    EntradaHostInvalid { host: String, reason: String },
7255    #[error(":entrada :port must be in 1..=65535, got 0")]
7256    EntradaPortZero,
7257    #[error(":entrada :paths entry is empty (use the empty list to match all)")]
7258    EntradaPathEmpty,
7259    #[error(
7260        ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
7261    )]
7262    EntradaPathNotAbsolute { path: String },
7263    #[error(
7264        ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
7265         value: {reason} (the K8s apiserver enforces the same shape on \
7266         `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
7267         single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
7268         requires percent-encoding `%XX` for non-ASCII and whitespace)"
7269    )]
7270    EntradaPathInvalid { path: String, reason: String },
7271    #[error(":entrada :paths entry {path:?} appears more than once")]
7272    EntradaPathDuplicate { path: String },
7273    #[error(
7274        ":placement {estrategia} requires at least one :clusters entry \
7275         (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
7276    )]
7277    PlacementWithoutClusters { estrategia: PlacementStrategy },
7278    #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
7279    PlacementClusterEmpty,
7280    #[error(
7281        ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
7282         (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
7283         in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
7284         future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
7285         — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
7286         identifier like `\"rio\"` or `\"mar-east\"`)"
7287    )]
7288    PlacementClusterInvalid { cluster: String, reason: String },
7289    #[error(":placement :clusters entry {cluster:?} appears more than once")]
7290    PlacementClusterDuplicate { cluster: String },
7291    #[error(
7292        ":placement :affinity must be non-empty when set (omit :affinity to express \
7293         `no placement hint`)"
7294    )]
7295    PlacementAffinityEmpty,
7296    #[error(
7297        ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
7298         (placement hints land verbatim in the M3 Adaptive compression overlay's \
7299         `placement.affinity` field and in every future M4 placement-engine routing \
7300         axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
7301         selector — both enforce the DNS-1123 label rule on admission; use a \
7302         lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
7303         `\"low-latency\"`, or `\"anti-affinity\"`)"
7304    )]
7305    PlacementAffinityInvalid { affinity: String, reason: String },
7306    #[error(":placement Sharded requires :shard-key")]
7307    ShardedWithoutKey,
7308    #[error(
7309        ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
7310         hashes every entity onto the same shard, defeating sharding entirely)"
7311    )]
7312    ShardedKeyEmpty,
7313    #[error(
7314        ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
7315         entity-id extractor expression: {reason} (the future M4 Akka-style \
7316         cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
7317         as a single-token property reference and hashes the extracted entity ID \
7318         to compute shard placement; use a printable-ASCII extractor expression \
7319         like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
7320         `\"${{tenant}}\"`)"
7321    )]
7322    ShardKeyInvalid { shard_key: String, reason: String },
7323    #[error(
7324        ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
7325         Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
7326         convention); :estrategia Replicated runs every cluster active-active and \
7327         :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
7328         distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
7329         to :estrategia Sharded if hash-keyed routing is the intent"
7330    )]
7331    ShardKeyOnNonSharded {
7332        estrategia: PlacementStrategy,
7333        shard_key: String,
7334    },
7335    #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
7336    ContratoMissingTarget {
7337        de: String,
7338        para: String,
7339        wit: String,
7340        expected: &'static str,
7341    },
7342    #[error(
7343        "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
7344         expected `:{expected}` only"
7345    )]
7346    ContratoWrongTarget {
7347        de: String,
7348        para: String,
7349        wit: String,
7350        expected: &'static str,
7351    },
7352    #[error(
7353        "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
7354         like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
7355         that matches no traffic and silently drops every request)"
7356    )]
7357    ContratoEndpointEmpty { de: String, para: String },
7358    #[error(
7359        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
7360         (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
7361         :entrada :paths)"
7362    )]
7363    ContratoEndpointNotAbsolute {
7364        de: String,
7365        para: String,
7366        endpoint: String,
7367    },
7368    #[error(
7369        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
7370         Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
7371         emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
7372         caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
7373         shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
7374         like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
7375         and whitespace)"
7376    )]
7377    ContratoEndpointInvalid {
7378        de: String,
7379        para: String,
7380        endpoint: String,
7381        reason: String,
7382    },
7383    #[error(
7384        "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
7385         subject is a no-op subscribe; omit :subject only if the WIT world is not \
7386         pub-sub-shaped)"
7387    )]
7388    ContratoSubjectEmpty { de: String, para: String },
7389    #[error(
7390        "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
7391         NATS subject: {reason} (the NATS server's subject parser enforces the \
7392         same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
7393         single-token and `>` multi-token wildcards — at publish/subscribe time; \
7394         use a token-by-token form like `\"checkout.events.charge.failed\"` or \
7395         `\"orders.*.completed\"` — a malformed subject silently drops every \
7396         message at runtime far from the source caixa.lisp)"
7397    )]
7398    ContratoSubjectInvalid {
7399        de: String,
7400        para: String,
7401        subject: String,
7402        reason: String,
7403    },
7404    #[error(
7405        "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
7406         addresses the bucket root, defeating the per-key isolation the slot exists \
7407         for; omit :slot only if the WIT world is not store-shaped)"
7408    )]
7409    ContratoSlotEmpty { de: String, para: String },
7410    #[error(
7411        "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
7412         WASI keyvalue store slot template: {reason} (the substrate enforces \
7413         the printable-ASCII intersection-floor every kv backend admits — \
7414         use a single-token path / template expression like `\"checkout/$orderId\"`, \
7415         `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
7416         percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
7417         slot either gets rejected on write by strict backends or silently \
7418         corrupts the next read on permissive ones, far from the source caixa.lisp)"
7419    )]
7420    ContratoSlotInvalid {
7421        de: String,
7422        para: String,
7423        slot: String,
7424        reason: String,
7425    },
7426    #[error(
7427        "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
7428         or an event-sourced indirection (MESH-COMPOSITION §III.3)",
7429        cycle.join(" → ")
7430    )]
7431    ContratoCycle { cycle: Vec<String> },
7432    #[error(
7433        ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
7434         than once (the typed graph edges are a set, not a multiset; duplicate \
7435         contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
7436         values that K8s admission rejects far from the source caixa.lisp)"
7437    )]
7438    ContratoDuplicate {
7439        de: String,
7440        para: String,
7441        wit: String,
7442        target: String,
7443    },
7444    #[error(
7445        ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
7446         contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
7447         express `no per-call deadline on this axis`"
7448    )]
7449    PolicyTimeoutZero,
7450    #[error(
7451        ":politicas :retries must be > 0 when set; omit :retries to express \
7452         `no retries on transient failure`"
7453    )]
7454    PolicyRetriesZero,
7455    #[error(
7456        ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
7457         (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
7458         retry policy into a thundering-herd amplification vector on transient \
7459         failure (one caller request fans out to `(retries+1)^depth` server-side \
7460         calls across the synchronous-:contratos subgraph), exactly the failure \
7461         mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
7462         Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
7463         or omit :retries to disable retries entirely"
7464    )]
7465    PolicyRetriesExceedsCap { retries: u32 },
7466    #[error(
7467        ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
7468         breaker trips on the first call); omit :circuit-breaker to disable it"
7469    )]
7470    PolicyBreakerZeroFailures,
7471    #[error(
7472        ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
7473         mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
7474         above this cap turns the typed breaker policy into a no-op: the trip \
7475         threshold is structurally so high that no realistic failures-per-:window \
7476         traffic shape can reach it, so the breaker never trips and every typed-slot \
7477         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
7478         Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
7479         structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
7480         Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
7481         omit :circuit-breaker to disable the breaker entirely"
7482    )]
7483    PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
7484    #[error(
7485        ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
7486         tracks no failures); omit :circuit-breaker to disable it"
7487    )]
7488    PolicyBreakerZeroWindow,
7489    #[error(
7490        ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
7491         request); omit :rate-limit to disable rate limiting"
7492    )]
7493    PolicyRateLimitZero,
7494    #[error(
7495        ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
7496         (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
7497         rate-limit policy into a no-op limiter: the token-bucket capacity is \
7498         structurally so high that no realistic per-edge traffic shape can drain it, \
7499         so the limiter never trips and every typed-slot consumer (the future \
7500         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
7501         local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
7502         that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
7503         Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
7504         Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
7505         Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
7506         to disable rate limiting entirely"
7507    )]
7508    PolicyRateLimitExceedsCap { rate: u32 },
7509    #[error(
7510        ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
7511         the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
7512         rate-limit codec round-trips losslessly; got {window:?} which renders to a \
7513         non-round-trippable form (omit :rate-limit to disable, or pick one of the \
7514         three canonical windows)"
7515    )]
7516    PolicyRateLimitWindowNotCanonical { window: Duration },
7517    #[error(
7518        ":politicas :timeout must be an integer number of milliseconds — the canonical \
7519         authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
7520         duration codec round-trips losslessly; got {timeout:?} which carries a \
7521         sub-millisecond residue that either truncates to a different `Duration` on \
7522         re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
7523         to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
7524         zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
7525         (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
7526    )]
7527    PolicyTimeoutNotCanonical { timeout: Duration },
7528    #[error(
7529        ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
7530         (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
7531         per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
7532         overlays carry a deadline so long no realistic synchronous-:contratos \
7533         traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
7534         CSE invariant degenerates to enforcement only at the per-Servico \
7535         `:limits :wall-clock` layer — far above the per-edge granularity the typed \
7536         `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
7537         (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
7538         ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
7539         maxes out at the same `3600s` ceiling) or omit :timeout to express \
7540         `no per-call deadline on this axis` (the synchronous-call deadline then \
7541         relies entirely on the per-Servico `:limits :wall-clock` axis)"
7542    )]
7543    PolicyTimeoutExceedsCap { timeout: Duration },
7544    #[error(
7545        ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
7546         the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
7547         the shared duration codec round-trips losslessly; got {window:?} which carries a \
7548         sub-millisecond residue that either truncates to a different `Duration` on \
7549         re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
7550         Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
7551    )]
7552    PolicyBreakerWindowNotCanonical { window: Duration },
7553    #[error(
7554        ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
7555         (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
7556         rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
7557         is structurally so long that transient failures are never forgotten, the breaker \
7558         trips once and stays tripped for the lifetime of the component, and every typed-slot \
7559         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
7560         outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
7561         Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
7562         default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
7563         the breaker entirely"
7564    )]
7565    PolicyBreakerWindowExceedsCap { window: Duration },
7566}
7567
7568#[cfg(test)]
7569mod tests {
7570    use super::*;
7571
7572    fn membro(name: &str, ver: &str) -> Membro {
7573        Membro {
7574            caixa: name.into(),
7575            versao: ver.into(),
7576        }
7577    }
7578
7579    fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
7580        WitContract {
7581            de: de.into(),
7582            para: para.into(),
7583            wit: "wasi:http/proxy".into(),
7584            endpoint: Some(ep.into()),
7585            subject: None,
7586            slot: None,
7587        }
7588    }
7589
7590    fn three_member_spec() -> AplicacaoSpec {
7591        AplicacaoSpec {
7592            membros: vec![
7593                membro("catalog", "^0.1"),
7594                membro("cart", "^0.1"),
7595                membro("payment", "^0.2"),
7596            ],
7597            contratos: vec![
7598                contract_http("cart", "catalog", "/products/:id"),
7599                contract_http("cart", "payment", "/charge"),
7600            ],
7601            politicas: MeshPolicy {
7602                timeout: Some(Duration::from_secs(30)),
7603                retries: Some(3),
7604                mtls_required: Some(true),
7605                ..Default::default()
7606            },
7607            placement: Placement {
7608                estrategia: PlacementStrategy::Replicated,
7609                clusters: vec!["rio".into(), "mar".into()],
7610                affinity: Some("data-locality".into()),
7611                shard_key: None,
7612            },
7613            entrada: Some(Entrada {
7614                host: "checkout.quero.cloud".into(),
7615                para: "cart".into(),
7616                paths: vec!["/api/cart".into(), "/api/products".into()],
7617                port: 8080,
7618            }),
7619        }
7620    }
7621
7622    #[test]
7623    fn happy_path_validates() {
7624        three_member_spec().validate().unwrap();
7625    }
7626
7627    #[test]
7628    fn rejects_empty_membros() {
7629        let mut s = three_member_spec();
7630        s.membros = vec![];
7631        assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
7632    }
7633
7634    #[test]
7635    fn rejects_empty_membro_caixa() {
7636        // A `:caixa ""` entry has no name to render into programs.yaml
7637        // and no caixa.lisp to resolve at lacre time.
7638        let mut s = three_member_spec();
7639        s.membros[1].caixa = String::new();
7640        assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
7641    }
7642
7643    #[test]
7644    fn rejects_empty_membro_versao() {
7645        // A `:versao ""` entry can't pin a semver constraint, so the
7646        // lacre pipeline fails far from the source.
7647        let mut s = three_member_spec();
7648        s.membros[2].versao = String::new();
7649        let err = s.validate().unwrap_err();
7650        assert!(
7651            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
7652            "got {err:?}"
7653        );
7654    }
7655
7656    #[test]
7657    fn rejects_duplicate_membro_caixa() {
7658        // Two `:membros` entries with the same `:caixa` collapse to one
7659        // node in the membership HashSet, which masks `:contratos`
7660        // membership errors and produces duplicate programs.yaml entries.
7661        let mut s = three_member_spec();
7662        s.membros.push(membro("cart", "^0.2"));
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 rejects_invalid_membro_versao_requirement() {
7672        // The fail-before-pass-after pin: a non-empty but malformed
7673        // semver requirement (`"^bad-version"`) silently passed
7674        // `validate()` on every pre-gate codebase because the prior
7675        // shape only refused the empty string. The parse failure
7676        // surfaced far downstream at lacre-resolve time with a
7677        // `semver::Error` that didn't name which `:membros` entry
7678        // carried the typo. The new gate moves the check to caixa-build
7679        // time at the source caixa.lisp.
7680        let mut s = three_member_spec();
7681        s.membros[2].versao = "^bad-version".into();
7682        let err = s.validate().unwrap_err();
7683        assert!(
7684            matches!(
7685                err,
7686                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
7687                    if caixa == "payment" && versao == "^bad-version"
7688            ),
7689            "got {err:?}"
7690        );
7691    }
7692
7693    #[test]
7694    fn rejects_membro_versao_with_double_caret_typo() {
7695        // `"^^0.1"` is the canonical doubled-caret typo — looks like a
7696        // Cargo-shaped requirement on first glance but fails the parser
7697        // because semver doesn't accept stacked operators. Pin this
7698        // adjacent-shape footgun explicitly so a future relaxation that
7699        // accepts "looks-canonical-but-isn't" forms surfaces here.
7700        let mut s = three_member_spec();
7701        s.membros[0].versao = "^^0.1".into();
7702        let err = s.validate().unwrap_err();
7703        assert!(
7704            matches!(
7705                err,
7706                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
7707                    if caixa == "catalog" && versao == "^^0.1"
7708            ),
7709            "got {err:?}"
7710        );
7711    }
7712
7713    #[test]
7714    fn rejects_membro_versao_with_v_prefixed_tag() {
7715        // `"v0.1"` is the canonical "git-tag-shape leaking into the
7716        // semver requirement slot" typo — an author copies the
7717        // publish-side git-tag string verbatim into `:versao`, but
7718        // Cargo's semver parser rejects the leading `v` (only digits +
7719        // canonical operators are valid in the major-version
7720        // position). The gate's diagnostic names which member entry
7721        // carried the v-prefix so the fix is one edit, not a grep
7722        // through every member's `:versao`. (Note: bare `x`-glob
7723        // shorthands like `^0.1.x` are *accepted* by the semver crate
7724        // as an `*` wildcard on the patch axis — they're a Cargo-side
7725        // valid shape, not a typo, so the gate intentionally lets them
7726        // through.)
7727        let mut s = three_member_spec();
7728        s.membros[1].versao = "v0.1".into();
7729        let err = s.validate().unwrap_err();
7730        assert!(
7731            matches!(
7732                err,
7733                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
7734                    if caixa == "cart" && versao == "v0.1"
7735            ),
7736            "got {err:?}"
7737        );
7738    }
7739
7740    #[test]
7741    fn accepts_canonical_membro_versao_forms() {
7742        // The four Cargo-shaped requirement forms `:deps :versao`
7743        // already accepts via `crate::parse_requirement` must pass the
7744        // membros gate without re-validating at the resolver layer.
7745        // Pin every leg so a future tightening of the canonical set
7746        // surfaces here as a test failure.
7747        for form in [
7748            "^0.1",      // caret — minor-range pin (the most common shape)
7749            "~0.1.2",    // tilde — patch-range pin
7750            "0.1.0",     // exact — single-version pin
7751            "*",         // wildcard — explicitly any-version (semver::VersionReq::STAR)
7752            ">=0.1, <2", // multi-range — comma-separated comparators
7753        ] {
7754            let mut s = three_member_spec();
7755            for m in &mut s.membros {
7756                m.versao = form.into();
7757            }
7758            s.validate()
7759                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
7760        }
7761    }
7762
7763    #[test]
7764    fn membro_versao_empty_takes_precedence_over_invalid() {
7765        // Order pin: the existing `MembroVersaoEmpty` diagnostic
7766        // (which doesn't try to parse) fires before the new
7767        // `MembroVersaoInvalid` parse-side diagnostic, so an empty
7768        // `:versao` keeps its narrower error message — `parse_requirement`
7769        // would also reject `""`, but the empty-string arm is the more
7770        // self-locating diagnostic for the author.
7771        let mut s = three_member_spec();
7772        s.membros[1].versao = String::new();
7773        let err = s.validate().unwrap_err();
7774        assert!(
7775            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
7776            "got {err:?}"
7777        );
7778    }
7779
7780    #[test]
7781    fn membro_versao_invalid_fires_before_duplicate_check() {
7782        // Order pin: a malformed requirement on a non-duplicate entry
7783        // surfaces *its own* diagnostic (which names the offending
7784        // `:versao` string), even when a later entry would otherwise
7785        // collapse onto an earlier name. The per-entry shape gate runs
7786        // inline before the duplicate-key insert, parallel to
7787        // `membros_validation_runs_before_contratos_membership_check`
7788        // and `duplicate_contrato_gate_runs_after_target_shape_check`.
7789        let mut s = three_member_spec();
7790        s.membros[0].versao = "^bad".into();
7791        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
7792        let err = s.validate().unwrap_err();
7793        assert!(
7794            matches!(
7795                err,
7796                AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
7797            ),
7798            "got {err:?}"
7799        );
7800    }
7801
7802    #[test]
7803    fn membro_versao_invalid_diagnostic_carries_offending_versao() {
7804        // The diagnostic-shape pin: the error names the offending
7805        // `:versao` value verbatim so the author can grep their
7806        // caixa.lisp without re-running the build, and carries a
7807        // non-empty `reason` from `semver::VersionReq::parse` so the
7808        // parser's own wording flows through to the diagnostic.
7809        let mut s = three_member_spec();
7810        s.membros[2].versao = "not-a-req".into();
7811        let err = s.validate().unwrap_err();
7812        let AplicacaoError::MembroVersaoInvalid {
7813            caixa,
7814            versao,
7815            reason,
7816        } = err
7817        else {
7818            panic!("expected MembroVersaoInvalid, got other variant");
7819        };
7820        assert_eq!(caixa, "payment");
7821        assert_eq!(versao, "not-a-req");
7822        assert!(
7823            !reason.is_empty(),
7824            "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
7825        );
7826    }
7827
7828    #[test]
7829    fn membro_versao_invalid_runs_before_contratos_check() {
7830        // A malformed `:versao` on any member must surface its own
7831        // diagnostic (which names *which* member to fix) before any
7832        // `:contratos` membership lookup raises `ContratoMemberMissing`.
7833        // The `:contratos` gate runs after `validate_membros`, so this
7834        // is structurally guaranteed — pin it explicitly so a future
7835        // refactor that reorders the gates surfaces here.
7836        let mut s = three_member_spec();
7837        s.membros[1].versao = "^^0.1".into();
7838        // Add a contrato whose `:para` doesn't exist — would normally
7839        // raise ContratoMemberMissing at the membership lookup, but
7840        // the membros gate must fire first.
7841        s.contratos
7842            .push(contract_http("cart", "phantom", "/never-reached"));
7843        let err = s.validate().unwrap_err();
7844        assert!(
7845            matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
7846            "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
7847        );
7848    }
7849
7850    #[test]
7851    fn membros_validation_runs_before_contratos_membership_check() {
7852        // If `:membros` carries a duplicate, the membership-collapse
7853        // would silently accept a `:contratos :para "phantom"` so long
7854        // as some entry hashes to "phantom". Pinning order: the
7855        // duplicate-membros error fires first, regardless of whether
7856        // contratos reference real members.
7857        let mut s = three_member_spec();
7858        s.membros = vec![
7859            membro("cart", "^0.1"),
7860            membro("cart", "^0.2"),
7861            membro("catalog", "^0.1"),
7862            membro("payment", "^0.1"),
7863        ];
7864        let err = s.validate().unwrap_err();
7865        assert!(
7866            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
7867            "got {err:?}"
7868        );
7869    }
7870
7871    #[test]
7872    fn distinct_membros_validate() {
7873        // Pin the happy-path: every `:membros` entry has a non-empty
7874        // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
7875        // The fixture already satisfies this; this test makes the
7876        // invariant explicit so a future refactor of the fixture can't
7877        // silently break the guarantee.
7878        three_member_spec().validate().unwrap();
7879    }
7880
7881    // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
7882
7883    #[test]
7884    fn rejects_membro_caixa_with_uppercase() {
7885        // The canonical "I copied the Servico's display name verbatim"
7886        // typo — caixa names are lowercase per K8s DNS-1123 label rule,
7887        // but author tools often round-trip a TitleCase or CamelCase
7888        // identifier from an ADR or a sketch. Pin the diagnostic names
7889        // the offending name and suggests the lower-cased fix in one
7890        // edit, mirroring the `rejects_entrada_host_with_uppercase`
7891        // gate's shape (c7d05ec).
7892        let mut s = three_member_spec();
7893        s.membros[1].caixa = "Cart".into();
7894        let err = s.validate().unwrap_err();
7895        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
7896            panic!("expected MembroCaixaInvalid, got other variant");
7897        };
7898        assert_eq!(caixa, "Cart");
7899        assert!(
7900            reason.contains("uppercase"),
7901            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
7902        );
7903        assert!(
7904            reason.contains("\"cart\""),
7905            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
7906        );
7907    }
7908
7909    #[test]
7910    fn rejects_membro_caixa_with_underscore() {
7911        // The canonical "I'm thinking of a Python module / Postgres
7912        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
7913        // label schema. K8s rejects `metadata.name: my_cart` at admission
7914        // time with an opaque `field is invalid` (no source-citing
7915        // diagnostic). The gate moves it to caixa-build time.
7916        let mut s = three_member_spec();
7917        s.membros[0].caixa = "my_cart".into();
7918        let err = s.validate().unwrap_err();
7919        assert!(
7920            matches!(
7921                err,
7922                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
7923                    if caixa == "my_cart" && reason.contains('_')
7924            ),
7925            "got {err:?}"
7926        );
7927    }
7928
7929    #[test]
7930    fn rejects_membro_caixa_with_dot() {
7931        // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
7932        // subdomain — even though K8s `metadata.name` itself accepts
7933        // dots (DNS-1123 subdomain rule), this string also lands as a
7934        // K8s Service name (DNS-1035 label — no dots) and as a label
7935        // value on identity-based Cilium selectors. The strictest floor
7936        // among the use sites wins. The "I want to namespace my member
7937        // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
7938        let mut s = three_member_spec();
7939        s.membros[2].caixa = "team.cart".into();
7940        let err = s.validate().unwrap_err();
7941        assert!(
7942            matches!(
7943                err,
7944                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
7945                    if caixa == "team.cart" && reason.contains('.')
7946            ),
7947            "got {err:?}"
7948        );
7949    }
7950
7951    #[test]
7952    fn rejects_membro_caixa_with_leading_hyphen() {
7953        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
7954        // with an alphanumeric. The K8s apiserver rejects `-cart`
7955        // outright; the renderer would emit a `metadata.name: "-cart"`
7956        // that fails admission far from the source caixa.lisp.
7957        let mut s = three_member_spec();
7958        s.membros[0].caixa = "-cart".into();
7959        let err = s.validate().unwrap_err();
7960        assert!(
7961            matches!(
7962                err,
7963                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
7964                    if caixa == "-cart" && reason.contains("start and end")
7965            ),
7966            "got {err:?}"
7967        );
7968    }
7969
7970    #[test]
7971    fn rejects_membro_caixa_with_trailing_hyphen() {
7972        // The symmetric arm of the boundary rule. Pin separately so
7973        // both ends of the label are covered against a future relaxation
7974        // that only checks one boundary.
7975        let mut s = three_member_spec();
7976        s.membros[1].caixa = "cart-".into();
7977        let err = s.validate().unwrap_err();
7978        assert!(
7979            matches!(
7980                err,
7981                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
7982                    if caixa == "cart-"
7983            ),
7984            "got {err:?}"
7985        );
7986    }
7987
7988    #[test]
7989    fn rejects_membro_caixa_with_unicode() {
7990        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
7991        // (`xn--…`) by the author before it reaches K8s. The byte-by-
7992        // byte ASCII validity check rejects multi-byte UTF-8 sequences
7993        // by the first byte that fails the `[a-z0-9-]` predicate.
7994        let mut s = three_member_spec();
7995        s.membros[2].caixa = "café".into();
7996        let err = s.validate().unwrap_err();
7997        assert!(
7998            matches!(
7999                err,
8000                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
8001                    if caixa == "café"
8002            ),
8003            "got {err:?}"
8004        );
8005    }
8006
8007    #[test]
8008    fn rejects_membro_caixa_with_whitespace() {
8009        // Whitespace is the canonical "I pasted from a sketch / doc"
8010        // footgun. The apiserver rejects every `metadata.name` value
8011        // carrying whitespace; pin the gate fires at the right boundary.
8012        let mut s = three_member_spec();
8013        s.membros[0].caixa = "my cart".into();
8014        let err = s.validate().unwrap_err();
8015        assert!(
8016            matches!(
8017                err,
8018                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
8019                    if caixa == "my cart"
8020            ),
8021            "got {err:?}"
8022        );
8023    }
8024
8025    #[test]
8026    fn rejects_membro_caixa_too_long() {
8027        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
8028        // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
8029        // exactly. The gate's reason names both the cap and the actual
8030        // length so the author can shorten in one edit.
8031        let mut s = three_member_spec();
8032        let too_long = "a".repeat(64);
8033        s.membros[1].caixa = too_long.clone();
8034        let err = s.validate().unwrap_err();
8035        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
8036            panic!("expected MembroCaixaInvalid");
8037        };
8038        assert_eq!(caixa, too_long);
8039        assert!(
8040            reason.contains("63") && reason.contains("64"),
8041            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
8042        );
8043    }
8044
8045    #[test]
8046    fn membro_caixa_max_length_validates() {
8047        // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
8048        // so a future tightening (e.g. dropping to 62) surfaces here as
8049        // a regression, mirroring `entrada_host_max_length_validates`
8050        // (c7d05ec).
8051        let mut s = three_member_spec();
8052        s.membros[2].caixa = "a".repeat(63);
8053        s.entrada.as_mut().unwrap().para = "a".repeat(63);
8054        // remove contratos referencing the renamed member; they'd
8055        // raise ContratoMemberMissing otherwise
8056        s.contratos
8057            .retain(|c| c.de != "payment" && c.para != "payment");
8058        s.validate().unwrap();
8059    }
8060
8061    #[test]
8062    fn accepts_canonical_membro_caixa_forms() {
8063        // The DNS-1123 label shapes a caixa author is realistically
8064        // going to write: single-word lowercase, hyphen-joined, ending
8065        // in a digit-suffixed version (`cart-v2`), starting with a
8066        // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
8067        // DNS-1035 which requires a letter at position 0), single-
8068        // character (`a` — boundary). Pin every leg so a future
8069        // tightening that bans (e.g.) digit-start identifiers surfaces
8070        // here.
8071        for form in [
8072            "checkout",
8073            "cart",
8074            "cart-v2",
8075            "a",
8076            "c0",
8077            "3rd-party-shim",
8078            "x-1-2-3-4",
8079        ] {
8080            let mut s = three_member_spec();
8081            // Renaming a member also requires updating downstream refs;
8082            // drop everything else and rebuild a minimal spec around
8083            // just the one renamed member.
8084            s.membros = vec![membro(form, "^0.1")];
8085            s.contratos = vec![];
8086            s.entrada = None;
8087            s.validate()
8088                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
8089        }
8090    }
8091
8092    #[test]
8093    fn membro_caixa_empty_takes_precedence_over_invalid() {
8094        // Order pin: the existing `MembroCaixaEmpty` diagnostic
8095        // (which doesn't try to parse) fires before the new
8096        // `MembroCaixaInvalid` parse-side diagnostic, so an empty
8097        // `:caixa` keeps its narrower error message — the new gate
8098        // would also reject `""`, but the empty-string arm is the more
8099        // self-locating diagnostic for the author. Mirrors the
8100        // `entrada_host_empty_takes_precedence_over_invalid` pin
8101        // (c7d05ec).
8102        let mut s = three_member_spec();
8103        s.membros[1].caixa = String::new();
8104        let err = s.validate().unwrap_err();
8105        assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
8106    }
8107
8108    #[test]
8109    fn membro_caixa_invalid_fires_before_versao_check() {
8110        // Order pin: an invalid-shape `:caixa` surfaces *its own*
8111        // diagnostic (which names the offending caixa name), even when
8112        // the same entry's `:versao` is also empty/invalid. The shape
8113        // gate runs first because the diagnostic is more self-locating —
8114        // an empty/invalid `:versao` on an invalid-shape caixa name is
8115        // a downstream-fix-after-the-caixa-rename concern.
8116        let mut s = three_member_spec();
8117        s.membros[1].caixa = "Cart".into();
8118        s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
8119        let err = s.validate().unwrap_err();
8120        assert!(
8121            matches!(
8122                err,
8123                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
8124            ),
8125            "got {err:?}"
8126        );
8127    }
8128
8129    #[test]
8130    fn membro_caixa_invalid_fires_before_duplicate_check() {
8131        // Order pin: a malformed-shape `:caixa` on an earlier entry
8132        // surfaces *its own* diagnostic, even when a later entry would
8133        // otherwise collapse onto a duplicate name. The per-entry shape
8134        // gate runs inline before the duplicate-key insert, parallel
8135        // to `membro_versao_invalid_fires_before_duplicate_check`.
8136        let mut s = three_member_spec();
8137        s.membros[0].caixa = "Catalog".into();
8138        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
8139        let err = s.validate().unwrap_err();
8140        assert!(
8141            matches!(
8142                err,
8143                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
8144            ),
8145            "got {err:?}"
8146        );
8147    }
8148
8149    #[test]
8150    fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
8151        // The diagnostic-shape pin: the error names the offending
8152        // `:caixa` value verbatim so the author can grep their
8153        // caixa.lisp without re-running the build, and carries a
8154        // non-empty `reason` naming the specific violation. Same
8155        // shape every typed-shape gate enshrines (c7d05ec's
8156        // `entrada_host_diagnostic_carries_offending_host`,
8157        // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
8158        let mut s = three_member_spec();
8159        s.membros[2].caixa = "BAD_NAME".into();
8160        let err = s.validate().unwrap_err();
8161        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
8162            panic!("expected MembroCaixaInvalid");
8163        };
8164        assert_eq!(caixa, "BAD_NAME");
8165        assert!(
8166            !reason.is_empty(),
8167            "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
8168        );
8169    }
8170
8171    #[test]
8172    fn rejects_contrato_with_unknown_de() {
8173        let mut s = three_member_spec();
8174        s.contratos.push(contract_http("phantom", "catalog", "/x"));
8175        let err = s.validate().unwrap_err();
8176        assert!(
8177            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
8178        );
8179    }
8180
8181    #[test]
8182    fn rejects_contrato_with_unknown_para() {
8183        let mut s = three_member_spec();
8184        s.contratos.push(contract_http("cart", "phantom", "/x"));
8185        let err = s.validate().unwrap_err();
8186        assert!(
8187            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
8188        );
8189    }
8190
8191    #[test]
8192    fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
8193        // The read-path pin: the phantom-`:de` refusal arm's
8194        // `ContratoMemberMissing.caixa` carrier must be observed through
8195        // the lifted [`WitContract::source`] accessor, not the raw
8196        // `.de.clone()` field-access `String`-carry. Peer of the sibling
8197        // per-`:contratos` self-loop arm's `.source().to_string()` /
8198        // `.world_ref().to_string()` `String`-carry sites the earlier
8199        // convergence lifted onto the same accessor pair. A future
8200        // silent detour that reintroduced the raw `.de.clone()` at the
8201        // wrap envelope while the shape-gate and membership lookup
8202        // routed through the accessor would surface here as a byte-equal
8203        // miss between the fired diagnostic's `caixa:` field and the
8204        // offending edge's `.source()` — pinning the accessor as the
8205        // sole read path across the phantom-name refusal arm's arg +
8206        // wrap-envelope emit surface.
8207        let mut s = three_member_spec();
8208        let phantom = contract_http("phantom", "catalog", "/x");
8209        s.contratos.push(phantom.clone());
8210        let err = s.validate().unwrap_err();
8211        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
8212            panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
8213        };
8214        assert_eq!(
8215            caixa,
8216            phantom.source(),
8217            "ContratoMemberMissing.caixa on the phantom-:de arm must \
8218             byte-equal WitContract::source — the wrap envelope must \
8219             route through the lifted accessor rather than the raw \
8220             .de.clone() field-access String-carry"
8221        );
8222    }
8223
8224    #[test]
8225    fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
8226        // The symmetric read-path pin on the `:para` phantom-name
8227        // refusal arm — same shape as the sibling `:de` pin above but
8228        // on the callee-Servico axis. Pins the wrap envelope's
8229        // `caixa:` field is observed through the lifted
8230        // [`WitContract::destination`] accessor, not the raw
8231        // `.para.clone()` field-access `String`-carry.
8232        let mut s = three_member_spec();
8233        let phantom = contract_http("cart", "phantom", "/x");
8234        s.contratos.push(phantom.clone());
8235        let err = s.validate().unwrap_err();
8236        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
8237            panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
8238        };
8239        assert_eq!(
8240            caixa,
8241            phantom.destination(),
8242            "ContratoMemberMissing.caixa on the phantom-:para arm must \
8243             byte-equal WitContract::destination — the wrap envelope \
8244             must route through the lifted accessor rather than the raw \
8245             .para.clone() field-access String-carry"
8246        );
8247    }
8248
8249    #[test]
8250    fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
8251        // The read-path pin on the `:de` DNS-1123-malformed shape-gate
8252        // refusal arm — the `validate_contrato_caixa` arg must be
8253        // observed through the lifted [`WitContract::source`] accessor,
8254        // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
8255        // value routes through the shared
8256        // [`crate::render::require_valid_dns_1123_label`] floor with the
8257        // accessor-projected value; the fired
8258        // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
8259        // the offending edge's `.source()`, pinning that the arg + the
8260        // downstream `caixa: caixa.to_string()` wrap route through the
8261        // same accessor's read path.
8262        let mut s = three_member_spec();
8263        let malformed = contract_http("BAD_NAME", "catalog", "/x");
8264        s.contratos.push(malformed.clone());
8265        let err = s.validate().unwrap_err();
8266        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
8267            panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
8268        };
8269        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
8270        assert_eq!(
8271            caixa,
8272            malformed.source(),
8273            "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
8274             byte-equal WitContract::source — the shape-gate arg + wrap \
8275             envelope must route through the lifted accessor rather \
8276             than the raw &c.de &String-borrow"
8277        );
8278    }
8279
8280    #[test]
8281    fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
8282        // Symmetric arm to the sibling `:de` malformed-shape pin above,
8283        // on the `:para` axis. Pins the shape-gate arg + wrap envelope
8284        // route through the lifted [`WitContract::destination`]
8285        // accessor. `:para` runs after the `:de` shape gate in the
8286        // canonical edge-direction order, so the `:de` value must be
8287        // well-shaped for the `:para` gate to fire — the `cart` :de is
8288        // canonical.
8289        let mut s = three_member_spec();
8290        let malformed = contract_http("cart", "BAD_NAME", "/x");
8291        s.contratos.push(malformed.clone());
8292        let err = s.validate().unwrap_err();
8293        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
8294            panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
8295        };
8296        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
8297        assert_eq!(
8298            caixa,
8299            malformed.destination(),
8300            "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
8301             byte-equal WitContract::destination — the shape-gate arg + \
8302             wrap envelope must route through the lifted accessor \
8303             rather than the raw &c.para &String-borrow"
8304        );
8305    }
8306
8307    // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
8308
8309    #[test]
8310    fn rejects_contrato_de_empty() {
8311        // `:de ""` previously fell through to `ContratoMemberMissing`
8312        // (with `caixa: ""`) because the validated `:membros :caixa`
8313        // set never contains the empty string. The narrower
8314        // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
8315        // the offending slot.
8316        let mut s = three_member_spec();
8317        s.contratos.push(contract_http("", "catalog", "/x"));
8318        let err = s.validate().unwrap_err();
8319        assert_eq!(
8320            err,
8321            AplicacaoError::ContratoCaixaEmpty {
8322                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
8323            },
8324            "got {err:?}"
8325        );
8326    }
8327
8328    #[test]
8329    fn rejects_contrato_para_empty() {
8330        // Symmetric arm to `:de ""` — `:para ""` previously fell
8331        // through to `ContratoMemberMissing { caixa: "" }`.
8332        let mut s = three_member_spec();
8333        s.contratos.push(contract_http("cart", "", "/x"));
8334        let err = s.validate().unwrap_err();
8335        assert_eq!(
8336            err,
8337            AplicacaoError::ContratoCaixaEmpty {
8338                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
8339            },
8340            "got {err:?}"
8341        );
8342    }
8343
8344    #[test]
8345    fn rejects_contrato_de_with_uppercase() {
8346        // The canonical "I copied the Servico's TitleCase display
8347        // name from an ADR" typo. Until this gate landed `:de "Cart"`
8348        // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
8349        // as "this caixa isn't in `:membros`" when the root cause is
8350        // "this `:de` value's shape can never legitimately match a
8351        // validated member (DNS-1123 labels are lowercase)". The
8352        // narrower diagnostic names the offending slot, the value
8353        // verbatim, and the parser-shaped reason.
8354        let mut s = three_member_spec();
8355        s.contratos.push(contract_http("Cart", "catalog", "/x"));
8356        let err = s.validate().unwrap_err();
8357        let AplicacaoError::ContratoCaixaInvalid {
8358            slot,
8359            caixa,
8360            reason,
8361        } = err
8362        else {
8363            panic!("expected ContratoCaixaInvalid, got other variant");
8364        };
8365        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
8366        assert_eq!(caixa, "Cart");
8367        assert!(
8368            reason.contains("uppercase"),
8369            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
8370        );
8371    }
8372
8373    #[test]
8374    fn rejects_contrato_para_with_underscore() {
8375        // The canonical "I'm thinking of a Python module" leak —
8376        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
8377        // Pin the `:para` axis surfaces the same diagnostic shape as
8378        // the `:de` axis on the underscore violation.
8379        let mut s = three_member_spec();
8380        s.contratos.push(contract_http("cart", "my_catalog", "/x"));
8381        let err = s.validate().unwrap_err();
8382        assert!(
8383            matches!(
8384                err,
8385                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
8386                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
8387            ),
8388            "got {err:?}"
8389        );
8390    }
8391
8392    #[test]
8393    fn rejects_contrato_de_with_dot() {
8394        // A `:contratos :de` value is a single DNS-1123 *label*, not
8395        // a subdomain — mirroring the `:membros :caixa` floor. The
8396        // strictest floor among the use sites wins.
8397        let mut s = three_member_spec();
8398        s.contratos
8399            .push(contract_http("team.cart", "catalog", "/x"));
8400        let err = s.validate().unwrap_err();
8401        assert!(
8402            matches!(
8403                err,
8404                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
8405                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
8406            ),
8407            "got {err:?}"
8408        );
8409    }
8410
8411    #[test]
8412    fn rejects_contrato_para_with_unicode() {
8413        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
8414        // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
8415        // validity check rejects multi-byte UTF-8 by the first
8416        // non-`[a-z0-9-]` byte.
8417        let mut s = three_member_spec();
8418        s.contratos.push(contract_http("cart", "café", "/x"));
8419        let err = s.validate().unwrap_err();
8420        assert!(
8421            matches!(
8422                err,
8423                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
8424                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
8425            ),
8426            "got {err:?}"
8427        );
8428    }
8429
8430    #[test]
8431    fn rejects_contrato_de_with_leading_hyphen() {
8432        // DNS-1123 boundary rule: labels must start and end with an
8433        // alphanumeric. K8s rejects `-cart` outright; the narrower
8434        // shape diagnostic now names the violation at caixa-build
8435        // time rather than the misframed membership-lookup arm.
8436        let mut s = three_member_spec();
8437        s.contratos.push(contract_http("-cart", "catalog", "/x"));
8438        let err = s.validate().unwrap_err();
8439        assert!(
8440            matches!(
8441                err,
8442                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
8443                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
8444            ),
8445            "got {err:?}"
8446        );
8447    }
8448
8449    #[test]
8450    fn contrato_de_empty_takes_precedence_over_invalid() {
8451        // Order pin: the `ContratoCaixaEmpty` arm fires before the
8452        // `ContratoCaixaInvalid` parse-side arm — same empty-first
8453        // cascade `validate_membro_caixa` / `validate_placement_cluster`
8454        // / `validate_entrada_host` already establish on their peer
8455        // name axes. The empty string is a structurally distinct
8456        // authoring footgun (the author left the field blank, vs.
8457        // typed a malformed value), so it gets its own diagnostic.
8458        let mut s = three_member_spec();
8459        s.contratos.push(contract_http("", "catalog", "/x"));
8460        let err = s.validate().unwrap_err();
8461        assert_eq!(
8462            err,
8463            AplicacaoError::ContratoCaixaEmpty {
8464                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
8465            }
8466        );
8467    }
8468
8469    #[test]
8470    fn contrato_de_shape_fires_before_para_shape() {
8471        // Per-axis order pin: within one `:contratos` entry, the `:de`
8472        // shape gate fires before the `:para` shape gate — same
8473        // edge-direction order the existing `ContratoMemberMissing` /
8474        // `ContratoSelfLoop` / target-dispatch checks use, so the
8475        // diagnostic for a contract with both `:de` and `:para`
8476        // malformed is stable. Authors fixing the surfaced `:de`
8477        // first will see `:para`'s diagnostic on re-run.
8478        let mut s = three_member_spec();
8479        s.contratos.push(contract_http("Cart", "Catalog", "/x"));
8480        let err = s.validate().unwrap_err();
8481        assert!(
8482            matches!(
8483                err,
8484                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
8485                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
8486            ),
8487            "got {err:?}"
8488        );
8489    }
8490
8491    #[test]
8492    fn contrato_shape_fires_before_membership_lookup() {
8493        // The load-bearing pin: an invalid-shape `:de` surfaces its
8494        // *own* diagnostic, not the misframed `ContratoMemberMissing`.
8495        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
8496        // an invalid-shape `:de` could never legitimately match any
8497        // member — the prior `ContratoMemberMissing` diagnostic was
8498        // a structural impossibility framed as a graph-membership
8499        // failure. The shape gate now routes every such input through
8500        // the narrower self-locating diagnostic.
8501        let mut s = three_member_spec();
8502        s.contratos.push(contract_http("Cart", "catalog", "/x"));
8503        let err = s.validate().unwrap_err();
8504        assert!(
8505            matches!(
8506                err,
8507                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
8508            ),
8509            "got {err:?}"
8510        );
8511        // And the symmetric case: an invalid-shape `:para` surfaces
8512        // its own diagnostic too, even when `:de` is well-shaped.
8513        let mut s = three_member_spec();
8514        s.contratos.push(contract_http("cart", "Catalog", "/x"));
8515        let err = s.validate().unwrap_err();
8516        assert!(
8517            matches!(
8518                err,
8519                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
8520            ),
8521            "got {err:?}"
8522        );
8523    }
8524
8525    #[test]
8526    fn contrato_shape_fires_before_self_edge_check() {
8527        // A `:de "Cart" :para "Cart"` entry is two distinct authoring
8528        // bugs: the shape violation (uppercase) and the self-edge
8529        // violation. The narrower per-axis shape diagnostic surfaces
8530        // first because fixing the shape may reveal that the author
8531        // also meant to point `:para` at a different member — the
8532        // self-edge framing is only useful once both endpoints have
8533        // valid shape.
8534        let mut s = three_member_spec();
8535        s.contratos.push(contract_http("Cart", "Cart", "/x"));
8536        let err = s.validate().unwrap_err();
8537        assert!(
8538            matches!(
8539                err,
8540                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
8541                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
8542            ),
8543            "got {err:?}"
8544        );
8545    }
8546
8547    #[test]
8548    fn contrato_well_shaped_phantom_still_raises_member_missing() {
8549        // Strict-improvement pin: a well-shaped `:de` that simply
8550        // isn't in `:membros` (a phantom reference — author meant
8551        // to add the member but didn't, or renamed and missed an
8552        // update) still surfaces `ContratoMemberMissing`, unchanged.
8553        // The shape gate only intercepts inputs that could never
8554        // legitimately match a validated member; legitimately-shaped
8555        // phantom references remain on the graph-membership axis.
8556        let mut s = three_member_spec();
8557        s.contratos
8558            .push(contract_http("phantom-shim", "catalog", "/x"));
8559        let err = s.validate().unwrap_err();
8560        assert!(
8561            matches!(
8562                err,
8563                AplicacaoError::ContratoMemberMissing { ref caixa }
8564                    if caixa == "phantom-shim"
8565            ),
8566            "got {err:?}"
8567        );
8568    }
8569
8570    #[test]
8571    fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
8572        // The diagnostic-shape pin: the error names the offending
8573        // slot (`:de` or `:para`) verbatim and the offending value
8574        // verbatim plus a non-empty parser-shaped reason, so the
8575        // author can grep their caixa.lisp for `:de "<name>"` /
8576        // `:para "<name>"` and fix it in one edit. Same diagnostic
8577        // shape as `MembroCaixaInvalid` (3f9d7a0) and
8578        // `PlacementClusterInvalid` (6c8c00b).
8579        let mut s = three_member_spec();
8580        s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
8581        let err = s.validate().unwrap_err();
8582        let AplicacaoError::ContratoCaixaInvalid {
8583            slot,
8584            caixa,
8585            reason,
8586        } = err
8587        else {
8588            panic!("expected ContratoCaixaInvalid, got {err:?}");
8589        };
8590        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
8591        assert_eq!(caixa, "BAD_NAME");
8592        assert!(
8593            !reason.is_empty(),
8594            "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
8595        );
8596    }
8597
8598    #[test]
8599    fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
8600        // Scalar-value pin: the two author-facing kebab-case labels the
8601        // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
8602        // admits on the `:contratos` per-entry endpoint-shape axis,
8603        // one arm per typed sub-slot. Mirrors the peer scalar-value
8604        // pin the sibling top-level M2 / M3 / Supervisor
8605        // author-facing-label consts carry
8606        // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
8607        // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
8608        // slot itself), so every altitude of the typed-slot algebra
8609        // shares the same "one canonical byte-string per arm"
8610        // discipline. A future rebrand (`:de` → `:from` matching the
8611        // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
8612        // sibling, `:para` → `:to` matching the same, or
8613        // `:de`/`:para` → `:source`/`:target` matching the WIT
8614        // world's `import`/`export` half-vocabulary) lands as an
8615        // edit to exactly one const, and every consumer that reaches
8616        // for the label picks it up at build time rather than at
8617        // runtime as a downstream `ContratoCaixaEmpty` /
8618        // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
8619        // diagnostic mismatch far from the rename's commit.
8620        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
8621        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
8622    }
8623
8624    #[test]
8625    fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
8626        // Production-through-const pin: the two per-axis labels the
8627        // per-`:contratos` entry endpoint-shape gate at
8628        // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
8629        // argument to [`validate_contrato_caixa`] route through the
8630        // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
8631        // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
8632        // future rebrand that reaches the const but not the gate (or
8633        // vice versa) surfaces here at build time rather than at
8634        // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
8635        // `slot: <stale-kebab-case>` diagnostic far from the rename's
8636        // commit. Mirror of the peer
8637        // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
8638        // pin (882f498) on the sibling M3 top-level slot axis.
8639        let mut s = three_member_spec();
8640        s.contratos.push(contract_http("", "catalog", "/x"));
8641        assert_eq!(
8642            s.validate().unwrap_err(),
8643            AplicacaoError::ContratoCaixaEmpty {
8644                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
8645            }
8646        );
8647        let mut s = three_member_spec();
8648        s.contratos.push(contract_http("cart", "", "/x"));
8649        assert_eq!(
8650            s.validate().unwrap_err(),
8651            AplicacaoError::ContratoCaixaEmpty {
8652                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
8653            }
8654        );
8655    }
8656
8657    #[test]
8658    fn accepts_canonical_contrato_caixa_forms() {
8659        // The DNS-1123 label shapes a caixa author is realistically
8660        // going to write on a `:contratos :de` / `:para`. Pin every
8661        // leg so a future tightening that bans (e.g.) digit-start
8662        // identifiers surfaces here, mirroring
8663        // `accepts_canonical_membro_caixa_forms` on the peer name
8664        // axis.
8665        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
8666            let mut s = three_member_spec();
8667            s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
8668            s.contratos = vec![contract_http("checkout", form, "/x")];
8669            s.entrada = None;
8670            s.validate().unwrap_or_else(|e| {
8671                panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
8672            });
8673
8674            let mut s = three_member_spec();
8675            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
8676            s.contratos = vec![contract_http(form, "catalog", "/x")];
8677            s.entrada = None;
8678            s.validate().unwrap_or_else(|e| {
8679                panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
8680            });
8681        }
8682    }
8683
8684    #[test]
8685    fn rejects_empty_wit() {
8686        let mut s = three_member_spec();
8687        s.contratos.push(WitContract {
8688            de: "cart".into(),
8689            para: "catalog".into(),
8690            wit: "".into(),
8691            endpoint: None,
8692            subject: None,
8693            slot: None,
8694        });
8695        let err = s.validate().unwrap_err();
8696        assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
8697    }
8698
8699    #[test]
8700    fn rejects_entrada_to_unknown_member() {
8701        let mut s = three_member_spec();
8702        s.entrada.as_mut().unwrap().para = "phantom".into();
8703        assert!(matches!(
8704            s.validate().unwrap_err(),
8705            AplicacaoError::EntradaMemberMissing { .. }
8706        ));
8707    }
8708
8709    // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
8710
8711    #[test]
8712    fn rejects_entrada_para_empty() {
8713        // `:para ""` previously fell through to
8714        // `EntradaMemberMissing { para: "" }` because the validated
8715        // `:membros :caixa` set never contains the empty string. The
8716        // narrower `EntradaParaEmpty` diagnostic now names the
8717        // offending slot directly — same empty-first cascade
8718        // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
8719        // `ContratoCaixaEmpty` establish on the peer name axes.
8720        let mut s = three_member_spec();
8721        s.entrada.as_mut().unwrap().para = String::new();
8722        let err = s.validate().unwrap_err();
8723        assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
8724    }
8725
8726    #[test]
8727    fn rejects_entrada_para_with_uppercase() {
8728        // The canonical "I copied the Servico's TitleCase display
8729        // name from an ADR" typo. Until this gate landed `:para "Cart"`
8730        // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
8731        // as "this caixa isn't in `:membros`" when the root cause is
8732        // "this `:para` value's shape can never legitimately match a
8733        // validated member (DNS-1123 labels are lowercase)". The
8734        // narrower diagnostic names the value verbatim plus the
8735        // parser-shaped reason.
8736        let mut s = three_member_spec();
8737        s.entrada.as_mut().unwrap().para = "Cart".into();
8738        let err = s.validate().unwrap_err();
8739        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
8740            panic!("expected EntradaParaInvalid, got other variant");
8741        };
8742        assert_eq!(para, "Cart");
8743        assert!(
8744            reason.contains("uppercase"),
8745            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
8746        );
8747    }
8748
8749    #[test]
8750    fn rejects_entrada_para_with_underscore() {
8751        // The canonical "I'm thinking of a Python module" leak —
8752        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
8753        let mut s = three_member_spec();
8754        s.entrada.as_mut().unwrap().para = "my_cart".into();
8755        let err = s.validate().unwrap_err();
8756        assert!(
8757            matches!(
8758                err,
8759                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8760                    if para == "my_cart" && reason.contains('_')
8761            ),
8762            "got {err:?}"
8763        );
8764    }
8765
8766    #[test]
8767    fn rejects_entrada_para_with_dot() {
8768        // An `:entrada :para` value is a single DNS-1123 *label*, not
8769        // a subdomain — mirroring the `:membros :caixa` floor. The
8770        // strictest floor among the use sites wins.
8771        let mut s = three_member_spec();
8772        s.entrada.as_mut().unwrap().para = "team.cart".into();
8773        let err = s.validate().unwrap_err();
8774        assert!(
8775            matches!(
8776                err,
8777                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8778                    if para == "team.cart" && reason.contains('.')
8779            ),
8780            "got {err:?}"
8781        );
8782    }
8783
8784    #[test]
8785    fn rejects_entrada_para_with_unicode() {
8786        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
8787        // (`xn--…`) before it reaches K8s.
8788        let mut s = three_member_spec();
8789        s.entrada.as_mut().unwrap().para = "café".into();
8790        let err = s.validate().unwrap_err();
8791        assert!(
8792            matches!(
8793                err,
8794                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
8795            ),
8796            "got {err:?}"
8797        );
8798    }
8799
8800    #[test]
8801    fn rejects_entrada_para_with_leading_hyphen() {
8802        // DNS-1123 boundary rule: labels must start and end with an
8803        // alphanumeric. K8s rejects `-cart` outright.
8804        let mut s = three_member_spec();
8805        s.entrada.as_mut().unwrap().para = "-cart".into();
8806        let err = s.validate().unwrap_err();
8807        assert!(
8808            matches!(
8809                err,
8810                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8811                    if para == "-cart" && reason.contains("start and end")
8812            ),
8813            "got {err:?}"
8814        );
8815    }
8816
8817    #[test]
8818    fn rejects_entrada_para_with_trailing_hyphen() {
8819        // Symmetric boundary arm.
8820        let mut s = three_member_spec();
8821        s.entrada.as_mut().unwrap().para = "cart-".into();
8822        let err = s.validate().unwrap_err();
8823        assert!(
8824            matches!(
8825                err,
8826                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8827                    if para == "cart-" && reason.contains("start and end")
8828            ),
8829            "got {err:?}"
8830        );
8831    }
8832
8833    #[test]
8834    fn rejects_entrada_para_too_long() {
8835        // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
8836        // bytes per label. K8s rejects longer names at admission on
8837        // every `metadata.name` axis.
8838        let mut s = three_member_spec();
8839        s.entrada.as_mut().unwrap().para = "a".repeat(64);
8840        let err = s.validate().unwrap_err();
8841        assert!(
8842            matches!(
8843                err,
8844                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8845                    if para.len() == 64 && reason.contains("max length")
8846            ),
8847            "got {err:?}"
8848        );
8849    }
8850
8851    #[test]
8852    fn entrada_para_empty_takes_precedence_over_invalid() {
8853        // Order pin: the `EntradaParaEmpty` arm fires before the
8854        // `EntradaParaInvalid` parse-side arm — same empty-first
8855        // cascade `validate_membro_caixa` / `validate_placement_cluster`
8856        // / `validate_contrato_caixa` already establish.
8857        let mut s = three_member_spec();
8858        s.entrada.as_mut().unwrap().para = String::new();
8859        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
8860    }
8861
8862    #[test]
8863    fn entrada_para_shape_fires_before_membership_lookup() {
8864        // The load-bearing pin: an invalid-shape `:para` surfaces its
8865        // *own* diagnostic, not the misframed `EntradaMemberMissing`.
8866        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
8867        // an invalid-shape `:para` could never legitimately match any
8868        // member — the prior `EntradaMemberMissing` diagnostic framed
8869        // a structural impossibility as a graph-membership failure.
8870        let mut s = three_member_spec();
8871        s.entrada.as_mut().unwrap().para = "Cart".into();
8872        let err = s.validate().unwrap_err();
8873        assert!(
8874            matches!(
8875                err,
8876                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
8877            ),
8878            "got {err:?}"
8879        );
8880    }
8881
8882    #[test]
8883    fn entrada_para_shape_fires_before_host_gate() {
8884        // Per-`:entrada` order pin: the `:para` shape gate fires
8885        // before the `:host` gate, mirroring the existing
8886        // `entrada_host_member_missing_takes_precedence_over_host_invalid`
8887        // ordering where the member-lookup arm preceded the host gate.
8888        // The shape gate slots ahead of that, so a malformed `:para`
8889        // surfaces its own diagnostic even when `:host` is also wrong.
8890        let mut s = three_member_spec();
8891        let e = s.entrada.as_mut().unwrap();
8892        e.para = "Cart".into();
8893        e.host = "BAD HOST".into();
8894        let err = s.validate().unwrap_err();
8895        assert!(
8896            matches!(
8897                err,
8898                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
8899            ),
8900            "got {err:?}"
8901        );
8902    }
8903
8904    #[test]
8905    fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
8906        // Strict-improvement pin: a well-shaped `:para` that simply
8907        // isn't in `:membros` (a phantom reference — author meant to
8908        // add the member but didn't, or renamed and missed an
8909        // update) still surfaces `EntradaMemberMissing`, unchanged.
8910        // The shape gate only intercepts inputs that could never
8911        // legitimately match a validated member.
8912        let mut s = three_member_spec();
8913        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
8914        let err = s.validate().unwrap_err();
8915        assert!(
8916            matches!(
8917                err,
8918                AplicacaoError::EntradaMemberMissing { ref para }
8919                    if para == "phantom-shim"
8920            ),
8921            "got {err:?}"
8922        );
8923    }
8924
8925    #[test]
8926    fn entrada_para_invalid_diagnostic_carries_offending_para() {
8927        // The diagnostic-shape pin: the error names the offending
8928        // `:para` value verbatim plus a non-empty parser-shaped
8929        // reason, so the author can grep their caixa.lisp for
8930        // `:para "<name>"` and fix it in one edit. Same diagnostic
8931        // shape as `MembroCaixaInvalid` (3f9d7a0),
8932        // `PlacementClusterInvalid` (6c8c00b), and
8933        // `ContratoCaixaInvalid` (8d5af6b).
8934        let mut s = three_member_spec();
8935        s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
8936        let err = s.validate().unwrap_err();
8937        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
8938            panic!("expected EntradaParaInvalid, got {err:?}");
8939        };
8940        assert_eq!(para, "BAD_NAME");
8941        assert!(
8942            !reason.is_empty(),
8943            "EntradaParaInvalid `reason` must carry a parser-shaped wording"
8944        );
8945    }
8946
8947    #[test]
8948    fn accepts_canonical_entrada_para_forms() {
8949        // Positive-control sweep covering the DNS-1123 label shapes a
8950        // caixa author is realistically going to write on `:entrada
8951        // :para`. Pin every leg so a future tightening that bans
8952        // (e.g.) digit-start identifiers surfaces here, mirroring
8953        // `accepts_canonical_membro_caixa_forms` and
8954        // `accepts_canonical_contrato_caixa_forms` on the peer name
8955        // axes.
8956        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
8957            let mut s = three_member_spec();
8958            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
8959            s.contratos = vec![contract_http(form, "catalog", "/x")];
8960            s.entrada = Some(Entrada {
8961                host: "checkout.quero.cloud".into(),
8962                para: form.into(),
8963                paths: vec!["/api".into()],
8964                port: 8080,
8965            });
8966            s.validate().unwrap_or_else(|e| {
8967                panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
8968            });
8969        }
8970    }
8971
8972    #[test]
8973    fn rejects_replicated_without_clusters() {
8974        let mut s = three_member_spec();
8975        s.placement.clusters = vec![];
8976        assert!(matches!(
8977            s.validate().unwrap_err(),
8978            AplicacaoError::PlacementWithoutClusters { .. }
8979        ));
8980    }
8981
8982    #[test]
8983    fn rejects_sharded_without_key() {
8984        let mut s = three_member_spec();
8985        s.placement.estrategia = PlacementStrategy::Sharded;
8986        s.placement.shard_key = None;
8987        s.placement.clusters = vec!["rio".into()];
8988        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
8989    }
8990
8991    #[test]
8992    fn sharded_with_key_validates() {
8993        let mut s = three_member_spec();
8994        s.placement.estrategia = PlacementStrategy::Sharded;
8995        s.placement.shard_key = Some("$tenantId".into());
8996        s.validate().unwrap();
8997    }
8998
8999    #[test]
9000    fn round_trip_via_json_preserves_shape() {
9001        let s = three_member_spec();
9002        let json = serde_json::to_string(&s.membros).unwrap();
9003        let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
9004        assert_eq!(back, s.membros);
9005
9006        let json = serde_json::to_string(&s.contratos).unwrap();
9007        let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
9008        assert_eq!(back, s.contratos);
9009
9010        let json = serde_json::to_string(&s.placement).unwrap();
9011        let back: Placement = serde_json::from_str(&json).unwrap();
9012        assert_eq!(back, s.placement);
9013
9014        let json = serde_json::to_string(&s.entrada).unwrap();
9015        let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
9016        assert_eq!(back, s.entrada);
9017    }
9018
9019    #[test]
9020    fn rate_limit_round_trip_seconds() {
9021        let policy = MeshPolicy {
9022            rate_limit: Some(RateLimit {
9023                rate: 100,
9024                window: Duration::from_secs(1),
9025            }),
9026            ..Default::default()
9027        };
9028        let json = serde_json::to_string(&policy).unwrap();
9029        assert!(json.contains("\"100/s\""));
9030        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
9031        assert_eq!(back.rate_limit.unwrap().rate, 100);
9032        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
9033    }
9034
9035    #[test]
9036    fn rate_limit_round_trip_minutes() {
9037        let policy = MeshPolicy {
9038            rate_limit: Some(RateLimit {
9039                rate: 5000,
9040                window: Duration::from_secs(60),
9041            }),
9042            ..Default::default()
9043        };
9044        let json = serde_json::to_string(&policy).unwrap();
9045        assert!(json.contains("\"5000/m\""));
9046    }
9047
9048    #[test]
9049    fn circuit_breaker_round_trip() {
9050        let policy = MeshPolicy {
9051            circuit_breaker: Some(CircuitBreaker {
9052                max_failures: 5,
9053                window: Duration::from_secs(60),
9054            }),
9055            ..Default::default()
9056        };
9057        let json = serde_json::to_string(&policy).unwrap();
9058        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
9059        assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
9060        assert_eq!(
9061            back.circuit_breaker.unwrap().window,
9062            Duration::from_secs(60)
9063        );
9064    }
9065
9066    #[test]
9067    fn rejects_http_contrato_without_endpoint() {
9068        let mut s = three_member_spec();
9069        s.contratos.push(WitContract {
9070            de: "cart".into(),
9071            para: "catalog".into(),
9072            wit: "wasi:http/proxy".into(),
9073            endpoint: None,
9074            subject: None,
9075            slot: None,
9076        });
9077        let err = s.validate().unwrap_err();
9078        assert!(matches!(
9079            err,
9080            AplicacaoError::ContratoMissingTarget {
9081                expected: WitTarget::HTTP_FIELD_NAME,
9082                ..
9083            }
9084        ));
9085    }
9086
9087    #[test]
9088    fn rejects_http_contrato_with_subject() {
9089        let mut s = three_member_spec();
9090        s.contratos.push(WitContract {
9091            de: "cart".into(),
9092            para: "catalog".into(),
9093            wit: "wasi:http/proxy".into(),
9094            endpoint: Some("/x".into()),
9095            subject: Some("not.allowed.here".into()),
9096            slot: None,
9097        });
9098        let err = s.validate().unwrap_err();
9099        assert!(matches!(
9100            err,
9101            AplicacaoError::ContratoWrongTarget {
9102                expected: WitTarget::HTTP_FIELD_NAME,
9103                ..
9104            }
9105        ));
9106    }
9107
9108    #[test]
9109    fn rejects_pubsub_contrato_without_subject() {
9110        let mut s = three_member_spec();
9111        s.contratos.push(WitContract {
9112            de: "cart".into(),
9113            para: "catalog".into(),
9114            wit: "nats:pub-sub".into(),
9115            endpoint: None,
9116            subject: None,
9117            slot: None,
9118        });
9119        let err = s.validate().unwrap_err();
9120        assert!(matches!(
9121            err,
9122            AplicacaoError::ContratoMissingTarget {
9123                expected: WitTarget::PUBSUB_FIELD_NAME,
9124                ..
9125            }
9126        ));
9127    }
9128
9129    #[test]
9130    fn rejects_pubsub_contrato_with_endpoint() {
9131        let mut s = three_member_spec();
9132        s.contratos.push(WitContract {
9133            de: "cart".into(),
9134            para: "catalog".into(),
9135            wit: "kafka:topic".into(),
9136            endpoint: Some("/wrong".into()),
9137            subject: Some("topic.x".into()),
9138            slot: None,
9139        });
9140        let err = s.validate().unwrap_err();
9141        assert!(matches!(
9142            err,
9143            AplicacaoError::ContratoWrongTarget {
9144                expected: WitTarget::PUBSUB_FIELD_NAME,
9145                ..
9146            }
9147        ));
9148    }
9149
9150    #[test]
9151    fn rejects_store_contrato_without_slot() {
9152        let mut s = three_member_spec();
9153        s.contratos.push(WitContract {
9154            de: "cart".into(),
9155            para: "catalog".into(),
9156            wit: "wasi:keyvalue/store".into(),
9157            endpoint: None,
9158            subject: None,
9159            slot: None,
9160        });
9161        let err = s.validate().unwrap_err();
9162        assert!(matches!(
9163            err,
9164            AplicacaoError::ContratoMissingTarget {
9165                expected: WitTarget::STORE_FIELD_NAME,
9166                ..
9167            }
9168        ));
9169    }
9170
9171    // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
9172
9173    #[test]
9174    fn rejects_http_contrato_with_empty_endpoint() {
9175        // `Some("")` for an HTTP endpoint passes the presence check
9176        // (target() previously returned WitTarget::Http { endpoint: "" })
9177        // but renders as a `path: ""` Cilium L7 rule that matches no
9178        // traffic. Same value-shape footgun closed for :entrada :paths
9179        // entries (eb3456d).
9180        let mut s = three_member_spec();
9181        s.contratos.push(WitContract {
9182            de: "cart".into(),
9183            para: "catalog".into(),
9184            wit: "wasi:http/proxy".into(),
9185            endpoint: Some(String::new()),
9186            subject: None,
9187            slot: None,
9188        });
9189        let err = s.validate().unwrap_err();
9190        assert!(
9191            matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
9192                if de == "cart" && para == "catalog"),
9193            "got {err:?}"
9194        );
9195    }
9196
9197    #[test]
9198    fn rejects_http_contrato_with_relative_endpoint() {
9199        // Cilium L7 :path + Gateway API PathPrefix both require a
9200        // leading `/`. Same shape required of :entrada :paths
9201        // (eb3456d). Lifted into target() so every consumer of the
9202        // typed WitTarget view inherits the guarantee.
9203        let mut s = three_member_spec();
9204        s.contratos.push(WitContract {
9205            de: "cart".into(),
9206            para: "catalog".into(),
9207            wit: "wasi:http/proxy".into(),
9208            endpoint: Some("products/:id".into()),
9209            subject: None,
9210            slot: None,
9211        });
9212        let err = s.validate().unwrap_err();
9213        assert!(
9214            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
9215                if endpoint == "products/:id"),
9216            "got {err:?}"
9217        );
9218    }
9219
9220    #[test]
9221    fn rejects_pubsub_contrato_with_empty_subject() {
9222        // NATS / Kafka publish without a subject is a no-op subscribe;
9223        // never the author's intent. Same empty-string rejection as
9224        // :membros :caixa, :placement :clusters entries, :entrada
9225        // :paths entries — every value carried by every typed slot is
9226        // value-shape-checked at validate().
9227        let mut s = three_member_spec();
9228        s.contratos.push(WitContract {
9229            de: "cart".into(),
9230            para: "catalog".into(),
9231            wit: "nats:pub-sub".into(),
9232            endpoint: None,
9233            subject: Some(String::new()),
9234            slot: None,
9235        });
9236        let err = s.validate().unwrap_err();
9237        assert!(
9238            matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
9239                if de == "cart" && para == "catalog"),
9240            "got {err:?}"
9241        );
9242    }
9243
9244    #[test]
9245    fn rejects_store_contrato_with_empty_slot() {
9246        // An empty slot template addresses the bucket root, defeating
9247        // the per-key isolation the slot exists for — a footgun on
9248        // `wasi:keyvalue/store` whose closest analog is the empty
9249        // shard-key rejected on :placement Sharded (c7c7799).
9250        let mut s = three_member_spec();
9251        s.contratos.push(WitContract {
9252            de: "cart".into(),
9253            para: "catalog".into(),
9254            wit: "wasi:keyvalue/store".into(),
9255            endpoint: None,
9256            subject: None,
9257            slot: Some(String::new()),
9258        });
9259        let err = s.validate().unwrap_err();
9260        assert!(
9261            matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
9262                if de == "cart" && para == "catalog"),
9263            "got {err:?}"
9264        );
9265    }
9266
9267    #[test]
9268    fn http_contrato_root_endpoint_validates() {
9269        // Pin the boundary case: a single-`/` endpoint is the catch-all
9270        // form the Gateway HTTPRoute renderer falls back to when
9271        // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
9272        // must remain a valid contrato endpoint too.
9273        let mut s = three_member_spec();
9274        s.contratos.push(contract_http("cart", "catalog", "/"));
9275        s.validate().unwrap();
9276    }
9277
9278    // ── :contratos :endpoint value-shape gate ────────────────────────────
9279    //
9280    // Mirrors the `:entrada :paths` value-shape suite on the peer
9281    // HTTP-path axis. Until this gate landed `WitContract::target()`
9282    // only refused the empty string + the missing-leading-`/` form
9283    // (c4213a4); a structurally invalid endpoint passed validate and
9284    // landed verbatim as a Cilium L7 `path:` rule
9285    // (caixa-mesh/src/lib.rs:311) that either silently dropped all
9286    // traffic or was rejected at apply time by Cilium policy admission.
9287    // Every authoring footgun the K8s Gateway API webhook / Cilium
9288    // policy validator would catch on admission now becomes a caixa-
9289    // build-time `ContratoEndpointInvalid` with the offending
9290    // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
9291    // shape as `EntradaPathInvalid` on the sibling axis; same shared
9292    // predicate (`crate::render::is_gateway_api_http_path`) ensures
9293    // drift between the two axes' rule enforcement is a build error
9294    // at the predicate.
9295
9296    fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
9297        // Fresh spec per call so the would-be-duplicate edge
9298        // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
9299        // `three_member_spec`'s pre-existing
9300        // `(cart, catalog, …, /products/:id)` entry — only the
9301        // endpoint payload differs.
9302        let mut s = three_member_spec();
9303        s.contratos.push(contract_http("cart", "catalog", ep));
9304        s.validate().unwrap_err()
9305    }
9306
9307    #[test]
9308    fn rejects_http_contrato_endpoint_with_query() {
9309        // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
9310        // silently rendered as a Cilium L7 `path: "/charge?token=X"`
9311        // rule the L7 matcher would never satisfy.
9312        let err = contrato_endpoint_err("/charge?token=X");
9313        assert!(
9314            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9315                if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
9316            "got {err:?}"
9317        );
9318    }
9319
9320    #[test]
9321    fn rejects_http_contrato_endpoint_with_fragment() {
9322        let err = contrato_endpoint_err("/charge#frag");
9323        assert!(
9324            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9325                if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
9326            "got {err:?}"
9327        );
9328    }
9329
9330    #[test]
9331    fn rejects_http_contrato_endpoint_with_whitespace() {
9332        let err = contrato_endpoint_err("/foo bar");
9333        assert!(
9334            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9335                if endpoint == "/foo bar" && reason.contains("whitespace")),
9336            "got {err:?}"
9337        );
9338    }
9339
9340    #[test]
9341    fn rejects_http_contrato_endpoint_with_control_char() {
9342        let err = contrato_endpoint_err("/api/\x01bar");
9343        assert!(
9344            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9345                if endpoint == "/api/\x01bar" && reason.contains("control character")),
9346            "got {err:?}"
9347        );
9348    }
9349
9350    #[test]
9351    fn rejects_http_contrato_endpoint_with_non_ascii() {
9352        let err = contrato_endpoint_err("/api/café");
9353        assert!(
9354            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9355                if endpoint == "/api/café" && reason.contains("non-ASCII")),
9356            "got {err:?}"
9357        );
9358    }
9359
9360    #[test]
9361    fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
9362        let err = contrato_endpoint_err("/api//cart");
9363        assert!(
9364            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9365                if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
9366            "got {err:?}"
9367        );
9368    }
9369
9370    #[test]
9371    fn rejects_http_contrato_endpoint_with_dot_segment() {
9372        let err = contrato_endpoint_err("/api/./cart");
9373        assert!(
9374            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9375                if endpoint == "/api/./cart" && reason.contains("`.` segment")),
9376            "got {err:?}"
9377        );
9378    }
9379
9380    #[test]
9381    fn rejects_http_contrato_endpoint_with_parent_segment() {
9382        // Path-traversal in a contrato endpoint is the canonical
9383        // "L7 rule that the workload's HTTP server's path-resolution
9384        // logic interprets differently than the policy enforcer"
9385        // footgun. Rejected outright at validate time.
9386        let err = contrato_endpoint_err("/api/../etc");
9387        assert!(
9388            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9389                if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
9390            "got {err:?}"
9391        );
9392    }
9393
9394    #[test]
9395    fn rejects_http_contrato_endpoint_too_long() {
9396        // 1025-byte endpoint — one over the Gateway API
9397        // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
9398        // path matcher has no inherent length limit but the policy
9399        // CR itself rides through the K8s apiserver, which enforces
9400        // ConfigMap-shaped limits; sharing the Gateway API cap is the
9401        // conservative floor.
9402        let big = format!("/api/{}", "a".repeat(1020));
9403        assert_eq!(big.len(), 1025);
9404        let err = contrato_endpoint_err(&big);
9405        assert!(
9406            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9407                if endpoint == &big && reason.contains("max length of 1024")),
9408            "got {err:?}"
9409        );
9410    }
9411
9412    #[test]
9413    fn http_contrato_endpoint_max_length_validates() {
9414        // 1024-byte endpoint — exactly the cap. Boundary pin: drift
9415        // in the cap surfaces here and at
9416        // `rejects_http_contrato_endpoint_too_long` simultaneously,
9417        // mirroring `entrada_path_max_length_validates` on the peer
9418        // axis.
9419        let big = format!("/api/{}", "a".repeat(1019));
9420        assert_eq!(big.len(), 1024);
9421        let mut s = three_member_spec();
9422        s.contratos.push(contract_http("cart", "catalog", &big));
9423        s.validate().unwrap();
9424    }
9425
9426    #[test]
9427    fn http_contrato_endpoint_accepts_canonical_forms() {
9428        // Positive-set sweep: every canonical HTTP-path shape the
9429        // sibling `:entrada :paths` axis accepts (the bare-root `/`,
9430        // plain paths, hidden-file-style `.config` segments distinct
9431        // from the `.` segment, digit-bearing segments, the canonical
9432        // route-template `:param` form, trailing-slash form,
9433        // percent-encoded segments, the `/foo..bar` interior-`..`-
9434        // substring forms that are NOT `..` segments) must remain a
9435        // valid contrato endpoint too. Drift between this list and
9436        // the entrada path positive sweep surfaces at the shared
9437        // `is_gateway_api_http_path` substrate-side suite — one
9438        // source of truth. Uses a fresh `(payment, catalog)` edge so
9439        // none of the swept endpoints collide with the pre-existing
9440        // `(cart, catalog, /products/:id)` / `(cart, payment,
9441        // /charge)` entries in `three_member_spec`.
9442        for ep in [
9443            "/",
9444            "/charge",
9445            "/v1/charge",
9446            "/api/.config",
9447            "/products/:id",
9448            "/api/cart/",
9449            "/api/caf%C3%A9",
9450            "/foo..bar",
9451            "/...",
9452        ] {
9453            let mut s = three_member_spec();
9454            s.contratos.push(contract_http("payment", "catalog", ep));
9455            s.validate()
9456                .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
9457        }
9458    }
9459
9460    #[test]
9461    fn contrato_endpoint_empty_takes_precedence_over_invalid() {
9462        // Ordering pin: `ContratoEndpointEmpty` is the more self-
9463        // locating diagnostic on `""` and must lead — the value-
9464        // shape gate is only reached after the empty-check fires.
9465        // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
9466        // on the peer axis.
9467        let mut s = three_member_spec();
9468        s.contratos.push(WitContract {
9469            de: "cart".into(),
9470            para: "catalog".into(),
9471            wit: "wasi:http/proxy".into(),
9472            endpoint: Some(String::new()),
9473            subject: None,
9474            slot: None,
9475        });
9476        let err = s.validate().unwrap_err();
9477        assert!(
9478            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
9479            "got {err:?}"
9480        );
9481    }
9482
9483    #[test]
9484    fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
9485        // Ordering pin: an endpoint without a leading `/` surfaces the
9486        // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
9487        // value-shape gate is only consulted on endpoints that already
9488        // satisfy the absolute-prefix invariant. Mirrors
9489        // `entrada_path_not_absolute_takes_precedence_over_invalid`.
9490        let err = contrato_endpoint_err("bad path");
9491        assert!(
9492            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
9493                if endpoint == "bad path"),
9494            "got {err:?}"
9495        );
9496    }
9497
9498    #[test]
9499    fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
9500        // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
9501        // `:para` + a non-empty reason flow through verbatim so the
9502        // author can grep their caixa.lisp for the offending contrato
9503        // block and fix it in one edit. Same shape as
9504        // `entrada_path_diagnostic_carries_offending_path`.
9505        let err = contrato_endpoint_err("/api?q=1");
9506        match err {
9507            AplicacaoError::ContratoEndpointInvalid {
9508                de,
9509                para,
9510                endpoint,
9511                reason,
9512            } => {
9513                assert_eq!(de, "cart");
9514                assert_eq!(para, "catalog");
9515                assert_eq!(endpoint, "/api?q=1");
9516                assert!(!reason.is_empty(), "reason field must be non-empty");
9517            }
9518            other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
9519        }
9520    }
9521
9522    #[test]
9523    fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
9524        // The compounding theorem: every &str inside a WitTarget
9525        // returned by target() is non-empty (and absolute, for Http).
9526        // Renderers downstream of typed_view() can rely on this
9527        // without re-checking — the type system carries the proof.
9528        let http = contract_http("cart", "catalog", "/x");
9529        match http.target().unwrap() {
9530            WitTarget::Http { endpoint } => {
9531                assert!(!endpoint.is_empty());
9532                assert!(endpoint.starts_with('/'));
9533            }
9534            other => panic!("expected Http, got {other:?}"),
9535        }
9536        let nats = WitContract {
9537            de: "a".into(),
9538            para: "b".into(),
9539            wit: "nats:pub-sub".into(),
9540            endpoint: None,
9541            subject: Some("topic.x".into()),
9542            slot: None,
9543        };
9544        match nats.target().unwrap() {
9545            WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
9546            other => panic!("expected PubSub, got {other:?}"),
9547        }
9548        let kv = WitContract {
9549            de: "a".into(),
9550            para: "b".into(),
9551            wit: "wasi:keyvalue/store".into(),
9552            endpoint: None,
9553            subject: None,
9554            slot: Some("checkout/$orderId".into()),
9555        };
9556        match kv.target().unwrap() {
9557            WitTarget::Store { slot } => assert!(!slot.is_empty()),
9558            other => panic!("expected Store, got {other:?}"),
9559        }
9560    }
9561
9562    #[test]
9563    fn target_diagnostic_names_offending_endpoint_value() {
9564        // When the malformed endpoint string is non-trivial, the
9565        // diagnostic carries the actual value back to the author —
9566        // not a generic "endpoint malformed" error.
9567        let bad = WitContract {
9568            de: "src".into(),
9569            para: "dst".into(),
9570            wit: "wasi:http/proxy".into(),
9571            endpoint: Some("api/v1/charge".into()),
9572            subject: None,
9573            slot: None,
9574        };
9575        match bad.target().unwrap_err() {
9576            AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
9577                assert_eq!(de, "src");
9578                assert_eq!(para, "dst");
9579                assert_eq!(endpoint, "api/v1/charge");
9580            }
9581            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
9582        }
9583    }
9584
9585    #[test]
9586    fn rejects_unknown_wit_with_target_set() {
9587        let mut s = three_member_spec();
9588        s.contratos.push(WitContract {
9589            de: "cart".into(),
9590            para: "catalog".into(),
9591            wit: "custom:exchange".into(),
9592            endpoint: Some("/leaked".into()),
9593            subject: None,
9594            slot: None,
9595        });
9596        let err = s.validate().unwrap_err();
9597        assert!(matches!(
9598            err,
9599            AplicacaoError::ContratoWrongTarget {
9600                expected: WitTarget::CAPABILITY_EXPECTED,
9601                ..
9602            }
9603        ));
9604    }
9605
9606    #[test]
9607    fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
9608        // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
9609        // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
9610        // fourth arm of the same "which payload field name goes in the
9611        // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
9612        // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
9613        // consts cover on the peer HTTP / PubSub / Store arms
9614        // (`wit_target_field_name_pins_per_variant`). Until this lift
9615        // landed the byte-string sat twice — once inline in the
9616        // [`WitContract::target`] Capability-arm rejection at the
9617        // production dispatch, once in `rejects_unknown_wit_with_target_set`
9618        // pinning against the same literal — with no compile-time link
9619        // between them. Same "one canonical declaration, next to the
9620        // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
9621        // lift established for the payload-less arm's human-readable
9622        // label axis; this test is the shape peer of
9623        // `wit_target_label_pins_per_variant`'s Capability-arm assertion
9624        // pair (routes-through-const + scalar-value pin) on the
9625        // wrong-target diagnostic-scalar axis.
9626        //
9627        // Fail-before-pass-after was verified locally by mutating the
9628        // const declaration to `"capability"` — the scalar-value pin
9629        // below fires (`"capability" != "none"`) and the routes-through
9630        // assertion below still holds (production and const walk in
9631        // lockstep), which is the correct behavior: a rename on the
9632        // const drifts here first, not at a downstream consumer.
9633        assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
9634
9635        let mut s = three_member_spec();
9636        s.contratos.push(WitContract {
9637            de: "cart".into(),
9638            para: "catalog".into(),
9639            wit: "custom:exchange".into(),
9640            endpoint: Some("/leaked".into()),
9641            subject: None,
9642            slot: None,
9643        });
9644        match s.validate().unwrap_err() {
9645            AplicacaoError::ContratoWrongTarget { expected, .. } => {
9646                assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
9647            }
9648            other => panic!("expected ContratoWrongTarget, got {other:?}"),
9649        }
9650    }
9651
9652    #[test]
9653    fn unknown_wit_capability_only_validates() {
9654        let mut s = three_member_spec();
9655        s.contratos.push(WitContract {
9656            de: "cart".into(),
9657            para: "catalog".into(),
9658            // A WIT world we haven't yet shaped — accept it as a typed
9659            // capability edge so authors aren't blocked while the WIT
9660            // registry catches up. No payload field may be carried.
9661            wit: "custom:exchange".into(),
9662            endpoint: None,
9663            subject: None,
9664            slot: None,
9665        });
9666        s.validate().unwrap();
9667        let added = s.contratos.last().unwrap();
9668        assert_eq!(added.target().unwrap(), WitTarget::Capability);
9669    }
9670
9671    #[test]
9672    fn target_typed_view_round_trips_each_shape() {
9673        let http = contract_http("cart", "catalog", "/products/:id");
9674        assert_eq!(
9675            http.target().unwrap(),
9676            WitTarget::Http {
9677                endpoint: "/products/:id"
9678            }
9679        );
9680        let nats = WitContract {
9681            de: "a".into(),
9682            para: "b".into(),
9683            wit: "nats:pub-sub".into(),
9684            endpoint: None,
9685            subject: Some("topic.x".into()),
9686            slot: None,
9687        };
9688        assert_eq!(
9689            nats.target().unwrap(),
9690            WitTarget::PubSub { subject: "topic.x" }
9691        );
9692        let kv = WitContract {
9693            de: "a".into(),
9694            para: "b".into(),
9695            wit: "wasi:keyvalue/store".into(),
9696            endpoint: None,
9697            subject: None,
9698            slot: Some("checkout/$orderId".into()),
9699        };
9700        assert_eq!(
9701            kv.target().unwrap(),
9702            WitTarget::Store {
9703                slot: "checkout/$orderId"
9704            }
9705        );
9706    }
9707
9708    #[test]
9709    fn wit_contract_kind_predicates() {
9710        let http = contract_http("a", "b", "/x");
9711        assert!(http.is_http());
9712        assert!(!http.is_pubsub());
9713        assert!(!http.is_store());
9714
9715        let nats = WitContract {
9716            de: "a".into(),
9717            para: "b".into(),
9718            wit: "nats:pub-sub".into(),
9719            endpoint: None,
9720            subject: Some("topic.x".into()),
9721            slot: None,
9722        };
9723        assert!(nats.is_pubsub());
9724        assert!(!nats.is_http());
9725
9726        let kv = WitContract {
9727            de: "a".into(),
9728            para: "b".into(),
9729            wit: "wasi:keyvalue/store".into(),
9730            endpoint: None,
9731            subject: None,
9732            slot: Some("checkout/$orderId".into()),
9733        };
9734        assert!(kv.is_store());
9735        assert!(!kv.is_http());
9736    }
9737
9738    // ── :contratos :wit value-shape gate ─────────────────────────────────
9739    //
9740    // Mirrors the `:contratos :endpoint` value-shape suite on the peer
9741    // dispatch-discriminator axis. Until this gate landed
9742    // `WitContract::target()` accepted any non-empty string and
9743    // silently demoted unrecognized shapes to a capability-only L4
9744    // edge — the canonical "I thought I had L7 HTTP routing, got
9745    // L4-only" footgun. Every authoring footgun the WIT registry's
9746    // own grammar rejects (uppercase, hyphen-for-colon typo,
9747    // whitespace, empty package, doubled `@`, …) now becomes a
9748    // caixa-build-time `ContratoWitInvalid` with the offending
9749    // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
9750    // as `ContratoEndpointInvalid` on the sibling axis; same shared
9751    // predicate (`crate::render::is_wit_world_ref`) ensures drift
9752    // between any two axes' rule enforcement is a build error at the
9753    // predicate, not piecemeal across renderers.
9754
9755    fn contrato_wit_err(wit: &str) -> AplicacaoError {
9756        // Fresh spec per call so the new contract doesn't collide on
9757        // identity with `three_member_spec`'s pre-existing entries.
9758        // The new edge uses `(payment, catalog)` — a pair the fixture
9759        // doesn't already declare — with no payload field set, so the
9760        // wit-shape gate fires before any payload-shape arm.
9761        let mut s = three_member_spec();
9762        s.contratos.push(WitContract {
9763            de: "payment".into(),
9764            para: "catalog".into(),
9765            wit: wit.into(),
9766            endpoint: None,
9767            subject: None,
9768            slot: None,
9769        });
9770        s.validate().unwrap_err()
9771    }
9772
9773    #[test]
9774    fn rejects_wit_with_uppercase_namespace() {
9775        // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
9776        // didn't match the lowercase `wasi:http/` prefix is_http() keys
9777        // off, so the dispatch fell through to the capability arm and
9778        // the contract silently rendered as an L4-only Cilium edge.
9779        // The new gate surfaces the uppercase typo at validate time
9780        // with the offending `:wit` named.
9781        let err = contrato_wit_err("WASI:http/proxy");
9782        assert!(
9783            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9784                if wit == "WASI:http/proxy" && reason.contains("lowercase")),
9785            "got {err:?}"
9786        );
9787    }
9788
9789    #[test]
9790    fn rejects_wit_with_hyphen_for_colon_typo() {
9791        // The canonical "I forgot the `:` separator" typo — pre-gate
9792        // this passed as Capability silently, so the renderer emitted
9793        // an L4-only policy where the author expected L7 HTTP rules.
9794        let err = contrato_wit_err("wasi-http/proxy");
9795        assert!(
9796            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9797                if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
9798            "got {err:?}"
9799        );
9800    }
9801
9802    #[test]
9803    fn rejects_wit_with_multiple_colons() {
9804        // Doubled `:` — the namespace/package split has nowhere to
9805        // anchor, so the dispatch silently demotes to Capability.
9806        let err = contrato_wit_err("wasi:http:proxy");
9807        assert!(
9808            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9809                if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
9810            "got {err:?}"
9811        );
9812    }
9813
9814    #[test]
9815    fn rejects_wit_with_empty_package() {
9816        // `wasi:` — namespace alone with no package. Pre-gate this
9817        // failed neither the is_http nor is_pubsub nor is_store
9818        // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
9819        // a bare `wasi:`), so it silently demoted to Capability.
9820        let err = contrato_wit_err("wasi:");
9821        assert!(
9822            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9823                if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
9824            "got {err:?}"
9825        );
9826    }
9827
9828    #[test]
9829    fn rejects_wit_with_underscore() {
9830        // Underscore — WIT identifiers are kebab-case, same rule
9831        // DNS-1123 enforces on its peer axes. The diagnostic carries
9832        // the explicit "use `-` instead" remediation.
9833        let err = contrato_wit_err("wasi:http_proxy");
9834        assert!(
9835            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9836                if wit == "wasi:http_proxy" && reason.contains('_')),
9837            "got {err:?}"
9838        );
9839    }
9840
9841    #[test]
9842    fn rejects_wit_with_whitespace() {
9843        // Whitespace mid-token — the prefix check matches but the
9844        // package-and-onward parse silently demoted to Capability.
9845        let err = contrato_wit_err("wasi:http proxy");
9846        assert!(
9847            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9848                if wit == "wasi:http proxy" && reason.contains("whitespace")),
9849            "got {err:?}"
9850        );
9851    }
9852
9853    #[test]
9854    fn rejects_wit_with_non_ascii() {
9855        // Un-percent-encoded non-ASCII byte — the canonical "I copied
9856        // the package name from a doc with smart quotes / accented
9857        // characters" footgun.
9858        let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
9859        assert!(
9860            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9861                if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
9862            "got {err:?}"
9863        );
9864    }
9865
9866    #[test]
9867    fn rejects_wit_with_consecutive_hyphens() {
9868        // `pub--sub` — WIT identifiers join words with single hyphens.
9869        let err = contrato_wit_err("nats:pub--sub");
9870        assert!(
9871            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9872                if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
9873            "got {err:?}"
9874        );
9875    }
9876
9877    #[test]
9878    fn rejects_wit_with_trailing_at_no_version() {
9879        // `wasi:http/proxy@` — the version-suffix author started to
9880        // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
9881        // parser would reject this; surface it at validate time.
9882        let err = contrato_wit_err("wasi:http/proxy@");
9883        assert!(
9884            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9885                if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
9886            "got {err:?}"
9887        );
9888    }
9889
9890    #[test]
9891    fn rejects_wit_too_long() {
9892        // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
9893        // The legitimate-shape arms all pass (lowercase, single `:`,
9894        // kebab-case identifiers); only the cap arm fires. Surfaces
9895        // the paste-from-binary / accidental-multi-line-blob landing
9896        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
9897        // on the peer axis.
9898        let big = format!("wasi:{}", "a".repeat(124));
9899        assert_eq!(big.len(), 129);
9900        let err = contrato_wit_err(&big);
9901        assert!(
9902            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9903                if wit == &big && reason.contains("max length of 128")),
9904            "got {err:?}"
9905        );
9906    }
9907
9908    #[test]
9909    fn wit_max_length_validates() {
9910        // 128-byte WIT reference — exactly the cap. Boundary pin:
9911        // drift in the cap surfaces here and at `rejects_wit_too_long`
9912        // simultaneously, mirroring
9913        // `http_contrato_endpoint_max_length_validates` on the peer
9914        // axis.
9915        let big = format!("wasi:{}", "a".repeat(123));
9916        assert_eq!(big.len(), 128);
9917        let mut s = three_member_spec();
9918        s.contratos.push(WitContract {
9919            de: "payment".into(),
9920            para: "catalog".into(),
9921            wit: big,
9922            endpoint: None,
9923            subject: None,
9924            slot: None,
9925        });
9926        s.validate().unwrap();
9927    }
9928
9929    #[test]
9930    fn wit_accepts_canonical_forms_at_aplicacao_layer() {
9931        // Positive-set sweep through the AplicacaoSpec::validate
9932        // surface (rather than the substrate-side predicate directly)
9933        // — pins every shape the existing test fixtures + the
9934        // checkout-aplicacao example carry, so the gate's accept-set
9935        // matches the substrate's emit-set. Drift between this list
9936        // and `render::tests::wit_world_ref_accepts_canonical_forms`
9937        // surfaces at the substrate layer's positive sweep — one
9938        // source of truth for the rule.
9939        for wit in [
9940            "wasi:http/proxy",
9941            "wasi:keyvalue/store",
9942            "nats:pub-sub",
9943            "kafka:topic",
9944            "custom:exchange",
9945            "pleme:cap/audit",
9946            "wasi:http/proxy@0.2.0",
9947        ] {
9948            // Payload field paired to the dispatched WIT shape so the
9949            // shape-↔-target arm doesn't fire instead of the wit-shape
9950            // arm we're exercising. Routes off the same
9951            // `wit_shape_is_http` / `wit_shape_is_pubsub` /
9952            // `wit_shape_is_store` free functions the production
9953            // `WitContract::is_http` / `is_pubsub` / `is_store`
9954            // methods delegate to (both consult the lifted
9955            // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
9956            // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
9957            // future prefix addition to the routing accept-set
9958            // reaches this test's payload-dispatch arm by
9959            // construction — no per-test-site drift can hide a
9960            // shape-→-target-slot mismatch that would silently
9961            // demote a canonical `:wit` value to the
9962            // `(None, None, None)` capability-only arm and let the
9963            // `AplicacaoSpec::validate` positive sweep pass on a
9964            // shape it should exercise as HTTP / pub-sub / store.
9965            let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
9966                (Some("/x".into()), None, None)
9967            } else if wit_shape_is_pubsub(wit) {
9968                (None, Some("topic.x".into()), None)
9969            } else if wit_shape_is_store(wit) {
9970                (None, None, Some("bucket/$key".into()))
9971            } else {
9972                (None, None, None)
9973            };
9974            let mut s = three_member_spec();
9975            s.contratos.push(WitContract {
9976                de: "payment".into(),
9977                para: "catalog".into(),
9978                wit: wit.into(),
9979                endpoint,
9980                subject,
9981                slot,
9982            });
9983            s.validate()
9984                .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
9985        }
9986    }
9987
9988    #[test]
9989    fn wit_shape_predicates_accept_canonical_prefix_set() {
9990        // Positive-set sweep pinning every prefix in
9991        // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
9992        // WIT_STORE_SHAPE_PREFIXES against the three free-function
9993        // dispatch predicates. The six prefixes are the load-bearing
9994        // routing keys the substrate's WIT-shape dispatch consults
9995        // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
9996        // key/value-store-slot admission); any drift between the
9997        // free-function accept-set and this list surfaces here
9998        // rather than at apply time as a silent
9999        // shape-→-capability-only demotion.
10000        assert!(wit_shape_is_http("wasi:http/proxy"));
10001        assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
10002        assert!(wit_shape_is_http("http:incoming"));
10003
10004        assert!(wit_shape_is_pubsub("nats:pub-sub"));
10005        assert!(wit_shape_is_pubsub("kafka:topic"));
10006
10007        assert!(wit_shape_is_store("wasi:keyvalue/store"));
10008        assert!(wit_shape_is_store("kv:cache/session"));
10009    }
10010
10011    #[test]
10012    fn wit_shape_predicates_reject_uncanonical_forms() {
10013        // Negative-set pin: the six canonical prefixes are
10014        // lowercase-only (mirrors the `is_wit_world_ref` substrate
10015        // predicate's lowercase invariant — see its docstring on the
10016        // "I thought I had L7 HTTP routing, got L4-only" footgun).
10017        // The empty string, an uppercase-prefixed form, a hyphen-
10018        // instead-of-colon typo, and a bare kebab identifier all miss
10019        // every shape arm — reachable-by-construction only via the
10020        // `is_wit_world_ref` gate that admission-checks the `:wit`
10021        // value first, but pinned here so any future
10022        // free-function change (e.g. a case-insensitive
10023        // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
10024        // this unit level.
10025        for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
10026            assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
10027            assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
10028            assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
10029        }
10030    }
10031
10032    #[test]
10033    fn wit_shape_predicates_partition_canonical_set() {
10034        // Every canonical prefix routes to exactly one shape arm —
10035        // the three prefix sets are pairwise disjoint. Pins the
10036        // routing property [`WitContract::target`] relies on: an
10037        // `is_http()` return of `true` guarantees `is_pubsub()` and
10038        // `is_store()` return `false`, so the shape-→-target-slot
10039        // dispatch (endpoint vs subject vs slot) is unambiguous.
10040        // Drift (e.g. a future `"kv:"` moved into the HTTP set
10041        // without removal from the store set) would silently route
10042        // one prefix to two arms and the first-matching-arm order
10043        // becomes load-bearing — this pin surfaces it as a build
10044        // error instead.
10045        for prefix in WIT_HTTP_SHAPE_PREFIXES {
10046            let sample = format!("{prefix}x");
10047            assert!(wit_shape_is_http(&sample));
10048            assert!(!wit_shape_is_pubsub(&sample));
10049            assert!(!wit_shape_is_store(&sample));
10050        }
10051        for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
10052            let sample = format!("{prefix}x");
10053            assert!(!wit_shape_is_http(&sample));
10054            assert!(wit_shape_is_pubsub(&sample));
10055            assert!(!wit_shape_is_store(&sample));
10056        }
10057        for prefix in WIT_STORE_SHAPE_PREFIXES {
10058            let sample = format!("{prefix}x");
10059            assert!(!wit_shape_is_http(&sample));
10060            assert!(!wit_shape_is_pubsub(&sample));
10061            assert!(wit_shape_is_store(&sample));
10062        }
10063    }
10064
10065    #[test]
10066    fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
10067        // Positive pin: [`wit_shape_matches`] is exactly the
10068        // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
10069        // parameterized on the accept-set. Two-prefix accept-set,
10070        // one-prefix accept-set, and empty accept-set (which must
10071        // reject everything, including the empty string — an empty
10072        // `any()` fold returns `false`) all pinned so a future
10073        // reimplementation that swaps `starts_with` for `contains`,
10074        // `==`, or a case-folded comparator surfaces at unit-test
10075        // time.
10076        let two = &["wasi:http/", "http:"];
10077        assert!(wit_shape_matches("wasi:http/proxy", two));
10078        assert!(wit_shape_matches("http:incoming", two));
10079        assert!(!wit_shape_matches("wasi:keyvalue/store", two));
10080
10081        let one = &["nats:"];
10082        assert!(wit_shape_matches("nats:pub-sub", one));
10083        assert!(!wit_shape_matches("kafka:topic", one));
10084
10085        // Empty accept-set matches nothing — the identity element
10086        // for the disjunctive `any()` fold across the prefix set.
10087        // Reachable via a future `wit_shape_is_<name>` const paired
10088        // to a still-empty prefix table on a nascent shape-arm draft.
10089        let empty: &[&str] = &[];
10090        assert!(!wit_shape_matches("wasi:http/proxy", empty));
10091        assert!(!wit_shape_matches("", empty));
10092
10093        // starts_with, not contains: a prefix embedded mid-string
10094        // never matches. Pins the routing invariant [`WitContract::target`]
10095        // relies on (an authored `:wit "custom:wasi:http/"` string
10096        // does not silently route through the HTTP arm just because
10097        // it happens to contain the canonical HTTP prefix).
10098        assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
10099    }
10100
10101    #[test]
10102    fn wit_shape_predicates_delegate_to_wit_shape_matches() {
10103        // Equivalence pin: each per-shape predicate is exactly
10104        // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
10105        // every canonical prefix + the empty string + one negative
10106        // sample against every peer so a future predicate that grew
10107        // its own inline `iter().any(starts_with)` (rather than
10108        // delegating through the lifted combinator) drifts loudly here
10109        // — the peer-const table's contents must agree with the
10110        // predicate's accept-set by construction.
10111        let samples = [
10112            String::new(),
10113            "wasi:http/proxy".to_string(),
10114            "http:incoming".to_string(),
10115            "nats:pub-sub".to_string(),
10116            "kafka:topic".to_string(),
10117            "wasi:keyvalue/store".to_string(),
10118            "kv:cache/session".to_string(),
10119            "custom-shape".to_string(),
10120            "WASI:HTTP/proxy".to_string(),
10121        ];
10122        for wit in &samples {
10123            assert_eq!(
10124                wit_shape_is_http(wit),
10125                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
10126                "wit_shape_is_http drifted from combinator on {wit:?}",
10127            );
10128            assert_eq!(
10129                wit_shape_is_pubsub(wit),
10130                wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
10131                "wit_shape_is_pubsub drifted from combinator on {wit:?}",
10132            );
10133            assert_eq!(
10134                wit_shape_is_store(wit),
10135                wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
10136                "wit_shape_is_store drifted from combinator on {wit:?}",
10137            );
10138        }
10139    }
10140
10141    #[test]
10142    fn wit_contract_shape_methods_delegate_to_free_functions() {
10143        // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
10144        // `is_store` are `&self` conveniences on top of the free
10145        // functions — for every canonical prefix the method's return
10146        // matches its free-function peer. Sweeps the union of the
10147        // three prefix sets so a future method that grew its own
10148        // inline prefix logic (rather than delegating) drifts loudly
10149        // here on the first prefix the free function accepts and the
10150        // method doesn't.
10151        for shape_set in [
10152            WIT_HTTP_SHAPE_PREFIXES,
10153            WIT_PUBSUB_SHAPE_PREFIXES,
10154            WIT_STORE_SHAPE_PREFIXES,
10155        ] {
10156            for prefix in shape_set {
10157                let c = WitContract {
10158                    de: "cart".into(),
10159                    para: "catalog".into(),
10160                    wit: format!("{prefix}x"),
10161                    endpoint: None,
10162                    subject: None,
10163                    slot: None,
10164                };
10165                assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
10166                assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
10167                assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
10168            }
10169        }
10170    }
10171
10172    #[test]
10173    fn empty_wit_takes_precedence_over_invalid() {
10174        // Ordering pin: `EmptyWit` is the more self-locating
10175        // diagnostic on `""` and must lead — the value-shape gate is
10176        // only reached after the empty-check fires. Mirrors
10177        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
10178        // the peer payload axis.
10179        let mut s = three_member_spec();
10180        s.contratos.push(WitContract {
10181            de: "payment".into(),
10182            para: "catalog".into(),
10183            wit: String::new(),
10184            endpoint: None,
10185            subject: None,
10186            slot: None,
10187        });
10188        let err = s.validate().unwrap_err();
10189        assert!(
10190            matches!(err, AplicacaoError::EmptyWit { .. }),
10191            "got {err:?}"
10192        );
10193    }
10194
10195    #[test]
10196    fn wit_invalid_fires_before_payload_shape_arm() {
10197        // Ordering pin: a malformed `:wit` surfaces *its own*
10198        // diagnostic (which names the offending wit verbatim) before
10199        // any payload-field check — a contrato whose wit is
10200        // structurally invalid AND carries a wrong target field
10201        // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
10202        // because the dispatch on the wit is what decides which
10203        // payload field is "right" in the first place. Without this
10204        // ordering, the author would see "wrong target field" for a
10205        // wit that hasn't even been parsed, which doesn't name the
10206        // root cause.
10207        let mut s = three_member_spec();
10208        s.contratos.push(WitContract {
10209            de: "payment".into(),
10210            para: "catalog".into(),
10211            // Hyphen-for-colon typo + endpoint set: pre-gate this
10212            // raised `ContratoWrongTarget { expected: "none" }` (the
10213            // Capability arm rejecting the endpoint), masking the
10214            // real authoring mistake (the wit isn't `wasi:http/proxy`).
10215            wit: "wasi-http/proxy".into(),
10216            endpoint: Some("/x".into()),
10217            subject: None,
10218            slot: None,
10219        });
10220        let err = s.validate().unwrap_err();
10221        assert!(
10222            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
10223                if wit == "wasi-http/proxy"),
10224            "got {err:?}"
10225        );
10226    }
10227
10228    #[test]
10229    fn wit_invalid_diagnostic_carries_offending_wit() {
10230        // Diagnostic-shape pin — the offending `:wit` + `:de` +
10231        // `:para` + a non-empty reason flow through verbatim so the
10232        // author can grep their caixa.lisp for the offending contrato
10233        // block and fix it in one edit. Same shape as
10234        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
10235        let err = contrato_wit_err("WASI:HTTP/proxy");
10236        match err {
10237            AplicacaoError::ContratoWitInvalid {
10238                de,
10239                para,
10240                wit,
10241                reason,
10242            } => {
10243                assert_eq!(de, "payment");
10244                assert_eq!(para, "catalog");
10245                assert_eq!(wit, "WASI:HTTP/proxy");
10246                assert!(!reason.is_empty(), "reason field must be non-empty");
10247            }
10248            other => panic!("expected ContratoWitInvalid, got {other:?}"),
10249        }
10250    }
10251
10252    // ── :contratos :subject value-shape gate ─────────────────────────────
10253    //
10254    // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
10255    // suites on the peer payload axes. Until this gate landed
10256    // `WitContract::target()` only refused the empty string; a
10257    // structurally invalid subject silently passed validate and the
10258    // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
10259    // Subject'` on publish / subscribe, or as a silent message drop,
10260    // far from the source caixa.lisp. Every authoring footgun the
10261    // NATS server's subject parser would catch on admission now
10262    // becomes a caixa-build-time `ContratoSubjectInvalid` with the
10263    // offending `:subject` + `:de` + `:para` named verbatim. Same
10264    // diagnostic shape as `ContratoEndpointInvalid` /
10265    // `ContratoWitInvalid` on the peer payload axes; same shared
10266    // predicate (`crate::render::is_nats_subject`) ensures drift
10267    // between any two axes' rule enforcement is a build error at the
10268    // predicate, not piecemeal across renderers.
10269
10270    fn contrato_subject_err(subject: &str) -> AplicacaoError {
10271        // Fresh spec per call so the new contract doesn't collide on
10272        // identity with `three_member_spec`'s pre-existing entries.
10273        // The new edge uses `(payment, catalog)` — a pair the fixture
10274        // doesn't already declare — with `:wit "nats:pub-sub"` and the
10275        // varying `:subject`, so the subject-shape gate fires cleanly
10276        // after the wit-shape gate (which `"nats:pub-sub"` passes).
10277        let mut s = three_member_spec();
10278        s.contratos.push(WitContract {
10279            de: "payment".into(),
10280            para: "catalog".into(),
10281            wit: "nats:pub-sub".into(),
10282            endpoint: None,
10283            subject: Some(subject.into()),
10284            slot: None,
10285        });
10286        s.validate().unwrap_err()
10287    }
10288
10289    #[test]
10290    fn rejects_pubsub_contrato_subject_with_whitespace() {
10291        // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
10292        // landed at the NATS server as a malformed subject the parser
10293        // rejects with `-ERR 'Invalid Subject'`. Now caught at the
10294        // source caixa.lisp.
10295        let err = contrato_subject_err("foo bar");
10296        assert!(
10297            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10298                if subject == "foo bar" && reason.contains("whitespace")),
10299            "got {err:?}"
10300        );
10301    }
10302
10303    #[test]
10304    fn rejects_pubsub_contrato_subject_with_control_char() {
10305        let err = contrato_subject_err("foo\x01bar");
10306        assert!(
10307            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10308                if subject == "foo\x01bar" && reason.contains("control character")),
10309            "got {err:?}"
10310        );
10311    }
10312
10313    #[test]
10314    fn rejects_pubsub_contrato_subject_with_non_ascii() {
10315        // Un-percent-encoded non-ASCII byte — the canonical "I copied
10316        // the subject from a doc with smart quotes / accented
10317        // characters" footgun.
10318        let err = contrato_subject_err("foo.caf\u{e9}");
10319        assert!(
10320            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10321                if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
10322            "got {err:?}"
10323        );
10324    }
10325
10326    #[test]
10327    fn rejects_pubsub_contrato_subject_with_leading_dot() {
10328        // Empty leading token — NATS rejects.
10329        let err = contrato_subject_err(".foo");
10330        assert!(
10331            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10332                if subject == ".foo" && reason.contains("must not start with `.`")),
10333            "got {err:?}"
10334        );
10335    }
10336
10337    #[test]
10338    fn rejects_pubsub_contrato_subject_with_trailing_dot() {
10339        // Empty trailing token — NATS rejects. The remediation
10340        // (use `>` instead) is in the reason string.
10341        let err = contrato_subject_err("foo.");
10342        assert!(
10343            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10344                if subject == "foo." && reason.contains("must not end with `.`")),
10345            "got {err:?}"
10346        );
10347    }
10348
10349    #[test]
10350    fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
10351        // The canonical "I forgot to fill in the middle segment"
10352        // typo — `"foo..bar"`. NATS rejects empty tokens.
10353        let err = contrato_subject_err("foo..bar");
10354        assert!(
10355            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10356                if subject == "foo..bar" && reason.contains("consecutive `.`")),
10357            "got {err:?}"
10358        );
10359    }
10360
10361    #[test]
10362    fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
10363        // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
10364        // as the final segment. Pre-gate this passed as a typed edge
10365        // and surfaced at runtime as a NATS subscribe rejection.
10366        let err = contrato_subject_err("foo.>.bar");
10367        assert!(
10368            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10369                if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
10370            "got {err:?}"
10371        );
10372    }
10373
10374    #[test]
10375    fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
10376        // `foo*.bar` — NATS wildcards are standalone tokens. The
10377        // remediation is in the reason string.
10378        let err = contrato_subject_err("foo*.bar");
10379        assert!(
10380            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10381                if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
10382            "got {err:?}"
10383        );
10384    }
10385
10386    #[test]
10387    fn rejects_pubsub_contrato_subject_with_invalid_char() {
10388        // `foo,bar` — comma is not a valid NATS subject character.
10389        // Pinned separately from the wildcard arms so the invalid-
10390        // character diagnostic is in force.
10391        let err = contrato_subject_err("foo,bar");
10392        assert!(
10393            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10394                if subject == "foo,bar" && reason.contains("invalid character")),
10395            "got {err:?}"
10396        );
10397    }
10398
10399    #[test]
10400    fn rejects_pubsub_contrato_subject_too_long() {
10401        // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
10402        // The legitimate-shape arms all pass (one all-`a` token, no
10403        // `.`, no wildcards); only the cap arm fires. Surfaces the
10404        // paste-from-binary / accidental-multi-line-blob landing
10405        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
10406        // on the peer axis.
10407        let big = "a".repeat(257);
10408        assert_eq!(big.len(), 257);
10409        let err = contrato_subject_err(&big);
10410        assert!(
10411            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10412                if subject == &big && reason.contains("max length of 256")),
10413            "got {err:?}"
10414        );
10415    }
10416
10417    #[test]
10418    fn pubsub_contrato_subject_max_length_validates() {
10419        // 256-byte subject — exactly the cap. Boundary pin: drift in
10420        // the cap surfaces here and at
10421        // `rejects_pubsub_contrato_subject_too_long` simultaneously,
10422        // mirroring `http_contrato_endpoint_max_length_validates` and
10423        // `wit_max_length_validates` on the peer axes.
10424        let big = "a".repeat(256);
10425        assert_eq!(big.len(), 256);
10426        let mut s = three_member_spec();
10427        s.contratos.push(WitContract {
10428            de: "payment".into(),
10429            para: "catalog".into(),
10430            wit: "nats:pub-sub".into(),
10431            endpoint: None,
10432            subject: Some(big),
10433            slot: None,
10434        });
10435        s.validate().unwrap();
10436    }
10437
10438    #[test]
10439    fn pubsub_contrato_subject_accepts_canonical_forms() {
10440        // Positive-set sweep: every canonical NATS subject shape the
10441        // substrate-side `is_nats_subject` predicate accepts (the
10442        // multi-dot `events.order.charged`, the snake_case / kebab-
10443        // case / mixed-case tokens, the digit-bearing tokens, the
10444        // single-token wildcard `*` at every segment position, and
10445        // the trailing `>` multi-token wildcard) must remain a valid
10446        // contrato subject too. Drift between this list and the
10447        // substrate-side `nats_subject_accepts_canonical_forms` sweep
10448        // surfaces at the shared predicate — one source of truth.
10449        // Uses a fresh `(payment, catalog)` edge so none of the swept
10450        // subjects collide with the pre-existing entries in
10451        // `three_member_spec`.
10452        for subject in [
10453            "checkout.events.charge.failed",
10454            "rio.events.order.charged",
10455            "orders",
10456            "orders.123",
10457            "snake_case.token",
10458            "kebab-case.token",
10459            "MixedCase.Token",
10460            "orders.*.charged",
10461            "*.events.*",
10462            "orders.>",
10463        ] {
10464            let mut s = three_member_spec();
10465            s.contratos.push(WitContract {
10466                de: "payment".into(),
10467                para: "catalog".into(),
10468                wit: "nats:pub-sub".into(),
10469                endpoint: None,
10470                subject: Some(subject.into()),
10471                slot: None,
10472            });
10473            s.validate()
10474                .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
10475        }
10476    }
10477
10478    #[test]
10479    fn contrato_subject_empty_takes_precedence_over_invalid() {
10480        // Ordering pin: `ContratoSubjectEmpty` is the more self-
10481        // locating diagnostic on `""` and must lead — the value-shape
10482        // gate is only reached after the empty-check fires. Mirrors
10483        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
10484        // the peer payload axis.
10485        let mut s = three_member_spec();
10486        s.contratos.push(WitContract {
10487            de: "payment".into(),
10488            para: "catalog".into(),
10489            wit: "nats:pub-sub".into(),
10490            endpoint: None,
10491            subject: Some(String::new()),
10492            slot: None,
10493        });
10494        let err = s.validate().unwrap_err();
10495        assert!(
10496            matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
10497            "got {err:?}"
10498        );
10499    }
10500
10501    #[test]
10502    fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
10503        // Diagnostic-shape pin — the offending `:subject` + `:de` +
10504        // `:para` + a non-empty reason flow through verbatim so the
10505        // author can grep their caixa.lisp for the offending contrato
10506        // block and fix it in one edit. Same shape as
10507        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
10508        // and `wit_invalid_diagnostic_carries_offending_wit`.
10509        let err = contrato_subject_err("foo..bar");
10510        match err {
10511            AplicacaoError::ContratoSubjectInvalid {
10512                de,
10513                para,
10514                subject,
10515                reason,
10516            } => {
10517                assert_eq!(de, "payment");
10518                assert_eq!(para, "catalog");
10519                assert_eq!(subject, "foo..bar");
10520                assert!(!reason.is_empty(), "reason field must be non-empty");
10521            }
10522            other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
10523        }
10524    }
10525
10526    #[test]
10527    fn target_view_pubsub_subject_passes_through_to_typed_view() {
10528        // The compounding theorem on the pub-sub axis: every
10529        // `WitTarget::PubSub { subject }` returned by `target()` carries
10530        // a NATS-server-accepted subject. Renderers downstream of
10531        // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
10532        // NATS Stream/Consumer CR emitter, the future `feira app graph`
10533        // view's subject labeller) can rely on this without re-checking
10534        // — the type system carries the proof. Mirrors
10535        // `target_view_payload_is_guaranteed_nonempty_after_target_call`
10536        // on the peer axes.
10537        let nats = WitContract {
10538            de: "a".into(),
10539            para: "b".into(),
10540            wit: "nats:pub-sub".into(),
10541            endpoint: None,
10542            subject: Some("orders.events.*.charged".into()),
10543            slot: None,
10544        };
10545        match nats.target().unwrap() {
10546            WitTarget::PubSub { subject } => {
10547                assert_eq!(subject, "orders.events.*.charged");
10548            }
10549            other => panic!("expected PubSub, got {other:?}"),
10550        }
10551    }
10552
10553    // ── :contratos :slot value-shape gate ────────────────────────────────
10554    //
10555    // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
10556    // (63e18a0) value-shape suites on the peer payload axes. Until this
10557    // gate landed `WitContract::target()` only refused the empty string
10558    // for the Store arm; a structurally invalid slot (raw whitespace,
10559    // control character, non-ASCII byte, paste-from-binary multi-line
10560    // blob) silently passed validate and surfaced at runtime as a
10561    // per-backend kv write rejection or a silent next-read corruption,
10562    // far from the source caixa.lisp with no field naming which
10563    // `:contratos` edge carried the typo. Every authoring footgun the
10564    // kv backend intersection-floor would catch on write now becomes a
10565    // caixa-build-time `ContratoSlotInvalid` with the offending
10566    // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
10567    // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
10568    // peer payload axes; same shared predicate
10569    // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
10570    // any two axes' rule enforcement is a build error at the
10571    // predicate, not piecemeal across renderers. Closes the typed
10572    // payload-axis value-shape trajectory across all three legs of the
10573    // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
10574
10575    fn contrato_slot_err(slot: &str) -> AplicacaoError {
10576        // Fresh spec per call so the new contract doesn't collide on
10577        // identity with `three_member_spec`'s pre-existing entries
10578        // and doesn't close a synchronous cycle the cycle detector
10579        // would reject before the slot-shape gate fires. The new edge
10580        // uses `(payment, catalog)` — a pair the fixture doesn't
10581        // already declare in either direction (the fixture carries
10582        // `cart -> catalog` and `cart -> payment`, so `payment ->
10583        // catalog` doesn't form a cycle on the sync subgraph) — with
10584        // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
10585        // slot-shape gate fires cleanly after the wit-shape gate
10586        // (which `"wasi:keyvalue/store"` passes). Same edge pair the
10587        // peer `contrato_subject_err` helper uses (63e18a0).
10588        let mut s = three_member_spec();
10589        s.contratos.push(WitContract {
10590            de: "payment".into(),
10591            para: "catalog".into(),
10592            wit: "wasi:keyvalue/store".into(),
10593            endpoint: None,
10594            subject: None,
10595            slot: Some(slot.into()),
10596        });
10597        s.validate().unwrap_err()
10598    }
10599
10600    #[test]
10601    fn rejects_store_contrato_slot_with_whitespace() {
10602        // Fail-before-pass-after pin — pre-gate `"check out/$order"`
10603        // silently landed at the kv backend with whitespace whose
10604        // runtime behavior varies unpredictably across backends (etcd
10605        // accepts, Redis accepts then breaks on next CLI op, DynamoDB
10606        // rejects on write). Now caught at the source caixa.lisp.
10607        let err = contrato_slot_err("check out/$order");
10608        assert!(
10609            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10610                if slot == "check out/$order" && reason.contains("whitespace")),
10611            "got {err:?}"
10612        );
10613    }
10614
10615    #[test]
10616    fn rejects_store_contrato_slot_with_tab() {
10617        // Tab byte arm-pinned separately from the space arm so a
10618        // future relaxation that admits one but not the other surfaces
10619        // here.
10620        let err = contrato_slot_err("check\tout");
10621        assert!(
10622            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10623                if slot == "check\tout" && reason.contains("whitespace")),
10624            "got {err:?}"
10625        );
10626    }
10627
10628    #[test]
10629    fn rejects_store_contrato_slot_with_control_char() {
10630        // SOH (0x01) — distinct from the whitespace arm. Redis admits
10631        // and corrupts on RESP protocol framing; DynamoDB rejects on
10632        // write.
10633        let err = contrato_slot_err("checkout/\x01order");
10634        assert!(
10635            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10636                if slot == "checkout/\x01order" && reason.contains("control character")),
10637            "got {err:?}"
10638        );
10639    }
10640
10641    #[test]
10642    fn rejects_store_contrato_slot_with_newline() {
10643        // Embedded newline — the canonical "the paste-from-binary slug
10644        // spans multiple lines" footgun. Distinct from the whitespace
10645        // arm because `\n` is a control character (0x0A).
10646        let err = contrato_slot_err("checkout\norder");
10647        assert!(
10648            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10649                if slot == "checkout\norder" && reason.contains("control character")),
10650            "got {err:?}"
10651        );
10652    }
10653
10654    #[test]
10655    fn rejects_store_contrato_slot_with_non_ascii() {
10656        // Un-percent-encoded non-ASCII byte — the canonical "I copied
10657        // the slot from a doc with accented characters" footgun. Each
10658        // kv backend re-encodes non-ASCII differently (etcd preserves
10659        // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
10660        // rejects), so the typed slot's value set is the intersection-
10661        // floor every backend admits identically (printable ASCII).
10662        let err = contrato_slot_err("ch\u{e9}ckout/$order");
10663        assert!(
10664            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10665                if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
10666            "got {err:?}"
10667        );
10668    }
10669
10670    #[test]
10671    fn rejects_store_contrato_slot_too_long() {
10672        // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
10673        // legitimate-shape arms all pass (a single all-`a` token, no
10674        // separators); only the cap arm fires. Surfaces the paste-
10675        // from-binary / accidental-multi-line-blob landing footgun.
10676        // Mirrors `rejects_pubsub_contrato_subject_too_long` and
10677        // `rejects_http_contrato_endpoint_too_long` on the peer
10678        // payload axes.
10679        let big = "a".repeat(513);
10680        assert_eq!(big.len(), 513);
10681        let err = contrato_slot_err(&big);
10682        assert!(
10683            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10684                if slot == &big && reason.contains("max length of 512")),
10685            "got {err:?}"
10686        );
10687    }
10688
10689    #[test]
10690    fn store_contrato_slot_max_length_validates() {
10691        // 512-byte slot — exactly the cap. Boundary pin: drift in the
10692        // cap surfaces here and at `rejects_store_contrato_slot_too_long`
10693        // simultaneously, mirroring
10694        // `pubsub_contrato_subject_max_length_validates` and
10695        // `http_contrato_endpoint_max_length_validates` on the peer
10696        // payload axes.
10697        let big = "a".repeat(512);
10698        assert_eq!(big.len(), 512);
10699        let mut s = three_member_spec();
10700        s.contratos.push(WitContract {
10701            de: "payment".into(),
10702            para: "catalog".into(),
10703            wit: "wasi:keyvalue/store".into(),
10704            endpoint: None,
10705            subject: None,
10706            slot: Some(big),
10707        });
10708        s.validate().unwrap();
10709    }
10710
10711    #[test]
10712    fn store_contrato_slot_accepts_canonical_forms() {
10713        // Positive-set sweep: every canonical kv slot template the
10714        // substrate-side `is_wasi_keyvalue_slot` predicate accepts
10715        // (single-token identifiers, path-namespaced `$`-templates,
10716        // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
10717        // snake_case / kebab-case / MixedCase tokens, digit-bearing
10718        // tokens, percent-encoded fragments) must remain valid
10719        // contrato slots too. Drift between this list and the
10720        // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
10721        // surfaces at the shared predicate — one source of truth.
10722        // Uses a fresh `(payment, catalog)` edge so none of the swept
10723        // slots collide with the pre-existing entries in
10724        // `three_member_spec`.
10725        for slot in [
10726            "checkout",
10727            "checkout/$orderId",
10728            "users:{tenant}/{id}",
10729            "session.<sid>",
10730            "session.tokens.<sid>",
10731            "snake_case_key",
10732            "kebab-case-key",
10733            "MixedCase",
10734            "shard0",
10735            "v2/key",
10736            "users/caf%C3%A9",
10737        ] {
10738            let mut s = three_member_spec();
10739            s.contratos.push(WitContract {
10740                de: "payment".into(),
10741                para: "catalog".into(),
10742                wit: "wasi:keyvalue/store".into(),
10743                endpoint: None,
10744                subject: None,
10745                slot: Some(slot.into()),
10746            });
10747            s.validate()
10748                .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
10749        }
10750    }
10751
10752    #[test]
10753    fn contrato_slot_empty_takes_precedence_over_invalid() {
10754        // Ordering pin: `ContratoSlotEmpty` is the more self-locating
10755        // diagnostic on `""` and must lead — the value-shape gate is
10756        // only reached after the empty-check fires. Mirrors
10757        // `contrato_subject_empty_takes_precedence_over_invalid` and
10758        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
10759        // the peer payload axes.
10760        let mut s = three_member_spec();
10761        s.contratos.push(WitContract {
10762            de: "payment".into(),
10763            para: "catalog".into(),
10764            wit: "wasi:keyvalue/store".into(),
10765            endpoint: None,
10766            subject: None,
10767            slot: Some(String::new()),
10768        });
10769        let err = s.validate().unwrap_err();
10770        assert!(
10771            matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
10772            "got {err:?}"
10773        );
10774    }
10775
10776    #[test]
10777    fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
10778        // Diagnostic-shape pin — the offending `:slot` + `:de` +
10779        // `:para` + a non-empty reason flow through verbatim so the
10780        // author can grep their caixa.lisp for the offending contrato
10781        // block and fix it in one edit. Same shape as
10782        // `contrato_subject_invalid_diagnostic_carries_offending_subject`
10783        // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
10784        // on the peer payload axes.
10785        let err = contrato_slot_err("check out/$order");
10786        match err {
10787            AplicacaoError::ContratoSlotInvalid {
10788                de,
10789                para,
10790                slot,
10791                reason,
10792            } => {
10793                assert_eq!(de, "payment");
10794                assert_eq!(para, "catalog");
10795                assert_eq!(slot, "check out/$order");
10796                assert!(!reason.is_empty(), "reason field must be non-empty");
10797            }
10798            other => panic!("expected ContratoSlotInvalid, got {other:?}"),
10799        }
10800    }
10801
10802    #[test]
10803    fn target_view_store_slot_passes_through_to_typed_view() {
10804        // The compounding theorem on the store axis: every
10805        // `WitTarget::Store { slot }` returned by `target()` carries a
10806        // kv-backend-accepted slot template. Renderers downstream of
10807        // `typed_view()` (the future per-Servico `:capabilities
10808        // wasi:keyvalue/store` axis emitter, the future `feira app
10809        // graph` view's slot labeller, the future kv-provider CR
10810        // materializer) can rely on this without re-checking — the
10811        // type system carries the proof. Mirrors
10812        // `target_view_pubsub_subject_passes_through_to_typed_view` on
10813        // the peer payload axis.
10814        let store = WitContract {
10815            de: "a".into(),
10816            para: "b".into(),
10817            wit: "wasi:keyvalue/store".into(),
10818            endpoint: None,
10819            subject: None,
10820            slot: Some("checkout/$orderId".into()),
10821        };
10822        match store.target().unwrap() {
10823            WitTarget::Store { slot } => {
10824                assert_eq!(slot, "checkout/$orderId");
10825            }
10826            other => panic!("expected Store, got {other:?}"),
10827        }
10828    }
10829
10830    #[test]
10831    fn rejects_self_loop_in_synchronous_contratos() {
10832        // A synchronous self-edge (`cart → cart` over HTTP) is now
10833        // rejected by the dedicated `ContratoSelfLoop` gate — a precise
10834        // "this edge is degenerate" diagnostic — rather than incidentally
10835        // by the cycle detector framing it as a `["cart", "cart"]`
10836        // multi-node deadlock.
10837        let mut s = three_member_spec();
10838        s.contratos.push(contract_http("cart", "cart", "/loop"));
10839        let err = s.validate().unwrap_err();
10840        match err {
10841            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
10842                assert_eq!(caixa, "cart");
10843                assert_eq!(wit, "wasi:http/proxy");
10844            }
10845            other => panic!("expected ContratoSelfLoop, got {other:?}"),
10846        }
10847    }
10848
10849    #[test]
10850    fn rejects_self_loop_in_pubsub_contratos() {
10851        // The cycle detector excludes pub-sub edges (acyclic by
10852        // construction), so before the explicit gate a `nats:pub-sub`
10853        // self-edge silently validated and rendered a self-allow CNP.
10854        // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
10855        let mut s = three_member_spec();
10856        s.contratos.push(WitContract {
10857            de: "payment".into(),
10858            para: "payment".into(),
10859            wit: "nats:pub-sub".into(),
10860            endpoint: None,
10861            subject: Some("rio.events.payment".into()),
10862            slot: None,
10863        });
10864        let err = s.validate().unwrap_err();
10865        match err {
10866            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
10867                assert_eq!(caixa, "payment");
10868                assert_eq!(wit, "nats:pub-sub");
10869            }
10870            other => panic!("expected ContratoSelfLoop, got {other:?}"),
10871        }
10872    }
10873
10874    #[test]
10875    fn self_loop_fires_before_payload_shape_check() {
10876        // The structural "this edge can't exist" error precedes the
10877        // narrower payload-shape diagnostics: a self-edge carrying an
10878        // otherwise-malformed endpoint still reports ContratoSelfLoop,
10879        // not ContratoEndpointInvalid.
10880        let mut s = three_member_spec();
10881        s.contratos.push(WitContract {
10882            de: "cart".into(),
10883            para: "cart".into(),
10884            wit: "wasi:http/proxy".into(),
10885            endpoint: Some("not-absolute".into()),
10886            subject: None,
10887            slot: None,
10888        });
10889        match s.validate().unwrap_err() {
10890            AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
10891            other => panic!("expected ContratoSelfLoop, got {other:?}"),
10892        }
10893    }
10894
10895    #[test]
10896    fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
10897        // A self-edge naming a non-member reports the more fundamental
10898        // ContratoMemberMissing first (the member doesn't exist), so the
10899        // self-loop gate is reached only once both endpoints resolve.
10900        let mut s = three_member_spec();
10901        s.contratos.push(contract_http("ghost", "ghost", "/loop"));
10902        match s.validate().unwrap_err() {
10903            AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
10904            other => panic!("expected ContratoMemberMissing, got {other:?}"),
10905        }
10906    }
10907
10908    #[test]
10909    fn rejects_two_node_synchronous_cycle() {
10910        let mut s = three_member_spec();
10911        // existing edges: cart → catalog, cart → payment
10912        // adding catalog → cart closes a 2-cycle on the HTTP subgraph
10913        s.contratos
10914            .push(contract_http("catalog", "cart", "/refresh"));
10915        let err = s.validate().unwrap_err();
10916        match err {
10917            AplicacaoError::ContratoCycle { cycle } => {
10918                // Cycle traversal should mention both endpoints, with
10919                // the back-edge target appearing as both first and last
10920                // element to close the loop.
10921                assert!(cycle.len() >= 3);
10922                assert_eq!(cycle.first(), cycle.last());
10923                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
10924                assert!(body.contains("cart"));
10925                assert!(body.contains("catalog"));
10926            }
10927            other => panic!("expected ContratoCycle, got {other:?}"),
10928        }
10929    }
10930
10931    #[test]
10932    fn rejects_three_node_synchronous_cycle() {
10933        let mut s = three_member_spec();
10934        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
10935        s.contratos = vec![
10936            contract_http("catalog", "cart", "/x"),
10937            contract_http("cart", "payment", "/y"),
10938            contract_http("payment", "catalog", "/z"),
10939        ];
10940        let err = s.validate().unwrap_err();
10941        match err {
10942            AplicacaoError::ContratoCycle { cycle } => {
10943                assert_eq!(cycle.first(), cycle.last());
10944                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
10945                assert_eq!(body.len(), 3);
10946                assert!(body.contains("cart"));
10947                assert!(body.contains("catalog"));
10948                assert!(body.contains("payment"));
10949            }
10950            other => panic!("expected ContratoCycle, got {other:?}"),
10951        }
10952    }
10953
10954    #[test]
10955    fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
10956        // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
10957        // "acyclic by construction" — so a cycle whose closing edge
10958        // is pub-sub should NOT raise ContratoCycle.
10959        let mut s = three_member_spec();
10960        s.contratos = vec![
10961            contract_http("catalog", "cart", "/x"),
10962            contract_http("cart", "payment", "/y"),
10963            // Closing edge is pub-sub — async; not a sync deadlock.
10964            WitContract {
10965                de: "payment".into(),
10966                para: "catalog".into(),
10967                wit: "nats:pub-sub".into(),
10968                endpoint: None,
10969                subject: Some("checkout.events.charge.completed".into()),
10970                slot: None,
10971            },
10972        ];
10973        s.validate().expect("pub-sub edge breaks the sync cycle");
10974    }
10975
10976    #[test]
10977    fn store_edge_counts_as_synchronous_for_cycle_detection() {
10978        // wasi:keyvalue/store is request/response; a cycle through one
10979        // *is* a sync deadlock, just like HTTP.
10980        let mut s = three_member_spec();
10981        s.contratos = vec![
10982            contract_http("catalog", "cart", "/x"),
10983            WitContract {
10984                de: "cart".into(),
10985                para: "catalog".into(),
10986                wit: "wasi:keyvalue/store".into(),
10987                endpoint: None,
10988                subject: None,
10989                slot: Some("session/$id".into()),
10990            },
10991        ];
10992        let err = s.validate().unwrap_err();
10993        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
10994    }
10995
10996    #[test]
10997    fn capability_edge_counts_as_synchronous_for_cycle_detection() {
10998        // Capability-only edges (unknown WIT shape, no payload) default
10999        // to synchronous — safer; authors with truly async capability
11000        // semantics can model them as pub-sub explicitly.
11001        let mut s = three_member_spec();
11002        s.contratos = vec![
11003            contract_http("catalog", "cart", "/x"),
11004            WitContract {
11005                de: "cart".into(),
11006                para: "catalog".into(),
11007                wit: "custom:exchange".into(),
11008                endpoint: None,
11009                subject: None,
11010                slot: None,
11011            },
11012        ];
11013        let err = s.validate().unwrap_err();
11014        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
11015    }
11016
11017    #[test]
11018    fn long_acyclic_chain_validates() {
11019        // A long sync chain (no back-edges) must validate even when
11020        // every node is reachable from the first.
11021        let mut s = three_member_spec();
11022        s.membros = vec![
11023            membro("a", "^0.1"),
11024            membro("b", "^0.1"),
11025            membro("c", "^0.1"),
11026            membro("d", "^0.1"),
11027            membro("e", "^0.1"),
11028        ];
11029        s.contratos = vec![
11030            contract_http("a", "b", "/1"),
11031            contract_http("b", "c", "/2"),
11032            contract_http("c", "d", "/3"),
11033            contract_http("d", "e", "/4"),
11034        ];
11035        s.entrada.as_mut().unwrap().para = "a".into();
11036        s.validate().unwrap();
11037    }
11038
11039    #[test]
11040    fn diamond_acyclic_validates() {
11041        // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
11042        let mut s = three_member_spec();
11043        s.membros = vec![
11044            membro("a", "^0.1"),
11045            membro("b", "^0.1"),
11046            membro("c", "^0.1"),
11047            membro("d", "^0.1"),
11048        ];
11049        s.contratos = vec![
11050            contract_http("a", "b", "/1"),
11051            contract_http("a", "c", "/2"),
11052            contract_http("b", "d", "/3"),
11053            contract_http("c", "d", "/4"),
11054        ];
11055        s.entrada.as_mut().unwrap().para = "a".into();
11056        s.validate().unwrap();
11057    }
11058
11059    // ── duplicate-`:contratos` build-error gate ──────────────────────────
11060
11061    #[test]
11062    fn rejects_duplicate_http_contrato() {
11063        // Fail-before-pass-after pin: the fixture's `cart → catalog`
11064        // HTTP edge appears once. Push an identical entry — same
11065        // (de, para, wit, endpoint) — and validate() must reject it.
11066        // Until this gate landed the typed surface accepted the
11067        // duplicate silently and caixa-mesh's `cilium_network_policies`
11068        // emitted two ``CiliumNetworkPolicy`` objects with identical
11069        // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
11070        // admission rejects on `kubectl apply` far from the source.
11071        let mut s = three_member_spec();
11072        s.contratos
11073            .push(contract_http("cart", "catalog", "/products/:id"));
11074        let err = s.validate().unwrap_err();
11075        assert!(
11076            matches!(
11077                err,
11078                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
11079                    if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
11080            ),
11081            "got {err:?}"
11082        );
11083    }
11084
11085    #[test]
11086    fn rejects_duplicate_pubsub_contrato() {
11087        // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
11088        // edges with identical (de, para, subject) are degenerate;
11089        // pin that the typed surface refuses both at validate time.
11090        let mut s = three_member_spec();
11091        let pubsub = WitContract {
11092            de: "payment".into(),
11093            para: "cart".into(),
11094            wit: "nats:pub-sub".into(),
11095            endpoint: None,
11096            subject: Some("checkout.events.charge.failed".into()),
11097            slot: None,
11098        };
11099        s.contratos.push(pubsub.clone());
11100        s.contratos.push(pubsub);
11101        let err = s.validate().unwrap_err();
11102        assert!(
11103            matches!(
11104                err,
11105                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
11106                    if de == "payment" && para == "cart" && wit == "nats:pub-sub"
11107            ),
11108            "got {err:?}"
11109        );
11110    }
11111
11112    #[test]
11113    fn rejects_duplicate_store_contrato() {
11114        // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
11115        // edges with identical (de, para, slot) collapse to one mesh-
11116        // policy edge; pin the build error.
11117        let mut s = three_member_spec();
11118        let store = WitContract {
11119            de: "cart".into(),
11120            para: "payment".into(),
11121            wit: "wasi:keyvalue/store".into(),
11122            endpoint: None,
11123            subject: None,
11124            slot: Some("checkout/$orderId".into()),
11125        };
11126        // Drop the conflicting HTTP `cart → payment` edge from the
11127        // fixture so the duplicate-store pair is the only one
11128        // distinguishable on this pair.
11129        s.contratos
11130            .retain(|c| !(c.de == "cart" && c.para == "payment"));
11131        s.contratos.push(store.clone());
11132        s.contratos.push(store);
11133        let err = s.validate().unwrap_err();
11134        assert!(
11135            matches!(
11136                err,
11137                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
11138                    if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
11139            ),
11140            "got {err:?}"
11141        );
11142    }
11143
11144    #[test]
11145    fn rejects_duplicate_capability_contrato() {
11146        // Same gate on the pure-capability axis (no payload selector).
11147        // Two contracts with identical (de, para, wit) and no
11148        // endpoint/subject/slot are duplicate edges; pin so a future
11149        // `target_label` change can't accidentally collapse the
11150        // capability arm into a None-shaped key that compares equal
11151        // to a populated one.
11152        let mut s = three_member_spec();
11153        let capability = WitContract {
11154            de: "cart".into(),
11155            para: "catalog".into(),
11156            wit: "pleme:cap/audit".into(),
11157            endpoint: None,
11158            subject: None,
11159            slot: None,
11160        };
11161        s.contratos.push(capability.clone());
11162        s.contratos.push(capability);
11163        let err = s.validate().unwrap_err();
11164        match err {
11165            AplicacaoError::ContratoDuplicate {
11166                de,
11167                para,
11168                wit,
11169                target,
11170            } => {
11171                assert_eq!(de, "cart");
11172                assert_eq!(para, "catalog");
11173                assert_eq!(wit, "pleme:cap/audit");
11174                assert!(
11175                    target.contains("capability"),
11176                    "capability-edge duplicate diagnostic must surface the \
11177                     no-payload shape (got target = {target:?})"
11178                );
11179            }
11180            other => panic!("expected ContratoDuplicate, got {other:?}"),
11181        }
11182    }
11183
11184    #[test]
11185    fn accepts_distinct_http_paths_between_same_pair() {
11186        // Negative pin: two HTTP contracts cart → catalog at distinct
11187        // endpoints (`/products/:id` and `/search`) are *not*
11188        // duplicates — they're distinct typed edges differing on the
11189        // payload axis. The duplicate-gate must not over-match here,
11190        // since the cart-calls-catalog-on-multiple-paths shape is the
11191        // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
11192        // example: cart calls catalog at /products/:id, payment at
11193        // /charge — same shape extends to two paths on one para).
11194        let mut s = three_member_spec();
11195        s.contratos
11196            .push(contract_http("cart", "catalog", "/search"));
11197        s.validate()
11198            .expect("distinct endpoints between same (de, para) must validate");
11199    }
11200
11201    #[test]
11202    fn accepts_same_endpoint_on_different_pairs() {
11203        // Negative pin: the same `/charge` endpoint reused on two
11204        // different (de, para) pairs is two distinct edges, not a
11205        // duplicate. Pinning this shape so the gate's identity key
11206        // includes both `de` and `para` (not just `(wit, endpoint)`).
11207        let mut s = three_member_spec();
11208        s.contratos
11209            .push(contract_http("payment", "catalog", "/charge"));
11210        s.validate()
11211            .expect("same endpoint reused on distinct (de, para) must validate");
11212    }
11213
11214    #[test]
11215    fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
11216        // Pin the diagnostic shape: the duplicate-edge error names
11217        // *which* target field carried the conflict, so the author
11218        // doesn't have to re-grep the source caixa.lisp to find it.
11219        // Same self-locating diagnostic discipline as
11220        // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
11221        let mut s = three_member_spec();
11222        s.contratos
11223            .push(contract_http("cart", "catalog", "/products/:id"));
11224        let err = s.validate().unwrap_err();
11225        let msg = format!("{err}");
11226        assert!(
11227            msg.contains("\"/products/:id\""),
11228            "duplicate-contrato diagnostic must name the offending \
11229             :endpoint payload (got: {msg:?})"
11230        );
11231        assert!(
11232            msg.contains("cart") && msg.contains("catalog"),
11233            "diagnostic must name both endpoints of the duplicate edge \
11234             (got: {msg:?})"
11235        );
11236    }
11237
11238    #[test]
11239    fn duplicate_contrato_gate_runs_after_membership_check() {
11240        // Order pin: a duplicate contract whose `:de` is *also* not in
11241        // `:membros` surfaces the membership error first — the
11242        // missing-member diagnostic is more locating than the
11243        // duplicate-edge one (the author has to fix the membership
11244        // before the duplicate is meaningful). Same ordering
11245        // discipline as `membros_validation_runs_before_contratos_membership_check`.
11246        let mut s = three_member_spec();
11247        s.contratos.push(contract_http("phantom", "catalog", "/x"));
11248        s.contratos.push(contract_http("phantom", "catalog", "/x"));
11249        let err = s.validate().unwrap_err();
11250        assert!(
11251            matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
11252            "membership-missing must fire before duplicate-edge (got {err:?})"
11253        );
11254    }
11255
11256    #[test]
11257    fn duplicate_contrato_gate_runs_after_target_shape_check() {
11258        // Order pin: a contract with a malformed target (e.g. an HTTP
11259        // wit world with an empty :endpoint) surfaces the target-shape
11260        // error first, not the duplicate one. Even when two such
11261        // malformed entries are identical, the per-contract `target()`
11262        // check fires inside the loop *before* the duplicate-key
11263        // insert, so the diagnostic remains the most-locating one.
11264        let mut s = three_member_spec();
11265        let malformed = WitContract {
11266            de: "cart".into(),
11267            para: "catalog".into(),
11268            wit: "wasi:http/proxy".into(),
11269            endpoint: Some(String::new()),
11270            subject: None,
11271            slot: None,
11272        };
11273        s.contratos.push(malformed.clone());
11274        s.contratos.push(malformed);
11275        let err = s.validate().unwrap_err();
11276        assert!(
11277            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
11278            "endpoint-empty must fire before duplicate-edge (got {err:?})"
11279        );
11280    }
11281
11282    #[test]
11283    fn wit_target_label_pins_per_variant_format() {
11284        // Label format is the single source of truth every duplicate-
11285        // `:contratos` diagnostic + every future `feira app graph`
11286        // consumer routes through. Pin the shape per variant so a
11287        // future edit to `WitTarget::label` (e.g. a JSON emitter that
11288        // strips the leading `:`, or a rename from `endpoint` →
11289        // `path`) surfaces as a red-red test rather than as a silent
11290        // downstream diagnostic drift. Together with the exhaustive
11291        // `match` on `WitTarget` inside `label()`, adding a future
11292        // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
11293        // peer, per-edge WIT registry variants) is a compile error at
11294        // the label site — not a fall-through into the `Capability`
11295        // "no payload" default the prior raw-field-probe helper
11296        // silently landed on.
11297        assert_eq!(
11298            WitTarget::Http {
11299                endpoint: "/charge",
11300            }
11301            .label(),
11302            "\
11303:endpoint \"/charge\""
11304        );
11305        assert_eq!(
11306            WitTarget::PubSub {
11307                subject: "events.checkout.paid",
11308            }
11309            .label(),
11310            "\
11311:subject \"events.checkout.paid\""
11312        );
11313        assert_eq!(
11314            WitTarget::Store {
11315                slot: "checkout/$order",
11316            }
11317            .label(),
11318            "\
11319:slot \"checkout/$order\""
11320        );
11321        assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
11322        // Capability-arm label routes through the lifted
11323        // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
11324        // declaration per arm, next to the variant" discipline the
11325        // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
11326        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
11327        // consts already carry extends to the payload-less arm; the
11328        // byte-string equality pin below plus this label-routes-
11329        // through-the-const pin make a future rebrand on either the
11330        // const declaration or the `label()` template a build error
11331        // here rather than a downstream consumer surprise.
11332        assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
11333        assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
11334    }
11335
11336    #[test]
11337    fn wit_target_display_routes_through_label_helper() {
11338        // Fail-before-pass-after pin on the fourth (and only remaining)
11339        // typed-shape-discriminator axis to converge onto the
11340        // three-path-convergence discipline the sibling M3
11341        // [`PlacementStrategy`] (0a2f653) and M2
11342        // [`crate::supervisor::RestartStrategy`] /
11343        // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
11344        // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
11345        // through [`WitTarget::label`], so every consumer reaching for
11346        // `format!("{v}")` on a typed payload target lands on the same
11347        // stable author-facing byte-string [`WitTarget::label`] returns
11348        // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
11349        // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
11350        // `:contratos` gate seeds via [`WitTarget::label`] at
11351        // aplicacao.rs:5491 already threads through.
11352        //
11353        // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
11354        // through to the `Debug` derive's structural output
11355        // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
11356        // rather than the [`WitTarget::label`] helper's stable byte-
11357        // string (`:endpoint "/charge"` — the author-facing `:contratos`
11358        // keyword form). Every future consumer that reaches for
11359        // `format!("{target}")` — the canonical shape every user-facing
11360        // pretty-print site on the sibling typed-enum axes
11361        // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
11362        // [`crate::supervisor::RestartPolicy`]) already uses — would
11363        // silently land under a different byte-string than the
11364        // [`WitTarget::label`] callers that the duplicate-`:contratos`
11365        // diagnostic already threads through, with the mismatch
11366        // surfacing as a downstream diagnostic / graph / audit line
11367        // reading one spelling while the substrate's own gate emitted
11368        // another.
11369        //
11370        // Pin the routing here so a future
11371        // `impl std::fmt::Display for WitTarget<'_>` reimplementation
11372        // that hand-rolls the per-arm formatting instead of delegating
11373        // to [`WitTarget::label`] fails at caixa-core build time.
11374        for variant in [
11375            WitTarget::Http {
11376                endpoint: "/charge",
11377            },
11378            WitTarget::PubSub {
11379                subject: "events.checkout.paid",
11380            },
11381            WitTarget::Store {
11382                slot: "checkout/$order",
11383            },
11384            WitTarget::Capability,
11385        ] {
11386            assert_eq!(
11387                variant.to_string(),
11388                variant.label(),
11389                "WitTarget::{variant:?} Display must route through \
11390                 WitTarget::label (single source of truth: the lifted \
11391                 payload_pair 4-arm dispatch the label helper already \
11392                 threads through)"
11393            );
11394        }
11395    }
11396
11397    #[test]
11398    fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
11399        // Consumer-side pin on the three-path convergence:
11400        // [`std::fmt::Display`] agrees byte-for-byte with the
11401        // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
11402        // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
11403        // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
11404        // Pre-lift the two paths were structurally independent — the
11405        // substrate-side gate reached for `target_view.label()` while a
11406        // future downstream diagnostic / graph / audit line reaching
11407        // for `format!("{target}")` would silently land on the `Debug`
11408        // derive's structural output. Pin the two paths byte-for-byte
11409        // here so any future variant addition (M4 `Rest`/`Grpc` split
11410        // of [`WitTarget::Http`], `Queue`-shaped peer of
11411        // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
11412        // match error at [`WitTarget::payload_pair`] rather than a
11413        // silent per-consumer dispatch miss.
11414        for variant in [
11415            WitTarget::Http {
11416                endpoint: "/charge",
11417            },
11418            WitTarget::PubSub {
11419                subject: "events.checkout.paid",
11420            },
11421            WitTarget::Store {
11422                slot: "checkout/$order",
11423            },
11424            WitTarget::Capability,
11425        ] {
11426            assert_eq!(
11427                format!("{variant}"),
11428                variant.label(),
11429                "WitTarget::{variant:?} Display byte-string must match \
11430                 the AplicacaoError::ContratoDuplicate `target:` carrier \
11431                 the AplicacaoSpec::validate duplicate-`:contratos` gate \
11432                 seeds via WitTarget::label — three-path convergence: \
11433                 Display + label + payload_pair all resolve to the same \
11434                 per-arm byte-string"
11435            );
11436        }
11437    }
11438
11439    #[test]
11440    fn wit_target_payload_pair_pins_per_variant() {
11441        // Pin the per-arm `(field-name, payload)` pair single-sourced
11442        // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
11443        // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
11444        // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
11445        // and [`WitTarget::field_name`] (returns the first component)
11446        // route through. Until this lift landed [`WitTarget::label`]
11447        // dispatched on the same three arms with a per-arm
11448        // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
11449        // paired [`WitTarget::HTTP_FIELD_NAME`] /
11450        // [`WitTarget::PUBSUB_FIELD_NAME`] /
11451        // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
11452        // canonical "same shape, written N times" duplication
11453        // THEORY.md §I.3.5 promotes to a build-time concern. A future
11454        // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
11455        // [`WitTarget::Http`], `Queue`-shaped peer of
11456        // [`WitTarget::Store`]) is one match-arm edit at
11457        // [`WitTarget::payload_pair`], visible here as a compile-time
11458        // exhaustiveness error on both this pin and the label-format
11459        // pin above.
11460        assert_eq!(
11461            WitTarget::Http {
11462                endpoint: "/charge"
11463            }
11464            .payload_pair(),
11465            Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
11466        );
11467        assert_eq!(
11468            WitTarget::PubSub {
11469                subject: "events.x",
11470            }
11471            .payload_pair(),
11472            Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
11473        );
11474        assert_eq!(
11475            WitTarget::Store {
11476                slot: "checkout/$order",
11477            }
11478            .payload_pair(),
11479            Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
11480        );
11481        assert_eq!(WitTarget::Capability.payload_pair(), None);
11482    }
11483
11484    #[test]
11485    fn wit_target_field_name_pins_per_variant() {
11486        // Pin the per-arm author-facing `:contratos` payload field
11487        // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
11488        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
11489        // + returned by [`WitTarget::field_name`]. Every downstream
11490        // consumer (the [`WitContract::target`] gate's `expected:`
11491        // scalar, the [`WitTarget::label`] template's keyword prefix,
11492        // the `feira app graph` verb's `endpoint=…` prefix) routes
11493        // through the same three peer consts, so a rename on the
11494        // author-surface `(defcaixa … :contratos ((:de … :para …
11495        // :wit … :endpoint …)))` field lands in exactly one place.
11496        assert_eq!(
11497            WitTarget::Http {
11498                endpoint: "/charge"
11499            }
11500            .field_name(),
11501            Some(WitTarget::HTTP_FIELD_NAME),
11502        );
11503        assert_eq!(
11504            WitTarget::PubSub {
11505                subject: "events.x",
11506            }
11507            .field_name(),
11508            Some(WitTarget::PUBSUB_FIELD_NAME),
11509        );
11510        assert_eq!(
11511            WitTarget::Store {
11512                slot: "checkout/$order",
11513            }
11514            .field_name(),
11515            Some(WitTarget::STORE_FIELD_NAME),
11516        );
11517        // Capability arm carries no payload field — the diagnostic
11518        // never reports `expected: "capability"` because the gate's
11519        // Capability arm accepts no payload at all (it fires the
11520        // "expected: none" WrongTarget error instead), so the field-
11521        // name method returns None here rather than a placeholder.
11522        assert_eq!(WitTarget::Capability.field_name(), None);
11523
11524        // Peer const scalar values pinned so a rename on either side
11525        // (author-surface field name in the `(defcaixa …)` DSL, or
11526        // the diagnostic's `expected:` scalar) can't drift without
11527        // failing here first.
11528        assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
11529        assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
11530        assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
11531    }
11532
11533    #[test]
11534    fn wit_target_field_names_are_pairwise_distinct() {
11535        // Distinctness pin: if any two of the three payload-field-name
11536        // scalars ever collapse (e.g. an accidental `endpoint` copy-
11537        // paste over the `subject` const), the [`WitContract::target`]
11538        // gate's diagnostic would point authors at the wrong field —
11539        // an "expected `:endpoint`" error on a pub-sub edge would
11540        // silently misroute the fix. Same cross-axis-distinctness
11541        // discipline as the peer M3 `:placement :estrategia` variant-
11542        // discriminator scalar-value pins (cc8f749) applied to the
11543        // payload-field-name axis.
11544        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
11545        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
11546        assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
11547    }
11548
11549    #[test]
11550    fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
11551        // Fail-before-pass-after pin: the graph-verb payload column's
11552        // per-arm `{field}={payload}` byte-string is derived through the
11553        // single [`WitTarget::payload_pair`] 4-arm dispatch on the three
11554        // payload-carrying arms, not through a hand-rolled per-arm match
11555        // that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
11556        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
11557        // inline. A future variant addition — the M4-and-later per-edge
11558        // WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
11559        // peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
11560        // peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
11561        // and both [`WitTarget::label`] (duplicate-`:contratos`
11562        // diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
11563        // payload column) pick up the new arm from the same dispatch.
11564        // Prior to this lift the graph verb open-coded the 4-arm match
11565        // in caixa-feira, so a variant addition would have to be threaded
11566        // through both projections in lockstep or the graph verb would
11567        // silently drop the new arm to `(capability-only)`.
11568        for variant in [
11569            WitTarget::Http {
11570                endpoint: "/charge",
11571            },
11572            WitTarget::PubSub {
11573                subject: "events.checkout.paid",
11574            },
11575            WitTarget::Store {
11576                slot: "checkout/$order",
11577            },
11578        ] {
11579            let (field, payload) = variant
11580                .payload_pair()
11581                .expect("payload arm must expose (field, payload)");
11582            assert_eq!(
11583                variant.graph_label(),
11584                format!("{field}={payload}"),
11585                "WitTarget::{variant:?} graph_label must route the \
11586                 `{{field}}={{payload}}` template through payload_pair — \
11587                 a regression to a hand-rolled per-arm match at the graph \
11588                 verb would silently disagree with a future variant \
11589                 addition landed only at payload_pair"
11590            );
11591        }
11592    }
11593
11594    #[test]
11595    fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
11596        // Fail-before-pass-after pin on the payload-less arm: the graph
11597        // verb's `(capability-only)` byte-string routes through the
11598        // lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
11599        // [`WitTarget::Capability`] arm, not through an inline
11600        // `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
11601        // per-`:contratos` payload column. Peer of the sibling
11602        // [`wit_target_label_pins_per_variant_format`] Capability-arm
11603        // assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
11604        // extended here onto the third payload-less-arm consumer axis
11605        // (graph verb, sibling to the duplicate-`:contratos` diagnostic
11606        // axis and the wrong-target diagnostic axis).
11607        assert_eq!(
11608            WitTarget::Capability.graph_label(),
11609            WitTarget::CAPABILITY_GRAPH_LABEL,
11610        );
11611        assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
11612    }
11613
11614    #[test]
11615    fn wit_target_capability_graph_label_distinct_from_capability_label() {
11616        // Cross-consumer-axis distinctness pin: the graph-verb
11617        // payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
11618        // (`(capability-only)`) and the duplicate-`:contratos` diagnostic
11619        // label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
11620        // payload)`) surface the payload-less arm on two distinct
11621        // consumer axes; a collapse (an accidental rebrand that lands
11622        // one spelling on both consts, a copy-paste that unifies them
11623        // "for consistency") would silently merge the two byte-strings
11624        // and lose the vocabulary distinction the graph verb's
11625        // compact-column form and the diagnostic's descriptive-clause
11626        // form each carry on purpose. Peer of the sibling 4-way
11627        // [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
11628        // pin on the `ContratoWrongTarget::expected` scalar-value axis —
11629        // extended here onto the cross-consumer-axis distinctness of the
11630        // two payload-less-arm consts.
11631        assert_ne!(
11632            WitTarget::CAPABILITY_GRAPH_LABEL,
11633            WitTarget::CAPABILITY_LABEL,
11634            "WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
11635             and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
11636             diagnostic) must remain distinct — a collapse would silently \
11637             merge two consumer axes onto one spelling"
11638        );
11639    }
11640
11641    #[test]
11642    fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
11643        // 4-way distinctness pin extending the sibling
11644        // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
11645        // (which covers only the HTTP / PubSub / Store payload arms)
11646        // onto the fourth scalar the shared
11647        // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
11648        // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
11649        // (`"none"`), the payload-less Capability-arm rejection scalar.
11650        //
11651        // All four [`WitTarget::HTTP_FIELD_NAME`] /
11652        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
11653        // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
11654        // dispatch surface [`WitContract::target`] writes onto the
11655        // `ContratoWrongTarget::expected` field — the same `&'static
11656        // str` axis authors read as "this WIT world's shape admits
11657        // (only|not) `:<field>`". Pairwise-distinctness is the invariant
11658        // downstream consumers rely on: an `expected: "endpoint"`
11659        // diagnostic on a Capability-shaped edge tells the author to
11660        // add a `:endpoint "…"` slot to a WIT world that admits none,
11661        // silently misrouting the fix. Until this pin landed the three
11662        // payload-arm consts were distinctness-guarded by the sibling
11663        // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
11664        // scalar (d4f54f2) sat unguarded — a rebrand collision (the
11665        // author-facing vocabulary shift from `"none"` to `"endpoint"`
11666        // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
11667        // into per-shape peers) would have silently landed one
11668        // Capability-arm rejection on a payload-arm's `expected:` byte-
11669        // string and desynchronized the diagnostic from the author's
11670        // typed shape.
11671        //
11672        // Same 4-way pairwise-distinctness pin discipline as the peer
11673        // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
11674        // (cc8f749) applies on the sibling M3 closed-set typed-enum
11675        // scalar-value dispatch axis; extends the pin trajectory the
11676        // sibling `wit_target_field_names_are_pairwise_distinct`
11677        // 3-way pin opened to cover the last unguarded corner on the
11678        // `ContratoWrongTarget::expected` scalar-value axis.
11679        //
11680        // Fail-before-pass-after locally verified by mutating
11681        // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
11682        // — this pin fires as expected; restoring passes.
11683        let all = [
11684            WitTarget::HTTP_FIELD_NAME,
11685            WitTarget::PUBSUB_FIELD_NAME,
11686            WitTarget::STORE_FIELD_NAME,
11687            WitTarget::CAPABILITY_EXPECTED,
11688        ];
11689        for (i, a) in all.iter().enumerate() {
11690            for (j, b) in all.iter().enumerate() {
11691                if i != j {
11692                    assert_ne!(
11693                        a, b,
11694                        "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
11695                         STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
11696                         pairwise distinct — got duplicate {a:?} at indices \
11697                         {i} and {j}; all four scalars thread through the \
11698                         shared `AplicacaoError::ContratoWrongTarget::expected` \
11699                         &'static str axis, so a collapse silently misdirects \
11700                         the diagnostic on which typed shape the WIT world admits",
11701                    );
11702                }
11703            }
11704        }
11705    }
11706
11707    #[test]
11708    fn wit_target_is_variant_predicates_partition_the_arm_set() {
11709        // Fail-before-pass-after pin on the
11710        // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
11711        // each of the four variants exactly one of the generated
11712        // `is_http` / `is_pubsub` / `is_store` / `is_capability`
11713        // predicates returns `true` and the other three return
11714        // `false`. Prior to this derive the only production
11715        // arm-discriminator on [`WitTarget`] — the sync-cycle
11716        // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
11717        // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
11718        // the variant that expressed no compile-time link back to
11719        // the closed-set typed dispatch a future fifth
11720        // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
11721        // split of [`WitTarget::PubSub`] into shape-specific peers,
11722        // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
11723        // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
11724        // to thread through in lockstep or the DFS exclusion would
11725        // silently disagree with the peer diagnostic templates on
11726        // which arms carry sync-versus-async semantics. Peer of the
11727        // sibling [`crate::CaixaKind`] (f5bba80),
11728        // [`PlacementStrategy`] (766ec63),
11729        // [`crate::supervisor::RestartStrategy`],
11730        // [`crate::supervisor::RestartPolicy`], and
11731        // [`crate::upgrade::UpgradeInstruction`] (915a934)
11732        // `IsVariant` derives on the sibling closed-set typed-enum
11733        // discriminator axes — extends the same one-typed-dispatch-
11734        // per-variant discipline onto the last unlifted closed-set
11735        // typed-enum discriminator on the caixa surface (the M3
11736        // mesh-slot per-`:contratos` target-arm axis), closing the
11737        // arm-discriminator convergence trajectory across every
11738        // closed-set typed enum in caixa-core.
11739        let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
11740            (
11741                WitTarget::Http { endpoint: "/x" },
11742                [true, false, false, false],
11743            ),
11744            (
11745                WitTarget::PubSub {
11746                    subject: "events.x",
11747                },
11748                [false, true, false, false],
11749            ),
11750            (
11751                WitTarget::Store { slot: "kv/x" },
11752                [false, false, true, false],
11753            ),
11754            (WitTarget::Capability, [false, false, false, true]),
11755        ];
11756        for (variant, expected) in rows {
11757            let observed = [
11758                variant.is_http(),
11759                variant.is_pubsub(),
11760                variant.is_store(),
11761                variant.is_capability(),
11762            ];
11763            assert_eq!(
11764                observed, expected,
11765                "WitTarget::{variant:?} is_* predicates must partition \
11766                 the arm set (http, pubsub, store, capability); got {observed:?}"
11767            );
11768        }
11769    }
11770
11771    #[test]
11772    fn wit_target_is_variant_predicates_are_const_fn() {
11773        // The [`gen_platform::IsVariant`] derive emits `const fn`
11774        // predicates on the peer [`crate::CaixaKind`] +
11775        // [`crate::upgrade::UpgradeInstruction`] +
11776        // [`crate::supervisor::RestartStrategy`] +
11777        // [`crate::supervisor::RestartPolicy`] +
11778        // [`PlacementStrategy`] closed-set typed enums — pin the
11779        // same posture on [`WitTarget`] so a future accidental
11780        // downgrade to non-`const` (an added runtime helper reachable
11781        // only from a non-`const` context, a manual hand-rolled
11782        // `impl` that shadows the derive-generated method) trips at
11783        // caixa-core build time rather than surfacing as a downstream
11784        // `const`-context regression far from the derive declaration.
11785        //
11786        // Unlike the peer unit-variant enums (`CaixaKind` /
11787        // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
11788        // whose `const` constructors need no arguments, the three
11789        // payload-carrying [`WitTarget`] arms are const-constructed
11790        // through `&'static str` payloads — the same `'static`
11791        // lifetime the closed-set typed enum's four-arm partition
11792        // pin above already threads through.
11793        const HTTP: WitTarget<'static> = WitTarget::Http { endpoint: "/x" };
11794        const PUBSUB: WitTarget<'static> = WitTarget::PubSub { subject: "e" };
11795        const STORE: WitTarget<'static> = WitTarget::Store { slot: "kv/x" };
11796        const CAPABILITY: WitTarget<'static> = WitTarget::Capability;
11797        const IS_HTTP: bool = HTTP.is_http();
11798        const IS_PUBSUB: bool = PUBSUB.is_pubsub();
11799        const IS_STORE: bool = STORE.is_store();
11800        const IS_CAPABILITY: bool = CAPABILITY.is_capability();
11801        assert!(IS_HTTP);
11802        assert!(IS_PUBSUB);
11803        assert!(IS_STORE);
11804        assert!(IS_CAPABILITY);
11805    }
11806
11807    #[test]
11808    fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
11809        // Consumer-side pin on the sole production converge site:
11810        // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
11811        // edges from the synchronous-subgraph DFS via the lifted
11812        // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
11813        // predicate (rebound from the prior raw
11814        // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
11815        // variant). Byte-equivalent today (`is_pubsub` is the
11816        // derive-generated `matches!(self, Self::PubSub { .. })` by
11817        // construction, the `#[is_variant(name = "pubsub")]` override
11818        // aliasing the auto-derived `is_pub_sub` back to the sibling
11819        // [`WitContract::is_pubsub`] name); pin the behavior so a
11820        // future accidental drift (a rebind onto a peer arm
11821        // predicate, a manual hand-rolled `impl` that shadows the
11822        // derive-generated method with different semantics, a peer
11823        // arm rename that shifts which variant carries sync-versus-
11824        // async semantics) trips at caixa-core test time rather than
11825        // at some downstream operator's runtime dispatch far from the
11826        // rebind commit.
11827        //
11828        // The fixture constructs a two-Servico Aplicacao with one
11829        // pub-sub edge that would close a sync-cycle if the DFS did
11830        // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
11831        // pub-sub exclusion means the DFS sees only the `b → a` HTTP
11832        // edge, which is not a cycle. A regression in the converge
11833        // (a rebind that reads the pub-sub arm as sync) would report
11834        // `AplicacaoError::ContratoCycle`.
11835        let s = AplicacaoSpec {
11836            membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
11837            contratos: vec![
11838                // Pub-sub edge: DFS must skip via is_pubsub().
11839                WitContract {
11840                    de: "a".into(),
11841                    para: "b".into(),
11842                    wit: "nats:pub-sub".into(),
11843                    endpoint: None,
11844                    subject: Some("events.x".into()),
11845                    slot: None,
11846                },
11847                // HTTP edge: DFS must include.
11848                WitContract {
11849                    de: "b".into(),
11850                    para: "a".into(),
11851                    wit: "wasi:http/proxy".into(),
11852                    endpoint: Some("/x".into()),
11853                    subject: None,
11854                    slot: None,
11855                },
11856            ],
11857            politicas: MeshPolicy::default(),
11858            placement: Placement {
11859                estrategia: PlacementStrategy::Replicated,
11860                clusters: vec!["rio".into()],
11861                affinity: None,
11862                shard_key: None,
11863            },
11864            entrada: None,
11865        };
11866        s.validate()
11867            .expect("pub-sub edge must be excluded from sync-cycle DFS");
11868    }
11869
11870    #[test]
11871    fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
11872        // Consumer-side pin: the same three peer consts thread through
11873        // both the [`WitTarget::label`] template (leading-`:` keyword
11874        // prefix in the duplicate-`:contratos` diagnostic) and the
11875        // [`WitContract::target`] gate's [`AplicacaoError::
11876        // ContratoMissingTarget`] `expected:` scalar (the field the
11877        // author needs to add). Pin both routes at once so a future
11878        // refactor can't accidentally split them onto separate string
11879        // literals — the "one place, everywhere reaches for it"
11880        // invariant the peer const set carries.
11881        let http_label = WitTarget::Http { endpoint: "/x" }.label();
11882        assert!(
11883            http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
11884            "label must lead with :{} keyword (got {http_label:?})",
11885            WitTarget::HTTP_FIELD_NAME,
11886        );
11887
11888        let mut s = three_member_spec();
11889        s.contratos.push(WitContract {
11890            de: "cart".into(),
11891            para: "catalog".into(),
11892            wit: "kafka:topic".into(),
11893            endpoint: None,
11894            subject: None,
11895            slot: None,
11896        });
11897        match s.validate().unwrap_err() {
11898            AplicacaoError::ContratoMissingTarget { expected, .. } => {
11899                assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
11900            }
11901            other => panic!("expected ContratoMissingTarget, got {other:?}"),
11902        }
11903    }
11904
11905    #[test]
11906    fn duplicate_pubsub_diagnostic_names_offending_subject() {
11907        // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
11908        // on the pub-sub target axis: the duplicate-edge diagnostic
11909        // must name the `:subject` payload verbatim (not just the
11910        // `(de, para, wit)` triple). Prior to lifting the label onto
11911        // [`WitTarget::label`] the diagnostic derived the label from
11912        // raw [`WitContract`] `Option<String>` probes — a future
11913        // `WitTarget` variant addition (M4 per-edge WIT registry)
11914        // would silently fall through to the `Capability` "no
11915        // payload" default without a compiler warning. Pinning the
11916        // pub-sub arm's format closes the second of three
11917        // payload-carrying `WitTarget` arms this diagnostic threads
11918        // through.
11919        let mut s = three_member_spec();
11920        let pubsub = WitContract {
11921            de: "payment".into(),
11922            para: "cart".into(),
11923            wit: "nats:pub-sub".into(),
11924            endpoint: None,
11925            subject: Some("events.checkout.paid".into()),
11926            slot: None,
11927        };
11928        s.contratos.push(pubsub.clone());
11929        s.contratos.push(pubsub);
11930        let err = s.validate().unwrap_err();
11931        let msg = format!("{err}");
11932        assert!(
11933            msg.contains(":subject \"events.checkout.paid\""),
11934            "duplicate-pubsub diagnostic must name the offending \
11935             :subject payload (got: {msg:?})"
11936        );
11937    }
11938
11939    #[test]
11940    fn duplicate_store_diagnostic_names_offending_slot() {
11941        // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
11942        // key-value target axis: the diagnostic must name the `:slot`
11943        // payload verbatim. Third of three payload-carrying
11944        // `WitTarget` arms this diagnostic threads through, closing
11945        // the per-arm label pin trilogy (`Http` — 6841,
11946        // `PubSub` + `Store` — this test + peer above).
11947        let mut s = three_member_spec();
11948        let store = WitContract {
11949            de: "cart".into(),
11950            para: "payment".into(),
11951            wit: "wasi:keyvalue/store".into(),
11952            endpoint: None,
11953            subject: None,
11954            slot: Some("checkout/$orderId".into()),
11955        };
11956        s.contratos
11957            .retain(|c| !(c.de == "cart" && c.para == "payment"));
11958        s.contratos.push(store.clone());
11959        s.contratos.push(store);
11960        let err = s.validate().unwrap_err();
11961        let msg = format!("{err}");
11962        assert!(
11963            msg.contains(":slot \"checkout/$orderId\""),
11964            "duplicate-store diagnostic must name the offending :slot \
11965             payload (got: {msg:?})"
11966        );
11967    }
11968
11969    #[test]
11970    fn rejects_entrada_path_without_leading_slash() {
11971        let mut s = three_member_spec();
11972        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
11973        let err = s.validate().unwrap_err();
11974        assert!(
11975            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
11976            "got {err:?}"
11977        );
11978    }
11979
11980    #[test]
11981    fn rejects_empty_entrada_path() {
11982        let mut s = three_member_spec();
11983        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "".into()];
11984        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
11985    }
11986
11987    #[test]
11988    fn rejects_duplicate_entrada_paths() {
11989        let mut s = three_member_spec();
11990        s.entrada.as_mut().unwrap().paths = vec![
11991            "/api/cart".into(),
11992            "/api/products".into(),
11993            "/api/cart".into(),
11994        ];
11995        let err = s.validate().unwrap_err();
11996        assert!(
11997            matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
11998            "got {err:?}"
11999        );
12000    }
12001
12002    #[test]
12003    fn rejects_zero_entrada_port() {
12004        let mut s = three_member_spec();
12005        s.entrada.as_mut().unwrap().port = 0;
12006        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
12007    }
12008
12009    // ── :entrada :paths value-shape gate ─────────────────────────────
12010    //
12011    // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
12012    // sibling `:paths` axis. Every authoring footgun the K8s Gateway
12013    // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
12014    // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
12015    // time now becomes a caixa-build-time `EntradaPathInvalid` with
12016    // the offending `:paths` entry named verbatim.
12017
12018    #[test]
12019    fn rejects_entrada_path_with_query() {
12020        // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
12021        // silently passed validate and the Gateway API webhook
12022        // rejected it at apply time with no source citation.
12023        let mut s = three_member_spec();
12024        s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
12025        let err = s.validate().unwrap_err();
12026        assert!(
12027            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12028                if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
12029            "got {err:?}"
12030        );
12031    }
12032
12033    #[test]
12034    fn rejects_entrada_path_with_fragment() {
12035        let mut s = three_member_spec();
12036        s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
12037        let err = s.validate().unwrap_err();
12038        assert!(
12039            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12040                if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
12041            "got {err:?}"
12042        );
12043    }
12044
12045    #[test]
12046    fn rejects_entrada_path_with_space() {
12047        let mut s = three_member_spec();
12048        s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
12049        let err = s.validate().unwrap_err();
12050        assert!(
12051            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12052                if path == "/api/my cart" && reason.contains("whitespace")),
12053            "got {err:?}"
12054        );
12055    }
12056
12057    #[test]
12058    fn rejects_entrada_path_with_tab() {
12059        let mut s = three_member_spec();
12060        s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
12061        let err = s.validate().unwrap_err();
12062        assert!(
12063            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12064                if path == "/api/\tcart" && reason.contains("whitespace")),
12065            "got {err:?}"
12066        );
12067    }
12068
12069    #[test]
12070    fn rejects_entrada_path_with_control_char() {
12071        // 0x01 (SOH) — a non-whitespace control char surfaces the
12072        // distinct "control character" reason arm, separate from
12073        // the whitespace arm. Pinned so a future refactor that
12074        // collapses the two arms can't accidentally drop the more
12075        // self-locating diagnostic.
12076        let mut s = three_member_spec();
12077        s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
12078        let err = s.validate().unwrap_err();
12079        assert!(
12080            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12081                if path == "/api/\x01cart" && reason.contains("control character")),
12082            "got {err:?}"
12083        );
12084    }
12085
12086    #[test]
12087    fn rejects_entrada_path_with_non_ascii() {
12088        // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
12089        // unreserved-set rule rejects. The Gateway API webhook
12090        // rejects literal non-ASCII bytes; percent-encoding is the
12091        // only way to author non-ASCII in a path.
12092        let mut s = three_member_spec();
12093        s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
12094        let err = s.validate().unwrap_err();
12095        assert!(
12096            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12097                if path == "/api/café" && reason.contains("non-ASCII")),
12098            "got {err:?}"
12099        );
12100    }
12101
12102    #[test]
12103    fn rejects_entrada_path_with_consecutive_slashes() {
12104        let mut s = three_member_spec();
12105        s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
12106        let err = s.validate().unwrap_err();
12107        assert!(
12108            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12109                if path == "/api//cart" && reason.contains("consecutive `/`")),
12110            "got {err:?}"
12111        );
12112    }
12113
12114    #[test]
12115    fn rejects_entrada_path_with_dot_segment() {
12116        let mut s = three_member_spec();
12117        s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
12118        let err = s.validate().unwrap_err();
12119        assert!(
12120            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12121                if path == "/api/./cart" && reason.contains("`.` segment")),
12122            "got {err:?}"
12123        );
12124    }
12125
12126    #[test]
12127    fn rejects_entrada_path_with_trailing_dot_segment() {
12128        // The bare `/.` and the trailing `/foo/.` are both rejected
12129        // by the Gateway API webhook; pinned separately so a future
12130        // narrowing that catches only the inner form surfaces here.
12131        let mut s = three_member_spec();
12132        s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
12133        let err = s.validate().unwrap_err();
12134        assert!(
12135            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12136                if path == "/api/." && reason.contains("`.` segment")),
12137            "got {err:?}"
12138        );
12139    }
12140
12141    #[test]
12142    fn rejects_entrada_path_with_parent_segment() {
12143        let mut s = three_member_spec();
12144        s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
12145        let err = s.validate().unwrap_err();
12146        assert!(
12147            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12148                if path == "/api/../etc" && reason.contains("`..` parent-segment")),
12149            "got {err:?}"
12150        );
12151    }
12152
12153    #[test]
12154    fn rejects_entrada_path_with_trailing_parent_segment() {
12155        // Trailing `/..` — symmetric arm of the parent-segment rule,
12156        // pinned separately so a future relaxation that only checks
12157        // the inner form (`/../`) surfaces here.
12158        let mut s = three_member_spec();
12159        s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
12160        let err = s.validate().unwrap_err();
12161        assert!(
12162            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12163                if path == "/api/.." && reason.contains("`..` parent-segment")),
12164            "got {err:?}"
12165        );
12166    }
12167
12168    #[test]
12169    fn rejects_entrada_path_too_long() {
12170        // 1025-byte path — one over the Gateway API HTTPPathMatch.value
12171        // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
12172        // ASCII-alphanumeric body so only the length rule fires.
12173        let mut s = three_member_spec();
12174        let big = format!("/api/{}", "a".repeat(1020));
12175        assert_eq!(big.len(), 1025);
12176        s.entrada.as_mut().unwrap().paths = vec![big.clone()];
12177        let err = s.validate().unwrap_err();
12178        assert!(
12179            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12180                if path == &big && reason.contains("max length of 1024")),
12181            "got {err:?}"
12182        );
12183    }
12184
12185    #[test]
12186    fn entrada_path_max_length_validates() {
12187        // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
12188        // maxLength cap. Boundary pin: drift in the cap surfaces here
12189        // and at `rejects_entrada_path_too_long` simultaneously.
12190        let mut s = three_member_spec();
12191        let big = format!("/api/{}", "a".repeat(1019));
12192        assert_eq!(big.len(), 1024);
12193        s.entrada.as_mut().unwrap().paths = vec![big];
12194        s.validate().unwrap();
12195    }
12196
12197    #[test]
12198    fn entrada_accepts_canonical_paths() {
12199        // Positive-control sweep — every form the Gateway API
12200        // apiserver accepts must round-trip through validate. Covers
12201        // the root catch-all, plain paths, dot-prefixed segments
12202        // (hidden-file-style, distinct from `.` and `..` segments
12203        // which are rejected), digit-bearing segments, the canonical
12204        // route-template `:param` form (`:` is RFC 3986 reserved-set
12205        // valid in paths), trailing-slash form, percent-encoded
12206        // segments, and an interior `..` *substring* (`/foo..bar` is
12207        // not the `..` segment and is allowed).
12208        for path in [
12209            "/",
12210            "/api/cart",
12211            "/healthz",
12212            "/api/.config",
12213            "/v1/products",
12214            "/products/:id",
12215            "/api/cart/",
12216            "/api/caf%C3%A9",
12217            "/foo..bar",
12218            "/...",
12219        ] {
12220            let mut s = three_member_spec();
12221            s.entrada.as_mut().unwrap().paths = vec![path.into()];
12222            s.validate()
12223                .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
12224        }
12225    }
12226
12227    #[test]
12228    fn entrada_path_empty_takes_precedence_over_invalid() {
12229        // Ordering pin: `EntradaPathEmpty` is the more self-locating
12230        // diagnostic on `""` and must lead — `validate_entrada_path`
12231        // is only reached after the empty-check fires at the call
12232        // site. (The predicate itself defends against direct
12233        // invocation by returning the same error on `""`.)
12234        let mut s = three_member_spec();
12235        s.entrada.as_mut().unwrap().paths = vec!["".into()];
12236        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
12237    }
12238
12239    #[test]
12240    fn entrada_path_not_absolute_takes_precedence_over_invalid() {
12241        // Ordering pin: a path without a leading `/` surfaces the
12242        // narrower `EntradaPathNotAbsolute` diagnostic first; the
12243        // value-shape gate is only consulted on paths that already
12244        // satisfy the absolute-prefix invariant.
12245        let mut s = three_member_spec();
12246        // `bad path` would fire the whitespace rule under the
12247        // value-shape gate, but missing-leading-`/` is the more
12248        // self-locating diagnostic.
12249        s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
12250        let err = s.validate().unwrap_err();
12251        assert!(
12252            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
12253            "got {err:?}"
12254        );
12255    }
12256
12257    #[test]
12258    fn entrada_path_invalid_fires_before_duplicate_check() {
12259        // Ordering pin: a malformed path on the *first* entry of a
12260        // would-be duplicate pair fires the value-shape gate before
12261        // the duplicate gate, mirroring the
12262        // `placement_cluster_invalid_fires_before_duplicate_check`
12263        // (6cbb900) pattern on the peer axis.
12264        let mut s = three_member_spec();
12265        s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
12266        let err = s.validate().unwrap_err();
12267        assert!(
12268            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
12269            "got {err:?}"
12270        );
12271    }
12272
12273    #[test]
12274    fn entrada_path_diagnostic_carries_offending_path() {
12275        // Diagnostic-shape pin — the offending path + a non-empty
12276        // reason flow through verbatim so the author can grep their
12277        // caixa.lisp for `:paths` and fix it in one edit. Same shape
12278        // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
12279        let mut s = three_member_spec();
12280        s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
12281        let err = s.validate().unwrap_err();
12282        match err {
12283            AplicacaoError::EntradaPathInvalid { path, reason } => {
12284                assert_eq!(path, "/api?q=1");
12285                assert!(!reason.is_empty(), "reason field must be non-empty");
12286            }
12287            other => panic!("expected EntradaPathInvalid, got {other:?}"),
12288        }
12289    }
12290
12291    #[test]
12292    fn rejects_entrada_path_with_curly_brace_template_form() {
12293        // Per-axis pin on the shared `is_gateway_api_http_path`
12294        // reserved-byte arm: the canonical "I wrote an OpenAPI
12295        // path-template `{id}` instead of the Gateway API `:id` form"
12296        // footgun the K8s apiserver would otherwise catch at admission
12297        // time on every `HTTPRoute.spec.rules[].matches[].path.value`
12298        // landing site, far from the caixa.lisp. Surfaces as
12299        // `EntradaPathInvalid` carrying the offending path verbatim
12300        // plus the canonical `%7B`/`%7D` percent-encoding remediation
12301        // — the substrate-side `gateway_api_http_path_rejects_every_
12302        // reserved_printable_ascii_byte` predicate-level sweep pins the
12303        // full eleven-byte set; this per-axis pin confirms the
12304        // diagnostic flows through to the `EntradaPathInvalid` variant.
12305        let mut s = three_member_spec();
12306        s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
12307        let err = s.validate().unwrap_err();
12308        assert!(
12309            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12310                if path == "/api/cart/{id}"
12311                    && reason.contains("reserved character")
12312                    && reason.contains("'{'")
12313                    && reason.contains("%7B")),
12314            "got {err:?}"
12315        );
12316    }
12317
12318    #[test]
12319    fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
12320        // Per-axis peer of `rejects_entrada_path_with_curly_brace_
12321        // template_form` on the sibling `:contratos :endpoint` axis.
12322        // Same shared `is_gateway_api_http_path` reserved-byte arm
12323        // fires through `ContratoEndpointInvalid`, with the offending
12324        // endpoint + `:de` + `:para` + reason flowing through verbatim.
12325        // Pins that the lifted predicate's tightening lands on both
12326        // caller axes simultaneously — one source of truth for the
12327        // Gateway API HTTPPathMatch.value accepted set.
12328        let err = contrato_endpoint_err("/api/cart/{id}");
12329        assert!(
12330            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12331                if endpoint == "/api/cart/{id}"
12332                    && reason.contains("reserved character")
12333                    && reason.contains("'{'")
12334                    && reason.contains("%7B")),
12335            "got {err:?}"
12336        );
12337    }
12338
12339    // ── :entrada :host value-shape gate ──────────────────────────────
12340    //
12341    // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
12342    // the sibling `:host` axis. Every authoring footgun the K8s
12343    // Gateway API v1 apiserver would catch at admission time becomes
12344    // a caixa-build-time `EntradaHostInvalid` with the offending
12345    // `:host` named verbatim. Same diagnostic shape as
12346    // `MembroVersaoInvalid` (9888b13).
12347
12348    #[test]
12349    fn rejects_entrada_host_with_scheme() {
12350        // Fail-before-pass-after pin — pre-gate codebases silently
12351        // accepted `https://…` and the apiserver rejected it at apply
12352        // time with no source citation.
12353        let mut s = three_member_spec();
12354        s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
12355        let err = s.validate().unwrap_err();
12356        assert!(
12357            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
12358                if host == "https://checkout.quero.cloud"),
12359            "got {err:?}"
12360        );
12361    }
12362
12363    #[test]
12364    fn rejects_entrada_host_with_port() {
12365        // The `:8080` port suffix is the canonical "I forgot the port
12366        // belongs in `:entrada :port`" footgun. The top-level `:` arm
12367        // (introduced after the per-label loop-only impl silently
12368        // surfaced a deep "label \"cloud:8080\" contains invalid
12369        // character ':'" leak) names the canonical fix verbatim — the
12370        // `:entrada :port` slot.
12371        let mut s = three_member_spec();
12372        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
12373        let err = s.validate().unwrap_err();
12374        assert!(
12375            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
12376                if host == "checkout.quero.cloud:8080"
12377                && reason.contains(":entrada :port")),
12378            "got {err:?}"
12379        );
12380    }
12381
12382    #[test]
12383    fn rejects_entrada_host_with_trailing_colon() {
12384        // Trailing `:` (e.g. an in-progress `:host "example.com:"`
12385        // edit) — the per-label loop would land it as a deep
12386        // "label \"com:\" must start and end with an alphanumeric"
12387        // / "contains invalid character ':'" leak. The top-level
12388        // `:` arm pre-empts with the canonical `:port` slot
12389        // diagnostic.
12390        let mut s = three_member_spec();
12391        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
12392        let err = s.validate().unwrap_err();
12393        assert!(
12394            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
12395                if host == "checkout.quero.cloud:"
12396                && reason.contains(":entrada :port")),
12397            "got {err:?}"
12398        );
12399    }
12400
12401    #[test]
12402    fn rejects_entrada_host_unbracketed_ipv6_literal() {
12403        // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
12404        // literals across the board (peer with `rejects_entrada_host_
12405        // ipv4_literal` above for the four-label-all-digit IPv4 arm).
12406        // Before this top-level `:` arm landed the per-label loop
12407        // surfaced a single-label byte-class diagnostic that named the
12408        // `:` byte but not the IP-literal prohibition. The top-level
12409        // `:` arm names both the `:port` slot and the IP-literal
12410        // prohibition verbatim, so an author whose `:host "2001:..."`
12411        // value lands here gets a self-locating fix either way.
12412        let mut s = three_member_spec();
12413        s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
12414        let err = s.validate().unwrap_err();
12415        assert!(
12416            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
12417                if host == "2001:db8::1"
12418                && reason.contains("IPv6")),
12419            "got {err:?}"
12420        );
12421    }
12422
12423    #[test]
12424    fn rejects_entrada_host_wildcard_with_port() {
12425        // Wildcard host with port suffix — the `*.` strip and the
12426        // per-label loop on `["foo", "quero", "cloud:8080"]` would
12427        // surface the deep byte-class leak. The top-level `:` arm sits
12428        // upstream of the `*.` strip, so it names the canonical `:port`
12429        // fix verbatim regardless of whether the host is wildcard-led.
12430        let mut s = three_member_spec();
12431        s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
12432        let err = s.validate().unwrap_err();
12433        assert!(
12434            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
12435                if host == "*.quero.cloud:8080"
12436                && reason.contains(":entrada :port")),
12437            "got {err:?}"
12438        );
12439    }
12440
12441    #[test]
12442    fn rejects_entrada_host_with_path() {
12443        let mut s = three_member_spec();
12444        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
12445        let err = s.validate().unwrap_err();
12446        assert!(
12447            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
12448                if host == "checkout.quero.cloud/api"),
12449            "got {err:?}"
12450        );
12451    }
12452
12453    #[test]
12454    fn rejects_entrada_host_with_uppercase() {
12455        // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
12456        // rejected, not silently lower-cased.
12457        let mut s = three_member_spec();
12458        s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
12459        let err = s.validate().unwrap_err();
12460        assert!(
12461            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12462                if reason.contains("uppercase")),
12463            "got {err:?}"
12464        );
12465    }
12466
12467    #[test]
12468    fn rejects_entrada_host_with_underscore() {
12469        // RFC 1123 allows `[a-z0-9-]` only; underscore is the
12470        // canonical "I'm thinking of HTTP cookies / SRV records" leak.
12471        let mut s = three_member_spec();
12472        s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
12473        let err = s.validate().unwrap_err();
12474        assert!(
12475            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12476                if reason.contains('_')),
12477            "got {err:?}"
12478        );
12479    }
12480
12481    #[test]
12482    fn rejects_entrada_host_ipv4_literal() {
12483        // Gateway API v1 explicitly forbids IP literals as Hostnames.
12484        let mut s = three_member_spec();
12485        s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
12486        let err = s.validate().unwrap_err();
12487        assert!(
12488            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12489                if reason.contains("IPv4")),
12490            "got {err:?}"
12491        );
12492    }
12493
12494    #[test]
12495    fn rejects_entrada_host_with_trailing_dot() {
12496        // The Gateway API regex anchors at end-of-string with no
12497        // trailing `.` allowance — the FQDN root-dot form is rejected.
12498        let mut s = three_member_spec();
12499        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
12500        let err = s.validate().unwrap_err();
12501        assert!(
12502            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
12503                if host == "checkout.quero.cloud."),
12504            "got {err:?}"
12505        );
12506    }
12507
12508    #[test]
12509    fn rejects_entrada_host_with_leading_dot() {
12510        let mut s = three_member_spec();
12511        s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
12512        let err = s.validate().unwrap_err();
12513        assert!(
12514            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12515                if reason.contains("empty label")),
12516            "got {err:?}"
12517        );
12518    }
12519
12520    #[test]
12521    fn rejects_entrada_host_with_consecutive_dots() {
12522        let mut s = three_member_spec();
12523        s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
12524        let err = s.validate().unwrap_err();
12525        assert!(
12526            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12527                if reason.contains("empty label")),
12528            "got {err:?}"
12529        );
12530    }
12531
12532    #[test]
12533    fn rejects_entrada_host_with_leading_hyphen_label() {
12534        let mut s = three_member_spec();
12535        s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
12536        let err = s.validate().unwrap_err();
12537        assert!(
12538            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12539                if reason.contains("alphanumeric")),
12540            "got {err:?}"
12541        );
12542    }
12543
12544    #[test]
12545    fn rejects_entrada_host_with_trailing_hyphen_label() {
12546        let mut s = three_member_spec();
12547        s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
12548        let err = s.validate().unwrap_err();
12549        assert!(
12550            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12551                if reason.contains("alphanumeric")),
12552            "got {err:?}"
12553        );
12554    }
12555
12556    #[test]
12557    fn rejects_entrada_host_with_inner_wildcard() {
12558        // Gateway API allows `*` only as the first label (`*.foo`);
12559        // any inner or trailing `*` is rejected.
12560        let mut s = three_member_spec();
12561        s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
12562        let err = s.validate().unwrap_err();
12563        assert!(
12564            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12565                if reason.contains("wildcard")),
12566            "got {err:?}"
12567        );
12568    }
12569
12570    #[test]
12571    fn rejects_entrada_host_bare_wildcard() {
12572        // `*.` with no domain is meaningless; Gateway API rejects it.
12573        let mut s = three_member_spec();
12574        s.entrada.as_mut().unwrap().host = "*.".into();
12575        let err = s.validate().unwrap_err();
12576        assert!(
12577            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12578                if reason.contains("wildcard")),
12579            "got {err:?}"
12580        );
12581    }
12582
12583    #[test]
12584    fn rejects_entrada_host_with_whitespace() {
12585        let mut s = three_member_spec();
12586        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
12587        let err = s.validate().unwrap_err();
12588        assert!(
12589            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12590                if reason.contains("whitespace")),
12591            "got {err:?}"
12592        );
12593    }
12594
12595    #[test]
12596    fn rejects_entrada_host_space_names_offending_byte() {
12597        // Embedded space in the `:entrada :host` axis surfaces the
12598        // byte-naming diagnostic through the lifted
12599        // `find_ascii_whitespace_byte` predicate. Peer with the
12600        // sibling `parse_rejects_leading_whitespace` pins on
12601        // `supervisor::duration_codec` (a7ae622) — same "the
12602        // diagnostic carries the offending byte's `0x{b:02x}` shape"
12603        // discipline extended from the shared duration codec to the
12604        // Gateway API v1 Hostname axis.
12605        let mut s = three_member_spec();
12606        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
12607        let err = s.validate().unwrap_err();
12608        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12609            panic!("expected EntradaHostInvalid, got {err:?}");
12610        };
12611        assert!(
12612            reason.contains("ASCII whitespace byte"),
12613            "expected byte-naming diagnostic, got {reason:?}"
12614        );
12615        assert!(
12616            reason.contains("0x20"),
12617            "expected offending space byte 0x20, got {reason:?}"
12618        );
12619    }
12620
12621    #[test]
12622    fn rejects_entrada_host_tab_names_offending_byte() {
12623        // Embedded tab byte in the `:entrada :host` axis — the
12624        // canonical paste-from-YAML-block-scalar / paste-from-
12625        // indented-doc footgun. Pins that the lifted predicate covers
12626        // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
12627        // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
12628        // not just the leading-space case the pre-lift `.bytes().any`
12629        // arm's opaque "must not contain whitespace" reason already
12630        // covered. Peer with `parse_rejects_tab_byte` on
12631        // `supervisor::duration_codec` (a7ae622).
12632        let mut s = three_member_spec();
12633        s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
12634        let err = s.validate().unwrap_err();
12635        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12636            panic!("expected EntradaHostInvalid, got {err:?}");
12637        };
12638        assert!(
12639            reason.contains("ASCII whitespace byte"),
12640            "expected byte-naming diagnostic, got {reason:?}"
12641        );
12642        assert!(
12643            reason.contains("0x09"),
12644            "expected offending tab byte 0x09, got {reason:?}"
12645        );
12646    }
12647
12648    #[test]
12649    fn rejects_entrada_host_lf_names_offending_byte() {
12650        // Embedded LF byte in the `:entrada :host` axis — the
12651        // canonical paste-from-shell-heredoc / paste-from-multiline-
12652        // doc footgun the caixa-mesh YAML emitter would silently
12653        // reinterpret at the Gateway API v1 HTTPRoute admission
12654        // layer (an embedded LF byte in a YAML plain scalar either
12655        // truncates the value at the emitter or crashes the parser
12656        // on the k8s-apiserver side). Pins the third representative
12657        // of the full ASCII-whitespace set through the shared
12658        // predicate.
12659        let mut s = three_member_spec();
12660        s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
12661        let err = s.validate().unwrap_err();
12662        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12663            panic!("expected EntradaHostInvalid, got {err:?}");
12664        };
12665        assert!(
12666            reason.contains("ASCII whitespace byte"),
12667            "expected byte-naming diagnostic, got {reason:?}"
12668        );
12669        assert!(
12670            reason.contains("0x0a"),
12671            "expected offending LF byte 0x0a, got {reason:?}"
12672        );
12673    }
12674
12675    #[test]
12676    fn rejects_entrada_host_nbsp_names_offending_codepoint() {
12677        // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
12678        // axis — the canonical paste-from-typography /
12679        // paste-from-word-processor footgun. Before the non-ASCII
12680        // Unicode `White_Space` scan lifted through the shared
12681        // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
12682        // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
12683        // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
12684        // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
12685        // with the far-from-source `label "…" must start and end
12686        // with an alphanumeric` diagnostic — burying the
12687        // paste-from-typography origin under a label-shape leak.
12688        // Peer with the sibling non-ASCII-whitespace pins at
12689        // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
12690        // — 1b75b38), `limits::parse_duration`,
12691        // `limits::parse_millicores`, and the shared duration codec
12692        // — same "the diagnostic carries the offending Unicode
12693        // codepoint's `U+XXXX` shape" discipline extended from every
12694        // typed-magnitude codec to the Gateway API v1 Hostname axis.
12695        let mut s = three_member_spec();
12696        s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
12697        let err = s.validate().unwrap_err();
12698        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12699            panic!("expected EntradaHostInvalid, got {err:?}");
12700        };
12701        assert!(
12702            reason.contains("non-ASCII Unicode whitespace character"),
12703            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
12704        );
12705        assert!(
12706            reason.contains("U+00A0"),
12707            "expected offending NBSP codepoint U+00A0, got {reason:?}"
12708        );
12709    }
12710
12711    #[test]
12712    fn rejects_entrada_host_line_separator_names_offending_codepoint() {
12713        // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
12714        // `:entrada :host` axis — the canonical paste-from-web-doc /
12715        // paste-from-published-HTML footgun. `char::is_whitespace`
12716        // returns true for `U+2028` per the Unicode `White_Space`
12717        // property, so `str::trim` at any downstream site would
12718        // silently strip it — same drift class as NBSP but on a
12719        // different codepoint region. Pins the second representative
12720        // (non-Latin-1 `char::is_whitespace` member) through the
12721        // shared predicate. Peer with
12722        // `parse_byte_size_rejects_internal_line_separator` on
12723        // `limits::parse_byte_size` (1b75b38).
12724        let mut s = three_member_spec();
12725        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
12726        let err = s.validate().unwrap_err();
12727        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12728            panic!("expected EntradaHostInvalid, got {err:?}");
12729        };
12730        assert!(
12731            reason.contains("non-ASCII Unicode whitespace character"),
12732            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
12733        );
12734        assert!(
12735            reason.contains("U+2028"),
12736            "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
12737        );
12738    }
12739
12740    #[test]
12741    fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
12742        // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
12743        // labels in the `:entrada :host` axis — the canonical
12744        // paste-from-CJK-typography footgun (CJK IMEs default to
12745        // full-width whitespace when the space bar is pressed in
12746        // Japanese / Chinese input modes). Pins the third
12747        // representative of the non-ASCII Unicode `White_Space` set
12748        // through the shared predicate: the CJK block, distinct from
12749        // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
12750        // SEPARATOR `U+2028` — covering the same axis breadth the
12751        // sibling `parse_byte_size_rejects_trailing_ideographic_space`
12752        // (1b75b38) pins on `limits::parse_byte_size`.
12753        let mut s = three_member_spec();
12754        s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
12755        let err = s.validate().unwrap_err();
12756        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12757            panic!("expected EntradaHostInvalid, got {err:?}");
12758        };
12759        assert!(
12760            reason.contains("non-ASCII Unicode whitespace character"),
12761            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
12762        );
12763        assert!(
12764            reason.contains("U+3000"),
12765            "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
12766        );
12767    }
12768
12769    #[test]
12770    fn rejects_entrada_host_too_long() {
12771        // Total length cap = 253; build a 254-byte host out of two
12772        // 63-byte labels + one 62-byte label + dots.
12773        let mut s = three_member_spec();
12774        let big = format!(
12775            "{}.{}.{}.{}",
12776            "a".repeat(63),
12777            "b".repeat(63),
12778            "c".repeat(63),
12779            "d".repeat(254 - 63 * 3 - 3)
12780        );
12781        assert_eq!(big.len(), 254);
12782        s.entrada.as_mut().unwrap().host = big;
12783        let err = s.validate().unwrap_err();
12784        assert!(
12785            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12786                if reason.contains("max length of 253")),
12787            "got {err:?}"
12788        );
12789    }
12790
12791    #[test]
12792    fn rejects_entrada_host_label_too_long() {
12793        let mut s = three_member_spec();
12794        // 64-byte label — one over the per-label cap.
12795        s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
12796        let err = s.validate().unwrap_err();
12797        assert!(
12798            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12799                if reason.contains("label max length of 63")),
12800            "got {err:?}"
12801        );
12802    }
12803
12804    #[test]
12805    fn entrada_host_diagnostic_carries_offending_host() {
12806        // Diagnostic-shape pin — the offending host + a non-empty
12807        // reason flow through verbatim so the author can grep their
12808        // caixa.lisp for `:host "<host>"` and fix it in one edit.
12809        let mut s = three_member_spec();
12810        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
12811        let err = s.validate().unwrap_err();
12812        match err {
12813            AplicacaoError::EntradaHostInvalid { host, reason } => {
12814                assert_eq!(host, "checkout.quero.cloud:8080");
12815                assert!(!reason.is_empty(), "reason field must be non-empty");
12816            }
12817            other => panic!("expected EntradaHostInvalid, got {other:?}"),
12818        }
12819    }
12820
12821    #[test]
12822    fn entrada_host_empty_takes_precedence_over_invalid() {
12823        // Ordering pin: `EmptyEntradaHost` is the more self-locating
12824        // diagnostic on `""` and must lead — `validate_entrada_host`
12825        // is only reached after the empty-check fires at the call
12826        // site. (The predicate itself defends against direct
12827        // invocation by returning the same error on `""`.)
12828        let mut s = three_member_spec();
12829        s.entrada.as_mut().unwrap().host = String::new();
12830        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
12831    }
12832
12833    #[test]
12834    fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
12835        // Ordering pin: a missing :para member is the more
12836        // self-locating diagnostic and fires before the host gate.
12837        let mut s = three_member_spec();
12838        let e = s.entrada.as_mut().unwrap();
12839        e.para = "ghost".into();
12840        e.host = "BAD HOST".into();
12841        let err = s.validate().unwrap_err();
12842        assert!(
12843            matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
12844            "got {err:?}"
12845        );
12846    }
12847
12848    #[test]
12849    fn entrada_host_invalid_fires_before_port_zero() {
12850        // Ordering pin: the host gate fires before the port gate so
12851        // a malformed host is named even when the port is also wrong.
12852        let mut s = three_member_spec();
12853        let e = s.entrada.as_mut().unwrap();
12854        e.host = "Checkout.quero.cloud".into();
12855        e.port = 0;
12856        let err = s.validate().unwrap_err();
12857        assert!(
12858            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
12859                if host == "Checkout.quero.cloud"),
12860            "got {err:?}"
12861        );
12862    }
12863
12864    #[test]
12865    fn entrada_accepts_canonical_hosts() {
12866        // Positive-control sweep — every form the Gateway API
12867        // apiserver accepts must round-trip through validate. Covers
12868        // a plain DNS subdomain, a leading wildcard, a single-label
12869        // host (cluster-internal), a max-length-edge label, a
12870        // hyphen-bearing label, and a Punycode IDN label.
12871        for host in [
12872            "checkout.quero.cloud",
12873            "*.quero.cloud",
12874            "checkout",
12875            // 63-byte label — exactly the per-label cap.
12876            "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
12877            "foo-bar.quero.cloud",
12878            // Punycode IDN — valid because the author pre-encoded.
12879            "xn--bcher-kva.example.com",
12880        ] {
12881            let mut s = three_member_spec();
12882            s.entrada.as_mut().unwrap().host = host.into();
12883            s.validate()
12884                .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
12885        }
12886    }
12887
12888    #[test]
12889    fn entrada_host_max_length_validates() {
12890        // 253-byte host is the cap exactly — must validate. Build a
12891        // 253-byte host out of three 63-byte labels + one 61-byte
12892        // label + 3 dots = 252 bytes, then pad one byte to 253.
12893        let mut s = three_member_spec();
12894        let host = format!(
12895            "{}.{}.{}.{}",
12896            "a".repeat(63),
12897            "b".repeat(63),
12898            "c".repeat(63),
12899            "d".repeat(253 - 63 * 3 - 3)
12900        );
12901        assert_eq!(host.len(), 253);
12902        s.entrada.as_mut().unwrap().host = host;
12903        s.validate().unwrap();
12904    }
12905
12906    #[test]
12907    fn entrada_host_total_length_cap_threads_lifted_render_const() {
12908        // Cross-crate-side pin: the aplicacao-side `:entrada :host`
12909        // total-length gate now reads the K8s Gateway API v1 Hostname
12910        // `maxLength: 253` cap from the lifted
12911        // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
12912        // of truth — the same constant every future Gateway-API-Hostname
12913        // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
12914        // materializer's per-host validator, the future per-`Certificate`
12915        // SAN emitter for cert-manager, the multi-`:entrada`
12916        // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
12917        // from. Before the lift, the aplicacao-side reader consumed a
12918        // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
12919        // 253-byte value as the peer render-side canonical bounds
12920        // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
12921        // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
12922        // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
12923        // module boundary — a future 253-byte drift on either side would
12924        // silently split into two axes' worth of admission-schema mismatch
12925        // without a build-time signal. Pin the cap through a fresh 254-
12926        // byte host that hits the total-length arm, then read the reason
12927        // for the exact byte count the shared constant carries: any future
12928        // regression on the lift (a private alias reintroduced, a hard-
12929        // coded literal at the arm, a mismatch between the aplicacao-side
12930        // and render-side canonicals) surfaces as this pin's diagnostic
12931        // failing to match, not as a per-cluster admission rejection far
12932        // from the caixa.lisp source line.
12933        let mut s = three_member_spec();
12934        let over_cap = format!(
12935            "{}.{}.{}.{}",
12936            "a".repeat(63),
12937            "b".repeat(63),
12938            "c".repeat(63),
12939            "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
12940        );
12941        assert_eq!(
12942            over_cap.len(),
12943            crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
12944        );
12945        s.entrada.as_mut().unwrap().host = over_cap;
12946        let err = s.validate().unwrap_err();
12947        match err {
12948            AplicacaoError::EntradaHostInvalid { reason, .. } => {
12949                let needle = format!(
12950                    "max length of {} bytes",
12951                    crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
12952                );
12953                assert!(
12954                    reason.contains(&needle),
12955                    "diagnostic must name the lifted \
12956                     GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
12957                );
12958            }
12959            other => panic!("expected EntradaHostInvalid, got {other:?}"),
12960        }
12961    }
12962
12963    #[test]
12964    fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
12965        // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
12966        // on the per-label-cap axis. Before the lift, the aplicacao-side
12967        // per-label arm consumed a private const alias
12968        // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
12969        // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
12970        // split from it at the module boundary — every `.`-separated
12971        // label in a Gateway API v1 Hostname is a DNS-1123 label under
12972        // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
12973        // so the private alias's 63 and the canonical const's 63 were
12974        // pinning the same underlying rule twice. Pin the cap through a
12975        // 64-byte label that hits the per-label arm, then read the reason
12976        // for the exact byte count the shared constant carries: any
12977        // future drift on either side (a private alias reintroduced, a
12978        // hard-coded literal at the arm, a mismatch between the two
12979        // 63-byte pins) surfaces at this pin's diagnostic rather than at
12980        // a per-cluster admission rejection whose "field is invalid"
12981        // opacity misframes the root cause.
12982        let mut s = three_member_spec();
12983        let over_cap_label = format!(
12984            "{}.quero.cloud",
12985            "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
12986        );
12987        s.entrada.as_mut().unwrap().host = over_cap_label;
12988        let err = s.validate().unwrap_err();
12989        match err {
12990            AplicacaoError::EntradaHostInvalid { reason, .. } => {
12991                let needle = format!(
12992                    "label max length of {} bytes",
12993                    crate::render::DNS_1123_LABEL_MAX_LEN,
12994                );
12995                assert!(
12996                    reason.contains(&needle),
12997                    "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
12998                     cap verbatim on the per-label arm, got: {reason:?}",
12999                );
13000            }
13001            other => panic!("expected EntradaHostInvalid, got {other:?}"),
13002        }
13003    }
13004
13005    #[test]
13006    fn entrada_with_empty_paths_validates() {
13007        // Empty `:paths` is the documented "match every path" form;
13008        // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
13009        let mut s = three_member_spec();
13010        s.entrada.as_mut().unwrap().paths = vec![];
13011        s.validate().unwrap();
13012    }
13013
13014    #[test]
13015    fn entrada_root_path_validates() {
13016        // The author-supplied bare-root `:entrada :paths` entry is the
13017        // same byte-shape the peer emit-side catch-all constant
13018        // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
13019        // the author's `:paths` list is empty — sweeping the test-side
13020        // probe literal onto the lifted const closes the two-axis pin
13021        // (author-side admit + emit-side canonical fallback) around
13022        // one `&'static str`, so a future rebrand of the catch-all
13023        // reaches both consumers by construction. Peer to
13024        // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
13025        // on the canonical-literal pin surface.
13026        let mut s = three_member_spec();
13027        s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
13028        s.validate().unwrap();
13029    }
13030
13031    #[test]
13032    fn placement_strategy_variants_round_trip() {
13033        for s in [
13034            PlacementStrategy::SingleNode,
13035            PlacementStrategy::Replicated,
13036            PlacementStrategy::Sharded,
13037        ] {
13038            let p = Placement {
13039                estrategia: s,
13040                clusters: vec!["rio".into()],
13041                affinity: None,
13042                shard_key: if s.is_sharded() {
13043                    Some("$key".into())
13044                } else {
13045                    None
13046                },
13047            };
13048            let json = serde_json::to_string(&p).unwrap();
13049            let back: Placement = serde_json::from_str(&json).unwrap();
13050            assert_eq!(back, p);
13051        }
13052    }
13053
13054    #[test]
13055    fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
13056        // The fail-before-pass-after pin: pre-lift there was no
13057        // single-source binding between the [`PlacementStrategy`]
13058        // variant name the `Serialize` derive emits and the byte-
13059        // string every downstream cluster-side dispatcher (the
13060        // `lareira-fleet-programs` aggregator's per-entry strategy
13061        // branch, the future `app-operator` reconciler, the M3
13062        // Adaptive compression pass's per-strategy weighting) probes
13063        // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
13064        // future `#[serde(rename_all = "kebab-case")]` attribute on
13065        // the enum — or a variant rename in the source — would
13066        // silently rebrand the emitted scalar under one spelling
13067        // while every downstream dispatcher still probed the other,
13068        // with the failure surfacing at the aggregator's dispatch
13069        // step or the operator's reconcile posture (workloads coming
13070        // up under the `default()` `Replicated` arm rather than the
13071        // typed slot's declared strategy) far from the source
13072        // rebrand commit and with no field naming the drift. Pinning
13073        // the two paths (the `Serialize` derive's serialized string
13074        // AND the [`PlacementStrategy::as_str`] helper) to the same
13075        // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
13076        // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
13077        // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
13078        // makes any future drift on either endpoint fail here at
13079        // caixa-core build time.
13080        for (variant, expected) in [
13081            (
13082                PlacementStrategy::SingleNode,
13083                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
13084            ),
13085            (
13086                PlacementStrategy::Replicated,
13087                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
13088            ),
13089            (
13090                PlacementStrategy::Sharded,
13091                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
13092            ),
13093        ] {
13094            let json = serde_json::to_string(&variant).unwrap();
13095            assert_eq!(
13096                json,
13097                format!("\"{expected}\""),
13098                "PlacementStrategy::{variant:?} must serialize to {expected:?}"
13099            );
13100            assert_eq!(
13101                variant.as_str(),
13102                expected,
13103                "PlacementStrategy::{variant:?}.as_str() must return the lifted \
13104                 M3_PLACEMENT_ESTRATEGIA_* constant"
13105            );
13106        }
13107    }
13108
13109    #[test]
13110    fn m3_placement_estrategia_consts_are_pairwise_distinct() {
13111        // Cross-arm drift-detection pin on the M3
13112        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
13113        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
13114        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
13115        // scalar-value pentad: a future collapse of two canonical
13116        // variant byte-strings onto the same value (an accidental
13117        // copy-paste flip of
13118        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
13119        // read `"SingleNode"`, a per-arm rebrand that lands one const
13120        // without touching its paired peer) would silently reroute
13121        // every downstream operator's per-strategy dispatch onto the
13122        // sibling arm's reconcile branch and pass every
13123        // propagation-probe test that expected only the stale arm's
13124        // value — a `Replicated`-declared Aplicacao would come up
13125        // under the `SingleNode` primary-and-standby reconcile
13126        // posture, so every-cluster active-active workload would
13127        // silently collapse onto one-cluster-runs-at-a-time takeover
13128        // semantics against its declared strategy, with no field
13129        // naming the strategy-value drift root cause. Peer of the
13130        // sibling
13131        // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
13132        // (09ffb2d) /
13133        // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
13134        // (ccdf955) /
13135        // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
13136        // (d739850) distinctness pins on the sibling OTP-shape /
13137        // caixa-kind closed-set typed-enum discriminator axes — the
13138        // fourth (and structurally the M3 mesh-primitive-defining)
13139        // closed-set typed-enum axis to converge on the same
13140        // "pairwise-distinct-by-construction" discipline.
13141        //
13142        // Fail-before-pass-after locally verified by mutating
13143        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
13144        // also read `"SingleNode"` — this pin fires as expected;
13145        // restoring passes.
13146        let all = [
13147            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
13148            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
13149            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
13150        ];
13151        for (i, a) in all.iter().enumerate() {
13152            for (j, b) in all.iter().enumerate() {
13153                if i != j {
13154                    assert_ne!(
13155                        a, b,
13156                        "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
13157                         distinct — got duplicate {a:?} at indices {i} and {j}",
13158                    );
13159                }
13160            }
13161        }
13162    }
13163
13164    #[test]
13165    fn placement_strategy_display_routes_through_as_str_helper() {
13166        // The fail-before-pass-after pin: pre-lift the sibling
13167        // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
13168        // / [`crate::supervisor::RestartPolicy`] both carried a stable
13169        // [`std::fmt::Display`] surface via their
13170        // `#[discriminant(also_display)]` gen-platform derive, but
13171        // [`PlacementStrategy`] did not — every consumer reaching for
13172        // a strategy byte-string past the wire format had to pick
13173        // between three paths ([`PlacementStrategy::as_str`], the
13174        // `Serialize` derive's serialized string, or `format!("{v:?}")`
13175        // on the `Debug` derive), any two of which a future variant
13176        // rename or `#[serde(rename_all = "kebab-case")]` attribute
13177        // would silently desynchronize. Wiring [`std::fmt::Display`]
13178        // through [`PlacementStrategy::as_str`] closes the third path:
13179        // every `format!("{v}")` call reaches the same lifted
13180        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
13181        // and the [`PlacementStrategy::as_str`] helper already route
13182        // through, so a future variant rename lands at exactly one
13183        // place. Pin the routing here so a future
13184        // `impl std::fmt::Display for PlacementStrategy` reimplementation
13185        // that hand-rolls the arms instead of delegating to
13186        // [`PlacementStrategy::as_str`] fails at caixa-core build time.
13187        for variant in [
13188            PlacementStrategy::SingleNode,
13189            PlacementStrategy::Replicated,
13190            PlacementStrategy::Sharded,
13191        ] {
13192            assert_eq!(
13193                variant.to_string(),
13194                variant.as_str(),
13195                "PlacementStrategy::{variant:?} Display must route through \
13196                 PlacementStrategy::as_str (single source of truth: the lifted \
13197                 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
13198            );
13199        }
13200    }
13201
13202    #[test]
13203    fn placement_strategy_display_matches_serialized_wire_byte_string() {
13204        // The fail-before-pass-after pin on the second half of the
13205        // three-path convergence: `Display` (user-facing text) agrees
13206        // byte-for-byte with the `Serialize` derive's wire format
13207        // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
13208        // scalar) on every variant. Pre-lift the two paths were
13209        // structurally independent — a future
13210        // `#[serde(rename_all = "kebab-case")]` attribute on the enum
13211        // would silently rebrand the emitted wire scalar
13212        // (`single-node`, `replicated`, `sharded`) while every consumer
13213        // that pretty-prints the strategy (the M3 diagnostic templates,
13214        // the future `feira app graph` per-Aplicacao strategy line,
13215        // the future M4 CR materializer's admission-webhook rejection
13216        // body) would still emit the TitleCase form the `as_str` /
13217        // `Display` route returns, with the mismatch surfacing at
13218        // consumer parse time / operator dispatch time far from the
13219        // source rebrand commit. Pin the two paths byte-for-byte here
13220        // so any future serde-attribute or variant-rename drift is a
13221        // caixa-core-build-time test failure at this call, not a
13222        // silent per-consumer dispatch miss.
13223        for variant in [
13224            PlacementStrategy::SingleNode,
13225            PlacementStrategy::Replicated,
13226            PlacementStrategy::Sharded,
13227        ] {
13228            let wire = serde_json::to_string(&variant).unwrap();
13229            // Strip the outer `"…"` the JSON string form carries — the
13230            // wire scalar the K8s / YAML apiserver consumes is the
13231            // enclosed byte-string, not the quote wrapper.
13232            let unquoted = wire
13233                .strip_prefix('"')
13234                .and_then(|s| s.strip_suffix('"'))
13235                .expect("serialized PlacementStrategy is a JSON string");
13236            assert_eq!(
13237                variant.to_string(),
13238                unquoted,
13239                "PlacementStrategy::{variant:?} Display byte-string must match the \
13240                 Serialize derive's wire byte-string (three-path convergence: \
13241                 Display + as_str + Serialize all resolve to the same \
13242                 M3_PLACEMENT_ESTRATEGIA_* const)"
13243            );
13244        }
13245    }
13246
13247    #[test]
13248    fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
13249        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
13250        // derive on [`PlacementStrategy`]: for each of the three variants
13251        // exactly one of the generated `is_single_node` / `is_replicated`
13252        // / `is_sharded` predicates returns `true` and the other two
13253        // return `false`. Prior to this derive the three per-arm
13254        // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
13255        // (the `placement_strategy_variants_round_trip` fixture, the
13256        // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
13257        // fixture, and the
13258        // `validate_placement_reads_through_lifted_estrategia_accessor`
13259        // fixture) each open-coded a per-arm PartialEq compare against
13260        // the enum variant — three sites that expressed no compile-time
13261        // link back to the closed-set typed dispatch a future fourth
13262        // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
13263        // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
13264        // would have to thread through in lockstep or one fixture would
13265        // silently disagree with the others on which arms consume the
13266        // `:shard-key` axis. Peer of the sibling
13267        // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
13268        // / [`crate::supervisor::RestartPolicy`] /
13269        // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
13270        // the sibling closed-set typed-enum discriminator axes — extends
13271        // the same one-typed-dispatch-per-variant discipline onto the
13272        // fifth (and only remaining) closed-set typed-enum discriminator
13273        // on the caixa surface, closing the axis on the M3 mesh-slot
13274        // family.
13275        let rows: [(PlacementStrategy, [bool; 3]); 3] = [
13276            (PlacementStrategy::SingleNode, [true, false, false]),
13277            (PlacementStrategy::Replicated, [false, true, false]),
13278            (PlacementStrategy::Sharded, [false, false, true]),
13279        ];
13280        for (variant, expected) in rows {
13281            let observed = [
13282                variant.is_single_node(),
13283                variant.is_replicated(),
13284                variant.is_sharded(),
13285            ];
13286            assert_eq!(
13287                observed, expected,
13288                "PlacementStrategy::{variant:?} is_* predicates must partition \
13289                 the arm set (single_node, replicated, sharded); got {observed:?}"
13290            );
13291        }
13292    }
13293
13294    #[test]
13295    fn placement_strategy_is_variant_predicates_are_const_fn() {
13296        // The [`gen_platform::IsVariant`] derive emits `const fn`
13297        // predicates on the peer [`crate::CaixaKind`] +
13298        // [`crate::upgrade::UpgradeInstruction`] +
13299        // [`crate::supervisor::RestartStrategy`] +
13300        // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
13301        // pin the same posture on [`PlacementStrategy`] so a future
13302        // accidental downgrade to non-`const` (an added runtime helper
13303        // reachable only from a non-`const` context, a manual hand-rolled
13304        // `impl` that shadows the derive-generated method) trips at
13305        // caixa-core build time rather than surfacing as a downstream
13306        // `const`-context regression far from the derive declaration.
13307        const IS_SINGLE_NODE: bool = PlacementStrategy::SingleNode.is_single_node();
13308        const IS_REPLICATED: bool = PlacementStrategy::Replicated.is_replicated();
13309        const IS_SHARDED: bool = PlacementStrategy::Sharded.is_sharded();
13310        assert!(IS_SINGLE_NODE);
13311        assert!(IS_REPLICATED);
13312        assert!(IS_SHARDED);
13313    }
13314
13315    #[test]
13316    fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
13317        // Pin the M3 diagnostic template routes through the typed
13318        // [`PlacementStrategy`] Display byte-string (rebound from the
13319        // prior `{estrategia:?}` `Debug` route). Pre-lift the two
13320        // routes emitted identical bytes (the `Debug` derive on a
13321        // unit variant emits the variant name verbatim, exactly what
13322        // `as_str` returns), but the two paths were structurally
13323        // independent — a future `#[serde(rename_all = "…")]`
13324        // attribute or variant rename would coordinate the wire /
13325        // `Display` / `as_str` triple through the lifted const but
13326        // leave the `Debug` route on the compiler-derived variant name,
13327        // silently desynchronizing the diagnostic byte-string from the
13328        // wire byte-string. Rebinding the template onto `Display`
13329        // ties the diagnostic to the same lifted
13330        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
13331        // emits — drift becomes structurally impossible. Pin the
13332        // byte-string here so a future edit that reverts the template
13333        // to `{estrategia:?}` is caught at caixa-core test time, not
13334        // at consumer dispatch time.
13335        for (variant, expected_scalar) in [
13336            (
13337                PlacementStrategy::SingleNode,
13338                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
13339            ),
13340            (
13341                PlacementStrategy::Replicated,
13342                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
13343            ),
13344            (
13345                PlacementStrategy::Sharded,
13346                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
13347            ),
13348        ] {
13349            let err = AplicacaoError::PlacementWithoutClusters {
13350                estrategia: variant,
13351            };
13352            let msg = err.to_string();
13353            assert!(
13354                msg.starts_with(&format!(":placement {expected_scalar} requires")),
13355                "PlacementWithoutClusters diagnostic for {variant:?} must open \
13356                 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
13357            );
13358        }
13359    }
13360
13361    #[test]
13362    fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
13363        // Peer of
13364        // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
13365        // on the second M3 diagnostic that carries the typed
13366        // [`PlacementStrategy`] in its `#[error(…)]` template. Both
13367        // diagnostics now route the strategy scalar through the same
13368        // [`std::fmt::Display`] surface, tying the diagnostic
13369        // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
13370        // const set the wire format also emits. The two non-Sharded
13371        // arms are exercised here (the diagnostic exists to flag a
13372        // `:shard-key` slot the current strategy will never consume);
13373        // the peer `Sharded` arm never reaches this diagnostic (the
13374        // `Sharded` strategy consumes `:shard-key` — the
13375        // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
13376        // slot instead).
13377        for (variant, expected_scalar) in [
13378            (
13379                PlacementStrategy::SingleNode,
13380                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
13381            ),
13382            (
13383                PlacementStrategy::Replicated,
13384                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
13385            ),
13386        ] {
13387            let err = AplicacaoError::ShardKeyOnNonSharded {
13388                estrategia: variant,
13389                shard_key: "$tenantId".into(),
13390            };
13391            let msg = err.to_string();
13392            assert!(
13393                msg.starts_with(&format!(":placement {expected_scalar} carries")),
13394                "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
13395                 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
13396            );
13397        }
13398    }
13399
13400    #[test]
13401    fn placement_strategy_all_enumerates_every_variant_once() {
13402        // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
13403        // exhaustive-iteration surface: every variant appears exactly
13404        // once, and the slice length matches the arm count of the
13405        // closed set. Every consumer that walks the accepted-strategy
13406        // set (a future `feira app placement --list` CLI-side surfacing,
13407        // a future M4 admission-webhook's rejection body naming the
13408        // accepted-strategy list, the [`PlacementStrategy::from_wire`]
13409        // reverse-projection consumers that iterate the accept-set for
13410        // a "did you mean" hint) reads through this slice, so a future
13411        // variant addition (an `Anycast` mesh-anycast arm the
13412        // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
13413        // grows the enum but forgets to grow [`Self::ALL`] silently
13414        // truncates every downstream consumer's accept-set at the same
13415        // pre-addition boundary — this pin fails at caixa-core build
13416        // time on the pairwise-distinct + arm-count invariants.
13417        //
13418        // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
13419        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
13420        // pins on the peer closed-set typed-enum axes.
13421        let all: &[PlacementStrategy] = PlacementStrategy::ALL;
13422        assert_eq!(
13423            all.len(),
13424            3,
13425            "PlacementStrategy::ALL must enumerate every variant of the \
13426             three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
13427        );
13428        for (i, a) in all.iter().enumerate() {
13429            for (j, b) in all.iter().enumerate() {
13430                if i != j {
13431                    assert_ne!(
13432                        a, b,
13433                        "PlacementStrategy::ALL must carry every variant exactly \
13434                         once — got duplicate {a:?} at indices {i} and {j}"
13435                    );
13436                }
13437            }
13438        }
13439        for variant in [
13440            PlacementStrategy::SingleNode,
13441            PlacementStrategy::Replicated,
13442            PlacementStrategy::Sharded,
13443        ] {
13444            assert!(
13445                all.contains(&variant),
13446                "PlacementStrategy::ALL must contain {variant:?} — a future variant \
13447                 addition that grows the enum but forgets to grow the ALL slice \
13448                 silently truncates every downstream consumer's accept-set at the \
13449                 pre-addition boundary"
13450            );
13451        }
13452    }
13453
13454    #[test]
13455    fn placement_strategy_from_wire_accepts_every_lifted_constant() {
13456        // Fail-before-pass-after pin on the forward accept-set of the
13457        // [`PlacementStrategy::from_wire`] reverse projection: every
13458        // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
13459        // constant the [`PlacementStrategy::as_str`] emitter walks
13460        // parses back to its paired variant. Any future arm addition
13461        // that grows the emitter's `as_str` match but forgets to grow
13462        // the parser's `from_str` match silently splits the two halves
13463        // of the round-trip — the wire byte-string one non-serde
13464        // consumer parses from the one the emitter wrote — with the
13465        // failure surfacing at parse time far from the rebrand commit.
13466        // Pinning the three-arm accept-set here catches the drift at
13467        // caixa-core build time.
13468        //
13469        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
13470        // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
13471        // closed-set typed-enum `str → Self` axes.
13472        for (wire, expected) in [
13473            (
13474                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
13475                PlacementStrategy::SingleNode,
13476            ),
13477            (
13478                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
13479                PlacementStrategy::Replicated,
13480            ),
13481            (
13482                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
13483                PlacementStrategy::Sharded,
13484            ),
13485        ] {
13486            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
13487                panic!(
13488                    "PlacementStrategy::from_wire({wire:?}) must accept every \
13489                     M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
13490                     lifted canonical byte-string that PlacementStrategy::{expected:?} \
13491                     serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
13492                )
13493            });
13494            assert_eq!(
13495                parsed, expected,
13496                "PlacementStrategy::from_wire({wire:?}) must return \
13497                 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
13498            );
13499        }
13500    }
13501
13502    #[test]
13503    fn placement_strategy_from_wire_round_trips_through_as_str() {
13504        // Fail-before-pass-after pin on the closed round-trip between
13505        // the forward [`PlacementStrategy::as_str`] emitter and the
13506        // reverse [`PlacementStrategy::from_wire`] parser: for every
13507        // variant in [`PlacementStrategy::ALL`], parsing the emitter's
13508        // output must return exactly the same variant. Any per-arm
13509        // divergence — a future arm added to `as_str` but not
13510        // `from_str`, an accidental copy-paste flip in one but not the
13511        // other — silently splits the emit and parse halves and the
13512        // failure surfaces at consumer parse time far from the drift
13513        // site. The `ALL`-iterating shape means a future variant
13514        // addition picks up the coverage by construction.
13515        //
13516        // Peer of the sibling [`crate::kind::tests`] round-trip pin on
13517        // [`crate::CaixaKind::from_wire`] and the
13518        // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
13519        // sibling round-trip pin on [`RateLimitUnit`].
13520        for &variant in PlacementStrategy::ALL {
13521            let wire = variant.as_str();
13522            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
13523                panic!(
13524                    "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
13525                     must be Some({variant:?}) — the two halves of the round-trip \
13526                     dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
13527                     got None on wire byte-string {wire:?}"
13528                )
13529            });
13530            assert_eq!(
13531                parsed, variant,
13532                "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
13533                 must round-trip to the same variant; got {parsed:?}"
13534            );
13535        }
13536    }
13537
13538    #[test]
13539    fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
13540        // Fail-before-pass-after pin on the closed-set refusal
13541        // discipline of [`PlacementStrategy::from_wire`]: every
13542        // byte-string outside the three-arm accept-set returns `None`
13543        // rather than silently collapsing onto the [`Default`]
13544        // (`Replicated`) arm or an arbitrary neighbor. The refusal set
13545        // exercised here sweeps the load-bearing drift shapes: the
13546        // empty string (a stripped serde-attribute drift), an all-
13547        // whitespace string (the canonical text-editor accidental
13548        // padding shape), the lowercased kebab-case forms a future
13549        // `#[serde(rename_all = "kebab-case")]` attribute would emit
13550        // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
13551        // coincidentally match the accepted canonical scalars, so only
13552        // `"single-node"` fires as a refusal, but pinning the case-
13553        // sensitivity of the accepted arms via the peer [`SingleNode`]
13554        // assertion in the round-trip pin makes the discipline
13555        // structurally clear), the lowercased single-word forms
13556        // (`"singlenode"`), the padded canonical scalar
13557        // (`" Sharded "`), the trailing-comma / trailing-newline shapes
13558        // (`"Sharded\n"`), and a pointer-different `&'static str` that
13559        // happens to alias a canonical byte-string by content but not
13560        // by identity (validated implicitly by the emitter's routing
13561        // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
13562        // identity a paired [`crate::assert_str_reexport_identity`] pin
13563        // in caixa-core's per-const declaration surface would catch).
13564        //
13565        // Peer of the sibling
13566        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
13567        // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
13568        for bad in [
13569            "",
13570            " ",
13571            "\n",
13572            "\t",
13573            "single-node",
13574            "singlenode",
13575            "SingleNodes",
13576            "single_node",
13577            "single node",
13578            "SINGLENODE",
13579            "SingleNode ",
13580            " SingleNode",
13581            " Sharded ",
13582            "Sharded\n",
13583            "replicated ",
13584            "sharded",
13585            "REPLICATED",
13586            "Anycast",
13587            "Global",
13588            "?",
13589        ] {
13590            assert!(
13591                PlacementStrategy::from_wire(bad).is_none(),
13592                "PlacementStrategy::from_wire({bad:?}) must return None — the \
13593                 parser's accept-set is exactly the three PlacementStrategy::as_str \
13594                 outputs (SingleNode, Replicated, Sharded), and this byte-string \
13595                 is outside that closed set"
13596            );
13597        }
13598    }
13599
13600    #[test]
13601    fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
13602        // Fail-before-pass-after pin on the third path of the four-path
13603        // convergence: `from_str` (the reverse projection) inverts the
13604        // `Serialize` derive's wire byte-string on every variant.
13605        // Together with the pre-existing three-path convergence
13606        // (`Display` + `as_str` + `Serialize` all resolve to the same
13607        // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
13608        // the peer
13609        // [`placement_strategy_display_matches_serialized_wire_byte_string`])
13610        // this closes the round-trip: the wire byte-string the
13611        // `Serialize` derive emits parses back to the same variant
13612        // through `from_str`, so any future serde-attribute or variant-
13613        // rename drift on the emit half now surfaces as a matched drift
13614        // on the parse half at caixa-core build time — the two halves
13615        // migrate as a unit through the lifted consts on any future
13616        // rename, and the round-trip cannot silently split.
13617        //
13618        // Peer of the sibling
13619        // [`placement_strategy_display_matches_serialized_wire_byte_string`]
13620        // wire-format pin — extends the three-path convergence
13621        // (`Display` + `as_str` + `Serialize`) onto the fourth path
13622        // (`from_str`), closing the `str ↔ Self` round-trip on the
13623        // M3 `:placement :estrategia` closed-set axis.
13624        for &variant in PlacementStrategy::ALL {
13625            let wire = serde_json::to_string(&variant).unwrap();
13626            let unquoted = wire
13627                .strip_prefix('"')
13628                .and_then(|s| s.strip_suffix('"'))
13629                .expect("serialized PlacementStrategy is a JSON string");
13630            let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
13631                panic!(
13632                    "PlacementStrategy::from_wire({unquoted:?}) must accept the \
13633                     Serialize derive's wire byte-string for \
13634                     PlacementStrategy::{variant:?} — the four-path convergence \
13635                     (Display + as_str + Serialize + from_str) resolves through \
13636                     the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
13637                )
13638            });
13639            assert_eq!(
13640                parsed, variant,
13641                "PlacementStrategy::from_wire of the Serialize derive's wire \
13642                 byte-string for PlacementStrategy::{variant:?} must round-trip \
13643                 to the same variant; got {parsed:?}"
13644            );
13645        }
13646    }
13647
13648    #[test]
13649    fn rejects_zero_policy_timeout() {
13650        let mut s = three_member_spec();
13651        s.politicas.timeout = Some(Duration::ZERO);
13652        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
13653    }
13654
13655    #[test]
13656    fn rejects_zero_policy_retries() {
13657        let mut s = three_member_spec();
13658        s.politicas.retries = Some(0);
13659        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
13660    }
13661
13662    #[test]
13663    fn rejects_policy_retries_above_cap() {
13664        // The fail-before-pass-after pin: `Some(11)` is structurally
13665        // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
13666        // passed validate on every pre-gate codebase because the
13667        // typed slot's only check was the zero-floor arm. The
13668        // thundering-herd amplification vector only surfaced at the
13669        // runtime substrate (Envoy / Cilium L7 retry overlay)
13670        // far from the source caixa.lisp with no field naming the
13671        // offending policy.
13672        let mut s = three_member_spec();
13673        s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
13674        assert_eq!(
13675            s.validate().unwrap_err(),
13676            AplicacaoError::PolicyRetriesExceedsCap {
13677                retries: POLICY_RETRIES_MAX + 1
13678            }
13679        );
13680    }
13681
13682    #[test]
13683    fn rejects_policy_retries_far_above_cap() {
13684        // The `u32::MAX` worst case — the four-billion-retry policy
13685        // a typo (`(:retries 4294967295)`) or struct-literal
13686        // copy-paste lands in the slot. Pin the cap arm's coverage
13687        // explicitly across the full `u32` overflow so a future
13688        // relaxation that drops the upper bound surfaces here.
13689        let mut s = three_member_spec();
13690        s.politicas.retries = Some(u32::MAX);
13691        assert_eq!(
13692            s.validate().unwrap_err(),
13693            AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
13694        );
13695    }
13696
13697    #[test]
13698    fn accepts_policy_retries_at_cap() {
13699        // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
13700        // must validate. The cap is inclusive on the top edge,
13701        // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
13702        // discipline on the sibling [`crate::LimitsSpec::memory`]
13703        // axis. Pin the boundary explicitly so a future off-by-one
13704        // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
13705        // surfaces here as a test failure rather than a silent
13706        // contract narrowing.
13707        let mut s = three_member_spec();
13708        s.politicas.retries = Some(POLICY_RETRIES_MAX);
13709        s.validate()
13710            .expect("retries == POLICY_RETRIES_MAX must validate");
13711    }
13712
13713    #[test]
13714    fn accepts_policy_retries_typical_values() {
13715        // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
13716        // every value in the validated set must pass. The
13717        // Envoy / Istio production-playbook recommendation band
13718        // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
13719        // (`maxRetries ≤ 10`) both lie within this set.
13720        for r in 1..=POLICY_RETRIES_MAX {
13721            let mut s = three_member_spec();
13722            s.politicas.retries = Some(r);
13723            s.validate()
13724                .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
13725        }
13726    }
13727
13728    #[test]
13729    fn policy_retries_zero_takes_precedence_over_cap() {
13730        // The cross-arm ordering pin: `Some(0)` is structurally
13731        // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
13732        // (cap), but the zero-floor diagnostic is the more
13733        // self-locating one (it directly names the omit-axis
13734        // remediation), so the validate gate must fire on zero
13735        // first. Pin the order so a future refactor that reorders
13736        // the arms surfaces here as a test failure rather than a
13737        // silent diagnostic regression. Same shape every other
13738        // zero-then-shape ordering on this surface uses
13739        // ([`AplicacaoError::PolicyTimeoutZero`] then
13740        // [`AplicacaoError::PolicyTimeoutNotCanonical`];
13741        // [`AplicacaoError::PolicyBreakerZeroWindow`] then
13742        // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
13743        let mut s = three_member_spec();
13744        s.politicas.retries = Some(0);
13745        assert_eq!(
13746            s.validate().unwrap_err(),
13747            AplicacaoError::PolicyRetriesZero,
13748            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
13749        );
13750    }
13751
13752    #[test]
13753    fn policy_retries_cap_diagnostic_carries_offending_value() {
13754        // The diagnostic-shape pin: the offending `u32` is carried
13755        // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
13756        // variant so the surfaced error message names the value the
13757        // author wrote (`":politicas :retries (47) exceeds the
13758        // mesh-policy ceiling …"`), not just the cap. Same
13759        // self-locating diagnostic shape every other typed-cap arm
13760        // on this surface carries
13761        // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
13762        // offending byte count verbatim).
13763        let mut s = three_member_spec();
13764        s.politicas.retries = Some(47);
13765        let err = s.validate().unwrap_err();
13766        assert!(
13767            matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
13768            "got {err:?}"
13769        );
13770        let msg = err.to_string();
13771        assert!(
13772            msg.contains("47"),
13773            ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
13774        );
13775    }
13776
13777    #[test]
13778    fn policy_retries_cap_is_aws_app_mesh_aligned() {
13779        // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
13780        // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
13781        // schema cap — the only upstream mesh-policy schema that
13782        // documents an explicit hard cap. Pinning the literal value
13783        // here surfaces a future drift (a relaxation to 20, a
13784        // tightening to 5) as a deliberate test edit, not a silent
13785        // contract narrowing.
13786        assert_eq!(POLICY_RETRIES_MAX, 10);
13787    }
13788
13789    #[test]
13790    fn rejects_circuit_breaker_zero_max_failures() {
13791        let mut s = three_member_spec();
13792        s.politicas.circuit_breaker = Some(CircuitBreaker {
13793            max_failures: 0,
13794            window: Duration::from_secs(60),
13795        });
13796        assert_eq!(
13797            s.validate().unwrap_err(),
13798            AplicacaoError::PolicyBreakerZeroFailures
13799        );
13800    }
13801
13802    #[test]
13803    fn rejects_circuit_breaker_max_failures_above_cap() {
13804        // The fail-before-pass-after pin: `1001` is structurally one
13805        // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
13806        // silently passed validate on every pre-gate codebase
13807        // because the typed slot's only check was the zero-floor
13808        // arm. The breaker-no-op vector only surfaced at the runtime
13809        // substrate (Envoy / Cilium L7 outlier-detection overlay)
13810        // far from the source caixa.lisp with no field naming the
13811        // offending policy.
13812        let mut s = three_member_spec();
13813        s.politicas.circuit_breaker = Some(CircuitBreaker {
13814            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
13815            window: Duration::from_secs(60),
13816        });
13817        assert_eq!(
13818            s.validate().unwrap_err(),
13819            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
13820                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
13821            }
13822        );
13823    }
13824
13825    #[test]
13826    fn rejects_circuit_breaker_max_failures_far_above_cap() {
13827        // The `u32::MAX` worst case — the four-billion-failure
13828        // threshold a typo (`(:max-failures 4294967295)`) or a
13829        // struct-literal copy-paste lands in the slot. Pin the cap
13830        // arm's coverage explicitly across the full `u32` overflow
13831        // so a future relaxation that drops the upper bound surfaces
13832        // here.
13833        let mut s = three_member_spec();
13834        s.politicas.circuit_breaker = Some(CircuitBreaker {
13835            max_failures: u32::MAX,
13836            window: Duration::from_secs(60),
13837        });
13838        assert_eq!(
13839            s.validate().unwrap_err(),
13840            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
13841                max_failures: u32::MAX,
13842            }
13843        );
13844    }
13845
13846    #[test]
13847    fn accepts_circuit_breaker_max_failures_at_cap() {
13848        // The boundary value — exactly
13849        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
13850        // cap is inclusive on the top edge, matching the
13851        // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
13852        // discipline on the sibling capped axes. Pin the boundary
13853        // explicitly so a future off-by-one tightening
13854        // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
13855        // surfaces here as a test failure rather than a silent
13856        // contract narrowing.
13857        let mut s = three_member_spec();
13858        s.politicas.circuit_breaker = Some(CircuitBreaker {
13859            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
13860            window: Duration::from_secs(60),
13861        });
13862        s.validate()
13863            .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
13864    }
13865
13866    #[test]
13867    fn accepts_circuit_breaker_max_failures_typical_values() {
13868        // The documented production-playbook band positive-control
13869        // sweep — every value Hystrix / Istio / Envoy / Polly /
13870        // Resilience4j recommend (5..=50) must pass, plus a sweep
13871        // through the hyperscale band (100, 500, 1000) the cap
13872        // accepts. Pin the inclusive validated set explicitly so a
13873        // future tightening of the ceiling surfaces here.
13874        for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
13875            let mut s = three_member_spec();
13876            s.politicas.circuit_breaker = Some(CircuitBreaker {
13877                max_failures: n,
13878                window: Duration::from_secs(60),
13879            });
13880            s.validate()
13881                .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
13882        }
13883    }
13884
13885    #[test]
13886    fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
13887        // The cross-arm ordering pin: `0` is structurally outside
13888        // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
13889        // (cap), but the zero-floor diagnostic is the more
13890        // self-locating one (it directly names the omit-axis
13891        // remediation), so the validate gate must fire on zero
13892        // first. Same shape every other zero-then-shape ordering on
13893        // this surface uses
13894        // ([`AplicacaoError::PolicyRetriesZero`] then
13895        // [`AplicacaoError::PolicyRetriesExceedsCap`];
13896        // [`AplicacaoError::PolicyTimeoutZero`] then
13897        // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
13898        let mut s = three_member_spec();
13899        s.politicas.circuit_breaker = Some(CircuitBreaker {
13900            max_failures: 0,
13901            window: Duration::from_secs(60),
13902        });
13903        assert_eq!(
13904            s.validate().unwrap_err(),
13905            AplicacaoError::PolicyBreakerZeroFailures,
13906            "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
13907        );
13908    }
13909
13910    #[test]
13911    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
13912        // The cross-arm ordering pin between the cap and the
13913        // sibling `:window` gates (zero-window, canonical-window).
13914        // A breaker carrying both an over-cap `max_failures` AND a
13915        // structurally invalid window (zero, sub-ms) must surface
13916        // the cap diagnostic first — the cap arm is wired
13917        // immediately after the zero-failure arm and strictly
13918        // before the window arms, so the offending value the
13919        // diagnostic names matches the order the author would
13920        // discover the gates by reading top-to-bottom through
13921        // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
13922        // future refactor that reorders the arms surfaces here as a
13923        // test failure rather than a silent diagnostic regression.
13924        let mut s = three_member_spec();
13925        s.politicas.circuit_breaker = Some(CircuitBreaker {
13926            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
13927            window: Duration::ZERO,
13928        });
13929        assert_eq!(
13930            s.validate().unwrap_err(),
13931            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
13932                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
13933            },
13934            "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
13935        );
13936    }
13937
13938    #[test]
13939    fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
13940        // The diagnostic-shape pin: the offending `u32` is carried
13941        // verbatim into the
13942        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
13943        // variant so the surfaced error message names the value the
13944        // author wrote (`":politicas :circuit-breaker :max-failures
13945        // (50000) exceeds the mesh-policy ceiling …"`), not just
13946        // the cap. Same self-locating diagnostic shape every other
13947        // typed-cap arm on this surface carries
13948        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
13949        // offending retry count verbatim,
13950        // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
13951        // offending byte count verbatim).
13952        let mut s = three_member_spec();
13953        s.politicas.circuit_breaker = Some(CircuitBreaker {
13954            max_failures: 50_000,
13955            window: Duration::from_secs(60),
13956        });
13957        let err = s.validate().unwrap_err();
13958        assert!(
13959            matches!(
13960                err,
13961                AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
13962                    max_failures: 50_000
13963                }
13964            ),
13965            "got {err:?}"
13966        );
13967        let msg = err.to_string();
13968        assert!(
13969            msg.contains("50000"),
13970            ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
13971        );
13972    }
13973
13974    #[test]
13975    fn policy_breaker_max_failures_cap_pins_canonical_value() {
13976        // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
13977        // value at 1000 — an order of magnitude above every
13978        // documented production-playbook recommendation band
13979        // (Hystrix `requestVolumeThreshold` default 20, Istio
13980        // `outlierDetection.consecutive5xxErrors` default 5, Envoy
13981        // `outlier_detection.consecutive_5xx` default 5, Polly /
13982        // Resilience4j typical 5..=50) and below the
13983        // clearly-pathological "effectively no protection" floor
13984        // (10_000, 100_000, u32::MAX). Pinning the literal value
13985        // here surfaces a future drift (a relaxation to 10_000, a
13986        // tightening to 100) as a deliberate test edit, not a
13987        // silent contract narrowing.
13988        assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
13989    }
13990
13991    #[test]
13992    fn rejects_circuit_breaker_zero_window() {
13993        let mut s = three_member_spec();
13994        s.politicas.circuit_breaker = Some(CircuitBreaker {
13995            max_failures: 5,
13996            window: Duration::ZERO,
13997        });
13998        assert_eq!(
13999            s.validate().unwrap_err(),
14000            AplicacaoError::PolicyBreakerZeroWindow
14001        );
14002    }
14003
14004    #[test]
14005    fn rejects_zero_rate_limit() {
14006        let mut s = three_member_spec();
14007        s.politicas.rate_limit = Some(RateLimit {
14008            rate: 0,
14009            window: Duration::from_secs(1),
14010        });
14011        assert_eq!(
14012            s.validate().unwrap_err(),
14013            AplicacaoError::PolicyRateLimitZero
14014        );
14015    }
14016
14017    #[test]
14018    fn rejects_rate_limit_zero_window() {
14019        // `RateLimit { rate: 100, window: Duration::ZERO }` is
14020        // constructible programmatically (the typed `Duration` field
14021        // imposes no nonzero invariant) but renders through
14022        // `rate_limit_codec::render` as `"100/0s"` — a fragment the
14023        // codec's `parse` rejects as `unknown rate-limit window unit
14024        // "0s"`. Until this validate-time gate landed the typed slot
14025        // accepted the value silently and the round-trip break only
14026        // surfaced at deserialize time (potentially in a downstream
14027        // consumer that never re-validates). Pin the rejection at
14028        // `AplicacaoSpec::validate` so the typed slot's valid set
14029        // matches the codec's round-trippable set structurally.
14030        let mut s = three_member_spec();
14031        s.politicas.rate_limit = Some(RateLimit {
14032            rate: 100,
14033            window: Duration::ZERO,
14034        });
14035        assert_eq!(
14036            s.validate().unwrap_err(),
14037            AplicacaoError::PolicyRateLimitWindowNotCanonical {
14038                window: Duration::ZERO
14039            }
14040        );
14041    }
14042
14043    #[test]
14044    fn rejects_rate_limit_arbitrary_seconds_window() {
14045        // 45 seconds is a valid `Duration` but not one of the three
14046        // canonical rate-limit windows the codec round-trips
14047        // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
14048        // refuses on round-trip — same round-trip-break shape the
14049        // zero-window arm above pins, with a non-zero magnitude to
14050        // guard against a future "reject only zero" half-measure.
14051        let mut s = three_member_spec();
14052        let window = Duration::from_secs(45);
14053        s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
14054        assert_eq!(
14055            s.validate().unwrap_err(),
14056            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
14057        );
14058    }
14059
14060    #[test]
14061    fn rejects_rate_limit_two_minute_window() {
14062        // 120 seconds = 2 minutes is a "looks-canonical" but
14063        // not-canonical window: it's a clean integer multiple of the
14064        // minute unit, but the codec only round-trips the
14065        // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
14066        // A `Duration::from_secs(120)` window renders as `"100/120s"`
14067        // which the parser rejects. Pinning this case rules out a
14068        // future "accept any clean multiple of s/m/h" relaxation
14069        // that would silently break the codec contract.
14070        let mut s = three_member_spec();
14071        let window = Duration::from_secs(120);
14072        s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
14073        assert_eq!(
14074            s.validate().unwrap_err(),
14075            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
14076        );
14077    }
14078
14079    #[test]
14080    fn rejects_rate_limit_subsecond_window() {
14081        // A sub-second window (e.g. 500ms) is a valid `Duration` but
14082        // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
14083        // Pin the rejection so a future relaxation can't silently
14084        // admit fractional-second windows that the codec can't
14085        // round-trip.
14086        let mut s = three_member_spec();
14087        let window = Duration::from_millis(500);
14088        s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
14089        assert_eq!(
14090            s.validate().unwrap_err(),
14091            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
14092        );
14093    }
14094
14095    #[test]
14096    fn rejects_policy_rate_limit_above_cap() {
14097        // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
14098        // is structurally one past the cap and silently passed
14099        // validate on every pre-gate codebase because the typed slot's
14100        // only `rate` check was the zero-floor arm. The no-op-limiter
14101        // shape only surfaced at the runtime substrate (Envoy's
14102        // `local_rate_limit.token_bucket.max_tokens`, the future
14103        // Cilium L7 rate-limit overlay) far from the source caixa.lisp
14104        // with no field naming the offending policy.
14105        let mut s = three_member_spec();
14106        s.politicas.rate_limit = Some(RateLimit {
14107            rate: POLICY_RATE_LIMIT_MAX + 1,
14108            window: Duration::from_secs(1),
14109        });
14110        assert_eq!(
14111            s.validate().unwrap_err(),
14112            AplicacaoError::PolicyRateLimitExceedsCap {
14113                rate: POLICY_RATE_LIMIT_MAX + 1
14114            }
14115        );
14116    }
14117
14118    #[test]
14119    fn rejects_policy_rate_limit_far_above_cap() {
14120        // The `u32::MAX` worst case — the four-billion-token rate-limit
14121        // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
14122        // copy-paste lands in the slot. Pin the cap arm's coverage
14123        // explicitly across the full `u32` overflow so a future
14124        // relaxation that drops the upper bound surfaces here. Peer to
14125        // `rejects_policy_retries_far_above_cap` on the sibling
14126        // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
14127        // on the sibling `:max-failures` axis.
14128        let mut s = three_member_spec();
14129        s.politicas.rate_limit = Some(RateLimit {
14130            rate: u32::MAX,
14131            window: Duration::from_secs(1),
14132        });
14133        assert_eq!(
14134            s.validate().unwrap_err(),
14135            AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
14136        );
14137    }
14138
14139    #[test]
14140    fn accepts_policy_rate_limit_at_cap() {
14141        // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
14142        // must validate. The cap is inclusive on the top edge, matching
14143        // every other typed upper bound in this crate
14144        // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
14145        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
14146        // across all three canonical windows so a future off-by-one
14147        // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
14148        // window-conditional cap surfaces here as a test failure rather
14149        // than a silent contract narrowing.
14150        for secs in [1u64, 60, 3600] {
14151            let mut s = three_member_spec();
14152            s.politicas.rate_limit = Some(RateLimit {
14153                rate: POLICY_RATE_LIMIT_MAX,
14154                window: Duration::from_secs(secs),
14155            });
14156            s.validate().unwrap_or_else(|e| {
14157                panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
14158            });
14159        }
14160    }
14161
14162    #[test]
14163    fn accepts_policy_rate_limit_typical_values() {
14164        // The documented production-playbook recommendation band —
14165        // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
14166        // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
14167        // Enterprise ~1M per-hour. Every value in the validated set
14168        // must pass; pin the band explicitly so a future tightening
14169        // surfaces here.
14170        for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
14171            for secs in [1u64, 60, 3600] {
14172                let mut s = three_member_spec();
14173                s.politicas.rate_limit = Some(RateLimit {
14174                    rate,
14175                    window: Duration::from_secs(secs),
14176                });
14177                s.validate().unwrap_or_else(|e| {
14178                    panic!("rate={rate} window={secs}s must validate; got {e:?}")
14179                });
14180            }
14181        }
14182    }
14183
14184    #[test]
14185    fn policy_rate_limit_zero_takes_precedence_over_cap() {
14186        // The cross-arm ordering pin: `rate == 0` is structurally
14187        // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
14188        // (cap), but the zero-floor diagnostic is the more
14189        // self-locating one (it directly names the omit-axis
14190        // remediation). Pin the order so a future refactor that
14191        // reorders the arms surfaces here as a test failure rather
14192        // than a silent diagnostic regression. Same shape every other
14193        // zero-then-cap ordering on this surface uses
14194        // ([`AplicacaoError::PolicyRetriesZero`] then
14195        // [`AplicacaoError::PolicyRetriesExceedsCap`];
14196        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
14197        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
14198        let mut s = three_member_spec();
14199        s.politicas.rate_limit = Some(RateLimit {
14200            rate: 0,
14201            window: Duration::from_secs(1),
14202        });
14203        assert_eq!(
14204            s.validate().unwrap_err(),
14205            AplicacaoError::PolicyRateLimitZero,
14206            "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
14207        );
14208    }
14209
14210    #[test]
14211    fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
14212        // Two-axis-bad pin: rate above cap *and* window non-canonical.
14213        // The validate gate must fire on the rate cap first — the
14214        // amplification-shape (no-op limiter) diagnostic is the more
14215        // fundamental one; the window-canonical diagnostic is the
14216        // narrower codec-round-trip shape. Pin the ordering so a future
14217        // refactor that reorders the rate-then-window check arms
14218        // surfaces here as a test failure rather than a silent
14219        // diagnostic regression.
14220        let mut s = three_member_spec();
14221        s.politicas.rate_limit = Some(RateLimit {
14222            rate: POLICY_RATE_LIMIT_MAX + 1,
14223            window: Duration::from_secs(45),
14224        });
14225        assert_eq!(
14226            s.validate().unwrap_err(),
14227            AplicacaoError::PolicyRateLimitExceedsCap {
14228                rate: POLICY_RATE_LIMIT_MAX + 1
14229            },
14230            "above-cap rate must surface the cap diagnostic, not the window diagnostic"
14231        );
14232    }
14233
14234    #[test]
14235    fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
14236        // The diagnostic-shape pin: the offending `u32` is carried
14237        // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
14238        // variant so the surfaced error message names the value the
14239        // author wrote (`":politicas :rate-limit rate (5000000) exceeds
14240        // the mesh-policy ceiling …"`), not just the cap. Same
14241        // self-locating diagnostic shape every other typed-cap arm on
14242        // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
14243        // carries the offending retries count verbatim,
14244        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
14245        // the offending failure count verbatim).
14246        let mut s = three_member_spec();
14247        s.politicas.rate_limit = Some(RateLimit {
14248            rate: 5_000_000,
14249            window: Duration::from_secs(1),
14250        });
14251        let err = s.validate().unwrap_err();
14252        assert!(
14253            matches!(
14254                err,
14255                AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
14256            ),
14257            "got {err:?}"
14258        );
14259        let msg = err.to_string();
14260        assert!(
14261            msg.contains("5000000"),
14262            ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
14263        );
14264    }
14265
14266    #[test]
14267    fn policy_rate_limit_cap_pins_canonical_value() {
14268        // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
14269        // 1_000_000 — two-to-three orders of magnitude above every
14270        // documented production-playbook recommendation band (Envoy /
14271        // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
14272        // Gateway 10_000..=100_000 per-minute) and below the
14273        // clearly-pathological "paste-from-binary blob" floor
14274        // (100_000_000, u32::MAX). Pinning the literal value here
14275        // surfaces a future drift (a relaxation to 10_000_000, a
14276        // tightening to 100_000) as a deliberate test edit, not a
14277        // silent contract narrowing.
14278        assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
14279    }
14280
14281    #[test]
14282    fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
14283        // Both axes are invalid here: rate == 0 *and* window is
14284        // non-canonical. The validate gate must fire on rate first
14285        // (matching the existing `rejects_zero_rate_limit` ordering),
14286        // so the existing diagnostic continues to lead with the
14287        // simpler "zero rate" framing. Pinning the order of checks
14288        // so a future refactor that reorders the arms surfaces here
14289        // as a test failure rather than a silent diagnostic
14290        // regression.
14291        let mut s = three_member_spec();
14292        s.politicas.rate_limit = Some(RateLimit {
14293            rate: 0,
14294            window: Duration::from_secs(45),
14295        });
14296        assert_eq!(
14297            s.validate().unwrap_err(),
14298            AplicacaoError::PolicyRateLimitZero
14299        );
14300    }
14301
14302    #[test]
14303    fn rate_limit_canonical_windows_validate() {
14304        // The three canonical windows the codec round-trips
14305        // losslessly — 1s / 60s / 3600s — must all pass `validate()`
14306        // unchanged. Pin the full canonical set as a positive case
14307        // (the existing `rate_limit_round_trip_seconds` /
14308        // `rate_limit_round_trip_minutes` tests pin the
14309        // serialize-then-deserialize property at the codec layer; this
14310        // test pins the validate-side complement so a future tightening
14311        // of the canonical set — e.g. dropping `:hour` — surfaces here
14312        // as a test failure rather than a silent contract narrowing).
14313        for secs in [1u64, 60, 3600] {
14314            let mut s = three_member_spec();
14315            s.politicas.rate_limit = Some(RateLimit {
14316                rate: 100,
14317                window: Duration::from_secs(secs),
14318            });
14319            s.validate().expect("canonical window must validate");
14320        }
14321    }
14322
14323    #[test]
14324    fn rate_limit_validated_value_round_trips_through_codec() {
14325        // The structural property the validate gate enforces:
14326        // every `RateLimit` past `AplicacaoSpec::validate` round-trips
14327        // losslessly through the `rate_limit_codec` (serialize → string
14328        // → deserialize → equal value). Pin this end-to-end so a future
14329        // change to either side (the validate gate's accepted window
14330        // set, the codec's parse/render unit set) that breaks the
14331        // alignment surfaces here. The previous-state shape (typed
14332        // slot accepts arbitrary `Duration`, codec only round-trips
14333        // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
14334        // window — the validate gate now forecloses that.
14335        for secs in [1u64, 60, 3600] {
14336            let mut s = three_member_spec();
14337            s.politicas.rate_limit = Some(RateLimit {
14338                rate: 250,
14339                window: Duration::from_secs(secs),
14340            });
14341            s.validate().unwrap();
14342            let json = serde_json::to_string(&s.politicas).unwrap();
14343            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
14344            assert_eq!(
14345                back.rate_limit, s.politicas.rate_limit,
14346                "every validated :rate-limit must round-trip losslessly through the codec"
14347            );
14348        }
14349    }
14350
14351    #[test]
14352    fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
14353        // The hour-window canonical form (`"<n>/h"`) was missing from
14354        // the prior `rate_limit_round_trip_seconds` / `_minutes` test
14355        // pair. Now that the validate gate pins 3600s as part of the
14356        // canonical set, pin its serialize-side render shape too so
14357        // the third leg of the s/m/h tripod is explicitly tested.
14358        let policy = MeshPolicy {
14359            rate_limit: Some(RateLimit {
14360                rate: 10000,
14361                window: Duration::from_secs(3600),
14362            }),
14363            ..Default::default()
14364        };
14365        let json = serde_json::to_string(&policy).unwrap();
14366        assert!(
14367            json.contains("\"10000/h\""),
14368            "hour-window canonical form must render with `h` suffix (got: {json})"
14369        );
14370        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
14371        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
14372    }
14373
14374    #[test]
14375    fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
14376        // Pin the substrate-primitive [`RateLimit::canonical_unit`]
14377        // typed accessor's accepted-window set against the codec's
14378        // accepted set explicitly. A future addition to the codec
14379        // (e.g. accepting `:day`/`:week` as authoring units) must be
14380        // accompanied by a parallel addition here, and a regression
14381        // that drops one of the three canonical units from either
14382        // side surfaces as a test failure. The accessor is the
14383        // single source of truth for the canonical-window set —
14384        // [`AplicacaoSpec::validate_politicas`]'s canonical-window
14385        // gate and [`rate_limit_codec::render`]'s canonical arm both
14386        // read through it — this test enshrines that its
14387        // `Duration → Option<RateLimitUnit>` projection matches the
14388        // codec's parse / render arms' accepted-window set exactly.
14389        //
14390        // Predecessor: this pin previously read the module-private
14391        // free helper `is_canonical_rate_limit_window` — a delegate
14392        // that composed [`RateLimitUnit::from_window`] with `.is_some()`
14393        // — but the helper had no production consumers left after the
14394        // validate-gate migration onto [`RateLimit::canonical_unit`]
14395        // and was deleted; the closed-set arm-window bijection now
14396        // lives on exactly one typed dispatch on the substrate
14397        // primitive.
14398        let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
14399            RateLimit { rate: 1, window }.canonical_unit()
14400        };
14401        assert!(canonical_unit(Duration::from_secs(1)).is_some());
14402        assert!(canonical_unit(Duration::from_secs(60)).is_some());
14403        assert!(canonical_unit(Duration::from_secs(3600)).is_some());
14404        // Non-canonical windows the accessor rejects.
14405        assert!(canonical_unit(Duration::ZERO).is_none());
14406        assert!(canonical_unit(Duration::from_secs(2)).is_none());
14407        assert!(canonical_unit(Duration::from_secs(30)).is_none());
14408        assert!(canonical_unit(Duration::from_secs(120)).is_none());
14409        assert!(canonical_unit(Duration::from_secs(86400)).is_none());
14410        // Sub-second windows: even `Duration::from_millis(1000)` is
14411        // exactly 1s and accepted; `Duration::from_millis(500)` is
14412        // sub-second and rejected.
14413        assert!(canonical_unit(Duration::from_millis(1000)).is_some());
14414        assert!(canonical_unit(Duration::from_millis(500)).is_none());
14415        assert!(canonical_unit(Duration::from_millis(1500)).is_none());
14416    }
14417
14418    #[test]
14419    fn rate_limit_unit_table_projections_are_mutual_inverses() {
14420        // Bidirection pin against the closed-set typed enum
14421        // [`RateLimitUnit`] arm-table (the canonical
14422        // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
14423        // of the rate-limit unit surface reads from). The two
14424        // projection directions [`RateLimitUnit::from_suffix`] /
14425        // [`RateLimitUnit::window`] (str → Duration, exposed as one
14426        // typed dispatch through [`RateLimitUnit::window_from_suffix`])
14427        // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
14428        // (Duration → str, exposed as one typed dispatch through
14429        // [`RateLimit::canonical_unit`] composed with
14430        // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
14431        // codec's parse arm ([`rate_limit_codec::parse`] via
14432        // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
14433        // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
14434        // and the validate gate ([`AplicacaoSpec::validate_politicas`]
14435        // via [`RateLimit::canonical_unit`]) all key off. A future
14436        // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
14437        // sub-second window) is one variant + one arm per method on the
14438        // closed-set enum; the compiler-enforced exhaustiveness on
14439        // every consumer's `match self` arms picks it up by
14440        // construction. This pin enshrines that both projection
14441        // directions agree on every canonical arm row and neither
14442        // leaks a spurious entry the other doesn't recognize.
14443        //
14444        // Predecessor: this test previously read the two vestigial
14445        // module-private free helpers `rate_limit_window_unit` and
14446        // `rate_limit_window_from_unit` on the `Duration → &str` and
14447        // `&str → Duration` axes; the former was deleted after its
14448        // sole production consumer ([`rate_limit_codec::render`])
14449        // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
14450        // the latter is folded here into the substrate primitive
14451        // [`RateLimitUnit::window_from_suffix`] so both projection
14452        // directions live on the closed-set enum's arm-table.
14453        for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
14454            let window = super::RateLimitUnit::window_from_suffix(unit)
14455                .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
14456            assert_eq!(
14457                window,
14458                Duration::from_secs(secs),
14459                "unit {unit:?} must resolve to {secs}s"
14460            );
14461            let projected_suffix = RateLimit { rate: 1, window }
14462                .canonical_unit()
14463                .map(super::RateLimitUnit::as_suffix);
14464            assert_eq!(
14465                projected_suffix,
14466                Some(unit),
14467                "Duration({secs}s) must render as {unit:?} \
14468                 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
14469            );
14470        }
14471        // Non-table units yield None on the `unit → Duration`
14472        // projection — a future `"d"` addition to the table would
14473        // flip this arm; today it pins the current three-row table's
14474        // rejection semantics.
14475        assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
14476        assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
14477        assert!(super::RateLimitUnit::window_from_suffix("").is_none());
14478        // Non-table Durations yield None on the `Duration → unit`
14479        // projection — pins that the two projections agree on the
14480        // "not in the table" semantic too, so a drift where the
14481        // parse-side accepts a value the render-side can't emit is
14482        // a build error at the two-arm pair, not a silent codec
14483        // round-trip break.
14484        let projected_suffix = |window: Duration| -> Option<&'static str> {
14485            RateLimit { rate: 1, window }
14486                .canonical_unit()
14487                .map(super::RateLimitUnit::as_suffix)
14488        };
14489        assert!(projected_suffix(Duration::from_secs(2)).is_none());
14490        assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
14491        assert!(projected_suffix(Duration::from_millis(1500)).is_none());
14492    }
14493
14494    #[test]
14495    fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
14496        // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
14497        // substrate-primitive `&str → Duration` associated method the
14498        // codec's parse arm ([`rate_limit_codec::parse`]) now routes
14499        // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
14500        // to the same [`Duration`] the two-step composition
14501        // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
14502        // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
14503        // `"MIN"`) must project to [`None`] on both paths. A future
14504        // implementation of `window_from_suffix` that took a shortcut
14505        // through a per-suffix `match` table (bypassing the arm-table's
14506        // `Self::from_suffix` scan and the arm-table's `Self::window`
14507        // dispatch) would silently split the accept-set — the parse
14508        // arm would accept a suffix the enum's arm-table doesn't know,
14509        // or reject a suffix the enum's arm-table does; this pin
14510        // surfaces that drift at caixa-core build time rather than at a
14511        // downstream serde round-trip audit on a live `MeshPolicy`.
14512        //
14513        // Same byte-parity discipline the sibling
14514        // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
14515        // pin carries on the peer `Duration → RateLimitUnit` axis via
14516        // [`RateLimit::canonical_unit`], and the peer
14517        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
14518        // carries on the bidirectional arm-table axis — extended here
14519        // onto the fifth (and last unlifted) projection axis on the
14520        // closed-set enum's arm-table.
14521        let composition = |suffix: &str| -> Option<Duration> {
14522            super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
14523        };
14524        for suffix in ["s", "m", "h"] {
14525            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
14526            let via_composition = composition(suffix);
14527            assert_eq!(
14528                via_method, via_composition,
14529                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
14530                 from_suffix({suffix:?}).map(window) — the substrate-primitive \
14531                 method must delegate to the arm-table's two typed dispatches, \
14532                 not shortcut through a per-suffix match table"
14533            );
14534            assert!(
14535                via_method.is_some(),
14536                "canonical suffix {suffix:?} must resolve to Some(Duration) via \
14537                 RateLimitUnit::window_from_suffix"
14538            );
14539        }
14540        for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
14541            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
14542            let via_composition = composition(suffix);
14543            assert_eq!(
14544                via_method, via_composition,
14545                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
14546                 from_suffix({suffix:?}).map(window) on the non-arm rejection \
14547                 axis too"
14548            );
14549            assert!(
14550                via_method.is_none(),
14551                "non-arm suffix {suffix:?} must project to None via \
14552                 RateLimitUnit::window_from_suffix — a future extension that \
14553                 accepted this suffix without a corresponding arm on the enum \
14554                 would split the codec's parse-accepted set from the enum's \
14555                 arm-table"
14556            );
14557        }
14558        // And the codec's parse arm now reads through this method: a
14559        // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
14560        // the same `Duration` the method returns for its unit, closing
14561        // the two-consumer drift surface (the codec's parse arm and the
14562        // enum's arm-table) with one typed dispatch on the substrate
14563        // primitive.
14564        for suffix in ["s", "m", "h"] {
14565            let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
14566            let mp: MeshPolicy = serde_json::from_str(&wire)
14567                .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
14568            let parsed = mp.rate_limit().expect("rate_limit payload present");
14569            let via_method = super::RateLimitUnit::window_from_suffix(suffix)
14570                .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
14571            assert_eq!(
14572                parsed.window(),
14573                via_method,
14574                "codec parse arm on {wire:?} must resolve the window through \
14575                 RateLimitUnit::window_from_suffix, not a divergent path"
14576            );
14577        }
14578    }
14579
14580    #[test]
14581    fn rate_limit_unit_all_enumerates_every_arm_once() {
14582        // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
14583        // enumerate every arm of the closed-set enum exactly once, in
14584        // the canonical shortest-to-longest window order (Second before
14585        // Minute before Hour) — the same order the sibling
14586        // [`crate::supervisor::RestartStrategy`] /
14587        // [`crate::supervisor::RestartPolicy`] /
14588        // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
14589        // typed enums carry (the arm declared first is the arm listed
14590        // first). A future variant addition that extends the enum
14591        // without appending to [`RateLimitUnit::ALL`] leaves the
14592        // exhaustive iteration surface silently short one arm — the
14593        // codec's parse arm would then reject the new suffix even
14594        // though the enum knows it. This pin closes the drift.
14595        assert_eq!(
14596            super::RateLimitUnit::ALL,
14597            &[
14598                super::RateLimitUnit::Second,
14599                super::RateLimitUnit::Minute,
14600                super::RateLimitUnit::Hour,
14601            ],
14602            "RateLimitUnit::ALL must enumerate every arm exactly once, \
14603             in canonical shortest-to-longest window order"
14604        );
14605    }
14606
14607    #[test]
14608    fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
14609        // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
14610        // every arm's [`RateLimitUnit::as_suffix`] output must parse
14611        // back through [`RateLimitUnit::from_suffix`] to the same
14612        // variant. A future arm addition that lands `as_suffix` but
14613        // forgets `from_suffix` (`from_suffix` iterates
14614        // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
14615        // is the load-bearing carrier of the round-trip; the sibling
14616        // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
14617        // the `ALL` half) trips here at caixa-core build time rather
14618        // than surfacing as a codec round-trip miss (a `render` emit
14619        // that lands a suffix the paired `parse` cannot decode).
14620        for unit in super::RateLimitUnit::ALL {
14621            let suffix = unit.as_suffix();
14622            let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
14623                panic!(
14624                    "RateLimitUnit::from_suffix({suffix:?}) must accept every \
14625                     RateLimitUnit::as_suffix output — got None for {unit:?}"
14626                )
14627            });
14628            assert_eq!(
14629                parsed, *unit,
14630                "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
14631                 must return RateLimitUnit::{unit:?}"
14632            );
14633        }
14634    }
14635
14636    #[test]
14637    fn rate_limit_unit_from_window_and_window_round_trip() {
14638        // Total round-trip pin on the `(from_window, window)` pair:
14639        // every arm's [`RateLimitUnit::window`] output must parse back
14640        // through [`RateLimitUnit::from_window`] to the same variant.
14641        // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
14642        // on the peer `Duration` axis — the two round-trip pins
14643        // together enshrine that both projections of the typed
14644        // canonical-unit bijection are total on the arm-set.
14645        for unit in super::RateLimitUnit::ALL {
14646            let window = unit.window();
14647            let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
14648                panic!(
14649                    "RateLimitUnit::from_window({window:?}) must accept every \
14650                     RateLimitUnit::window output — got None for {unit:?}"
14651                )
14652            });
14653            assert_eq!(
14654                parsed, *unit,
14655                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
14656                 must return RateLimitUnit::{unit:?}"
14657            );
14658        }
14659    }
14660
14661    #[test]
14662    fn rate_limit_unit_projections_are_pairwise_distinct() {
14663        // Distinctness pin: [`RateLimitUnit::as_suffix`] and
14664        // [`RateLimitUnit::window`] outputs must be pairwise distinct
14665        // across every arm — an accidental copy-paste flip that
14666        // reroutes one arm's suffix or window to also match another
14667        // silently collapses two arms onto one, so
14668        // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
14669        // (both using `find` on `Self::ALL`) would return whichever
14670        // arm the linear scan lands on first — a match-arm-ordering-
14671        // dependent outcome the closed-set typed-enum shape is meant
14672        // to rule out structurally. Peer of the sibling
14673        // `caixa_kind_wire_consts_are_pairwise_distinct` /
14674        // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
14675        // other closed-set typed-enum discriminator axes.
14676        let all = super::RateLimitUnit::ALL;
14677        for (i, a) in all.iter().enumerate() {
14678            for (j, b) in all.iter().enumerate() {
14679                if i != j {
14680                    assert_ne!(
14681                        a.as_suffix(),
14682                        b.as_suffix(),
14683                        "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
14684                         must be distinct — a collision silently collapses two \
14685                         arms onto one under from_suffix's linear scan"
14686                    );
14687                    assert_ne!(
14688                        a.window(),
14689                        b.window(),
14690                        "RateLimitUnit::{a:?}.window() and {b:?}.window() \
14691                         must be distinct — a collision silently collapses two \
14692                         arms onto one under from_window's linear scan"
14693                    );
14694                }
14695            }
14696        }
14697    }
14698
14699    #[test]
14700    fn rate_limit_unit_display_routes_through_as_suffix() {
14701        // Route pin: [`std::fmt::Display`] must byte-equal
14702        // [`RateLimitUnit::as_suffix`] on every arm — the single
14703        // source of truth for the canonical suffix. A future
14704        // reimplementation that hand-rolls the arms instead of
14705        // delegating to [`RateLimitUnit::as_suffix`] would silently
14706        // desynchronize `format!("{u}")` from the codec's parse arm
14707        // (which uses `as_suffix` to compare suffixes). Peer of the
14708        // sibling `caixa_kind_display_routes_through_as_str_helper` /
14709        // `placement_strategy_display_routes_through_as_str_helper`
14710        // pins on the peer closed-set typed-enum Display axes.
14711        for unit in super::RateLimitUnit::ALL {
14712            assert_eq!(
14713                unit.to_string(),
14714                unit.as_suffix(),
14715                "RateLimitUnit::{unit:?} Display must route through \
14716                 as_suffix (single source of truth: the canonical suffix \
14717                 the codec parses and renders)"
14718            );
14719        }
14720    }
14721
14722    #[test]
14723    fn rate_limit_unit_from_window_rejects_non_canonical() {
14724        // Rejection pin on the parser's accept-set: any Duration
14725        // outside the three-arm [`RateLimitUnit::window`] output set
14726        // (sub-second residue, or a second-magnitude outside `{1, 60,
14727        // 3600}`) must return `None`. A future accidental widening of
14728        // the accept-set (rounding down sub-second residue to the
14729        // nearest arm, admitting `Duration::from_secs(30)` as a
14730        // half-minute unit) would silently drift the parser's accept-
14731        // set from the emitter's — a validated slot with a
14732        // non-canonical window would then round-trip through the
14733        // codec to a canonical form the author never wrote.
14734        assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
14735        assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
14736        assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
14737        assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
14738        assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
14739        assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
14740        assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
14741    }
14742
14743    #[test]
14744    fn rate_limit_unit_from_suffix_rejects_unknown() {
14745        // Rejection pin on the suffix parser's accept-set: any string
14746        // outside the three-arm [`RateLimitUnit::as_suffix`] output
14747        // set must return `None`. Peer of the sibling
14748        // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
14749        // the [`crate::CaixaKind`] `from_wire` accept-set.
14750        for bad in [
14751            "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
14752            " s",
14753        ] {
14754            assert!(
14755                super::RateLimitUnit::from_suffix(bad).is_none(),
14756                "RateLimitUnit::from_suffix({bad:?}) must return None — the \
14757                 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
14758                 outputs"
14759            );
14760        }
14761    }
14762
14763    #[test]
14764    fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
14765        // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
14766        // every canonical `:window` magnitude the validate gate
14767        // accepts must map to the paired [`RateLimitUnit`] arm through
14768        // this accessor. A future validate-gate rebrand that widened
14769        // the accepted-window set without extending [`RateLimitUnit`]
14770        // would silently split the accessor's `Some`-return set from
14771        // the validate gate's accept-set — a slot that satisfies
14772        // validate would land at the accessor with `None`, so a
14773        // consumer past validate that pattern-matches on the returned
14774        // `Some` would silently miss the newly-accepted magnitude.
14775        for (window_secs, expected) in [
14776            (1u64, super::RateLimitUnit::Second),
14777            (60, super::RateLimitUnit::Minute),
14778            (3600, super::RateLimitUnit::Hour),
14779        ] {
14780            let rl = RateLimit {
14781                rate: 100,
14782                window: Duration::from_secs(window_secs),
14783            };
14784            assert_eq!(
14785                rl.canonical_unit(),
14786                Some(expected),
14787                "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
14788                 must return Some({expected:?})"
14789            );
14790        }
14791        // Non-canonical windows the validate gate rejects also return
14792        // None here — the accessor is the typed-enum projection of
14793        // the sibling `is_canonical_rate_limit_window` predicate.
14794        let bad = RateLimit {
14795            rate: 100,
14796            window: Duration::from_secs(30),
14797        };
14798        assert!(
14799            bad.canonical_unit().is_none(),
14800            "RateLimit with a non-canonical window must return None from \
14801             canonical_unit — the validate gate rejects the same set"
14802        );
14803    }
14804
14805    #[test]
14806    fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
14807        // Fail-before-pass-after byte-parity pin: for every canonical
14808        // window the [`rate_limit_codec::render`] arm's emitted string
14809        // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
14810        // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
14811        // the vestigial free helper [`rate_limit_window_unit`] (a
14812        // `find_map`-walked `Duration → &'static str` delegate) onto the
14813        // substrate primitive [`RateLimit::canonical_unit`] typed method
14814        // (a closed-set `match self.window` arm on
14815        // [`RateLimitUnit::from_window`], projected through
14816        // [`RateLimitUnit::as_suffix`] via the enum's
14817        // [`std::fmt::Display`] impl). A future re-routing of the render
14818        // arm through a differently-computed unit projection would break
14819        // this pin at build time rather than as a silent per-consumer
14820        // codec round-trip drift far from the substrate primitive edit.
14821        //
14822        // Sibling to the peer
14823        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
14824        // on the free-helper axis: that pin locks the two projections
14825        // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
14826        // on the closed-set arm table; this pin locks the codec's render
14827        // arm reads through the typed accessor rather than the free
14828        // helper. Two production consumers of the canonical-unit axis
14829        // now key off one typed dispatch on the substrate primitive.
14830        for (window_secs, unit) in [
14831            (1u64, super::RateLimitUnit::Second),
14832            (60, super::RateLimitUnit::Minute),
14833            (3600, super::RateLimitUnit::Hour),
14834        ] {
14835            let rl = RateLimit {
14836                rate: 42,
14837                window: Duration::from_secs(window_secs),
14838            };
14839            let policy = MeshPolicy {
14840                rate_limit: Some(rl),
14841                ..Default::default()
14842            };
14843            let json = serde_json::to_string(&policy).unwrap();
14844            let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
14845            assert!(
14846                json.contains(&expected),
14847                "rate_limit_codec::render must emit {expected} (via \
14848                 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
14849                 for a {window_secs}s window; serialized MeshPolicy was: {json}"
14850            );
14851            // And the accessor route resolves to the same typed unit
14852            // the render arm's Display formatting is asked to produce —
14853            // so a future edit that split the two paths (one through
14854            // the accessor, one through a re-introduced free helper)
14855            // trips this pin.
14856            assert_eq!(
14857                rl.canonical_unit(),
14858                Some(unit),
14859                "RateLimit::canonical_unit must return Some({unit:?}) for a \
14860                 {window_secs}s window; the codec render arm reads the same \
14861                 typed unit through this accessor"
14862            );
14863        }
14864    }
14865
14866    #[test]
14867    fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
14868        // Fail-before-pass-after byte-parity pin on the validate gate's
14869        // canonical-window shape probe: every non-canonical `:window`
14870        // the free-helper predicate [`is_canonical_rate_limit_window`]
14871        // rejects is also rejected by the substrate primitive
14872        // [`RateLimit::canonical_unit`] `.is_none()` route the validate
14873        // gate now reads through, and vice versa on the accepted set
14874        // (the three canonical windows). Locks the migration from the
14875        // free helper onto the substrate primitive: a future re-routing
14876        // of one of the two paths through a differently-computed unit
14877        // projection would silently split the codec's accepted set from
14878        // the validate gate's accepted set — a two-consumer drift the
14879        // codec-round-trip pin
14880        // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
14881        // above closes on the render arm and this pin closes on the
14882        // validate arm.
14883        for canonical_window_secs in [1u64, 60, 3600] {
14884            let mut s = three_member_spec();
14885            let rl = RateLimit {
14886                rate: 100,
14887                window: Duration::from_secs(canonical_window_secs),
14888            };
14889            s.politicas.rate_limit = Some(rl);
14890            assert!(
14891                s.validate().is_ok(),
14892                "canonical {canonical_window_secs}s window must pass \
14893                 validate_politicas — the validate gate now reads \
14894                 RateLimit::canonical_unit().is_none() and the accessor \
14895                 returns Some on every canonical arm"
14896            );
14897            assert!(
14898                rl.canonical_unit().is_some(),
14899                "canonical {canonical_window_secs}s window must resolve to \
14900                 Some on RateLimit::canonical_unit — the validate gate reads \
14901                 this accessor directly"
14902            );
14903        }
14904        for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
14905            let mut s = three_member_spec();
14906            let rl = RateLimit {
14907                rate: 100,
14908                window: Duration::from_secs(non_canonical_window_secs),
14909            };
14910            s.politicas.rate_limit = Some(rl);
14911            assert_eq!(
14912                s.validate().unwrap_err(),
14913                AplicacaoError::PolicyRateLimitWindowNotCanonical {
14914                    window: rl.window(),
14915                },
14916                "non-canonical {non_canonical_window_secs}s window must be \
14917                 rejected by validate_politicas — the validate gate now \
14918                 keys off RateLimit::canonical_unit().is_none()"
14919            );
14920            assert!(
14921                rl.canonical_unit().is_none(),
14922                "non-canonical {non_canonical_window_secs}s window must \
14923                 resolve to None on RateLimit::canonical_unit — the two \
14924                 paths (the free helper the validate gate previously read \
14925                 and the substrate primitive the validate gate now reads) \
14926                 must agree on the same rejected set"
14927            );
14928        }
14929        // And the substrate-primitive [`RateLimit::canonical_unit`]
14930        // accessor's accepted-window set matches the codec's parse arm's
14931        // accepted-suffix set on every canonical / non-canonical shape,
14932        // so a future silent drift between the codec's accepted set and
14933        // the validate gate's accepted set is a build error at test time
14934        // (both consumers key off the same closed-set enum's `match self`
14935        // arms). The predecessor free helper `is_canonical_rate_limit_window`
14936        // — a delegate that composed [`RateLimitUnit::from_window`] with
14937        // `.is_some()` — was deleted after this migration; the
14938        // canonical-window set now lives on exactly one typed dispatch
14939        // on the substrate primitive.
14940        for (secs, expected) in [
14941            (1u64, true),
14942            (60, true),
14943            (3600, true),
14944            (2, false),
14945            (30, false),
14946            (86_400, false),
14947        ] {
14948            let window = Duration::from_secs(secs);
14949            let rl = RateLimit { rate: 1, window };
14950            assert_eq!(
14951                rl.canonical_unit().is_some(),
14952                expected,
14953                "RateLimit::canonical_unit().is_some() must agree with the \
14954                 codec-accepted canonical-window set on {secs}s"
14955            );
14956            let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
14957                1 => "s",
14958                60 => "m",
14959                3600 => "h",
14960                _ => return,
14961            })
14962            .is_some_and(|d| d == window);
14963            if expected {
14964                assert!(
14965                    suffix_from_axis,
14966                    "the codec's `&str → Duration` axis \
14967                     ({secs}s) must round-trip to the same Duration the \
14968                     substrate primitive's accessor returns Some on"
14969                );
14970            }
14971        }
14972    }
14973
14974    #[test]
14975    fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
14976        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
14977        // derive: for each of the three variants, exactly one of the
14978        // generated `is_second` / `is_minute` / `is_hour` predicates
14979        // returns `true` and the other two return `false`. Peer of
14980        // the sibling
14981        // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
14982        // sibling `IsVariant`-derived closed-set typed-enum pins.
14983        let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
14984            (super::RateLimitUnit::Second, [true, false, false]),
14985            (super::RateLimitUnit::Minute, [false, true, false]),
14986            (super::RateLimitUnit::Hour, [false, false, true]),
14987        ];
14988        for (variant, expected) in rows {
14989            let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
14990            assert_eq!(
14991                observed, expected,
14992                "RateLimitUnit::{variant:?} is_* predicates must partition \
14993                 the arm set (second, minute, hour); got {observed:?}"
14994            );
14995        }
14996    }
14997
14998    #[test]
14999    fn rejects_policy_timeout_sub_millisecond() {
15000        // A purely sub-millisecond `Duration` (`from_micros(500)` =
15001        // 500_000 ns) is not the zero `Duration` — the `is_zero()`
15002        // arm passes — but `as_millis() == 0`, so the shared codec's
15003        // `render` arm returns the literal `"0s"`, which the
15004        // codec's `parse` arm then deserializes as `Duration::ZERO`
15005        // and the `PolicyTimeoutZero` zero-floor gate would reject
15006        // on re-validate. Pin the rejection at the typed slot's
15007        // canonical-floor gate so the round-trip break surfaces at
15008        // validate time, naming the offending `Duration`, rather
15009        // than at the next serialize → deserialize round-trip far
15010        // from the source `caixa.lisp`.
15011        let mut s = three_member_spec();
15012        let timeout = Duration::from_micros(500);
15013        s.politicas.timeout = Some(timeout);
15014        assert_eq!(
15015            s.validate().unwrap_err(),
15016            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
15017        );
15018    }
15019
15020    #[test]
15021    fn rejects_policy_timeout_non_integer_millisecond() {
15022        // A `Duration` with non-integer-millisecond residue
15023        // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
15024        // through the shared codec's `render` arm as `"1ms"` (the
15025        // `as_millis()` floor truncates), which the codec's `parse`
15026        // arm then deserializes as `Duration::from_millis(1)` =
15027        // 1_000_000 ns — silently *different* from the original.
15028        // Pin the rejection so this round-trip break surfaces at
15029        // validate time, where the offending `Duration` is named,
15030        // rather than as a silent value-laundered round-trip on the
15031        // next codec round-trip.
15032        let mut s = three_member_spec();
15033        let timeout = Duration::from_micros(1500);
15034        s.politicas.timeout = Some(timeout);
15035        assert_eq!(
15036            s.validate().unwrap_err(),
15037            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
15038        );
15039    }
15040
15041    #[test]
15042    fn accepts_policy_timeout_integer_millisecond_forms() {
15043        // The codec's accepted set — integer multiples of 1ms — is
15044        // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
15045        // `1h` all pass the canonical gate. Pin the canonical-forms
15046        // sweep so a future tightening of the codec's grammar (e.g.
15047        // dropping `:ms`) surfaces here as a test failure rather
15048        // than a silent contract narrowing on the typed slot.
15049        for timeout in [
15050            Duration::from_millis(1),
15051            Duration::from_millis(500),
15052            Duration::from_millis(1500),
15053            Duration::from_secs(30),
15054            Duration::from_secs(120),
15055            Duration::from_secs(3600),
15056        ] {
15057            let mut s = three_member_spec();
15058            s.politicas.timeout = Some(timeout);
15059            s.validate()
15060                .expect("integer-millisecond :timeout must validate");
15061        }
15062    }
15063
15064    #[test]
15065    fn policy_timeout_zero_takes_precedence_over_canonical() {
15066        // `Duration::ZERO` carries `subsec_nanos() == 0` and would
15067        // pass the canonical-millisecond gate; the more self-locating
15068        // `PolicyTimeoutZero` arm (which names the omit-axis
15069        // remediation directly) must fire first. Pin the ordering so
15070        // a future refactor that reorders the arms surfaces here as a
15071        // test failure rather than a silent diagnostic regression.
15072        let mut s = three_member_spec();
15073        s.politicas.timeout = Some(Duration::ZERO);
15074        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
15075    }
15076
15077    #[test]
15078    fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
15079        // The diagnostic envelope carries the offending `Duration`
15080        // verbatim so the author can grep their `caixa.lisp` for
15081        // `:timeout "<value>"` and fix it in one edit. Same
15082        // diagnostic shape every other typed-slot canonical-form
15083        // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
15084        // peer `:rate-limit :window` axis.
15085        let mut s = three_member_spec();
15086        let timeout = Duration::from_nanos(1_000_001);
15087        s.politicas.timeout = Some(timeout);
15088        match s.validate().unwrap_err() {
15089            AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
15090                assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
15091            }
15092            other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
15093        }
15094    }
15095
15096    #[test]
15097    fn rejects_policy_timeout_above_cap() {
15098        // The fail-before-pass-after pin: 3601s = 1h + 1s is
15099        // structurally one canonical-tick past the
15100        // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
15101        // integer-millisecond magnitude the canonical-form arm above
15102        // accepts cleanly, that the codec round-trips losslessly as
15103        // `"3601s"`, and that silently passed validate on every
15104        // pre-gate codebase because the typed slot's only checks were
15105        // the zero-floor and canonical-form arms. The mesh-level
15106        // deadline degenerates only at the runtime substrate (Envoy
15107        // / Cilium L7 timeout overlay) far from the source
15108        // `caixa.lisp` with no field naming the offending policy.
15109        let mut s = three_member_spec();
15110        let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
15111        s.politicas.timeout = Some(timeout);
15112        assert_eq!(
15113            s.validate().unwrap_err(),
15114            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
15115        );
15116    }
15117
15118    #[test]
15119    fn rejects_policy_timeout_one_millisecond_above_cap() {
15120        // Boundary case: exactly 1ms past the cap (the granularity
15121        // the canonical-form gate enforces). Catches a future
15122        // "strictly less than" half-measure and pins the diagnostic
15123        // to name the offending `Duration` verbatim. Peer of
15124        // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
15125        // boundary pin on the sibling `:limits :memory` top edge.
15126        let mut s = three_member_spec();
15127        let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
15128        s.politicas.timeout = Some(timeout);
15129        assert_eq!(
15130            s.validate().unwrap_err(),
15131            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
15132        );
15133    }
15134
15135    #[test]
15136    fn rejects_policy_timeout_far_above_cap() {
15137        // The "obvious authoring footgun" case: a `(:timeout "24h")`
15138        // or `(:timeout "86400s")` — values the canonical-form arm
15139        // accepts as integer-millisecond magnitudes, the codec
15140        // round-trips losslessly through serde, but the mesh-level
15141        // policy cannot honor (a 24-hour synchronous-`:contratos`
15142        // deadline is operationally indistinguishable from
15143        // omit-the-axis). Until this gate landed validate accepted
15144        // it. Pin both common above-cap values (24h, 7d) so a future
15145        // relaxation that drops the upper bound surfaces here.
15146        for timeout in [
15147            Duration::from_secs(86_400),    // 24h
15148            Duration::from_secs(604_800),   // 7d
15149            Duration::from_secs(1_000_000), // ~11.5 days
15150        ] {
15151            let mut s = three_member_spec();
15152            s.politicas.timeout = Some(timeout);
15153            assert_eq!(
15154                s.validate().unwrap_err(),
15155                AplicacaoError::PolicyTimeoutExceedsCap { timeout }
15156            );
15157        }
15158    }
15159
15160    #[test]
15161    fn accepts_policy_timeout_at_cap() {
15162        // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
15163        // must validate. The cap is inclusive on the top edge,
15164        // matching the [`POLICY_RETRIES_MAX`] /
15165        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
15166        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
15167        // sibling capped axes. Pin the boundary explicitly so a
15168        // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
15169        // instead of `>`) surfaces here as a test failure rather
15170        // than a silent contract narrowing.
15171        let mut s = three_member_spec();
15172        s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
15173        s.validate()
15174            .expect("timeout == POLICY_TIMEOUT_MAX must validate");
15175    }
15176
15177    #[test]
15178    fn accepts_policy_timeout_typical_values() {
15179        // The documented production-playbook band positive-control
15180        // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
15181        // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
15182        // plus a sweep through the long-running-workflow band
15183        // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
15184        // validated set explicitly so a future tightening of the
15185        // ceiling surfaces here as a deliberate test edit, not a
15186        // silent contract narrowing.
15187        for timeout in [
15188            Duration::from_millis(1),
15189            Duration::from_millis(500),
15190            Duration::from_secs(1),
15191            Duration::from_secs(10),
15192            Duration::from_secs(15), // Envoy default
15193            Duration::from_secs(30),
15194            Duration::from_secs(60), // AWS App Mesh typical
15195            Duration::from_secs(300),
15196            Duration::from_secs(900),
15197            Duration::from_secs(1800),
15198            Duration::from_secs(3600), // exactly 1h, the cap
15199        ] {
15200            let mut s = three_member_spec();
15201            s.politicas.timeout = Some(timeout);
15202            s.validate()
15203                .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
15204        }
15205    }
15206
15207    #[test]
15208    fn policy_timeout_zero_takes_precedence_over_cap() {
15209        // The cross-arm ordering pin: `Duration::ZERO` is
15210        // structurally outside both `>= 1ms` (zero-floor) and
15211        // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
15212        // diagnostic is the more self-locating one (it directly
15213        // names the omit-axis remediation), so the validate gate
15214        // must fire on zero first. Same shape every other
15215        // zero-then-shape ordering on this surface uses
15216        // ([`AplicacaoError::PolicyRetriesZero`] then
15217        // [`AplicacaoError::PolicyRetriesExceedsCap`];
15218        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
15219        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
15220        let mut s = three_member_spec();
15221        s.politicas.timeout = Some(Duration::ZERO);
15222        assert_eq!(
15223            s.validate().unwrap_err(),
15224            AplicacaoError::PolicyTimeoutZero,
15225            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
15226        );
15227    }
15228
15229    #[test]
15230    fn policy_timeout_canonical_takes_precedence_over_cap() {
15231        // The cross-arm ordering pin: a `Duration` that is *both*
15232        // sub-millisecond (non-canonical-form) and structurally
15233        // above the cap surfaces the canonical-form diagnostic
15234        // first, because the round-trip-shape break is the more
15235        // fundamental issue (the value can't even round-trip
15236        // through the codec, so the cap diagnostic naming
15237        // `1ms..=1h` would be misleading — there's no integer-ms
15238        // form of the offending value). Pin the order so a future
15239        // refactor that reorders the arms surfaces here as a test
15240        // failure rather than a silent diagnostic regression.
15241        let mut s = three_member_spec();
15242        // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
15243        // *and* total magnitude above the 1h cap.
15244        let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
15245        s.politicas.timeout = Some(timeout);
15246        assert_eq!(
15247            s.validate().unwrap_err(),
15248            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
15249            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
15250        );
15251    }
15252
15253    #[test]
15254    fn policy_timeout_cap_diagnostic_carries_offending_value() {
15255        // The diagnostic-shape pin: the offending `Duration` is
15256        // carried verbatim into the
15257        // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
15258        // surfaced error message names the value the author wrote
15259        // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
15260        // exceeds the mesh-policy ceiling …"`), not just the cap.
15261        // Same self-locating diagnostic shape every other typed-cap
15262        // arm on this surface carries
15263        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
15264        // offending retry count verbatim).
15265        let mut s = three_member_spec();
15266        let timeout = Duration::from_secs(7200); // 2h
15267        s.politicas.timeout = Some(timeout);
15268        let err = s.validate().unwrap_err();
15269        assert!(
15270            matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
15271            "got {err:?}"
15272        );
15273        let msg = err.to_string();
15274        assert!(
15275            msg.contains("7200"),
15276            ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
15277        );
15278    }
15279
15280    #[test]
15281    fn policy_timeout_cap_pins_canonical_value() {
15282        // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
15283        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
15284        // the shared duration codec emits as a clean canonical
15285        // string (`"<n>h"`). Pinning the literal value here surfaces
15286        // a future drift (a relaxation to 24h, a tightening to 5m)
15287        // as a deliberate test edit, not a silent contract
15288        // narrowing. Same shape every other typed-cap value pin on
15289        // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
15290        assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
15291        assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
15292    }
15293
15294    #[test]
15295    fn policy_timeout_cap_value_round_trips_through_codec() {
15296        // The codec round-trip property the cap arm preserves: the
15297        // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
15298        // the shared duration codec — every value at the cap renders
15299        // to a clean canonical string (`"1h"`) and parses back to
15300        // the same `Duration`. Pin this so a future drift between
15301        // the cap constant and the codec's largest emitted unit
15302        // surfaces here. Same shape every other typed boundary pin
15303        // on this surface uses
15304        // (`wasm32_memory_cap_matches_parsed_4_gib`).
15305        let policy = MeshPolicy {
15306            timeout: Some(POLICY_TIMEOUT_MAX),
15307            ..Default::default()
15308        };
15309        let json = serde_json::to_string(&policy).unwrap();
15310        // The codec emits `"1h"` for the canonical 1-hour magnitude.
15311        assert!(
15312            json.contains("\"1h\""),
15313            "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
15314        );
15315        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
15316        assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
15317    }
15318
15319    #[test]
15320    fn rejects_circuit_breaker_window_sub_millisecond() {
15321        // Peer of the `:timeout` sub-millisecond arm on the second
15322        // typed-`Duration` `:politicas` axis: a purely sub-ms
15323        // `Duration` (`from_micros(500)`) renders through the shared
15324        // codec as `"0s"`, which the codec parses back to
15325        // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
15326        // zero-floor gate then rejects on re-validate.
15327        let mut s = three_member_spec();
15328        let window = Duration::from_micros(500);
15329        s.politicas.circuit_breaker = Some(CircuitBreaker {
15330            max_failures: 5,
15331            window,
15332        });
15333        assert_eq!(
15334            s.validate().unwrap_err(),
15335            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
15336        );
15337    }
15338
15339    #[test]
15340    fn rejects_circuit_breaker_window_non_integer_millisecond() {
15341        // Peer of the `:timeout` non-integer-ms arm: a `Duration`
15342        // with non-integer-millisecond residue renders through the
15343        // shared codec as the truncated `"<n>ms"` form, parsing back
15344        // to a *different* `Duration` on the next round-trip.
15345        let mut s = three_member_spec();
15346        let window = Duration::from_micros(1500);
15347        s.politicas.circuit_breaker = Some(CircuitBreaker {
15348            max_failures: 5,
15349            window,
15350        });
15351        assert_eq!(
15352            s.validate().unwrap_err(),
15353            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
15354        );
15355    }
15356
15357    #[test]
15358    fn accepts_circuit_breaker_window_integer_millisecond_forms() {
15359        // The canonical-forms sweep on the breaker axis: every
15360        // integer-ms multiple the codec round-trips losslessly
15361        // passes the canonical gate.
15362        for window in [
15363            Duration::from_millis(1),
15364            Duration::from_millis(500),
15365            Duration::from_millis(1500),
15366            Duration::from_secs(30),
15367            Duration::from_secs(60),
15368            Duration::from_secs(3600),
15369        ] {
15370            let mut s = three_member_spec();
15371            s.politicas.circuit_breaker = Some(CircuitBreaker {
15372                max_failures: 5,
15373                window,
15374            });
15375            s.validate()
15376                .expect("integer-millisecond :circuit-breaker :window must validate");
15377        }
15378    }
15379
15380    #[test]
15381    fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
15382        // `Duration::ZERO` would pass the canonical-ms gate (the
15383        // sub-ns residue is zero) but must surface the narrower
15384        // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
15385        // remediation.
15386        let mut s = three_member_spec();
15387        s.politicas.circuit_breaker = Some(CircuitBreaker {
15388            max_failures: 5,
15389            window: Duration::ZERO,
15390        });
15391        assert_eq!(
15392            s.validate().unwrap_err(),
15393            AplicacaoError::PolicyBreakerZeroWindow
15394        );
15395    }
15396
15397    #[test]
15398    fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
15399        // Both axes invalid: max_failures == 0 *and* window is
15400        // sub-ms. The validate gate must fire on max_failures first
15401        // (matching the existing ordering pin
15402        // `rejects_circuit_breaker_zero_max_failures` enshrines), so
15403        // the existing diagnostic continues to lead with the simpler
15404        // "zero threshold" framing.
15405        let mut s = three_member_spec();
15406        s.politicas.circuit_breaker = Some(CircuitBreaker {
15407            max_failures: 0,
15408            window: Duration::from_micros(500),
15409        });
15410        assert_eq!(
15411            s.validate().unwrap_err(),
15412            AplicacaoError::PolicyBreakerZeroFailures
15413        );
15414    }
15415
15416    #[test]
15417    fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
15418        let mut s = three_member_spec();
15419        let window = Duration::from_nanos(60_000_000_001);
15420        s.politicas.circuit_breaker = Some(CircuitBreaker {
15421            max_failures: 5,
15422            window,
15423        });
15424        match s.validate().unwrap_err() {
15425            AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
15426                assert_eq!(w, window, "diagnostic must carry the offending Duration");
15427            }
15428            other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
15429        }
15430    }
15431
15432    #[test]
15433    fn rejects_circuit_breaker_window_above_cap() {
15434        // The fail-before-pass-after pin: 3601s = 1h + 1s is
15435        // structurally one canonical-tick past the
15436        // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
15437        // integer-millisecond magnitude the canonical-form arm above
15438        // accepts cleanly, that the codec round-trips losslessly as
15439        // `"3601s"`, and that silently passed validate on every
15440        // pre-gate codebase because the typed slot's only checks were
15441        // the zero-floor and canonical-form arms. The
15442        // rolling-window-to-lifetime-counter degeneration surfaces
15443        // only at the runtime substrate (Envoy's outlier_detection
15444        // interval, the future CiliumClusterwideEnvoyConfig overlay)
15445        // far from the source `caixa.lisp` with no field naming the
15446        // offending policy.
15447        let mut s = three_member_spec();
15448        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
15449        s.politicas.circuit_breaker = Some(CircuitBreaker {
15450            max_failures: 5,
15451            window,
15452        });
15453        assert_eq!(
15454            s.validate().unwrap_err(),
15455            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
15456        );
15457    }
15458
15459    #[test]
15460    fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
15461        // Boundary case: exactly 1ms past the cap (the granularity the
15462        // canonical-form gate enforces). Catches a future "strictly
15463        // less than" half-measure and pins the diagnostic to name the
15464        // offending `Duration` verbatim. Peer of
15465        // `rejects_policy_timeout_one_millisecond_above_cap` on the
15466        // sibling duration-typed `:politicas :timeout` top edge.
15467        let mut s = three_member_spec();
15468        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
15469        s.politicas.circuit_breaker = Some(CircuitBreaker {
15470            max_failures: 5,
15471            window,
15472        });
15473        assert_eq!(
15474            s.validate().unwrap_err(),
15475            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
15476        );
15477    }
15478
15479    #[test]
15480    fn rejects_circuit_breaker_window_far_above_cap() {
15481        // The "obvious authoring footgun" case: a `(:window "24h")` or
15482        // `(:window "86400s")` — values the canonical-form arm
15483        // accepts as integer-millisecond magnitudes, the codec
15484        // round-trips losslessly through serde, but the
15485        // rolling-window breaker contract cannot honor (a 24-hour
15486        // rolling failure window is operationally a lifetime counter).
15487        // Until this gate landed validate accepted it. Pin both common
15488        // above-cap values (24h, 7d) so a future relaxation that
15489        // drops the upper bound surfaces here.
15490        for window in [
15491            Duration::from_secs(86_400),    // 24h
15492            Duration::from_secs(604_800),   // 7d
15493            Duration::from_secs(1_000_000), // ~11.5 days
15494        ] {
15495            let mut s = three_member_spec();
15496            s.politicas.circuit_breaker = Some(CircuitBreaker {
15497                max_failures: 5,
15498                window,
15499            });
15500            assert_eq!(
15501                s.validate().unwrap_err(),
15502                AplicacaoError::PolicyBreakerWindowExceedsCap { window }
15503            );
15504        }
15505    }
15506
15507    #[test]
15508    fn accepts_circuit_breaker_window_at_cap() {
15509        // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
15510        // (1h) — must validate. The cap is inclusive on the top edge,
15511        // matching the [`POLICY_TIMEOUT_MAX`] /
15512        // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
15513        // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
15514        // sibling capped axes. Pin the boundary explicitly so a
15515        // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
15516        // instead of `>`) surfaces here as a test failure rather than
15517        // a silent contract narrowing.
15518        let mut s = three_member_spec();
15519        s.politicas.circuit_breaker = Some(CircuitBreaker {
15520            max_failures: 5,
15521            window: POLICY_BREAKER_WINDOW_MAX,
15522        });
15523        s.validate()
15524            .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
15525    }
15526
15527    #[test]
15528    fn accepts_circuit_breaker_window_typical_values() {
15529        // The documented production-playbook band positive-control
15530        // sweep — every value Hystrix / resilience4j / Istio / Envoy
15531        // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
15532        // through the long-tail failure-detection band (15m, 30m, 1h)
15533        // the cap accepts. Pin the inclusive validated set explicitly
15534        // so a future tightening of the ceiling surfaces here as a
15535        // deliberate test edit, not a silent contract narrowing.
15536        for window in [
15537            Duration::from_millis(1),
15538            Duration::from_millis(500),
15539            Duration::from_secs(1),
15540            Duration::from_secs(10), // Hystrix / Istio / Envoy default
15541            Duration::from_secs(30),
15542            Duration::from_secs(60),  // resilience4j typical
15543            Duration::from_secs(300), // AWS App Mesh typical
15544            Duration::from_secs(900),
15545            Duration::from_secs(1800),
15546            Duration::from_secs(3600), // exactly 1h, the cap
15547        ] {
15548            let mut s = three_member_spec();
15549            s.politicas.circuit_breaker = Some(CircuitBreaker {
15550                max_failures: 5,
15551                window,
15552            });
15553            s.validate()
15554                .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
15555        }
15556    }
15557
15558    #[test]
15559    fn circuit_breaker_zero_window_takes_precedence_over_cap() {
15560        // The cross-arm ordering pin: `Duration::ZERO` is structurally
15561        // outside both `>= 1ms` (zero-floor) and
15562        // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
15563        // diagnostic is the more self-locating one (it directly names
15564        // the omit-axis remediation), so the validate gate must fire
15565        // on zero first. Same shape every other zero-then-cap
15566        // ordering on this surface uses
15567        // ([`AplicacaoError::PolicyTimeoutZero`] then
15568        // [`AplicacaoError::PolicyTimeoutExceedsCap`];
15569        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
15570        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
15571        let mut s = three_member_spec();
15572        s.politicas.circuit_breaker = Some(CircuitBreaker {
15573            max_failures: 5,
15574            window: Duration::ZERO,
15575        });
15576        assert_eq!(
15577            s.validate().unwrap_err(),
15578            AplicacaoError::PolicyBreakerZeroWindow,
15579            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
15580        );
15581    }
15582
15583    #[test]
15584    fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
15585        // The cross-arm ordering pin: a `Duration` that is *both*
15586        // sub-millisecond (non-canonical-form) and structurally above
15587        // the cap surfaces the canonical-form diagnostic first,
15588        // because the round-trip-shape break is the more fundamental
15589        // issue (the value can't even round-trip through the codec, so
15590        // the cap diagnostic naming `1ms..=1h` would be misleading —
15591        // there's no integer-ms form of the offending value). Pin the
15592        // order so a future refactor that reorders the arms surfaces
15593        // here as a test failure rather than a silent diagnostic
15594        // regression. Peer of
15595        // `policy_timeout_canonical_takes_precedence_over_cap` on the
15596        // sibling duration-typed `:politicas :timeout` axis.
15597        let mut s = three_member_spec();
15598        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
15599        s.politicas.circuit_breaker = Some(CircuitBreaker {
15600            max_failures: 5,
15601            window,
15602        });
15603        assert_eq!(
15604            s.validate().unwrap_err(),
15605            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
15606            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
15607        );
15608    }
15609
15610    #[test]
15611    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
15612        // The cross-arm ordering pin between the two breaker axes: a
15613        // `CircuitBreaker` whose *both* `max_failures` is above its
15614        // cap *and* `window` is above its cap surfaces the
15615        // max-failures cap diagnostic first, because the validate
15616        // gate visits the failures arm before the window arm. Pin the
15617        // order so a future refactor that reorders the breaker arms
15618        // surfaces here.
15619        let mut s = three_member_spec();
15620        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
15621        s.politicas.circuit_breaker = Some(CircuitBreaker {
15622            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
15623            window,
15624        });
15625        assert_eq!(
15626            s.validate().unwrap_err(),
15627            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
15628                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
15629            },
15630            "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
15631        );
15632    }
15633
15634    #[test]
15635    fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
15636        // The diagnostic-shape pin: the offending `Duration` is
15637        // carried verbatim into the
15638        // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
15639        // the surfaced error message names the value the author wrote
15640        // (`":politicas :circuit-breaker :window (Duration { secs:
15641        // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
15642        // just the cap. Same self-locating diagnostic shape every
15643        // other typed-cap arm on this surface carries
15644        // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
15645        // offending `Duration` verbatim).
15646        let mut s = three_member_spec();
15647        let window = Duration::from_secs(7200); // 2h
15648        s.politicas.circuit_breaker = Some(CircuitBreaker {
15649            max_failures: 5,
15650            window,
15651        });
15652        let err = s.validate().unwrap_err();
15653        assert!(
15654            matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
15655            "got {err:?}"
15656        );
15657        let msg = err.to_string();
15658        assert!(
15659            msg.contains("7200"),
15660            ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
15661        );
15662    }
15663
15664    #[test]
15665    fn circuit_breaker_window_cap_pins_canonical_value() {
15666        // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
15667        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
15668        // shared duration codec emits as a clean canonical string
15669        // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
15670        // the sibling duration-typed `:politicas :timeout` axis (the
15671        // two duration-typed `:politicas` axes share a uniform top
15672        // edge). Pinning the literal value here surfaces a future
15673        // drift (a relaxation to 24h, a tightening to 5m) as a
15674        // deliberate test edit, not a silent contract narrowing. Same
15675        // shape every other typed-cap value pin on this surface uses
15676        // (`policy_timeout_cap_pins_canonical_value`).
15677        assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
15678        assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
15679        assert_eq!(
15680            POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
15681            "the two duration-typed `:politicas` caps share the same top edge"
15682        );
15683    }
15684
15685    #[test]
15686    fn circuit_breaker_window_cap_value_round_trips_through_codec() {
15687        // The codec round-trip property the cap arm preserves: the
15688        // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
15689        // through the shared duration codec — every value at the cap
15690        // renders to a clean canonical string (`"1h"`) and parses back
15691        // to the same `Duration`. Pin this so a future drift between
15692        // the cap constant and the codec's largest emitted unit
15693        // surfaces here. Same shape every other typed boundary pin on
15694        // this surface uses
15695        // (`policy_timeout_cap_value_round_trips_through_codec`).
15696        let policy = MeshPolicy {
15697            circuit_breaker: Some(CircuitBreaker {
15698                max_failures: 5,
15699                window: POLICY_BREAKER_WINDOW_MAX,
15700            }),
15701            ..Default::default()
15702        };
15703        let json = serde_json::to_string(&policy).unwrap();
15704        // The codec emits `"1h"` for the canonical 1-hour magnitude.
15705        assert!(
15706            json.contains("\"1h\""),
15707            "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
15708        );
15709        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
15710        assert_eq!(
15711            back.circuit_breaker.unwrap().window,
15712            POLICY_BREAKER_WINDOW_MAX
15713        );
15714    }
15715
15716    #[test]
15717    fn is_integer_millisecond_duration_predicate_tracks_codec() {
15718        // Pin the predicate's accepted set against the codec's
15719        // accepted set explicitly. The codec parses
15720        // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
15721        // accepted value is an integer-millisecond multiple — so the
15722        // predicate must accept exactly that set. Same shape every
15723        // other predicate-on-the-typed-slot helper carries
15724        // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
15725        // Read directly from the codec-owned predicate — the crate's
15726        // single source of truth every typed-`Duration` axis now routes
15727        // through via
15728        // [`crate::render::require_positive_canonical_bounded_duration`].
15729        use super::supervisor::duration_codec::is_integer_millisecond_duration;
15730        assert!(is_integer_millisecond_duration(Duration::ZERO));
15731        assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
15732        assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
15733        assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
15734        assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
15735        assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
15736        // Non-integer-millisecond residue: rejected.
15737        assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
15738        assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
15739        assert!(!is_integer_millisecond_duration(Duration::from_micros(
15740            1500
15741        )));
15742        assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
15743        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
15744            999_999
15745        )));
15746        // The 1-ns-past-1ms boundary: rejected (no longer a clean
15747        // integer-millisecond multiple).
15748        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
15749            1_000_001
15750        )));
15751    }
15752
15753    #[test]
15754    fn policy_timeout_validated_value_round_trips_through_codec() {
15755        // The structural property the canonical-ms gate enforces:
15756        // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
15757        // round-trips losslessly through the shared `duration_codec`
15758        // (serialize → string → deserialize → equal value). Pin this
15759        // end-to-end so a future change to either side (the validate
15760        // gate's accepted granularity, the codec's parse/render unit
15761        // set) that breaks the alignment surfaces here. The
15762        // previous-state shape (typed slot accepts arbitrary
15763        // `Duration`, codec only round-trips integer-ms) would fail
15764        // this test for any `Duration::from_micros(1500)` timeout —
15765        // the validate gate now forecloses that.
15766        for timeout in [
15767            Duration::from_millis(1),
15768            Duration::from_millis(1500),
15769            Duration::from_secs(30),
15770            Duration::from_secs(3600),
15771        ] {
15772            let mut s = three_member_spec();
15773            s.politicas.timeout = Some(timeout);
15774            s.validate().unwrap();
15775            let json = serde_json::to_string(&s.politicas).unwrap();
15776            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
15777            assert_eq!(
15778                back.timeout, s.politicas.timeout,
15779                "every validated :timeout must round-trip losslessly through the codec"
15780            );
15781        }
15782    }
15783
15784    #[test]
15785    fn circuit_breaker_window_validated_value_round_trips_through_codec() {
15786        // Peer of the `:timeout` round-trip property on the breaker
15787        // axis.
15788        for window in [
15789            Duration::from_millis(1),
15790            Duration::from_millis(1500),
15791            Duration::from_secs(30),
15792            Duration::from_secs(3600),
15793        ] {
15794            let mut s = three_member_spec();
15795            s.politicas.circuit_breaker = Some(CircuitBreaker {
15796                max_failures: 5,
15797                window,
15798            });
15799            s.validate().unwrap();
15800            let json = serde_json::to_string(&s.politicas).unwrap();
15801            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
15802            assert_eq!(
15803                back.circuit_breaker.unwrap().window,
15804                window,
15805                "every validated :circuit-breaker :window must round-trip losslessly"
15806            );
15807        }
15808    }
15809
15810    #[test]
15811    fn empty_politicas_validates() {
15812        // Omitting every policy axis is fine — defaults express "no
15813        // policy on this axis", not "policy = 0". The fixture's typical
15814        // values continue to validate; this test pins that
15815        // MeshPolicy::default() is a clean pass through validate().
15816        let mut s = three_member_spec();
15817        s.politicas = MeshPolicy::default();
15818        s.validate().unwrap();
15819    }
15820
15821    #[test]
15822    fn typical_politicas_validates_with_every_axis_set() {
15823        // The full §III.1 example block (timeout + retries + breaker +
15824        // mtls + rate-limit) — every axis nonzero — must remain a
15825        // clean pass.
15826        let mut s = three_member_spec();
15827        s.politicas = MeshPolicy {
15828            timeout: Some(Duration::from_secs(30)),
15829            retries: Some(3),
15830            circuit_breaker: Some(CircuitBreaker {
15831                max_failures: 5,
15832                window: Duration::from_secs(60),
15833            }),
15834            mtls_required: Some(true),
15835            rate_limit: Some(RateLimit {
15836                rate: 100,
15837                window: Duration::from_secs(1),
15838            }),
15839        };
15840        s.validate().unwrap();
15841    }
15842
15843    #[test]
15844    fn rejects_empty_cluster_name() {
15845        let mut s = three_member_spec();
15846        s.placement.clusters = vec!["rio".into(), "".into()];
15847        assert_eq!(
15848            s.validate().unwrap_err(),
15849            AplicacaoError::PlacementClusterEmpty
15850        );
15851    }
15852
15853    #[test]
15854    fn rejects_duplicate_cluster_names() {
15855        let mut s = three_member_spec();
15856        s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
15857        let err = s.validate().unwrap_err();
15858        assert!(
15859            matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
15860            "got {err:?}"
15861        );
15862    }
15863
15864    #[test]
15865    fn rejects_placement_cluster_with_uppercase() {
15866        // The canonical "I copied the cluster's display name verbatim"
15867        // typo — K8s context names are lowercase per DNS-1123 label
15868        // rule, but org docs often round-trip a TitleCase identifier
15869        // (`Rio`, `Mar-East`) from an ADR. Mirrors the
15870        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
15871        // on the peer name axis.
15872        let mut s = three_member_spec();
15873        s.placement.clusters = vec!["Rio".into(), "mar".into()];
15874        let err = s.validate().unwrap_err();
15875        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
15876            panic!("expected PlacementClusterInvalid, got other variant");
15877        };
15878        assert_eq!(cluster, "Rio");
15879        assert!(
15880            reason.contains("uppercase"),
15881            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
15882        );
15883        assert!(
15884            reason.contains("\"rio\""),
15885            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
15886        );
15887    }
15888
15889    #[test]
15890    fn rejects_placement_cluster_with_underscore() {
15891        // The canonical "I'm thinking of an env var / hostname slug"
15892        // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
15893        // schema. K8s context filtering on `my_cluster` silently misses
15894        // the cluster the author intended; the gate moves it to caixa-
15895        // build time. Same shape as `rejects_membro_caixa_with_underscore`
15896        // (3f9d7a0).
15897        let mut s = three_member_spec();
15898        s.placement.clusters = vec!["my_cluster".into()];
15899        let err = s.validate().unwrap_err();
15900        assert!(
15901            matches!(
15902                err,
15903                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
15904                    if cluster == "my_cluster" && reason.contains('_')
15905            ),
15906            "got {err:?}"
15907        );
15908    }
15909
15910    #[test]
15911    fn rejects_placement_cluster_with_dot() {
15912        // A `:placement :clusters` entry is a single DNS-1123 *label*,
15913        // not a subdomain — even though K8s context names sometimes
15914        // carry a dotted form via kubeconfig conventions, the strictest
15915        // floor among the use sites (DNS-1035 cluster.x-k8s.io
15916        // `metadata.name`, Cilium identity label values) wins. The "I
15917        // want to namespace my cluster names with `.`" intent is
15918        // expressed via `-` (`mar-east`).
15919        let mut s = three_member_spec();
15920        s.placement.clusters = vec!["team.rio".into()];
15921        let err = s.validate().unwrap_err();
15922        assert!(
15923            matches!(
15924                err,
15925                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
15926                    if cluster == "team.rio" && reason.contains('.')
15927            ),
15928            "got {err:?}"
15929        );
15930    }
15931
15932    #[test]
15933    fn rejects_placement_cluster_with_leading_hyphen() {
15934        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
15935        // with an alphanumeric. The K8s apiserver rejects `-rio`
15936        // outright; the rendered fan-out would emit a `metadata.name:
15937        // "-rio"` that fails admission far from the source caixa.lisp.
15938        let mut s = three_member_spec();
15939        s.placement.clusters = vec!["-rio".into()];
15940        let err = s.validate().unwrap_err();
15941        assert!(
15942            matches!(
15943                err,
15944                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
15945                    if cluster == "-rio" && reason.contains("start and end")
15946            ),
15947            "got {err:?}"
15948        );
15949    }
15950
15951    #[test]
15952    fn rejects_placement_cluster_with_trailing_hyphen() {
15953        // The symmetric arm of the boundary rule. Pin separately so
15954        // both ends are covered against a future relaxation that only
15955        // checks one boundary (parallel to
15956        // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
15957        let mut s = three_member_spec();
15958        s.placement.clusters = vec!["rio-".into()];
15959        let err = s.validate().unwrap_err();
15960        assert!(
15961            matches!(
15962                err,
15963                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
15964                    if cluster == "rio-"
15965            ),
15966            "got {err:?}"
15967        );
15968    }
15969
15970    #[test]
15971    fn rejects_placement_cluster_with_unicode() {
15972        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
15973        // before it reaches K8s. The byte-by-byte ASCII validity check
15974        // rejects multi-byte UTF-8 sequences by the first byte that
15975        // fails `[a-z0-9-]`.
15976        let mut s = three_member_spec();
15977        s.placement.clusters = vec!["rió".into()];
15978        let err = s.validate().unwrap_err();
15979        assert!(
15980            matches!(
15981                err,
15982                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
15983                    if cluster == "rió"
15984            ),
15985            "got {err:?}"
15986        );
15987    }
15988
15989    #[test]
15990    fn rejects_placement_cluster_with_whitespace() {
15991        // Whitespace is the canonical "I pasted from a sketch / doc"
15992        // footgun. The apiserver rejects every cluster `metadata.name`
15993        // value carrying whitespace.
15994        let mut s = three_member_spec();
15995        s.placement.clusters = vec!["rio cluster".into()];
15996        let err = s.validate().unwrap_err();
15997        assert!(
15998            matches!(
15999                err,
16000                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
16001                    if cluster == "rio cluster"
16002            ),
16003            "got {err:?}"
16004        );
16005    }
16006
16007    #[test]
16008    fn rejects_placement_cluster_too_long() {
16009        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
16010        // pin. The diagnostic names both the cap (63) and the actual
16011        // length so the author can shorten in one edit. Mirrors
16012        // `rejects_membro_caixa_too_long` (3f9d7a0).
16013        let mut s = three_member_spec();
16014        let too_long = "a".repeat(64);
16015        s.placement.clusters = vec![too_long.clone()];
16016        let err = s.validate().unwrap_err();
16017        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
16018            panic!("expected PlacementClusterInvalid");
16019        };
16020        assert_eq!(cluster, too_long);
16021        assert!(
16022            reason.contains("63") && reason.contains("64"),
16023            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
16024        );
16025    }
16026
16027    #[test]
16028    fn placement_cluster_max_length_validates() {
16029        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
16030        // future tightening (e.g. dropping to 62) surfaces here as a
16031        // regression, mirroring `membro_caixa_max_length_validates`
16032        // (3f9d7a0).
16033        let mut s = three_member_spec();
16034        s.placement.clusters = vec!["a".repeat(63)];
16035        s.validate().unwrap();
16036    }
16037
16038    #[test]
16039    fn accepts_canonical_placement_cluster_forms() {
16040        // The DNS-1123 label shapes a caixa author is realistically
16041        // going to write for cluster names: single-word lowercase
16042        // (`rio`), regional hyphen-joined (`mar-east`), single
16043        // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
16044        // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
16045        // Pin every leg so a future tightening that bans (e.g.) digit-
16046        // start identifiers surfaces here.
16047        for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
16048            let mut s = three_member_spec();
16049            s.placement.clusters = vec![form.into()];
16050            s.validate().unwrap_or_else(|e| {
16051                panic!("canonical cluster form {form:?} must validate, got {e:?}")
16052            });
16053        }
16054    }
16055
16056    #[test]
16057    fn placement_cluster_empty_takes_precedence_over_invalid() {
16058        // Order pin: the existing `PlacementClusterEmpty` diagnostic
16059        // (which doesn't try to parse) fires before the new
16060        // `PlacementClusterInvalid` parse-side diagnostic, so an empty
16061        // `:clusters` entry keeps its narrower error message — the new
16062        // gate would also reject `""`, but the empty-string arm is the
16063        // more self-locating diagnostic. Mirrors the
16064        // `membro_caixa_empty_takes_precedence_over_invalid` pin
16065        // (3f9d7a0).
16066        let mut s = three_member_spec();
16067        s.placement.clusters = vec!["rio".into(), "".into()];
16068        let err = s.validate().unwrap_err();
16069        assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
16070    }
16071
16072    #[test]
16073    fn placement_cluster_invalid_fires_before_duplicate_check() {
16074        // Order pin: a malformed-shape `:clusters` entry surfaces *its
16075        // own* diagnostic, even when a later entry would otherwise
16076        // collapse onto a duplicate name. The per-entry shape gate runs
16077        // inline before the duplicate-key insert, parallel to
16078        // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
16079        let mut s = three_member_spec();
16080        s.placement.clusters = vec!["Rio".into(), "rio".into()];
16081        let err = s.validate().unwrap_err();
16082        assert!(
16083            matches!(
16084                err,
16085                AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
16086            ),
16087            "got {err:?}"
16088        );
16089    }
16090
16091    #[test]
16092    fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
16093        // The diagnostic-shape pin: the error names the offending
16094        // `:clusters` value verbatim so the author can grep their
16095        // caixa.lisp without re-running the build, and carries a
16096        // non-empty `reason` naming the specific violation. Same shape
16097        // every typed-shape gate enshrines
16098        // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
16099        // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
16100        let mut s = three_member_spec();
16101        s.placement.clusters = vec!["BAD_CLUSTER".into()];
16102        let err = s.validate().unwrap_err();
16103        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
16104            panic!("expected PlacementClusterInvalid");
16105        };
16106        assert_eq!(cluster, "BAD_CLUSTER");
16107        assert!(
16108            !reason.is_empty(),
16109            "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
16110        );
16111    }
16112
16113    #[test]
16114    fn rejects_sharded_with_empty_clusters() {
16115        // §III.1: Sharded uses :clusters as the shard pool. An empty
16116        // pool means "shard across no clusters" — meaningless, same as
16117        // Replicated with no hosts.
16118        let mut s = three_member_spec();
16119        s.placement.estrategia = PlacementStrategy::Sharded;
16120        s.placement.shard_key = Some("$tenantId".into());
16121        s.placement.clusters = vec![];
16122        assert!(matches!(
16123            s.validate().unwrap_err(),
16124            AplicacaoError::PlacementWithoutClusters {
16125                estrategia: PlacementStrategy::Sharded
16126            }
16127        ));
16128    }
16129
16130    #[test]
16131    fn rejects_sharded_with_empty_shard_key() {
16132        let mut s = three_member_spec();
16133        s.placement.estrategia = PlacementStrategy::Sharded;
16134        s.placement.shard_key = Some("".into());
16135        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
16136    }
16137
16138    #[test]
16139    fn rejects_shard_key_under_replicated_strategy() {
16140        // The fail-before-pass-after pin: a `:placement (:estrategia
16141        // Replicated :shard-key "tenantId")` manifest carries the
16142        // hash-keyed-distribution slot on a strategy that never consumes
16143        // it. Before the gate the typed slot's value silently vanished
16144        // at the renderer layer (caixa-mesh emits `placement.shardKey`
16145        // verbatim regardless of strategy; the Akka-style cluster-
16146        // sharding reconciler keys off `estrategia == Sharded` and
16147        // ignores the slot otherwise), with no diagnostic. Lifting the
16148        // rejection to a build-time gate makes the
16149        // `shard_key.is_some() == matches!(estrategia, Sharded)`
16150        // partition a structural property of every validated
16151        // [`Placement`].
16152        let mut s = three_member_spec();
16153        // The fixture already uses Replicated; just add a shard-key.
16154        s.placement.shard_key = Some("$tenantId".into());
16155        let err = s.validate().unwrap_err();
16156        let AplicacaoError::ShardKeyOnNonSharded {
16157            estrategia,
16158            shard_key,
16159        } = err
16160        else {
16161            panic!("expected ShardKeyOnNonSharded, got {err:?}");
16162        };
16163        assert_eq!(estrategia, PlacementStrategy::Replicated);
16164        assert_eq!(shard_key, "$tenantId");
16165    }
16166
16167    #[test]
16168    fn rejects_shard_key_under_singlenode_strategy() {
16169        // Peer of the Replicated case above on the SingleNode arm: OTP
16170        // distributed-app takeover (one cluster runs at a time) has no
16171        // hash-keyed routing axis to consume `:shard-key` either, so
16172        // the rejection fires on both non-Sharded arms uniformly.
16173        let mut s = three_member_spec();
16174        s.placement.estrategia = PlacementStrategy::SingleNode;
16175        s.placement.shard_key = Some("$tenantId".into());
16176        let err = s.validate().unwrap_err();
16177        let AplicacaoError::ShardKeyOnNonSharded {
16178            estrategia,
16179            shard_key,
16180        } = err
16181        else {
16182            panic!("expected ShardKeyOnNonSharded, got {err:?}");
16183        };
16184        assert_eq!(estrategia, PlacementStrategy::SingleNode);
16185        assert_eq!(shard_key, "$tenantId");
16186    }
16187
16188    #[test]
16189    fn rejects_empty_shard_key_under_replicated_strategy() {
16190        // The `Some("")` case under non-Sharded is rejected by
16191        // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
16192        // fires before the empty-value gate), not
16193        // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
16194        // the `Sharded` arm). Pin the partition so a future reorder of
16195        // the validate_placement match arms doesn't silently swap which
16196        // diagnostic the author sees — both are author errors, but
16197        // ShardKeyOnNonSharded names which strategy is the actual fix
16198        // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
16199        // only says "pick a non-empty key".
16200        let mut s = three_member_spec();
16201        s.placement.shard_key = Some(String::new());
16202        let err = s.validate().unwrap_err();
16203        assert!(
16204            matches!(
16205                err,
16206                AplicacaoError::ShardKeyOnNonSharded {
16207                    estrategia: PlacementStrategy::Replicated,
16208                    ref shard_key,
16209                } if shard_key.is_empty()
16210            ),
16211            "got {err:?}"
16212        );
16213    }
16214
16215    #[test]
16216    fn replicated_without_shard_key_validates() {
16217        // The complement of the rejection: `:placement :estrategia
16218        // Replicated` with `:shard-key None` is the canonical happy
16219        // path on every existing fixture. Pin the no-shard-key case so
16220        // the new gate doesn't accidentally fire on `None`.
16221        let mut s = three_member_spec();
16222        assert!(matches!(
16223            s.placement.estrategia,
16224            PlacementStrategy::Replicated
16225        ));
16226        s.placement.shard_key = None;
16227        s.validate().unwrap();
16228    }
16229
16230    #[test]
16231    fn singlenode_without_shard_key_validates() {
16232        // Peer of the Replicated no-shard-key case on the SingleNode
16233        // arm — both non-Sharded strategies must validate cleanly when
16234        // the slot is omitted.
16235        let mut s = three_member_spec();
16236        s.placement.estrategia = PlacementStrategy::SingleNode;
16237        s.placement.shard_key = None;
16238        s.validate().unwrap();
16239    }
16240
16241    fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
16242        // Fixture builder for the `:placement :shard-key` shape gate
16243        // tests: a three-member Aplicacao on the `Sharded` strategy
16244        // with the supplied `:shard-key` slot. Co-locates the
16245        // arm-construction so every test below carries one line of
16246        // setup (the offending `:shard-key` value) and the assertion.
16247        let mut s = three_member_spec();
16248        s.placement.estrategia = PlacementStrategy::Sharded;
16249        s.placement.shard_key = Some(key.into());
16250        s
16251    }
16252
16253    #[test]
16254    fn rejects_shard_key_with_embedded_space() {
16255        // The canonical paste-from-aligned-doc footgun:
16256        // `:shard-key "$tenant Id"` — the Akka-style entity-id
16257        // extractor reads the slot as a single-token reference, and an
16258        // embedded space breaks the token boundary at the runtime
16259        // hash-extractor pass with no diagnostic naming the offending
16260        // entry.
16261        let s = sharded_spec_with_key("$tenant Id");
16262        let err = s.validate().unwrap_err();
16263        assert!(
16264            matches!(
16265                err,
16266                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
16267                    if shard_key == "$tenant Id" && reason.contains("space")
16268            ),
16269            "got {err:?}"
16270        );
16271    }
16272
16273    #[test]
16274    fn rejects_shard_key_with_leading_space() {
16275        // Leading-space arm of the embedded-whitespace footgun — the
16276        // paste-from-aligned-doc / paste-from-CSV-cell variant where
16277        // the leading column-padding leaked into the slot.
16278        let s = sharded_spec_with_key(" $tenantId");
16279        let err = s.validate().unwrap_err();
16280        assert!(
16281            matches!(
16282                err,
16283                AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
16284                    if shard_key == " $tenantId"
16285            ),
16286            "got {err:?}"
16287        );
16288    }
16289
16290    #[test]
16291    fn rejects_shard_key_with_trailing_newline() {
16292        // The canonical paste-from-shell-heredoc footgun — every
16293        // `<<EOF` heredoc terminator paste leaves a trailing newline
16294        // the YAML emitter then folds away inconsistently across
16295        // emitter implementations.
16296        let s = sharded_spec_with_key("$tenantId\n");
16297        let err = s.validate().unwrap_err();
16298        assert!(
16299            matches!(
16300                err,
16301                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
16302                    if shard_key == "$tenantId\n" && reason.contains("0x0a")
16303            ),
16304            "got {err:?}"
16305        );
16306    }
16307
16308    #[test]
16309    fn rejects_shard_key_with_embedded_tab() {
16310        // The paste-from-aligned-doc tab-stop variant — tabs land
16311        // alongside spaces in copy-paste from formatted columns.
16312        let s = sharded_spec_with_key("$tenant\tId");
16313        let err = s.validate().unwrap_err();
16314        assert!(
16315            matches!(
16316                err,
16317                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
16318                    if shard_key == "$tenant\tId" && reason.contains("tab")
16319            ),
16320            "got {err:?}"
16321        );
16322    }
16323
16324    #[test]
16325    fn rejects_shard_key_with_control_character() {
16326        // The paste-from-binary / paste-from-screen-cleared-terminal
16327        // footgun — an embedded `\x01` (SOH) byte that some YAML
16328        // emitters silently strip and others escape as ``,
16329        // breaking round-trip across emitter implementations.
16330        let s = sharded_spec_with_key("$tenant\u{0001}Id");
16331        let err = s.validate().unwrap_err();
16332        assert!(
16333            matches!(
16334                err,
16335                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
16336                    if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
16337            ),
16338            "got {err:?}"
16339        );
16340    }
16341
16342    #[test]
16343    fn rejects_shard_key_with_non_ascii() {
16344        // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
16345        // footgun — non-ASCII bytes normalize differently between the
16346        // caixa-mesh-side YAML emitter and the in-cluster reconciler's
16347        // YAML parser, the same entity ID can silently map to two
16348        // distinct shards on a re-render.
16349        let s = sharded_spec_with_key("$tenàntId");
16350        let err = s.validate().unwrap_err();
16351        assert!(
16352            matches!(
16353                err,
16354                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
16355                    if shard_key == "$tenàntId" && reason.contains("non-ASCII")
16356            ),
16357            "got {err:?}"
16358        );
16359    }
16360
16361    #[test]
16362    fn rejects_shard_key_too_long() {
16363        // Length cap pin: 64 bytes — one byte over the
16364        // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
16365        // here is a paste-from-doc multi-line blob landing in
16366        // `:shard-key` instead of a single-token extractor expression.
16367        let too_long = "a".repeat(64);
16368        let s = sharded_spec_with_key(&too_long);
16369        let err = s.validate().unwrap_err();
16370        let AplicacaoError::ShardKeyInvalid {
16371            ref shard_key,
16372            ref reason,
16373        } = err
16374        else {
16375            panic!("expected ShardKeyInvalid, got {err:?}");
16376        };
16377        assert_eq!(shard_key, &too_long);
16378        assert!(
16379            reason.contains("63") && reason.contains("64"),
16380            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
16381        );
16382    }
16383
16384    #[test]
16385    fn shard_key_max_length_validates() {
16386        // Boundary pin: 63 bytes exactly — the
16387        // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
16388        // dropping to 62) surfaces here as a regression, mirroring
16389        // `placement_cluster_max_length_validates` /
16390        // `placement_affinity_max_length_validates` on the peer
16391        // identifier-shaped slots.
16392        let s = sharded_spec_with_key(&"a".repeat(63));
16393        s.validate().unwrap();
16394    }
16395
16396    #[test]
16397    fn accepts_canonical_shard_key_forms() {
16398        // The Akka-style entity-id extractor shapes a caixa author is
16399        // realistically going to write — pin every leg so a future
16400        // tightening that bans (e.g.) the `${...}` interpolation
16401        // variant or the `metadata.<field>` JSONPath form surfaces
16402        // here as a regression. The canonical forms span:
16403        //
16404        //   - bare property name (`tenantId`, `customerId`)
16405        //   - Akka `ExtractEntityId` placeholder (`$tenantId`)
16406        //   - JSONPath-style nested reference (`metadata.tenantId`,
16407        //     `$.user.id`)
16408        //   - interpolation-style template (`${tenant}`)
16409        //   - snake_case property name (`customer_id`)
16410        //   - kebab-case property name (`customer-id` — accepted
16411        //     because the slot is a printable-ASCII single-token
16412        //     reference, not a DNS-1123 label like
16413        //     `:placement :affinity` / `:clusters`)
16414        //   - single character (`a`, `$` — boundary)
16415        for form in [
16416            "tenantId",
16417            "customerId",
16418            "$tenantId",
16419            "metadata.tenantId",
16420            "$.user.id",
16421            "${tenant}",
16422            "customer_id",
16423            "customer-id",
16424            "a",
16425            "$",
16426        ] {
16427            let s = sharded_spec_with_key(form);
16428            s.validate().unwrap_or_else(|e| {
16429                panic!("canonical shard-key form {form:?} must validate, got {e:?}")
16430            });
16431        }
16432    }
16433
16434    #[test]
16435    fn shard_key_empty_takes_precedence_over_invalid() {
16436        // Order pin: the existing `ShardedKeyEmpty` diagnostic
16437        // (reserved for the `Sharded` `Some("")` arm) fires before the
16438        // new `ShardKeyInvalid` parse-side diagnostic, so an empty
16439        // `:shard-key` keeps its narrower error message — the new gate
16440        // would also reject `""` defensively, but the empty-string arm
16441        // is the more self-locating diagnostic. Mirrors the
16442        // `placement_cluster_empty_takes_precedence_over_invalid` pin
16443        // on the peer identifier-shaped slot.
16444        let s = sharded_spec_with_key("");
16445        let err = s.validate().unwrap_err();
16446        assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
16447    }
16448
16449    #[test]
16450    fn shard_key_invalid_diagnostic_carries_offending_value() {
16451        // The diagnostic-shape pin: the error names the offending
16452        // `:shard-key` value verbatim so the author can grep their
16453        // caixa.lisp without re-running the build, and carries a
16454        // parser-shaped `reason:` naming the specific violation —
16455        // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
16456        // on the peer identifier-shaped slot.
16457        let s = sharded_spec_with_key("$tenant Id");
16458        let err = s.validate().unwrap_err();
16459        let AplicacaoError::ShardKeyInvalid {
16460            ref shard_key,
16461            ref reason,
16462        } = err
16463        else {
16464            panic!("expected ShardKeyInvalid, got {err:?}");
16465        };
16466        assert_eq!(shard_key, "$tenant Id");
16467        assert!(
16468            !reason.is_empty(),
16469            "reason must name the specific violation, got empty string"
16470        );
16471    }
16472
16473    #[test]
16474    fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
16475        // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
16476        // `:shard-key` carried on non-Sharded strategies) fires before
16477        // the shape gate, so a malformed `:shard-key` carried on (e.g.)
16478        // a `Replicated` strategy surfaces the more self-locating
16479        // strategy-mismatch diagnostic (naming the actual fix — drop
16480        // the slot, or switch to Sharded) rather than the shape
16481        // diagnostic. The strategy-mismatch arm is the more actionable
16482        // diagnostic: a malformed shard-key on Replicated is "you
16483        // shouldn't have a :shard-key here at all", not "your
16484        // :shard-key value is malformed".
16485        let mut s = three_member_spec();
16486        // Replicated is the default fixture strategy.
16487        s.placement.shard_key = Some("$tenant Id".into());
16488        let err = s.validate().unwrap_err();
16489        assert!(
16490            matches!(
16491                err,
16492                AplicacaoError::ShardKeyOnNonSharded {
16493                    estrategia: PlacementStrategy::Replicated,
16494                    ..
16495                }
16496            ),
16497            "got {err:?}"
16498        );
16499    }
16500
16501    #[test]
16502    fn rejects_empty_affinity_hint() {
16503        let mut s = three_member_spec();
16504        s.placement.affinity = Some("".into());
16505        assert_eq!(
16506            s.validate().unwrap_err(),
16507            AplicacaoError::PlacementAffinityEmpty
16508        );
16509    }
16510
16511    #[test]
16512    fn placement_without_affinity_validates() {
16513        // Omitting :affinity is fine — the placement engine falls back
16514        // to the default heuristic. Pin the no-hint case so the
16515        // affinity-empty rejection doesn't accidentally fire on `None`.
16516        let mut s = three_member_spec();
16517        s.placement.affinity = None;
16518        s.validate().unwrap();
16519    }
16520
16521    #[test]
16522    fn rejects_placement_affinity_with_uppercase() {
16523        // The canonical "I copied the ADR's display name verbatim" typo
16524        // — placement hints land verbatim in K8s label-selector
16525        // territory, where the apiserver enforces the DNS-1123 label
16526        // rule (lowercase-only) on every identity-keyed admission axis.
16527        // Mirrors `rejects_placement_cluster_with_uppercase` on the
16528        // sibling slot.
16529        let mut s = three_member_spec();
16530        s.placement.affinity = Some("DataLocality".into());
16531        let err = s.validate().unwrap_err();
16532        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
16533            panic!("expected PlacementAffinityInvalid, got other variant");
16534        };
16535        assert_eq!(affinity, "DataLocality");
16536        assert!(
16537            reason.contains("uppercase"),
16538            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
16539        );
16540        assert!(
16541            reason.contains("\"datalocality\""),
16542            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
16543        );
16544    }
16545
16546    #[test]
16547    fn rejects_placement_affinity_with_underscore() {
16548        // The canonical "I'm thinking of an env var / Python identifier"
16549        // leak — `_` is forbidden by every DNS-1123 label schema. Same
16550        // shape as `rejects_placement_cluster_with_underscore` on the
16551        // sibling slot.
16552        let mut s = three_member_spec();
16553        s.placement.affinity = Some("data_locality".into());
16554        let err = s.validate().unwrap_err();
16555        assert!(
16556            matches!(
16557                err,
16558                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
16559                    if affinity == "data_locality" && reason.contains('_')
16560            ),
16561            "got {err:?}"
16562        );
16563    }
16564
16565    #[test]
16566    fn rejects_placement_affinity_with_dot() {
16567        // A `:placement :affinity` value is a single DNS-1123 *label*
16568        // (it lands as a K8s label value selector key), not a subdomain.
16569        // The "I want to namespace my hint with `.`" intent is expressed
16570        // via `-` (`data-locality-east`).
16571        let mut s = three_member_spec();
16572        s.placement.affinity = Some("data.locality".into());
16573        let err = s.validate().unwrap_err();
16574        assert!(
16575            matches!(
16576                err,
16577                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
16578                    if affinity == "data.locality" && reason.contains('.')
16579            ),
16580            "got {err:?}"
16581        );
16582    }
16583
16584    #[test]
16585    fn rejects_placement_affinity_with_unicode() {
16586        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
16587        // before it reaches K8s. The byte-by-byte ASCII validity check
16588        // rejects multi-byte UTF-8 sequences by the first byte that
16589        // fails `[a-z0-9-]`.
16590        let mut s = three_member_spec();
16591        s.placement.affinity = Some("data-localité".into());
16592        let err = s.validate().unwrap_err();
16593        assert!(
16594            matches!(
16595                err,
16596                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
16597                    if affinity == "data-localité"
16598            ),
16599            "got {err:?}"
16600        );
16601    }
16602
16603    #[test]
16604    fn rejects_placement_affinity_with_leading_hyphen() {
16605        // DNS-1123 boundary rule: labels must start with an
16606        // alphanumeric. Pin separately from the trailing-hyphen arm so
16607        // a future relaxation that only checks one boundary surfaces
16608        // here as a regression (parallel to
16609        // `rejects_placement_cluster_with_leading_hyphen`).
16610        let mut s = three_member_spec();
16611        s.placement.affinity = Some("-data-locality".into());
16612        let err = s.validate().unwrap_err();
16613        assert!(
16614            matches!(
16615                err,
16616                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
16617                    if affinity == "-data-locality" && reason.contains("start and end")
16618            ),
16619            "got {err:?}"
16620        );
16621    }
16622
16623    #[test]
16624    fn rejects_placement_affinity_with_trailing_hyphen() {
16625        // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
16626        // ends are covered against a future relaxation.
16627        let mut s = three_member_spec();
16628        s.placement.affinity = Some("data-locality-".into());
16629        let err = s.validate().unwrap_err();
16630        assert!(
16631            matches!(
16632                err,
16633                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
16634                    if affinity == "data-locality-"
16635            ),
16636            "got {err:?}"
16637        );
16638    }
16639
16640    #[test]
16641    fn rejects_placement_affinity_with_whitespace() {
16642        // Whitespace is the canonical "I pasted from a sketch / doc"
16643        // footgun. The apiserver rejects every label-selector value
16644        // carrying whitespace.
16645        let mut s = three_member_spec();
16646        s.placement.affinity = Some("data locality".into());
16647        let err = s.validate().unwrap_err();
16648        assert!(
16649            matches!(
16650                err,
16651                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
16652                    if affinity == "data locality"
16653            ),
16654            "got {err:?}"
16655        );
16656    }
16657
16658    #[test]
16659    fn rejects_placement_affinity_too_long() {
16660        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
16661        // pin. The diagnostic names both the cap (63) and the actual
16662        // length so the author can shorten in one edit. Mirrors
16663        // `rejects_placement_cluster_too_long`.
16664        let mut s = three_member_spec();
16665        let too_long = "a".repeat(64);
16666        s.placement.affinity = Some(too_long.clone());
16667        let err = s.validate().unwrap_err();
16668        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
16669            panic!("expected PlacementAffinityInvalid");
16670        };
16671        assert_eq!(affinity, too_long);
16672        assert!(
16673            reason.contains("63") && reason.contains("64"),
16674            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
16675        );
16676    }
16677
16678    #[test]
16679    fn placement_affinity_max_length_validates() {
16680        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
16681        // future tightening (e.g. dropping to 62) surfaces here as a
16682        // regression, mirroring `placement_cluster_max_length_validates`.
16683        let mut s = three_member_spec();
16684        s.placement.affinity = Some("a".repeat(63));
16685        s.validate().unwrap();
16686    }
16687
16688    #[test]
16689    fn accepts_canonical_placement_affinity_forms() {
16690        // The DNS-1123 label shapes a caixa author is realistically
16691        // going to write for placement hints: the M3 canonical examples
16692        // (`data-locality`, `low-latency`, `anti-affinity`), the
16693        // single-token form (`affinity`), the single-character boundary
16694        // (`a`), the digit-start (DNS-1123 allows this, unlike
16695        // DNS-1035), and a regional-suffixed form. Pin every leg so a
16696        // future tightening that bans (e.g.) digit-start identifiers
16697        // surfaces here.
16698        for form in [
16699            "data-locality",
16700            "low-latency",
16701            "anti-affinity",
16702            "affinity",
16703            "a",
16704            "3-tier",
16705            "locality-east",
16706        ] {
16707            let mut s = three_member_spec();
16708            s.placement.affinity = Some(form.into());
16709            s.validate().unwrap_or_else(|e| {
16710                panic!("canonical affinity form {form:?} must validate, got {e:?}")
16711            });
16712        }
16713    }
16714
16715    #[test]
16716    fn placement_affinity_empty_takes_precedence_over_invalid() {
16717        // Order pin: the existing `PlacementAffinityEmpty` diagnostic
16718        // (which doesn't try to parse) fires before the new
16719        // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
16720        // `:affinity` keeps its narrower error message — the new gate
16721        // would also reject `""`, but the empty-string arm is the more
16722        // self-locating diagnostic. Mirrors the
16723        // `placement_cluster_empty_takes_precedence_over_invalid` pin.
16724        let mut s = three_member_spec();
16725        s.placement.affinity = Some(String::new());
16726        let err = s.validate().unwrap_err();
16727        assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
16728    }
16729
16730    #[test]
16731    fn placement_affinity_invalid_diagnostic_carries_offending_value() {
16732        // The diagnostic shape pin: every rejection carries the offending
16733        // `affinity:` verbatim plus a parser-shaped `reason:` so the
16734        // author can grep their caixa.lisp for `:affinity "<hint>"` and
16735        // fix it in one edit. Mirrors the
16736        // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
16737        // pin on the sibling slot.
16738        let mut s = three_member_spec();
16739        s.placement.affinity = Some("Data_Locality".into());
16740        let err = s.validate().unwrap_err();
16741        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
16742            panic!("expected PlacementAffinityInvalid");
16743        };
16744        assert_eq!(affinity, "Data_Locality");
16745        assert!(
16746            !reason.is_empty(),
16747            "diagnostic reason must not be empty (got: {reason:?})"
16748        );
16749    }
16750
16751    #[test]
16752    fn singlenode_with_takeover_candidates_validates() {
16753        // OTP distributed-application convention (MESH-COMPOSITION
16754        // §II.1): SingleNode runs on one cluster at a time but the
16755        // :clusters list enumerates the takeover candidates. Multiple
16756        // entries are not a contradiction — they are the failover pool.
16757        let mut s = three_member_spec();
16758        s.placement.estrategia = PlacementStrategy::SingleNode;
16759        s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
16760        s.validate().unwrap();
16761    }
16762
16763    // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
16764
16765    #[test]
16766    fn mesh_policy_default_is_empty() {
16767        // The Default impl carries None on every axis — the typed
16768        // analog of an unset `:politicas (())` slot. Renderers that
16769        // overlay the policy onto a cluster artifact key off this
16770        // predicate to skip the slot entirely; pinning so a future
16771        // axis added to MeshPolicy can't silently break the contract
16772        // (a new field whose Default is non-None would flip is_empty
16773        // to false on every existing caixa, surfacing here).
16774        assert!(MeshPolicy::default().is_empty());
16775    }
16776
16777    #[test]
16778    fn mesh_policy_with_only_timeout_is_not_empty() {
16779        let p = MeshPolicy {
16780            timeout: Some(Duration::from_secs(30)),
16781            ..Default::default()
16782        };
16783        assert!(!p.is_empty());
16784    }
16785
16786    #[test]
16787    fn mesh_policy_with_only_retries_is_not_empty() {
16788        let p = MeshPolicy {
16789            retries: Some(3),
16790            ..Default::default()
16791        };
16792        assert!(!p.is_empty());
16793    }
16794
16795    #[test]
16796    fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
16797        let p = MeshPolicy {
16798            circuit_breaker: Some(CircuitBreaker {
16799                max_failures: 5,
16800                window: Duration::from_secs(60),
16801            }),
16802            ..Default::default()
16803        };
16804        assert!(!p.is_empty());
16805    }
16806
16807    #[test]
16808    fn mesh_policy_with_only_mtls_required_is_not_empty() {
16809        // Even `mtls_required: Some(false)` (an explicit opt-out) is
16810        // not empty — the author *named* the axis, the renderer needs
16811        // to honor that vs. fall back to the cluster default.
16812        let p = MeshPolicy {
16813            mtls_required: Some(false),
16814            ..Default::default()
16815        };
16816        assert!(!p.is_empty());
16817    }
16818
16819    #[test]
16820    fn mesh_policy_with_only_rate_limit_is_not_empty() {
16821        let p = MeshPolicy {
16822            rate_limit: Some(RateLimit {
16823                rate: 100,
16824                window: Duration::from_secs(1),
16825            }),
16826            ..Default::default()
16827        };
16828        assert!(!p.is_empty());
16829    }
16830
16831    #[test]
16832    fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
16833        // The three-member happy-path fixture sets timeout + retries +
16834        // mtls_required — every populated axis must read non-empty.
16835        // Pin the round-trip so the M3.x per-:politicas emitter (the
16836        // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
16837        // on is_empty() to decide whether to emit at all without
16838        // re-deriving the contract from inline field probes.
16839        assert!(!three_member_spec().politicas.is_empty());
16840    }
16841
16842    // ── shared duration codec: cross-slot integer-magnitude gate ──
16843    //
16844    // The integer-magnitude discipline applied to
16845    // `supervisor::duration_codec::parse` lifts onto every typed slot
16846    // that routes through the shared codec — `MeshPolicy::timeout`
16847    // (`:politicas :timeout`) and `CircuitBreaker::window`
16848    // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
16849    // These cross-slot tests pin that the gate fires at the serde
16850    // layer for both typed slots, not just for the supervisor side.
16851
16852    #[test]
16853    fn policy_timeout_serde_rejects_fractional_seconds() {
16854        // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
16855        // so the shared codec's integer-magnitude gate applies on
16856        // deserialize. `"1.5s"` previously parsed to 1500ms and round-
16857        // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
16858        // deserialize with the canonical-form diagnostic naming the
16859        // offending `"1.5"` and the remediation `"1500ms"`.
16860        let payload = r#"{"timeout":"1.5s"}"#;
16861        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16862        let msg = err.to_string();
16863        assert!(
16864            msg.contains("not a non-negative integer"),
16865            "expected integer-magnitude diagnostic in {msg:?}"
16866        );
16867        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
16868        assert!(
16869            msg.contains("\"1500ms\""),
16870            "missing canonical-form remediation in {msg:?}"
16871        );
16872    }
16873
16874    #[test]
16875    fn policy_timeout_serde_rejects_leading_plus_sign() {
16876        // Pin the leading-`+` arm cross-slot — the prior f64 parser
16877        // accepted `"+30s"` silently and round-tripped to `"30s"`.
16878        let payload = r#"{"timeout":"+30s"}"#;
16879        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16880        let msg = err.to_string();
16881        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
16882    }
16883
16884    #[test]
16885    fn circuit_breaker_window_serde_rejects_fractional_minutes() {
16886        // `CircuitBreaker::window` uses `with =
16887        // "supervisor::duration_codec_required"` (the required-Duration
16888        // variant that delegates to the same shared parser). `"0.5m"`
16889        // parsed to 30s and round-tripped to `"30s"` on next emit —
16890        // DRIFT closed.
16891        let payload = format!(
16892            r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
16893            max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
16894            window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
16895        );
16896        let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
16897        let msg = err.to_string();
16898        assert!(
16899            msg.contains("not a non-negative integer"),
16900            "expected integer-magnitude diagnostic in {msg:?}"
16901        );
16902        assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
16903        assert!(
16904            msg.contains("\"30s\""),
16905            "missing canonical-form remediation in {msg:?}"
16906        );
16907    }
16908
16909    #[test]
16910    fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
16911        // Pin the happy-path on the cross-slot side: every canonical
16912        // author shape `render` ever emits parses cleanly through the
16913        // shared codec on the `CircuitBreaker` slot. The
16914        // codec's accepted set (post-gate) is exactly its emitted set
16915        // for the integer-magnitude class.
16916        for window_lit in ["30s", "500ms", "2m", "1h"] {
16917            let payload = format!(
16918                r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
16919                max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
16920                window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
16921            );
16922            let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
16923                panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
16924            });
16925            assert_eq!(cb.max_failures, 5);
16926        }
16927    }
16928
16929    // ── rate_limit_codec: integer-magnitude gate ──
16930    //
16931    // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
16932    // / 737a676 / d53c922 trajectory landed on every typed-duration /
16933    // typed-byte-size codec in caixa-core lifts onto the fifth typed
16934    // codec — `rate_limit_codec` — through the digit-only magnitude
16935    // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
16936    // These tests pin the gate at the serde layer for `:politicas
16937    // :rate-limit` (the only typed slot the codec backs), and at the
16938    // codec-internal `parse` layer for the canonical positive cases.
16939
16940    #[test]
16941    fn rate_limit_serde_rejects_fractional_rate() {
16942        // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
16943        // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
16944        // wording, which didn't name the canonical-form remediation or
16945        // the round-trip drift the next emit would produce. Now refused
16946        // at deserialize with the canonical-form diagnostic naming the
16947        // offending `"1.5"` magnitude and the round-trip drift wording.
16948        let payload = r#"{"rateLimit":"1.5/s"}"#;
16949        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16950        let msg = err.to_string();
16951        assert!(
16952            msg.contains("not a non-negative integer"),
16953            "expected integer-magnitude diagnostic in {msg:?}"
16954        );
16955        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
16956        assert!(
16957            msg.contains("THEORY.md"),
16958            "missing render-determinism contract citation in {msg:?}"
16959        );
16960    }
16961
16962    #[test]
16963    fn rate_limit_serde_rejects_leading_plus_sign() {
16964        // `u32::from_str("+100")` returns `Ok(100)` (Rust's
16965        // permissive-`+` parse), so `"+100/s"` silently parsed to
16966        // `RateLimit { 100, 1s }` and round-tripped through `render` to
16967        // `"100/s"` — a *different* canonical string on the next emit,
16968        // breaking the THEORY.md Part V render-determinism contract
16969        // exactly the way the peer duration codecs' `"+30s"` case did.
16970        // This is the load-bearing class the digit-only gate closes
16971        // beyond what `u32::from_str`'s strictness covers on its own.
16972        let payload = r#"{"rateLimit":"+100/s"}"#;
16973        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16974        let msg = err.to_string();
16975        assert!(
16976            msg.contains("not a non-negative integer"),
16977            "expected integer-magnitude diagnostic in {msg:?}"
16978        );
16979        assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
16980    }
16981
16982    #[test]
16983    fn rate_limit_serde_rejects_leading_minus_sign() {
16984        // The signed-negative arm: `"-1/s"` lands on the
16985        // non-canonical-but-numeric branch via the `i64` fallback (the
16986        // `f64` parse also succeeds), surfacing the canonical-form
16987        // diagnostic. Replaces the prior value-laundered "not a u32"
16988        // wording with the unified diagnostic across signs.
16989        let payload = r#"{"rateLimit":"-1/s"}"#;
16990        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16991        let msg = err.to_string();
16992        assert!(
16993            msg.contains("not a non-negative integer"),
16994            "expected integer-magnitude diagnostic in {msg:?}"
16995        );
16996        assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
16997    }
16998
16999    #[test]
17000    fn rate_limit_serde_rejects_decimal_shaped_integer() {
17001        // `"100.0/s"` is integer-valued numerically but not in the
17002        // codec's accepted set — `render` emits `"100/s"`, so the
17003        // round-trip would drift. Lifted to the canonical-form
17004        // diagnostic peer with the duration codec's `"1.0s"` case
17005        // (1c55a2a).
17006        let payload = r#"{"rateLimit":"100.0/s"}"#;
17007        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17008        let msg = err.to_string();
17009        assert!(
17010            msg.contains("not a non-negative integer"),
17011            "expected integer-magnitude diagnostic in {msg:?}"
17012        );
17013        assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
17014    }
17015
17016    #[test]
17017    fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
17018        // Non-numeric, non-digit-only input lands on the existing
17019        // narrower `"not a u32"` arm (preserved for diagnostic-shape
17020        // stability on the parser-shape footgun case). Pin this so a
17021        // future relaxation of the numeric-fallback predicate doesn't
17022        // silently collapse garbage onto the canonical-form arm — same
17023        // partition the peer duration codecs draw between
17024        // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
17025        let payload = r#"{"rateLimit":"abc/s"}"#;
17026        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17027        let msg = err.to_string();
17028        assert!(
17029            msg.contains("not a u32"),
17030            "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
17031        );
17032        assert!(
17033            !msg.contains("not a non-negative integer"),
17034            "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
17035        );
17036    }
17037
17038    #[test]
17039    fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
17040        // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
17041        // u32's range. The digit-only gate passes; `u32::from_str`
17042        // fails on overflow. Surface that with the overflow-shaped
17043        // diagnostic naming the offending magnitude verbatim, peer
17044        // with `supervisor::duration_codec`'s overflow arm. Pinning
17045        // the wording so a future refactor doesn't silently collapse
17046        // overflow onto the canonical-form arm.
17047        let payload = r#"{"rateLimit":"4294967296/s"}"#;
17048        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17049        let msg = err.to_string();
17050        assert!(
17051            msg.contains("overflows u32"),
17052            "expected overflow diagnostic in {msg:?}"
17053        );
17054        assert!(
17055            msg.contains("\"4294967296\""),
17056            "missing offending magnitude in {msg:?}"
17057        );
17058    }
17059
17060    #[test]
17061    fn rate_limit_serde_rejects_leading_zero_magnitude() {
17062        // `"0100/s"` is digit-only, so the existing
17063        // non-digit-only / sign / fractional arm doesn't catch it —
17064        // `u32::from_str("0100")` returns `Ok(100)`, so before this
17065        // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
17066        // round-tripped through `render` to `"100/s"` — a *different*
17067        // canonical string on the next emit, breaking the THEORY.md
17068        // Part V render-determinism contract exactly the way the
17069        // peer `"+100/s"` case did before the leading-`+` arm landed.
17070        // This is the load-bearing class the leading-zero gate closes
17071        // beyond what the existing digit-only / sign / fractional
17072        // gates cover, and the peer arm to the leading-`+` test
17073        // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
17074        // canonical-form-drift axis.
17075        let payload = r#"{"rateLimit":"0100/s"}"#;
17076        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17077        let msg = err.to_string();
17078        assert!(
17079            msg.contains("non-canonical leading zero"),
17080            "expected leading-zero diagnostic in {msg:?}"
17081        );
17082        assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
17083        assert!(
17084            msg.contains("THEORY.md"),
17085            "missing render-determinism contract citation in {msg:?}"
17086        );
17087    }
17088
17089    #[test]
17090    fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
17091        // `"00/s"` is the degenerate leading-zero case — every byte
17092        // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
17093        // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
17094        // a *different* canonical string, same render-determinism
17095        // violation. The single-byte `"0/s"` itself is in the
17096        // accepted set (round-trips losslessly through `render`,
17097        // refused downstream by `PolicyRateLimitZero`); the
17098        // multi-byte `"00/s"` is not. Pins the boundary between the
17099        // accepted single-`0` and the rejected leading-zero class.
17100        let payload = r#"{"rateLimit":"00/s"}"#;
17101        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17102        let msg = err.to_string();
17103        assert!(
17104            msg.contains("non-canonical leading zero"),
17105            "expected leading-zero diagnostic in {msg:?}"
17106        );
17107        assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
17108    }
17109
17110    #[test]
17111    fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
17112        // Cross-window pin — the gate is window-agnostic; the
17113        // leading-zero class is a property of the magnitude, not the
17114        // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
17115        // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
17116        // single-window coverage extended across the three canonical
17117        // windows the codec accepts.
17118        let payload = r#"{"rateLimit":"007/h"}"#;
17119        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17120        let msg = err.to_string();
17121        assert!(
17122            msg.contains("non-canonical leading zero"),
17123            "expected leading-zero diagnostic in {msg:?}"
17124        );
17125        assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
17126    }
17127
17128    #[test]
17129    fn rate_limit_serde_rejects_leading_whitespace() {
17130        // `" 100/s"` — the canonical paste-from-aligned-doc /
17131        // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
17132        // the top-level `s.trim()` silently ate the leading space and
17133        // parsed the value to `RateLimit { 100, 1s }`, which then
17134        // round-tripped through `render` to `"100/s"` (a *different*
17135        // canonical string on the next emit) — the exact
17136        // canonical-form-drift class the leading-`+` / leading-zero
17137        // arms already close, extended to the whitespace byte class.
17138        let payload = r#"{"rateLimit":" 100/s"}"#;
17139        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17140        let msg = err.to_string();
17141        assert!(
17142            msg.contains("contains whitespace byte"),
17143            "expected whitespace diagnostic in {msg:?}"
17144        );
17145        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
17146        assert!(
17147            msg.contains("THEORY.md"),
17148            "missing render-determinism contract citation in {msg:?}"
17149        );
17150    }
17151
17152    #[test]
17153    fn rate_limit_serde_rejects_trailing_whitespace() {
17154        // `"100/s "` — the canonical shell-history / trailing-space
17155        // paste footgun. Before this gate the top-level `s.trim()`
17156        // silently ate the trailing space and parsed to
17157        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
17158        // next emit — same canonical-form drift as the leading-space
17159        // sibling, closed on the same whitespace-byte arm.
17160        let payload = r#"{"rateLimit":"100/s "}"#;
17161        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17162        let msg = err.to_string();
17163        assert!(
17164            msg.contains("contains whitespace byte"),
17165            "expected whitespace diagnostic in {msg:?}"
17166        );
17167        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
17168    }
17169
17170    #[test]
17171    fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
17172        // `"100 / s"` — the canonical typographically-spaced author
17173        // shape (the same idiom every prose reference to a rate limit
17174        // renders as, mistakenly retained when the value is pasted
17175        // into a codec-shaped slot). Before this gate the per-part
17176        // `rate_str.trim()` / `unit.trim()` calls silently ate both
17177        // spaces on either side of `/` and parsed to
17178        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
17179        // codec's *internal* whitespace-tolerance vector, orthogonal
17180        // to the leading / trailing surface but the same canonical-
17181        // form-drift class. Pins the arm as strictly stronger than the
17182        // pre-existing top-level `s.trim()` behavior: it fires on
17183        // whitespace anywhere in the value, not just at the string
17184        // boundary.
17185        let payload = r#"{"rateLimit":"100 / s"}"#;
17186        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17187        let msg = err.to_string();
17188        assert!(
17189            msg.contains("contains whitespace byte"),
17190            "expected whitespace diagnostic in {msg:?}"
17191        );
17192        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
17193    }
17194
17195    #[test]
17196    fn rate_limit_serde_rejects_tab_byte() {
17197        // `"\t100/s"` — the canonical paste-from-indented-doc /
17198        // paste-from-YAML-block-scalar footgun where a tab byte leads
17199        // the magnitude. Pins that the gate covers tab (`0x09`) as
17200        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
17201        // members and both would be silently swallowed by `s.trim()`
17202        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
17203        // space alone to the full ASCII-whitespace set (space `0x20`,
17204        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
17205        // the tab arm as a representative of the non-space members.
17206        let payload = r#"{"rateLimit":"\t100/s"}"#;
17207        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17208        let msg = err.to_string();
17209        assert!(
17210            msg.contains("contains whitespace byte"),
17211            "expected whitespace diagnostic in {msg:?}"
17212        );
17213        assert!(
17214            msg.contains("0x09"),
17215            "missing offending tab byte in {msg:?}"
17216        );
17217    }
17218
17219    // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
17220    //
17221    // Successor to the ASCII-whitespace arm (1ad7755) on
17222    // `rate_limit_codec` — closes the strictly-complementary class the
17223    // byte-scan cannot see, through the lifted
17224    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
17225
17226    #[test]
17227    fn rate_limit_serde_rejects_leading_nbsp() {
17228        // NBSP prefix — paste-from-typography footgun. Byte-scan
17229        // misses, `str::trim` silently strips it, value drifts to
17230        // `"100/s"` on next serialize.
17231        let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
17232        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17233        let msg = err.to_string();
17234        assert!(
17235            msg.contains("non-ASCII Unicode whitespace character"),
17236            "expected non-ASCII whitespace diagnostic in {msg:?}"
17237        );
17238        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
17239    }
17240
17241    #[test]
17242    fn rate_limit_serde_rejects_internal_em_space() {
17243        // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
17244        // paste-from-typography footgun on the `<integer>/<unit>`
17245        // shape.
17246        let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
17247        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17248        let msg = err.to_string();
17249        assert!(
17250            msg.contains("non-ASCII Unicode whitespace character"),
17251            "expected non-ASCII whitespace diagnostic in {msg:?}"
17252        );
17253        assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
17254    }
17255
17256    #[test]
17257    fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
17258        // Positive-control pin: every ASCII-only canonical form the
17259        // renderer emits stays accepted through the new arm.
17260        for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
17261            let payload = format!(r#"{{"rateLimit":{lit}}}"#);
17262            let p: MeshPolicy = serde_json::from_str(&payload)
17263                .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
17264            assert!(p.rate_limit.is_some());
17265        }
17266    }
17267
17268    #[test]
17269    fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
17270        // The boundary case — `"0/s"` is the canonical form
17271        // `render(RateLimit { 0, 1s })` emits, so the codec accepts
17272        // it at the parse layer; the downstream
17273        // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
17274        // `rate == 0` at the typed-validate layer above. Pins the
17275        // partition: the leading-zero gate at the codec layer does
17276        // not poach the rate-zero semantic-validation arm at the
17277        // typed-validate layer above (a future stricter codec must
17278        // not reject `"0/s"` here, or it'd collapse the diagnostic
17279        // partitioning that lets `PolicyRateLimitZero` name the
17280        // offending typed slot).
17281        let payload = r#"{"rateLimit":"0/s"}"#;
17282        let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
17283            panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
17284        });
17285        let rl = policy.rate_limit.expect("rate_limit must be Some");
17286        assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
17287        assert_eq!(
17288            rl.window,
17289            Duration::from_secs(1),
17290            "single-`0` magnitude with `s` unit must parse to window=1s"
17291        );
17292    }
17293
17294    #[test]
17295    fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
17296        // The complementary boundary pin — every magnitude
17297        // `render` emits starts with `[1-9]` (or is the single byte
17298        // `"0"`), so the canonical-form predicate is `(len == 1) ||
17299        // (first byte != '0')`. Pinning the `len > 1 && first byte ==
17300        // '1'` case explicitly so a future tightening of the gate
17301        // (e.g. an over-eager "no leading digit < 5" rule, or a
17302        // mistakenly anchored start-of-magnitude byte check) lands
17303        // here before the canonical-forms-iterating test would catch
17304        // it.
17305        let payload = r#"{"rateLimit":"100/s"}"#;
17306        let policy: MeshPolicy = serde_json::from_str(payload)
17307            .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
17308        let rl = policy.rate_limit.expect("rate_limit must be Some");
17309        assert_eq!(
17310            rl.rate, 100,
17311            "canonical-100 magnitude must parse to rate=100"
17312        );
17313    }
17314
17315    #[test]
17316    fn rate_limit_serde_accepts_integer_canonical_forms() {
17317        // Pin the happy-path: every canonical author shape `render`
17318        // ever emits parses cleanly through the codec post-gate. The
17319        // codec's accepted set (post-gate) is exactly its emitted set
17320        // for the integer-magnitude class — same property
17321        // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
17322        // gates guarantee on the peer codecs. Iterating across rate
17323        // magnitudes (including `"0"`, which the codec accepts even
17324        // though `validate_politicas` rejects `rate == 0` at the typed
17325        // layer above) closes the codec contract at the parse layer
17326        // independently of the validate layer.
17327        for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
17328            for unit_lit in ["s", "m", "h"] {
17329                let lit = format!("{rate_lit}/{unit_lit}");
17330                let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
17331                let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
17332                    panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
17333                });
17334                let rl = policy.rate_limit.expect("rate_limit must be Some");
17335                assert_eq!(
17336                    rl.rate,
17337                    rate_lit.parse::<u32>().unwrap(),
17338                    "rate mismatch for {lit:?}"
17339                );
17340            }
17341        }
17342    }
17343
17344    #[test]
17345    fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
17346        // The structural property the gate enforces: serialize ∘
17347        // deserialize is the identity on every canonical author shape.
17348        // Peer of `parse_byte_size`'s and `parse_duration`'s
17349        // `_round_trips_through_render_for_every_canonical_form` tests
17350        // on the rate-limit axis. Before the gate, `"+100/s"` violated
17351        // this (`parse` → `RateLimit { 100, 1s }` → `render` →
17352        // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
17353        for rate in [1u32, 100, 5000, 1_000_000] {
17354            for (window, unit) in [
17355                (Duration::from_secs(1), "s"),
17356                (Duration::from_secs(60), "m"),
17357                (Duration::from_secs(3600), "h"),
17358            ] {
17359                let policy = MeshPolicy {
17360                    rate_limit: Some(RateLimit { rate, window }),
17361                    ..Default::default()
17362                };
17363                let json = serde_json::to_string(&policy).unwrap();
17364                let expected = format!("\"{rate}/{unit}\"");
17365                assert!(
17366                    json.contains(&expected),
17367                    "expected {expected:?} in {json:?}"
17368                );
17369                let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17370                assert_eq!(
17371                    back.rate_limit, policy.rate_limit,
17372                    "round-trip for {json:?}"
17373                );
17374            }
17375        }
17376    }
17377
17378    // ── self-membership cross-slot gate ──────────────────────────────
17379
17380    #[test]
17381    fn validate_no_self_membership_rejects_self_named_membro() {
17382        // An Aplicacao whose `:membros` lists its own `:nome` is a
17383        // one-node lacre-closure recursion — rejected, naming the parent.
17384        let membros = vec![
17385            membro("catalog", "^0.1"),
17386            membro("checkout", "^0.1"),
17387            membro("cart", "^0.1"),
17388        ];
17389        let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
17390        assert!(
17391            matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
17392            "got {err:?}"
17393        );
17394    }
17395
17396    #[test]
17397    fn validate_no_self_membership_accepts_distinct_membros() {
17398        // Positive control: distinct member names (including a member
17399        // that is itself an Aplicacao — recursive composition is valid,
17400        // MESH-COMPOSITION §V) pass the gate.
17401        let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
17402        validate_no_self_membership(&membros, "checkout").unwrap();
17403    }
17404
17405    #[test]
17406    fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
17407        // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
17408        // `NoMembros` arm (the more-fundamental "graph must have nodes"
17409        // gate), not by this cross-slot self-edge gate. Keeping the
17410        // self-membership predicate vacuously-ok on the empty input
17411        // matches its supervisor-axis peer
17412        // (`validate_no_self_supervision_empty_children_is_ok`) and
17413        // makes the gate composable from any future call site (an M4
17414        // CR materializer's per-membros validator) without re-checking
17415        // emptiness.
17416        validate_no_self_membership(&[], "checkout").unwrap();
17417    }
17418
17419    #[test]
17420    fn validate_no_self_membership_diagnostic_names_offending_caixa() {
17421        // Pinning the Display: the self-membership diagnostic must name
17422        // the offending caixa verbatim + the "lists itself" framing the
17423        // author can grep for, so the cluster-far failure surfaces at
17424        // build time with one-line remediation. Same diagnostic shape
17425        // as the supervisor-axis `ChildSupervisesSelf` peer.
17426        let membros = vec![membro("orquestra", "^0.1")];
17427        let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
17428        let msg = err.to_string();
17429        assert!(
17430            msg.contains("orquestra"),
17431            "diagnostic must name the offending caixa nome (got: {msg:?})"
17432        );
17433        assert!(
17434            msg.contains("lists itself"),
17435            "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
17436        );
17437    }
17438
17439    #[test]
17440    fn default_servico_port_constant_pins_canonical_8080_literal() {
17441        // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
17442        // at the verbatim `8080` literal both consumers (the
17443        // `Entrada::port` serde default via [`default_port`] and the
17444        // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
17445        // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
17446        // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
17447        // discipline (a085b26) on the per-renderer canonical-K8s-axis
17448        // string-constant axis: a future refactor that drifts the
17449        // constant out from under either consumer surfaces here ahead
17450        // of every per-renderer's first emission. The literal value
17451        // matches the well-known HTTP-alt port the `pleme-computeunit`
17452        // library chart already emits as its `trigger.service.port`
17453        // default — by construction the same value the substrate
17454        // assumes about every Servico's in-cluster L4 listener.
17455        assert_eq!(
17456            DEFAULT_SERVICO_PORT, 8080,
17457            "canonical Servico port literal must remain `8080` verbatim — \
17458             this is the value both the `Entrada::port` serde default and the \
17459             caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
17460        );
17461    }
17462
17463    #[test]
17464    fn default_port_helper_returns_canonical_servico_port_constant() {
17465        // The bridge-arm — pins that the [`default_port`] helper
17466        // [`Entrada::port`]'s `#[serde(default = "default_port")]`
17467        // attribute hooks routes through the lifted
17468        // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
17469        // literal. A future refactor that re-introduces the `8080`
17470        // literal at the helper's return site (silently re-opening
17471        // the drift footgun this lift closed) surfaces here ahead of
17472        // every author-side `(:entrada (:host … :para …))` slot
17473        // without an explicit `:port`. Peer with the
17474        // `default_namespace_re_export_points_at_caixa_core_canonical`
17475        // pin on the caixa-mesh-side re-export axis.
17476        assert_eq!(
17477            default_port(),
17478            DEFAULT_SERVICO_PORT,
17479            "the serde-default helper must route through the lifted constant"
17480        );
17481    }
17482
17483    #[test]
17484    fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
17485        // The end-to-end pin — an author-surface `(:entrada (:host …
17486        // :para …))` without an explicit `:port` slot deserializes to
17487        // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
17488        // verbatim. Routes the canonical lifted constant through both
17489        // the serde-default machinery (the `#[serde(default =
17490        // "default_port")]` attribute) and the typed-value-shape
17491        // contract (the resulting [`Entrada::port`] value). A future
17492        // refactor that drifts either axis — replacing the serde
17493        // hook's helper, changing the typed slot's wire shape — would
17494        // surface here before any per-renderer's CNP / Gateway /
17495        // HTTPRoute emission consumed the drifted default.
17496        let entrada: Entrada =
17497            serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
17498        assert_eq!(
17499            entrada.port, DEFAULT_SERVICO_PORT,
17500            "the serde default must materialize as the lifted canonical Servico port"
17501        );
17502    }
17503
17504    #[test]
17505    fn servico_port_min_pins_canonical_accept_set_floor() {
17506        // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
17507        // verbatim `1` literal every typed `:entrada :port` acceptance
17508        // gate keys off. Peer with the
17509        // [`default_servico_port_constant_pins_canonical_8080_literal`]
17510        // discipline on the canonical-Servico-port-constant axis: a
17511        // future refactor that drifts the accept-set floor out from
17512        // under the sole consumer at [`AplicacaoSpec::validate`]'s
17513        // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
17514        // every per-`:entrada` `EntradaPortZero` diagnostic. The
17515        // literal value matches the IANA-registered TCP/UDP port
17516        // space floor (`1..=65535` — port `0` is the "any ephemeral"
17517        // sentinel, not a well-defined destination the substrate's
17518        // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
17519        // axis can honor).
17520        assert_eq!(
17521            SERVICO_PORT_MIN, 1,
17522            "canonical Servico port accept-set floor must remain `1` verbatim — \
17523             this is the value the `AplicacaoSpec::validate` gate at \
17524             `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
17525        );
17526    }
17527
17528    #[test]
17529    fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
17530        // The cross-const invariant pin — the substrate's canonical
17531        // default port must satisfy its own accept-set floor by
17532        // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
17533        // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
17534        // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
17535        // override the operator pins through a future
17536        // `:placement :default-port` slot that lands out-of-range, a
17537        // per-edition Servico-port migration that lifted the floor
17538        // above the previous default without coordinating the pair —
17539        // would silently invalidate the serde-default emission at
17540        // every author-side `(:entrada (:host … :para …))` slot
17541        // without an explicit `:port`: the default port would fall
17542        // below the accept-set floor, the `AplicacaoSpec::validate`
17543        // gate would reject every default-carrying Aplicacao as
17544        // `EntradaPortZero`, and the substrate's typed
17545        // `(defcaixa … :kind Aplicacao)` surface would fail validate
17546        // on every Aplicacao whose author omitted `:entrada :port`
17547        // for the substrate's chosen default — a class of authoring-
17548        // surface footguns the compile-time pin structurally closes.
17549        // Peer with the
17550        // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
17551        // (27f9b34) cross-const invariant pin discipline on the peer
17552        // canonical-Helm-per-values-block child-chart-enablement-toggle
17553        // axis pair.
17554        assert!(
17555            SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
17556            "the substrate's canonical default port ({DEFAULT_SERVICO_PORT}) must \
17557             satisfy its own accept-set floor (SERVICO_PORT_MIN = {SERVICO_PORT_MIN}) — \
17558             every default-carrying `(:entrada (:host … :para …))` slot without an \
17559             explicit `:port` inherits `DEFAULT_SERVICO_PORT` through the serde default \
17560             hook and must pass the `AplicacaoSpec::validate` floor gate by construction"
17561        );
17562    }
17563
17564    #[test]
17565    fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
17566        // The gate-site pin — asserts the `AplicacaoSpec::validate`
17567        // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
17568        // `EntradaPortZero` diagnostic on the below-floor input
17569        // `port: 0` (the only below-floor value the `u16` field can
17570        // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
17571        // is the singleton `{0}`). A future refactor that drifts the
17572        // gate off the lifted const (silently re-introducing an
17573        // inline `if e.port == 0` byte-check) surfaces here — the
17574        // pin cannot distinguish `< 1` from `== 0` on the current
17575        // floor, but it *does* pin that the diagnostic fires on `0`
17576        // through whichever gate is wired, so any future accept-set
17577        // floor migration (a hypothetical unprivileged-only
17578        // migration lifting `SERVICO_PORT_MIN` to `1024`) must
17579        // update this test alongside the const declaration —
17580        // structurally guaranteeing the gate + accept-set + pin
17581        // trio move together. Peer with the
17582        // [`rejects_zero_entrada_port`] behavioral pin on the same
17583        // per-`:entrada :port` axis — that pin asserts the pre-lift
17584        // behavioral contract (`port: 0` → `EntradaPortZero`); this
17585        // pin adds the structural link to the lifted floor const.
17586        assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
17587        let mut s = three_member_spec();
17588        s.entrada.as_mut().unwrap().port = 0;
17589        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
17590    }
17591
17592    // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
17593
17594    #[test]
17595    fn membro_serde_keys_match_lifted_membro_key_consts() {
17596        // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
17597        // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
17598        // name the exact camelCase JSON keys the
17599        // `#[serde(rename_all = "camelCase")]` attribute on
17600        // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
17601        // that each canonical byte-sequence appears verbatim in the
17602        // JSON — a future accidental `rename_all = "snake_case"` /
17603        // `"kebab-case"` / verbatim-field-name flip at the derive
17604        // attribute (any of which would silently break every downstream
17605        // JSON consumer that reaches for one of the two consts via
17606        // `Value::get(...)`) surfaces here as a build-time test failure
17607        // at `aplicacao.rs`, not as an apply-time
17608        // `.get(<stale-canonical-const>)` returning `None` far from the
17609        // derive-attr drift's commit. Peer with the sibling
17610        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
17611        // (40cc4e5) pin on the M2 supervision-tree top-level axis —
17612        // same discipline the SupervisorSpec top-level lift established,
17613        // extended here to the M3 [`Membro`] per-`:membros` axis.
17614        let m = Membro {
17615            caixa: "catalog".into(),
17616            versao: "^0.1".into(),
17617        };
17618        let json = serde_json::to_string(&m).unwrap();
17619        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
17620            let quoted = format!("\"{key}\"");
17621            assert!(
17622                json.contains(&quoted),
17623                "serialized Membro must carry the lifted MEMBRO_KEY_* \
17624                 byte-sequence {quoted} verbatim in the JSON emission \
17625                 (got: {json})",
17626            );
17627        }
17628    }
17629
17630    #[test]
17631    fn membro_key_consts_are_pairwise_distinct() {
17632        // Cross-axis drift-detection pin: a future collapse of the two
17633        // canonical [`Membro`] per-entry byte-strings onto the same
17634        // value (e.g. an accidental copy-paste flip of
17635        // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
17636        // silently reroute every downstream probe on one axis onto the
17637        // sibling axis's overlay entry and pass every propagation-probe
17638        // test that expected only the stale axis's value. Peer of the
17639        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
17640        // (40cc4e5).
17641        let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
17642        for (i, a) in all.iter().enumerate() {
17643            for b in all.iter().skip(i + 1) {
17644                assert_ne!(
17645                    a, b,
17646                    "MEMBRO_KEY_* consts must be pairwise-distinct \
17647                     canonical byte-sequences — got `{a}` == `{b}`",
17648                );
17649            }
17650        }
17651    }
17652
17653    // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
17654    //    URL-path fallback resolver every HTTPRoute-aware renderer
17655    //    reaching for a per-rule path-list resolution routes through.
17656    //    The four pin tests below fix the four-way accept-set the
17657    //    resolver must always honor: (:paths-non-empty-verbatim,
17658    //    :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
17659    //    :paths-preserves-order-across-multiple-entries) — drift on any
17660    //    arm surfaces at caixa-core build time rather than at cluster-
17661    //    apply time. Peer discipline with `MeshPolicy::is_empty` on the
17662    //    sibling `:politicas` typed-primitive dispatch axis.
17663
17664    fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
17665        Entrada {
17666            host: "example.com".into(),
17667            para: "cart".into(),
17668            paths: paths.into_iter().map(String::from).collect(),
17669            port: DEFAULT_SERVICO_PORT,
17670        }
17671    }
17672
17673    #[test]
17674    fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
17675        // The typed `:entrada :paths` slot carries an author-declared
17676        // list — the resolver returns each entry verbatim, no
17677        // catch-all substitution. The canonical "author declared
17678        // paths, honor them verbatim" arm of the path-list dispatch.
17679        let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
17680        assert_eq!(
17681            e.resolved_paths(),
17682            vec!["/api/cart", "/api/products"],
17683            "resolved_paths must return each `:entrada :paths` entry \
17684             verbatim when the typed slot is non-empty (got {:?})",
17685            e.resolved_paths(),
17686        );
17687    }
17688
17689    #[test]
17690    fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
17691        // Empty `:entrada :paths` slot — the resolver substitutes the
17692        // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
17693        // catch-all fallback verbatim. Pins the empty-arm of the
17694        // resolver's four-way accept-set against a future silent
17695        // detour that returned an empty Vec (which would emit an
17696        // HTTPRoute with zero rules — silently dropping every
17697        // external `:entrada` flow at admission time), routed to a
17698        // different fallback shape, or dropped the catch-all
17699        // altogether.
17700        let e = entrada_with_paths(vec![]);
17701        assert_eq!(
17702            e.resolved_paths(),
17703            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
17704            "resolved_paths on empty `:entrada :paths` must fall back \
17705             to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
17706             all — got {:?}",
17707            e.resolved_paths(),
17708        );
17709    }
17710
17711    #[test]
17712    fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
17713        // Single-entry `:entrada :paths` — the resolver returns the
17714        // single declared path verbatim, NOT the catch-all fallback
17715        // (author declared a path, honor it — the empty-arm and the
17716        // len-1 arm are semantically distinct axes of the resolver's
17717        // accept-set). Pins that the resolver treats "author declared
17718        // one path" as authored input, not as the empty case.
17719        let e = entrada_with_paths(vec!["/api/only"]);
17720        assert_eq!(
17721            e.resolved_paths(),
17722            vec!["/api/only"],
17723            "resolved_paths on single-entry `:entrada :paths` must \
17724             return the declared path verbatim, NOT the catch-all \
17725             fallback (got {:?})",
17726            e.resolved_paths(),
17727        );
17728    }
17729
17730    #[test]
17731    fn resolved_paths_preserves_author_declared_order() {
17732        // The `:entrada :paths` list is author-ordered — the resolver
17733        // preserves the author's declaration order verbatim, since
17734        // per-rule dispatch order at the K8s Gateway API HTTPRoute
17735        // consumer is significant (first-match-wins under the
17736        // path-prefix matcher). Pins against a future silent
17737        // re-sort / dedup / normalize detour that reordered author
17738        // input.
17739        let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
17740        assert_eq!(
17741            e.resolved_paths(),
17742            vec!["/z/last", "/a/first", "/m/mid"],
17743            "resolved_paths must preserve author-declared `:entrada \
17744             :paths` order verbatim — got {:?}",
17745            e.resolved_paths(),
17746        );
17747    }
17748
17749    // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
17750    //    slot `&[String]` slice accessor every per-`:entrada` consumer
17751    //    that must see the author's declaration verbatim (not the
17752    //    fallback-applied projection the sibling `resolved_paths`
17753    //    returns) routes through. The three pin tests below fix the
17754    //    accept-set the accessor must honor: (:non-empty-byte-equal,
17755    //    :empty-projects-empty-slice, :preserves-author-declared-order)
17756    //    — drift on any arm surfaces at caixa-core build time rather
17757    //    than at cluster-apply time. Peer discipline with the sibling
17758    //    [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
17759    //    peer M3 mesh-slot `Vec<String>`-carry axis.
17760
17761    #[test]
17762    fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
17763        // Byte-equal pin: [`Entrada::paths`] must project the raw
17764        // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
17765        // slice borrowed from the typed slot's own [`Vec<String>`]
17766        // storage — no re-ordering, no dedup, no per-entry normalization,
17767        // no fallback substitution (the fallback-applying projection is
17768        // the sibling [`Entrada::resolved_paths`] resolver). Pins against
17769        // a future silent detour that re-normalized the list, dropped
17770        // duplicates the [`AplicacaoSpec::validate`]
17771        // `EntradaPathDuplicate` refusal already rejects at build time,
17772        // or (most severe) accidentally routed through the fallback-
17773        // applying sibling and returned the substrate catch-all when
17774        // the author declared an empty list — collapsing the raw-slot
17775        // and fallback-applied axes into one and breaking the
17776        // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
17777        //
17778        // Peer of the sibling
17779        // [`Placement::clusters`]-shape byte-equal pin
17780        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
17781        // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
17782        let fixtures: Vec<Vec<String>> = vec![
17783            Vec::new(),
17784            vec!["/api/cart".into()],
17785            vec!["/api/cart".into(), "/api/products".into()],
17786            vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
17787        ];
17788        for paths in fixtures {
17789            let e = Entrada {
17790                host: "example.com".into(),
17791                para: "cart".into(),
17792                paths: paths.clone(),
17793                port: DEFAULT_SERVICO_PORT,
17794            };
17795            assert_eq!(
17796                e.paths(),
17797                paths.as_slice(),
17798                "Entrada::paths must return :entrada :paths verbatim \
17799                 (got {:?}, expected {:?})",
17800                e.paths(),
17801                paths.as_slice(),
17802            );
17803            assert_eq!(
17804                e.paths(),
17805                e.paths.as_slice(),
17806                "Entrada::paths accessor and .paths.as_slice() field \
17807                 access must byte-equal — the accessor is the substrate-\
17808                 primitive typed dispatch every downstream per-`:entrada` \
17809                 raw-slot path-list consumer must route through",
17810            );
17811            assert_eq!(
17812                e.paths().len(),
17813                e.paths.len(),
17814                "Entrada::paths().len() must byte-equal self.paths.len() \
17815                 — a length drift would silently split the paired \
17816                 pre-flight cascade-head `.is_empty()` probe input in \
17817                 the sibling [`Entrada::resolved_paths`] resolver from \
17818                 the per-entry validate loop's traversal input in \
17819                 [`AplicacaoSpec::validate`]",
17820            );
17821        }
17822    }
17823
17824    #[test]
17825    fn resolved_paths_reads_through_lifted_paths_accessor() {
17826        // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
17827        // pre-flight `.paths().is_empty()` cascade-head probe (which
17828        // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
17829        // catch-all fallback arm when the accessor projects the empty
17830        // slice) and the per-entry `.paths().iter().map(String::as_str)`
17831        // projection (which must reach every entry in the same order
17832        // the accessor projects, so the sibling
17833        // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
17834        // per-entry projection stay in lockstep by construction) must
17835        // both key off the lifted accessor. Pins the two-site coherence
17836        // by exercising each production consumer end-to-end: (1) the
17837        // catch-all-fallback arm under the empty slice, (2) the
17838        // author-declared-verbatim arm under a two-entry cohort whose
17839        // per-entry projection must byte-equal the input's per-entry
17840        // author-declared paths in the author's declared order.
17841        //
17842        // Peer of the sibling M3
17843        // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
17844        // `validate_placement_reads_through_lifted_clusters_accessor`
17845        // on the sibling `Placement::clusters` reader-site convergence.
17846        let empty = entrada_with_paths(vec![]);
17847        assert_eq!(
17848            empty.resolved_paths(),
17849            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
17850            "resolved_paths on empty :entrada :paths must trip the \
17851             lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
17852             catch-all fallback — routing through the lifted paths() \
17853             accessor must not silently drop the fallback arm",
17854        );
17855
17856        let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
17857        assert_eq!(
17858            declared.resolved_paths(),
17859            vec!["/api/cart", "/api/products"],
17860            "resolved_paths on non-empty :entrada :paths must return each \
17861             entry verbatim in the author's declared order — routing \
17862             through the lifted paths() accessor must not silently \
17863             reorder or drop entries",
17864        );
17865        // Byte-equal pin against the raw-slot accessor to keep the
17866        // fallback-applying resolver's per-entry projection input in
17867        // lockstep with the raw-slot accessor's projection.
17868        let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
17869        assert_eq!(
17870            declared.resolved_paths(),
17871            raw_projected,
17872            "resolved_paths non-empty projection must byte-equal the \
17873             lifted paths() accessor's per-entry String::as_str projection \
17874             — the two projections share the same input slice by \
17875             construction, so any drift here would surface a silent \
17876             re-ordering / dedup / normalization detour in the resolver",
17877        );
17878    }
17879
17880    #[test]
17881    fn validate_reads_through_lifted_entrada_paths_accessor() {
17882        // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
17883        // per-entry value-shape gate's `for p in e.paths()` traversal
17884        // (which must reach every entry in the same order the accessor
17885        // projects, so both the per-entry `EntradaPathEmpty` /
17886        // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
17887        // the duplicate-detection HashSet insert that trips
17888        // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
17889        // projection) must route through the lifted accessor. Pins the
17890        // coherence by exercising each production consumer end-to-end:
17891        // (1) the `EntradaPathEmpty` refusal fires on the second entry
17892        // of a two-entry cohort whose head is valid but tail is empty
17893        // (which requires the loop to reach the second entry through
17894        // the accessor), and (2) the `EntradaPathDuplicate` refusal
17895        // fires on the second entry of a two-entry cohort that shares
17896        // a path (which requires the loop to reach both entries — a
17897        // first-entry-only projection would silently pass since the
17898        // dedup HashSet has room for the first insert).
17899        //
17900        // Peer of the sibling
17901        // `validate_placement_reads_through_lifted_clusters_accessor`
17902        // on the sibling `Placement::clusters` reader-site convergence.
17903        let base = crate::AplicacaoSpec {
17904            membros: vec![crate::Membro {
17905                caixa: "cart".into(),
17906                versao: "^0.1".into(),
17907            }],
17908            contratos: Vec::new(),
17909            politicas: crate::MeshPolicy::default(),
17910            placement: crate::Placement {
17911                estrategia: crate::PlacementStrategy::SingleNode,
17912                clusters: vec!["rio".into()],
17913                shard_key: None,
17914                affinity: None,
17915            },
17916            entrada: Some(Entrada {
17917                host: "example.com".into(),
17918                para: "cart".into(),
17919                paths: vec!["/api/cart".into(), String::new()],
17920                port: DEFAULT_SERVICO_PORT,
17921            }),
17922        };
17923        assert_eq!(
17924            base.validate(),
17925            Err(crate::AplicacaoError::EntradaPathEmpty),
17926            "validate must trip EntradaPathEmpty on the second entry of \
17927             a two-entry cohort — routing through the lifted paths() \
17928             accessor must not silently short-circuit the loop at the \
17929             valid head entry",
17930        );
17931
17932        let mut dup = base;
17933        dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
17934        assert_eq!(
17935            dup.validate(),
17936            Err(crate::AplicacaoError::EntradaPathDuplicate {
17937                path: "/api/cart".into(),
17938            }),
17939            "validate must trip EntradaPathDuplicate on the second entry \
17940             of a two-entry cohort that shares a path — routing through \
17941             the lifted paths() accessor must not silently short-circuit \
17942             the dedup HashSet insert at the first entry",
17943        );
17944    }
17945
17946    // ── Entrada::hostname / Entrada::hostnames — the substrate-
17947    //    canonical per-`:entrada` DNS-hostname resolver pair every
17948    //    Gateway-API-aware renderer reaching for a per-listener
17949    //    singular `hostname:` filter (Gateway) or a per-route plural
17950    //    `spec.hostnames[]` filter list (HTTPRoute) routes through.
17951    //    The three pin tests below fix the two-way accept-set the pair
17952    //    must always honor: (:singular-byte-equal-to-host,
17953    //    :plural-is-singleton-of-singular, :plural-len-is-one) — drift
17954    //    on any arm surfaces at caixa-core build time rather than at
17955    //    cluster-apply time when the API server refuses the HTTPRoute
17956    //    for non-intersecting hostname filters. Peer discipline with
17957    //    the sibling `resolved_paths` accept-set pin block above on the
17958    //    per-`:entrada` path-list resolver axis.
17959
17960    fn entrada_with_host(host: &str) -> Entrada {
17961        Entrada {
17962            host: host.into(),
17963            para: "cart".into(),
17964            paths: Vec::new(),
17965            port: DEFAULT_SERVICO_PORT,
17966        }
17967    }
17968
17969    #[test]
17970    fn hostname_returns_entrada_host_byte_equal() {
17971        // The canonical singular-axis pin: [`Entrada::hostname`] must
17972        // return the `:entrada :host` field byte-for-byte, borrowed
17973        // from the typed slot's own [`String`] storage. Pins against a
17974        // future silent detour that re-normalized the host (an
17975        // accidental `.to_lowercase()` — validate_entrada_host already
17976        // enforces lowercase, so any re-normalization is redundant + a
17977        // drift surface between the validator and the accessor), a
17978        // trailing-`.` fully-qualified DNS shape substitution, or a
17979        // Punycode round-trip that lowered a Unicode host through IDNA.
17980        let e = entrada_with_host("checkout.quero.cloud");
17981        assert_eq!(
17982            e.hostname(),
17983            "checkout.quero.cloud",
17984            "Entrada::hostname must return :entrada :host verbatim \
17985             (got {:?})",
17986            e.hostname(),
17987        );
17988        assert_eq!(
17989            e.hostname(),
17990            e.host.as_str(),
17991            "Entrada::hostname must byte-equal the .host field access",
17992        );
17993    }
17994
17995    #[test]
17996    fn hostnames_returns_singleton_of_hostname_accessor() {
17997        // The pair-invariant pin: [`Entrada::hostnames`] must always
17998        // return exactly `vec![hostname()]` — the singleton list whose
17999        // sole entry is the substrate's canonical per-`:entrada`
18000        // singular hostname. Pins the two-consumer coherence axis: the
18001        // Gateway listener's singular `hostname:` filter and the
18002        // HTTPRoute's plural `spec.hostnames[]` filter list must
18003        // agree, else the Gateway API v1.x conformance layer rejects
18004        // the HTTPRoute at attach time with
18005        // `Accepted:False/NoMatchingParent` (the parent Gateway's
18006        // listener hostname doesn't intersect the route's hostname
18007        // filter list) — a divergence whose apply-time symptom is far
18008        // from any single-site commit and never surfaces in the
18009        // emitted YAML. Pinning the pair-invariant here makes any
18010        // future accidental split (an accidental `.to_string() + "."`
18011        // trailing-`.` on the plural side that didn't land on the
18012        // singular side, an accidental prefix stripping on one axis,
18013        // an accidental wildcard prepend the SNI fan-out overlay
18014        // authors on the plural side without a paired singular
18015        // migration) trip at caixa-core build time.
18016        let e = entrada_with_host("checkout.quero.cloud");
18017        assert_eq!(
18018            e.hostnames(),
18019            vec![e.hostname()],
18020            "Entrada::hostnames must return `vec![hostname()]` under \
18021             the pair-invariant — got {:?} vs. singleton {:?}",
18022            e.hostnames(),
18023            vec![e.hostname()],
18024        );
18025    }
18026
18027    #[test]
18028    fn hostnames_is_singleton_under_single_host_author_surface() {
18029        // The singleton-shape pin: under today's single-hostname-per-
18030        // `:entrada` author surface (the `:host` slot is a single
18031        // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
18032        // must always return a list of length exactly one. Pins
18033        // against a future silent detour that returned an empty list
18034        // (which would emit an HTTPRoute with `spec.hostnames: []` —
18035        // matching every incoming Host header regardless of the
18036        // Aplicacao's declared ingress apex, silently over-matching
18037        // every foreign VirtualHost the parent Gateway also fronts) or
18038        // a duplicated entry (which the Gateway API v1.x parser
18039        // accepts as a `[]-length-2 list of equal hostnames]` but
18040        // whose semantics differ from the intended singleton). The
18041        // author-surface extension point ("a future `:entrada
18042        // :alt-hosts` list overlay" the docstring names) is the sole
18043        // future axis that flips this pin — that migration will re-
18044        // author this test to pin the new plural cardinality.
18045        let e = entrada_with_host("checkout.quero.cloud");
18046        assert_eq!(
18047            e.hostnames().len(),
18048            1,
18049            "Entrada::hostnames must be a singleton under today's \
18050             single-hostname-per-`:entrada` author surface — got \
18051             length {}: {:?}",
18052            e.hostnames().len(),
18053            e.hostnames(),
18054        );
18055    }
18056
18057    // ── Entrada::destination — the substrate-canonical per-`:entrada`
18058    //    destination-Servico scalar accessor every Gateway-API
18059    //    HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
18060    //    discriminator arg (HTTPRoute name composer) or a per-rule
18061    //    `backendRefs[0].name` axis routes through. The two pin tests
18062    //    below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
18063    //    either arm surfaces at caixa-core build time rather than at
18064    //    cluster-apply time when an HTTPRoute's `metadata.name` and
18065    //    `backendRefs[]` silently disagree on which destination Servico
18066    //    the ingress fronts. Peer discipline with the sibling
18067    //    `resolved_paths` + `hostname` + `hostnames` accept-set pin
18068    //    blocks above on the per-`:entrada` path-list / DNS-hostname
18069    //    resolver axes.
18070
18071    #[test]
18072    fn destination_returns_entrada_para_byte_equal() {
18073        // The canonical destination-scalar pin: [`Entrada::destination`]
18074        // must return the `:entrada :para` field byte-for-byte, borrowed
18075        // from the typed slot's own [`String`] storage. Pins against a
18076        // future silent detour that re-normalized the destination (an
18077        // accidental `.to_lowercase()` — the destination Servico is
18078        // already validated as a DNS-1123 label upstream, so any
18079        // re-normalization is redundant + a drift surface between the
18080        // validator and the accessor), a namespace-prefix rewrite (an
18081        // accidental `format!("{namespace}/{para}")` per-CR fully-
18082        // qualified rewrite that didn't land on the peer axis), or a
18083        // per-cluster suffix stamp the operator authors on one
18084        // consumer without the other.
18085        for para in ["cart", "checkout", "catalog", "orders-v2"] {
18086            let e = Entrada {
18087                host: "checkout.quero.cloud".into(),
18088                para: para.into(),
18089                paths: Vec::new(),
18090                port: DEFAULT_SERVICO_PORT,
18091            };
18092            assert_eq!(
18093                e.destination(),
18094                para,
18095                "Entrada::destination must return :entrada :para verbatim \
18096                 (got {:?}, expected {para:?})",
18097                e.destination(),
18098            );
18099            assert_eq!(
18100                e.destination(),
18101                e.para.as_str(),
18102                "Entrada::destination must byte-equal the .para field access",
18103            );
18104        }
18105    }
18106
18107    #[test]
18108    fn destination_borrows_from_entrada_para_storage() {
18109        // The borrow-not-copy pin: [`Entrada::destination`] must
18110        // return a `&str` slice that borrows from the typed slot's
18111        // own [`String`] storage — same-address invariant with
18112        // `entrada.para.as_str()`. Pins against a future silent detour
18113        // that allocated a fresh `String` (`self.para.clone()` in the
18114        // body would type-check but silently drop the borrow, and
18115        // every downstream consumer that assumed the returned slice
18116        // outlives `&self` would break on a stale-reference use-after-
18117        // free). Peer with the sibling `hostname_returns_entrada_
18118        // host_byte_equal` on the singular-DNS-hostname axis.
18119        let e = entrada_with_host("checkout.quero.cloud");
18120        let dest = e.destination();
18121        let para_slice = e.para.as_str();
18122        assert_eq!(
18123            dest.as_ptr(),
18124            para_slice.as_ptr(),
18125            "Entrada::destination must borrow from the .para String's \
18126             backing storage — a fresh allocation here means the \
18127             accessor no longer names the substrate-primitive typed \
18128             dispatch and every downstream consumer would silently \
18129             carry a detached copy",
18130        );
18131        assert_eq!(
18132            dest.len(),
18133            para_slice.len(),
18134            "Entrada::destination and .para.as_str() must byte-equal in \
18135             length as well as in address",
18136        );
18137    }
18138
18139    #[test]
18140    fn port_returns_entrada_port_verbatim_across_permutations() {
18141        // The canonical L4-port-scalar pin: [`Entrada::port`] must
18142        // return the `:entrada :port` field verbatim as a `u16` across
18143        // every author-declared value in the validated accept-set
18144        // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
18145        // silent detour that clamped the port (an accidental
18146        // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
18147        // land on the peer [`AplicacaoSpec::port_for_destination`]
18148        // resolver), rewrote it through a per-cluster port-remap table
18149        // the operator authors on one consumer without the other, or
18150        // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
18151        // serde-default value (which would silently collapse the
18152        // distinction between "author explicitly declared `:port 8080`"
18153        // and "author omitted the slot and inherited the default" the
18154        // future per-cluster override slot depends on). Peer with the
18155        // sibling `destination_returns_entrada_para_byte_equal` +
18156        // `hostname_returns_entrada_host_byte_equal` pins on the
18157        // per-`:entrada` `&str` scalar axes.
18158        for port in [
18159            SERVICO_PORT_MIN,
18160            DEFAULT_SERVICO_PORT,
18161            8443u16,
18162            9090u16,
18163            u16::MAX,
18164        ] {
18165            let e = Entrada {
18166                host: "checkout.quero.cloud".into(),
18167                para: "cart".into(),
18168                paths: Vec::new(),
18169                port,
18170            };
18171            assert_eq!(
18172                e.port(),
18173                port,
18174                "Entrada::port must return :entrada :port verbatim \
18175                 (got {}, expected {port})",
18176                e.port(),
18177            );
18178            assert_eq!(
18179                e.port(),
18180                e.port,
18181                "Entrada::port accessor and .port field access must \
18182                 byte-equal — the accessor is the substrate-primitive \
18183                 typed dispatch every downstream L4-port consumer must \
18184                 route through",
18185            );
18186        }
18187    }
18188
18189    #[test]
18190    fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
18191        // Two-consumer coherence pin: the
18192        // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
18193        // (which reads through [`Entrada::port`] to compare against
18194        // [`SERVICO_PORT_MIN`]) and the
18195        // [`AplicacaoSpec::port_for_destination`] resolver (which reads
18196        // through [`Entrada::port`] to emit the per-destination
18197        // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
18198        // lifted accessor, so any future rebrand on the typed slot's
18199        // reader shape lands at exactly one place. Pins the two-site
18200        // coherence by exercising a below-floor port through validate
18201        // (which must reject) and a validated in-accept-set port through
18202        // port_for_destination (which must emit the same value the
18203        // accessor returns).
18204        let mut spec = three_member_spec();
18205        if let Some(e) = spec.entrada.as_mut() {
18206            e.port = 0;
18207        }
18208        assert_eq!(
18209            spec.validate().unwrap_err(),
18210            AplicacaoError::EntradaPortZero,
18211            "validate must reject `:entrada :port 0` through the lifted \
18212             Entrada::port accessor — port zero lies below \
18213             SERVICO_PORT_MIN and the validator routes through port() \
18214             to name the floor",
18215        );
18216
18217        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
18218            let mut spec = three_member_spec();
18219            if let Some(e) = spec.entrada.as_mut() {
18220                e.port = port;
18221            }
18222            spec.validate().expect(
18223                "entrada with in-accept-set :port must validate — the \
18224                 structural-floor gate reads through Entrada::port",
18225            );
18226            let entrada_ref = spec.entrada().expect(":entrada present");
18227            assert_eq!(
18228                spec.port_for_destination(entrada_ref.destination()),
18229                entrada_ref.port(),
18230                "port_for_destination(entrada.destination()) must equal \
18231                 entrada.port() — the two consumers of the per-:entrada \
18232                 L4-port axis (validator, per-destination resolver) both \
18233                 route through Entrada::port",
18234            );
18235        }
18236    }
18237
18238    #[test]
18239    fn wit_contract_source_returns_de_byte_equal_across_permutations() {
18240        // The canonical caller-Servico-scalar pin: [`WitContract::source`]
18241        // must return the `:contratos :de` field byte-for-byte, borrowed
18242        // from the typed slot's own [`String`] storage. Peer of the
18243        // sibling `destination_returns_entrada_para_byte_equal` pin on
18244        // the per-`:entrada` axis — same "the substrate-primitive
18245        // accessor must byte-equal the raw field access verbatim across
18246        // every author-declared value" discipline extended to the
18247        // per-`:contratos` caller arm. Pins against a future silent
18248        // detour that re-normalized the caller (an accidental
18249        // `.to_lowercase()` — every `:contratos :de` is validated as a
18250        // DNS-1123 label upstream via `validate_contrato_caixa`, so any
18251        // re-normalization is redundant + a drift surface between the
18252        // validator and the accessor), a namespace-prefix rewrite (an
18253        // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
18254        // rewrite that didn't land on the peer axis), or a per-cluster
18255        // suffix stamp the operator authors on one consumer without the
18256        // other.
18257        for de in ["cart", "checkout", "catalog", "orders-v2"] {
18258            let c = WitContract {
18259                de: de.into(),
18260                para: "downstream".into(),
18261                wit: "wasi:http/proxy".into(),
18262                endpoint: Some("/lookup".into()),
18263                subject: None,
18264                slot: None,
18265            };
18266            assert_eq!(
18267                c.source(),
18268                de,
18269                "WitContract::source must return :contratos :de verbatim \
18270                 (got {:?}, expected {de:?})",
18271                c.source(),
18272            );
18273            assert_eq!(
18274                c.source(),
18275                c.de.as_str(),
18276                "WitContract::source must byte-equal the .de field access",
18277            );
18278        }
18279    }
18280
18281    #[test]
18282    fn wit_contract_source_borrows_from_de_storage() {
18283        // The borrow-not-copy pin: [`WitContract::source`] must return a
18284        // `&str` slice that borrows from the typed slot's own [`String`]
18285        // storage — same-address invariant with `c.de.as_str()`. Pins
18286        // against a future silent detour that allocated a fresh `String`
18287        // (`self.de.clone()` in the body would type-check but silently
18288        // drop the borrow, and every downstream consumer that assumed
18289        // the returned slice outlives `&self` would break on a stale-
18290        // reference use-after-free). Peer of the sibling
18291        // `destination_borrows_from_entrada_para_storage` on the
18292        // per-`:entrada` axis.
18293        let c = WitContract {
18294            de: "cart".into(),
18295            para: "catalog".into(),
18296            wit: "wasi:http/proxy".into(),
18297            endpoint: Some("/lookup".into()),
18298            subject: None,
18299            slot: None,
18300        };
18301        let src = c.source();
18302        let de_slice = c.de.as_str();
18303        assert_eq!(
18304            src.as_ptr(),
18305            de_slice.as_ptr(),
18306            "WitContract::source must borrow from the .de String's \
18307             backing storage — a fresh allocation here means the \
18308             accessor no longer names the substrate-primitive typed \
18309             dispatch and every downstream consumer would silently \
18310             carry a detached copy",
18311        );
18312        assert_eq!(
18313            src.len(),
18314            de_slice.len(),
18315            "WitContract::source and .de.as_str() must byte-equal in \
18316             length as well as in address",
18317        );
18318    }
18319
18320    #[test]
18321    fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
18322        // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
18323        // must return the `:contratos :para` field byte-for-byte,
18324        // borrowed from the typed slot's own [`String`] storage. Peer of
18325        // the sibling `destination_returns_entrada_para_byte_equal` on
18326        // the per-`:entrada` axis — both accessors name "the destination-
18327        // Servico byte-string" concept on their respective mesh-slot
18328        // atoms (per-ingress apex vs. per-typed-edge callee) and both
18329        // must project the underlying `.para` field verbatim so every
18330        // downstream renderer that composes them with peer accessors
18331        // (e.g. `spec.port_for_destination(c.destination())` at the CNP
18332        // per-edge L4 port emit site) reads the same byte-string the
18333        // author declared.
18334        for para in ["catalog", "payment", "orders", "inventory-v3"] {
18335            let c = WitContract {
18336                de: "cart".into(),
18337                para: para.into(),
18338                wit: "wasi:http/proxy".into(),
18339                endpoint: Some("/lookup".into()),
18340                subject: None,
18341                slot: None,
18342            };
18343            assert_eq!(
18344                c.destination(),
18345                para,
18346                "WitContract::destination must return :contratos :para \
18347                 verbatim (got {:?}, expected {para:?})",
18348                c.destination(),
18349            );
18350            assert_eq!(
18351                c.destination(),
18352                c.para.as_str(),
18353                "WitContract::destination must byte-equal the .para \
18354                 field access",
18355            );
18356        }
18357    }
18358
18359    #[test]
18360    fn wit_contract_destination_borrows_from_para_storage() {
18361        // The borrow-not-copy pin: [`WitContract::destination`] must
18362        // return a `&str` slice that borrows from the typed slot's own
18363        // [`String`] storage — same-address invariant with
18364        // `c.para.as_str()`. Peer of the sibling
18365        // `destination_borrows_from_entrada_para_storage` on the
18366        // per-`:entrada` axis.
18367        let c = WitContract {
18368            de: "cart".into(),
18369            para: "catalog".into(),
18370            wit: "wasi:http/proxy".into(),
18371            endpoint: Some("/lookup".into()),
18372            subject: None,
18373            slot: None,
18374        };
18375        let dest = c.destination();
18376        let para_slice = c.para.as_str();
18377        assert_eq!(
18378            dest.as_ptr(),
18379            para_slice.as_ptr(),
18380            "WitContract::destination must borrow from the .para \
18381             String's backing storage — a fresh allocation here means \
18382             the accessor no longer names the substrate-primitive typed \
18383             dispatch and every downstream consumer would silently \
18384             carry a detached copy",
18385        );
18386        assert_eq!(
18387            dest.len(),
18388            para_slice.len(),
18389            "WitContract::destination and .para.as_str() must byte-equal \
18390             in length as well as in address",
18391        );
18392    }
18393
18394    #[test]
18395    fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
18396        // The canonical per-`:contratos` WIT-world-reference scalar pin:
18397        // [`WitContract::world_ref`] must return the `:contratos :wit`
18398        // field byte-for-byte, borrowed from the typed slot's own
18399        // [`String`] storage. Sibling of the peer per-`:contratos`
18400        // [`WitContract::source`] / [`WitContract::destination`]
18401        // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
18402        // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
18403        // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
18404        // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
18405        // "the substrate-primitive accessor must byte-equal the raw
18406        // field access verbatim across every author-declared value"
18407        // discipline extended to the per-`:contratos` WIT-world arm.
18408        // Pins against a future silent detour that re-canonicalized the
18409        // WIT world reference (an accidental `.to_lowercase()` pass that
18410        // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
18411        // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
18412        // gate is already lowercase-prefixed so any re-normalization is
18413        // redundant + a drift surface between the validator and the
18414        // accessor), an M4-promotion-shape rewrite that formatted a
18415        // typed WIT-world enum through [`Display`] and silently drifted
18416        // the printer output from the source `caixa.lisp`, or a per-
18417        // cluster WIT-alias rewrite that didn't land on the peer field-
18418        // access sites. Five values sweep the shape-dispatch accept-set
18419        // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
18420        // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
18421        // `wasi:keyvalue/`).
18422        for (wit, endpoint, subject, slot) in [
18423            ("wasi:http/proxy", Some("/lookup"), None, None),
18424            ("http:proxy", Some("/health"), None, None),
18425            ("nats:pub-sub", None, Some("orders.paid"), None),
18426            ("kafka:events", None, Some("checkout-events"), None),
18427            ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
18428        ] {
18429            let c = WitContract {
18430                de: "cart".into(),
18431                para: "downstream".into(),
18432                wit: wit.into(),
18433                endpoint: endpoint.map(str::to_string),
18434                subject: subject.map(str::to_string),
18435                slot: slot.map(str::to_string),
18436            };
18437            assert_eq!(
18438                c.world_ref(),
18439                wit,
18440                "WitContract::world_ref must return :contratos :wit \
18441                 verbatim (got {:?}, expected {wit:?})",
18442                c.world_ref(),
18443            );
18444            assert_eq!(
18445                c.world_ref(),
18446                c.wit.as_str(),
18447                "WitContract::world_ref must byte-equal the .wit field \
18448                 access",
18449            );
18450        }
18451    }
18452
18453    #[test]
18454    fn wit_contract_world_ref_borrows_from_wit_storage() {
18455        // The borrow-not-copy pin: [`WitContract::world_ref`] must
18456        // return a `&str` slice that borrows from the typed slot's own
18457        // [`String`] storage — same-address invariant with
18458        // `c.wit.as_str()`. Pins against a future silent detour that
18459        // allocated a fresh `String` (`self.wit.clone()` in the body
18460        // would type-check but silently drop the borrow, and every
18461        // downstream consumer that assumed the returned slice outlives
18462        // `&self` would break on a stale-reference use-after-free — the
18463        // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
18464        // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
18465        // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
18466        // / [`is_pubsub`][WitContract::is_pubsub] /
18467        // [`is_store`][WitContract::is_store] methods route through —
18468        // each borrow from the WitContract's own storage and each would
18469        // silently misbehave if this accessor produced a detached copy).
18470        // Peer of the sibling per-`:contratos` [`WitContract::source`] /
18471        // [`WitContract::destination`] and per-`:entrada`
18472        // [`Entrada::destination`] / [`Entrada::hostname`] and
18473        // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
18474        // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
18475        let c = WitContract {
18476            de: "cart".into(),
18477            para: "catalog".into(),
18478            wit: "wasi:http/proxy".into(),
18479            endpoint: Some("/lookup".into()),
18480            subject: None,
18481            slot: None,
18482        };
18483        let world = c.world_ref();
18484        let wit_slice = c.wit.as_str();
18485        assert_eq!(
18486            world.as_ptr(),
18487            wit_slice.as_ptr(),
18488            "WitContract::world_ref must borrow from the .wit String's \
18489             backing storage — a fresh allocation here means the \
18490             accessor no longer names the substrate-primitive typed \
18491             dispatch and every downstream consumer would silently carry \
18492             a detached copy",
18493        );
18494        assert_eq!(
18495            world.len(),
18496            wit_slice.len(),
18497            "WitContract::world_ref and .wit.as_str() must byte-equal in \
18498             length as well as in address",
18499        );
18500    }
18501
18502    #[test]
18503    fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
18504        // Sibling-triple invariant pin composing all three per-`:contratos`
18505        // substrate-primitive typed dispatches — [`WitContract::source`]
18506        // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
18507        // [`WitContract::world_ref`] — at the joint
18508        // `(source(), destination(), world_ref())` call shape every
18509        // renderer that fans on per-edge caller-callee-shape identity
18510        // keys off. The invariant, evaluated per-contract:
18511        //
18512        //   (c.source(), c.destination(), c.world_ref())
18513        //   == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
18514        //
18515        // Closes the last unlifted per-`:contratos` scalar axis — every
18516        // downstream consumer that reads the triple now routes through
18517        // exactly three typed dispatches on the substrate primitive,
18518        // not two typed + one open-coded field access. A future refactor
18519        // that silently split any one accessor's projection (an
18520        // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
18521        // canonicalization that didn't reach the peer `source`/
18522        // `destination` arms, an accidental `source()` per-cluster
18523        // caller-alias rewrite that didn't land on the `world_ref` peer)
18524        // surfaces at caixa-core build time. Peer of the sibling per-
18525        // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
18526        // per-`:entrada` `(hostname(), destination())` (6db982c /
18527        // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
18528        // axes, extended to the per-`:contratos` triple.
18529        for (de, para, wit, endpoint, subject, slot) in [
18530            (
18531                "cart",
18532                "catalog",
18533                "wasi:http/proxy",
18534                Some("/lookup"),
18535                None,
18536                None,
18537            ),
18538            (
18539                "checkout",
18540                "orders",
18541                "nats:pub-sub",
18542                None,
18543                Some("orders.paid"),
18544                None,
18545            ),
18546            (
18547                "cart",
18548                "kv",
18549                "wasi:keyvalue/store",
18550                None,
18551                None,
18552                Some("carts/{cart_id}"),
18553            ),
18554            (
18555                "orders-v2",
18556                "inventory-v3",
18557                "http:proxy",
18558                Some("/reserve"),
18559                None,
18560                None,
18561            ),
18562        ] {
18563            let c = WitContract {
18564                de: de.into(),
18565                para: para.into(),
18566                wit: wit.into(),
18567                endpoint: endpoint.map(str::to_string),
18568                subject: subject.map(str::to_string),
18569                slot: slot.map(str::to_string),
18570            };
18571            assert_eq!(
18572                (c.source(), c.destination(), c.world_ref()),
18573                (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
18574                "(WitContract::source, ::destination, ::world_ref) must \
18575                 project (.de, .para, .wit) verbatim across every author-\
18576                 declared triple (got ({:?}, {:?}, {:?}), expected \
18577                 ({de:?}, {para:?}, {wit:?}))",
18578                c.source(),
18579                c.destination(),
18580                c.world_ref(),
18581            );
18582        }
18583    }
18584
18585    #[test]
18586    fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
18587        // The canonical per-`:contratos` owned-form caller-callee-pair
18588        // pin: [`WitContract::edge_pair`] must return the
18589        // `(source(), destination())` tuple in owned form byte-for-byte,
18590        // projected through the lifted [`WitContract::source`] /
18591        // [`WitContract::destination`] scalar accessors. Pins the
18592        // composite-projection invariant on the per-`:contratos`
18593        // mesh-slot atom — every author-declared `(de, para)` pair must
18594        // round-trip verbatim through the substrate primitive's typed
18595        // dispatch, so the nine [`AplicacaoError`] diagnostic-
18596        // construction sites the accessor now feeds
18597        // ([`AplicacaoError::EmptyWit`],
18598        // [`AplicacaoError::ContratoEndpointEmpty`],
18599        // [`AplicacaoError::ContratoEndpointNotAbsolute`],
18600        // [`AplicacaoError::ContratoEndpointInvalid`],
18601        // [`AplicacaoError::ContratoSubjectEmpty`],
18602        // [`AplicacaoError::ContratoSubjectInvalid`],
18603        // [`AplicacaoError::ContratoSlotEmpty`],
18604        // [`AplicacaoError::ContratoSlotInvalid`],
18605        // [`AplicacaoError::ContratoDuplicate`]) all read the same
18606        // `(de, para)` label pair every author sees at the source
18607        // `caixa.lisp`. Pins against a future silent detour that swapped
18608        // the `.0` / `.1` arms (an accidental `(destination(),
18609        // source())` re-order in the body would silently invert every
18610        // downstream diagnostic's `de:` / `para:` label pair, silently
18611        // reversing the direction of every operator-facing typed error
18612        // arrow), a fresh-allocation shape drift (an accidental
18613        // `.to_string()` on one arm but not the other would leave the
18614        // owned/borrowed pair mismatched vs. the sibling `source()` /
18615        // `destination()` returns), or an M4 per-cluster caller/callee-
18616        // alias rewrite that landed on `source()` without reaching
18617        // `destination()` (or vice versa). Peer of the sibling per-
18618        // `:contratos` `(source, destination, world_ref)` triple
18619        // pin above on the mesh-slot-atom scalar-value axes, extended
18620        // to the owned-form pair-projection axis.
18621        for (de, para, wit, endpoint, subject, slot) in [
18622            (
18623                "cart",
18624                "catalog",
18625                "wasi:http/proxy",
18626                Some("/lookup"),
18627                None,
18628                None,
18629            ),
18630            (
18631                "checkout",
18632                "orders",
18633                "nats:pub-sub",
18634                None,
18635                Some("orders.paid"),
18636                None,
18637            ),
18638            (
18639                "cart",
18640                "kv",
18641                "wasi:keyvalue/store",
18642                None,
18643                None,
18644                Some("carts/{cart_id}"),
18645            ),
18646            (
18647                "orders-v2",
18648                "inventory-v3",
18649                "http:proxy",
18650                Some("/reserve"),
18651                None,
18652                None,
18653            ),
18654        ] {
18655            let c = WitContract {
18656                de: de.into(),
18657                para: para.into(),
18658                wit: wit.into(),
18659                endpoint: endpoint.map(str::to_string),
18660                subject: subject.map(str::to_string),
18661                slot: slot.map(str::to_string),
18662            };
18663            assert_eq!(
18664                c.edge_pair(),
18665                (de.to_string(), para.to_string()),
18666                "WitContract::edge_pair must return (:contratos :de, \
18667                 :contratos :para) as an owned tuple verbatim (got {:?}, \
18668                 expected ({de:?}, {para:?}))",
18669                c.edge_pair(),
18670            );
18671        }
18672    }
18673
18674    #[test]
18675    fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
18676        // The composition pin: [`WitContract::edge_pair`] must return
18677        // exactly `(source().to_string(), destination().to_string())` —
18678        // the owned form of the sibling accessor pair — so any future
18679        // refactor that silently re-authored the caller-arm / callee-arm
18680        // projection to bypass the lifted scalar accessors (an accidental
18681        // `(self.de.clone(), self.para.clone())` regression back to the
18682        // raw field-access shape, an M4-typed-caller-enum `Display`
18683        // re-canonicalization on `source()` that didn't reach
18684        // `edge_pair()`, a per-cluster alias rewrite the operator lands
18685        // on `destination()` without reaching this composite projection)
18686        // trips at caixa-core build time. Pins the "typed dispatch
18687        // composes with typed dispatch, not with raw field access"
18688        // discipline every downstream diagnostic-construction site now
18689        // routes through — a `de:` / `para:` label pair whose
18690        // projection silently drifted off the substrate primitive's
18691        // scalar accessors would silently split the diagnostic's self-
18692        // locating signal from the source `caixa.lisp` author's view.
18693        // Peer of the sibling per-`:politicas` `is_empty` /
18694        // `validate_politicas` accessor-routing-pin family on the M3
18695        // mesh-slot family (18575, 18739, 18918, 19140, 19371).
18696        let c = WitContract {
18697            de: "cart".into(),
18698            para: "catalog".into(),
18699            wit: "wasi:http/proxy".into(),
18700            endpoint: Some("/lookup".into()),
18701            subject: None,
18702            slot: None,
18703        };
18704        assert_eq!(
18705            c.edge_pair(),
18706            (c.source().to_string(), c.destination().to_string()),
18707            "WitContract::edge_pair must compose exactly \
18708             (source().to_string(), destination().to_string()) — a \
18709             bypass of either sibling accessor here would silently \
18710             decouple the composite-projection axis from the \
18711             substrate-primitive scalar accessors every downstream \
18712             consumer routes through",
18713        );
18714    }
18715
18716    #[test]
18717    fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
18718     {
18719        // The canonical per-`:contratos` owned-form
18720        // caller-callee-world-ref-triple pin:
18721        // [`WitContract::edge_triple`] must return the
18722        // `(source(), destination(), world_ref())` tuple in owned form
18723        // byte-for-byte, projected through the lifted
18724        // [`WitContract::source`] / [`WitContract::destination`] /
18725        // [`WitContract::world_ref`] scalar accessors. Pins the
18726        // composite-projection invariant on the per-`:contratos`
18727        // mesh-slot atom — every author-declared `(de, para, wit)`
18728        // triple must round-trip verbatim through the substrate
18729        // primitive's typed dispatch, so the nine
18730        // [`AplicacaoError`] diagnostic-construction sites the
18731        // accessor now feeds (the [`WitTarget`]-dispatch's eight
18732        // wrong-target / missing-target / invalid-wit / capability-
18733        // with-payload arms in [`WitContract::target`], plus the
18734        // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
18735        // diagnostic constructor in [`AplicacaoSpec::validate`]) all
18736        // read the same `(de, para, wit)` triple every author sees at
18737        // the source `caixa.lisp`. Pins against a future silent
18738        // detour that swapped any two arms (an accidental `(destination(),
18739        // source(), world_ref())` re-order in the body would silently
18740        // invert every downstream diagnostic's `de:` / `para:` label
18741        // pair, silently reversing the direction of every operator-
18742        // facing typed error arrow), a fresh-allocation shape drift
18743        // (an accidental `.to_string()` skipped on one arm would leave
18744        // the owned/borrowed triple mismatched vs. the sibling
18745        // `source()` / `destination()` / `world_ref()` returns), or an
18746        // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
18747        // canonicalization pass that landed on one accessor without
18748        // reaching the peers. Peer of the sibling per-`:contratos`
18749        // caller-callee-pair
18750        // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
18751        // pin on the mesh-slot-atom composite-projection axis,
18752        // extended to the triple-projection axis.
18753        for (de, para, wit, endpoint, subject, slot) in [
18754            (
18755                "cart",
18756                "catalog",
18757                "wasi:http/proxy",
18758                Some("/lookup"),
18759                None,
18760                None,
18761            ),
18762            (
18763                "checkout",
18764                "orders",
18765                "nats:pub-sub",
18766                None,
18767                Some("orders.paid"),
18768                None,
18769            ),
18770            (
18771                "cart",
18772                "kv",
18773                "wasi:keyvalue/store",
18774                None,
18775                None,
18776                Some("carts/{cart_id}"),
18777            ),
18778            (
18779                "orders-v2",
18780                "inventory-v3",
18781                "http:proxy",
18782                Some("/reserve"),
18783                None,
18784                None,
18785            ),
18786        ] {
18787            let c = WitContract {
18788                de: de.into(),
18789                para: para.into(),
18790                wit: wit.into(),
18791                endpoint: endpoint.map(str::to_string),
18792                subject: subject.map(str::to_string),
18793                slot: slot.map(str::to_string),
18794            };
18795            assert_eq!(
18796                c.edge_triple(),
18797                (de.to_string(), para.to_string(), wit.to_string()),
18798                "WitContract::edge_triple must return (:contratos :de, \
18799                 :contratos :para, :contratos :wit) as an owned triple \
18800                 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
18801                c.edge_triple(),
18802            );
18803        }
18804    }
18805
18806    #[test]
18807    fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
18808        // The composition pin: [`WitContract::edge_triple`] must return
18809        // exactly `(source().to_string(), destination().to_string(),
18810        // world_ref().to_string())` — the owned form of the sibling
18811        // scalar-accessor triple — so any future refactor that silently
18812        // re-authored one arm's projection to bypass the lifted scalar
18813        // accessors (an accidental `(self.de.clone(), self.para.clone(),
18814        // self.wit.clone())` regression back to the raw field-access
18815        // shape the internal `edge` closure and the ContratoDuplicate
18816        // diagnostic both carried before this lift landed, an
18817        // M4-typed-caller-enum `Display` re-canonicalization on
18818        // `source()` that didn't reach `edge_triple()`, a per-cluster
18819        // alias rewrite the operator lands on `destination()` /
18820        // `world_ref()` without reaching this composite projection)
18821        // trips at caixa-core build time. Pins the "typed dispatch
18822        // composes with typed dispatch, not with raw field access"
18823        // discipline every downstream diagnostic-construction site now
18824        // routes through — a `de:` / `para:` / `wit:` triple whose
18825        // projection silently drifted off the substrate primitive's
18826        // scalar accessors would silently split the diagnostic's self-
18827        // locating signal from the source `caixa.lisp` author's view.
18828        // Peer of the sibling per-`:contratos` edge_pair composition-
18829        // pin above on the mesh-slot-atom composite-projection axis.
18830        let c = WitContract {
18831            de: "cart".into(),
18832            para: "catalog".into(),
18833            wit: "wasi:http/proxy".into(),
18834            endpoint: Some("/lookup".into()),
18835            subject: None,
18836            slot: None,
18837        };
18838        assert_eq!(
18839            c.edge_triple(),
18840            (
18841                c.source().to_string(),
18842                c.destination().to_string(),
18843                c.world_ref().to_string(),
18844            ),
18845            "WitContract::edge_triple must compose exactly \
18846             (source().to_string(), destination().to_string(), \
18847             world_ref().to_string()) — a bypass of any sibling accessor \
18848             here would silently decouple the composite-projection axis \
18849             from the substrate-primitive scalar accessors every \
18850             downstream consumer routes through",
18851        );
18852    }
18853
18854    #[test]
18855    fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
18856        // The canonical semantics-pin: [`WitContract::edge_triple`] must
18857        // project the full `(de, para, wit)` identity of a `:contratos`
18858        // edge — the sub-triple every triple-carrying
18859        // [`AplicacaoError::Contrato*`] diagnostic weaves into its
18860        // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
18861        // missing-target, capability-with-payload, invalid-wit, and the
18862        // duplicate-gate). Rejects a drift in shape (an accidental
18863        // silent detour that returned a `(de, para)` pair or added an
18864        // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
18865        // would trip here because the return type would no longer
18866        // pattern-match the eight `let (de, para, wit) = edge();`
18867        // destructures the [`WitContract::target`] dispatch feeds off
18868        // + the paired duplicate-gate `let (de, para, wit) =
18869        // c.edge_triple();` destructure in
18870        // [`AplicacaoSpec::validate`]). Peer of the sibling per-
18871        // `:contratos` caller-callee-pair pin above extended to the
18872        // triple projection surface: closes the "one composite
18873        // accessor per typed diagnostic-construction sub-tuple"
18874        // discipline on the per-`:contratos` mesh-slot-atom axis.
18875        let c = WitContract {
18876            de: "checkout".into(),
18877            para: "orders".into(),
18878            wit: "nats:pub-sub".into(),
18879            endpoint: None,
18880            subject: Some("orders.paid".into()),
18881            slot: None,
18882        };
18883        let (de, para, wit) = c.edge_triple();
18884        assert_eq!(de, "checkout");
18885        assert_eq!(para, "orders");
18886        assert_eq!(wit, "nats:pub-sub");
18887    }
18888
18889    #[test]
18890    fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
18891     {
18892        // The composition pin: [`WitContract::identity`] must return
18893        // exactly `(source(), destination(), world_ref(), endpoint(),
18894        // subject(), slot())` — the borrowed form of the six-scalar-
18895        // accessor identity axis. Any future refactor that silently
18896        // re-authored one arm's projection to bypass a scalar accessor
18897        // (a `self.de.as_str()` regression back to raw field access on
18898        // any of the three required arms, a `self.endpoint.as_deref()`
18899        // regression on any of the three optional arms, an M4 per-
18900        // cluster caller/callee-alias rewrite the operator lands on
18901        // `source()` / `destination()` without reaching this composite
18902        // projection) trips at caixa-core build time. Sweeps four
18903        // permutations of the WIT-shape × payload lattice — HTTP with
18904        // endpoint, pub-sub with subject, store with slot, payload-less
18905        // capability — so every payload arm is exercised. Peer of the
18906        // sibling per-`:contratos`
18907        // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
18908        // composition pin on the mesh-slot-atom composite-projection
18909        // axis; extends the discipline from the (de, para, wit) prefix
18910        // onto the full-identity axis carrying the three payload arms.
18911        for (de, para, wit, endpoint, subject, slot) in [
18912            (
18913                "cart",
18914                "catalog",
18915                "wasi:http/proxy",
18916                Some("/lookup"),
18917                None,
18918                None,
18919            ),
18920            (
18921                "checkout",
18922                "orders",
18923                "nats:pub-sub",
18924                None,
18925                Some("orders.paid"),
18926                None,
18927            ),
18928            (
18929                "cart",
18930                "kv",
18931                "wasi:keyvalue/store",
18932                None,
18933                None,
18934                Some("carts/{cart_id}"),
18935            ),
18936            ("audit", "sink", "wasi:logging", None, None, None),
18937        ] {
18938            let c = WitContract {
18939                de: de.into(),
18940                para: para.into(),
18941                wit: wit.into(),
18942                endpoint: endpoint.map(str::to_owned),
18943                subject: subject.map(str::to_owned),
18944                slot: slot.map(str::to_owned),
18945            };
18946            assert_eq!(
18947                c.identity(),
18948                (
18949                    c.source(),
18950                    c.destination(),
18951                    c.world_ref(),
18952                    c.endpoint(),
18953                    c.subject(),
18954                    c.slot(),
18955                ),
18956                "WitContract::identity must compose exactly \
18957                 (source(), destination(), world_ref(), endpoint(), \
18958                 subject(), slot()) — a bypass of any sibling accessor \
18959                 here would silently decouple the identity-projection \
18960                 axis from the substrate-primitive scalar accessors \
18961                 every dedup-key consumer routes through",
18962            );
18963        }
18964    }
18965
18966    #[test]
18967    fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
18968        // The canonical semantics-pin: [`WitContract::identity`] must
18969        // project the six-axis (de, para, wit, endpoint, subject, slot)
18970        // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
18971        // gate keys off — two `WitContract`s that agree on all six axes
18972        // are the same typed edge declared twice, the graph-edge
18973        // analogue of duplicate `:membros` / `:placement :clusters` /
18974        // `:entrada :paths` entries. Rejects a shape drift (an
18975        // accidental silent detour that returned a prefix tuple or
18976        // added an extra field) by pattern-matching the six-arm shape.
18977        // Peer of the sibling per-`:contratos`
18978        // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
18979        // pin extended from the (de, para, wit) prefix onto the full
18980        // six-axis identity that the dedup key rides.
18981        let c = WitContract {
18982            de: "cart".into(),
18983            para: "catalog".into(),
18984            wit: "wasi:http/proxy".into(),
18985            endpoint: Some("/products/:id".into()),
18986            subject: None,
18987            slot: None,
18988        };
18989        let (de, para, wit, endpoint, subject, slot) = c.identity();
18990        assert_eq!(de, "cart");
18991        assert_eq!(para, "catalog");
18992        assert_eq!(wit, "wasi:http/proxy");
18993        assert_eq!(endpoint, Some("/products/:id"));
18994        assert_eq!(subject, None);
18995        assert_eq!(slot, None);
18996
18997        // Two byte-identical contracts must produce equal identities —
18998        // the dedup key's foundational invariant.
18999        let c2 = c.clone();
19000        assert_eq!(c.identity(), c2.identity());
19001
19002        // Any change on any of the six axes must break the identity —
19003        // sweeps by mutating one axis at a time.
19004        let mut mutated = c.clone();
19005        mutated.de = "search".into();
19006        assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
19007        let mut mutated = c.clone();
19008        mutated.para = "warehouse".into();
19009        assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
19010        let mut mutated = c.clone();
19011        mutated.wit = "http:legacy".into();
19012        assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
19013        let mut mutated = c.clone();
19014        mutated.endpoint = Some("/search".into());
19015        assert_ne!(
19016            c.identity(),
19017            mutated.identity(),
19018            "endpoint axis must partition"
19019        );
19020        let mut mutated = c.clone();
19021        mutated.subject = Some("orders.paid".into());
19022        assert_ne!(
19023            c.identity(),
19024            mutated.identity(),
19025            "subject axis must partition"
19026        );
19027        let mut mutated = c;
19028        mutated.slot = Some("carts/{id}".into());
19029        assert_ne!(mutated.identity().5, None, "slot axis must partition");
19030    }
19031
19032    #[test]
19033    fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
19034        // The canonical per-`:contratos` structural-self-edge pin:
19035        // [`WitContract::is_self_loop`] must return `true` when the
19036        // `:de` and `:para` fields agree byte-for-byte, across every
19037        // WIT-shape variant the per-edge shape family carries. Pins
19038        // the shape-agnostic identity-space partition the
19039        // [`AplicacaoSpec::validate`] self-edge gate at
19040        // caixa-core/src/aplicacao.rs:5559 fires against — all four
19041        // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
19042        // under the same one predicate. Four permutations sweep the
19043        // accept-set: HTTP with endpoint, pub-sub with subject, KV
19044        // store with slot, and payload-less capability.
19045        for (nome, wit, endpoint, subject, slot) in [
19046            ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
19047            ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
19048            (
19049                "kv",
19050                "wasi:keyvalue/store",
19051                None,
19052                None,
19053                Some("carts/{cart_id}"),
19054            ),
19055            ("audit", "wasi:logging", None, None, None),
19056        ] {
19057            let c = WitContract {
19058                de: nome.into(),
19059                para: nome.into(),
19060                wit: wit.into(),
19061                endpoint: endpoint.map(str::to_string),
19062                subject: subject.map(str::to_string),
19063                slot: slot.map(str::to_string),
19064            };
19065            assert!(
19066                c.is_self_loop(),
19067                "WitContract::is_self_loop must return true when \
19068                 :contratos :de == :contratos :para (got false on \
19069                 {nome:?} under {wit:?})",
19070            );
19071        }
19072    }
19073
19074    #[test]
19075    fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
19076        // The complement pin: [`WitContract::is_self_loop`] must return
19077        // `false` on every well-shaped inter-Servico contract (the
19078        // author-intended `:contratos` shape MESH-COMPOSITION §III.1
19079        // names — "Servico A calls Servico B" between two distinct
19080        // graph nodes). Pins against a future silent detour that
19081        // inverted the predicate (an accidental `!= ` swap for `==`
19082        // would silently reject every legitimate inter-Servico edge
19083        // and admit every self-edge — the exact inversion of the
19084        // author-intended shape). Four permutations sweep the same
19085        // WIT-shape accept-set the sibling positive-arm test carries.
19086        for (de, para, wit, endpoint, subject, slot) in [
19087            (
19088                "cart",
19089                "catalog",
19090                "wasi:http/proxy",
19091                Some("/lookup"),
19092                None,
19093                None,
19094            ),
19095            (
19096                "checkout",
19097                "orders",
19098                "nats:pub-sub",
19099                None,
19100                Some("orders.paid"),
19101                None,
19102            ),
19103            (
19104                "cart",
19105                "kv",
19106                "wasi:keyvalue/store",
19107                None,
19108                None,
19109                Some("carts/{cart_id}"),
19110            ),
19111            ("audit", "sink", "wasi:logging", None, None, None),
19112        ] {
19113            let c = WitContract {
19114                de: de.into(),
19115                para: para.into(),
19116                wit: wit.into(),
19117                endpoint: endpoint.map(str::to_string),
19118                subject: subject.map(str::to_string),
19119                slot: slot.map(str::to_string),
19120            };
19121            assert!(
19122                !c.is_self_loop(),
19123                "WitContract::is_self_loop must return false when \
19124                 :contratos :de differs from :contratos :para (got true \
19125                 on {de:?} → {para:?} under {wit:?})",
19126            );
19127        }
19128    }
19129
19130    #[test]
19131    fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
19132        // The composition pin: [`WitContract::is_self_loop`] must
19133        // resolve to exactly `self.source() == self.destination()` —
19134        // the equality probe of the sibling scalar-accessor pair — so
19135        // any future refactor that silently re-authored the predicate
19136        // to bypass the lifted scalar accessors (an accidental
19137        // `self.de == self.para` regression back to the raw field-
19138        // access shape, an M4-typed-caller-enum identity-comparison
19139        // rule that landed on `source()` without reaching
19140        // `destination()`, a per-cluster alias rewrite the operator
19141        // pins on `destination()` without reaching this predicate)
19142        // trips at caixa-core build time. Pins the "typed dispatch
19143        // composes with typed dispatch, not with raw field access"
19144        // discipline the sibling [`WitContract::edge_pair`] /
19145        // [`WitContract::edge_triple`] composite-projection accessors
19146        // already carry, extended onto the per-edge endpoint-equality
19147        // predicate axis. Positive and complement arms both fire.
19148        let self_edge = WitContract {
19149            de: "cart".into(),
19150            para: "cart".into(),
19151            wit: "wasi:http/proxy".into(),
19152            endpoint: Some("/lookup".into()),
19153            subject: None,
19154            slot: None,
19155        };
19156        assert_eq!(
19157            self_edge.is_self_loop(),
19158            self_edge.source() == self_edge.destination(),
19159            "WitContract::is_self_loop must compose exactly \
19160             `source() == destination()` — a bypass of either sibling \
19161             accessor here would silently decouple the endpoint-\
19162             equality predicate from the substrate-primitive scalar \
19163             accessors every downstream consumer routes through",
19164        );
19165        let inter_edge = WitContract {
19166            de: "cart".into(),
19167            para: "catalog".into(),
19168            wit: "wasi:http/proxy".into(),
19169            endpoint: Some("/lookup".into()),
19170            subject: None,
19171            slot: None,
19172        };
19173        assert_eq!(
19174            inter_edge.is_self_loop(),
19175            inter_edge.source() == inter_edge.destination(),
19176            "WitContract::is_self_loop must compose exactly \
19177             `source() == destination()` on the complement arm too",
19178        );
19179    }
19180
19181    #[test]
19182    fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
19183        // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
19184        // pin: [`WitContract::endpoint`] must return the `:contratos
19185        // :endpoint` field byte-for-byte, borrowed from the typed slot's
19186        // own `Option<String>` storage. Peer of the sibling
19187        // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
19188        // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
19189        // mesh-slot `Option<String>` optional-scalar axes — same "the
19190        // substrate-primitive accessor must byte-equal the raw field
19191        // access verbatim across every author-declared value" discipline
19192        // extended to the per-`:contratos` HTTP-payload-carrier arm.
19193        // Pins against a future silent detour that re-canonicalized the
19194        // endpoint (an accidental percent-encoding pass that didn't
19195        // reach the peer field-access site at the dedup key, a per-CR
19196        // fully-qualified prefix rewrite the operator authors on one
19197        // consumer without the other, or an M4 typed-path-template
19198        // `Display` re-canonicalization that silently drifted the
19199        // printer output from the source `caixa.lisp`). Four values
19200        // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
19201        // gate upstream admits (short root-path, dashed, param-shaped,
19202        // deep-hierarchy).
19203        for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
19204            let c = WitContract {
19205                de: "cart".into(),
19206                para: "catalog".into(),
19207                wit: "wasi:http/proxy".into(),
19208                endpoint: Some(endpoint.into()),
19209                subject: None,
19210                slot: None,
19211            };
19212            assert_eq!(
19213                c.endpoint(),
19214                Some(endpoint),
19215                "WitContract::endpoint must return :contratos :endpoint \
19216                 verbatim (got {:?}, expected Some({endpoint:?}))",
19217                c.endpoint(),
19218            );
19219            assert_eq!(
19220                c.endpoint(),
19221                c.endpoint.as_deref(),
19222                "WitContract::endpoint must byte-equal the .endpoint \
19223                 field's `.as_deref()` projection",
19224            );
19225        }
19226    }
19227
19228    #[test]
19229    fn wit_contract_endpoint_none_when_field_is_none() {
19230        // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
19231        // payload-carrier accessor pin: when the typed slot is absent —
19232        // the canonical shape under a non-HTTP `:wit` world per the
19233        // [`WitContract::target`]-enforced shape ↔ target partition
19234        // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
19235        // carries `:slot`, [`WitTarget::Capability`] carries none) —
19236        // [`WitContract::endpoint`] must return `None`. Pins against a
19237        // future silent detour that projected the absent slot to a
19238        // `Some("")` empty-string default (the canonical `Option<String>`
19239        // → `String` collapse footgun the sibling M2
19240        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
19241        // emptiness predicates already guard on the peer M2 typed-slot
19242        // surfaces), a `Some("None")` stringified-None round-trip, or a
19243        // `Some` arm whose contents were derived from a sibling slot (an
19244        // accidental fallback to the `:subject` / `:slot` payload that
19245        // read the pub-sub / store payload into the endpoint axis).
19246        // Three contracts sweep the accept-set every non-HTTP `:wit`
19247        // world lands on — pub-sub NATS, key/value, and payload-less
19248        // capability.
19249        for (wit, subject, slot) in [
19250            ("nats:pub-sub", Some("orders.paid"), None),
19251            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
19252            ("wasi:cli/environment", None, None),
19253        ] {
19254            let c = WitContract {
19255                de: "cart".into(),
19256                para: "downstream".into(),
19257                wit: wit.into(),
19258                endpoint: None,
19259                subject: subject.map(str::to_string),
19260                slot: slot.map(str::to_string),
19261            };
19262            assert!(
19263                c.endpoint().is_none(),
19264                "WitContract::endpoint must return None when the typed \
19265                 slot is absent under :wit {wit:?} (got {:?})",
19266                c.endpoint(),
19267            );
19268            assert_eq!(
19269                c.endpoint(),
19270                c.endpoint.as_deref(),
19271                "WitContract::endpoint must byte-equal the .endpoint \
19272                 field's `.as_deref()` projection in the absent arm",
19273            );
19274        }
19275    }
19276
19277    #[test]
19278    fn wit_contract_endpoint_borrows_from_endpoint_storage() {
19279        // The borrow-not-copy pin: [`WitContract::endpoint`] must return
19280        // an `Option<&str>` whose `Some` arm borrows from the typed
19281        // slot's own [`String`] storage — same-address invariant with
19282        // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
19283        // detour that allocated a fresh `String`
19284        // (`self.endpoint.clone().map(...)` in the body would type-check
19285        // but silently drop the borrow, and every downstream consumer
19286        // that assumed the returned slice outlives `&self` would break
19287        // on a stale-reference use-after-free — the [`WitContract::target`]
19288        // Http-arm payload extraction rebinds the returned `Option<&str>`
19289        // through `.ok_or_else(...)` and threads the `&str` payload into
19290        // [`WitTarget::Http { endpoint: &'a str }`], the
19291        // [`AplicacaoSpec::validate`] duplicate-`:contratos`
19292        // [`ContratoIdentity`] dedup key threads the returned
19293        // `Option<&str>` into the six-tuple's HTTP arm — each borrow
19294        // from the WitContract's own storage and each would silently
19295        // misbehave if this accessor produced a detached copy). Peer of
19296        // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
19297        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
19298        // shaped optional-scalar axes — first extension of the
19299        // `Option<&str>` borrow-not-copy discipline onto the
19300        // per-`:contratos` HTTP-shaped payload-carrier axis.
19301        let c = WitContract {
19302            de: "cart".into(),
19303            para: "catalog".into(),
19304            wit: "wasi:http/proxy".into(),
19305            endpoint: Some("/lookup".into()),
19306            subject: None,
19307            slot: None,
19308        };
19309        let ep = c.endpoint().expect("Some arm");
19310        let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
19311        assert_eq!(
19312            ep.as_ptr(),
19313            storage_slice.as_ptr(),
19314            "WitContract::endpoint must borrow from the .endpoint \
19315             String's backing storage — a fresh allocation here means \
19316             the accessor no longer names the substrate-primitive typed \
19317             dispatch and every downstream consumer would silently \
19318             carry a detached copy",
19319        );
19320        assert_eq!(
19321            ep.len(),
19322            storage_slice.len(),
19323            "WitContract::endpoint and .endpoint.as_deref() must byte-\
19324             equal in length as well as in address",
19325        );
19326    }
19327
19328    #[test]
19329    fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
19330        // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
19331        // pin: [`WitContract::subject`] must return the `:contratos
19332        // :subject` field byte-for-byte, borrowed from the typed slot's
19333        // own `Option<String>` storage. Peer of the sibling per-`:contratos`
19334        // [`WitContract::endpoint`] (7020470) accessor pin on the M3
19335        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
19336        // optional-scalar axis — same "the substrate-primitive accessor
19337        // must byte-equal the raw field access verbatim across every
19338        // author-declared value" discipline extended to the pub-sub arm.
19339        // Pins against a future silent detour that re-canonicalized the
19340        // subject (an accidental `.to_lowercase()` normalization that
19341        // didn't reach the peer field-access site at the dedup key, a
19342        // per-CR fully-qualified prefix rewrite the operator authors on
19343        // one consumer without the other, or an M4 typed-subject-template
19344        // `Display` re-canonicalization that silently drifted the printer
19345        // output from the source `caixa.lisp`). Four values sweep the
19346        // NATS accept-set every pub-sub author-declared subject lands on
19347        // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
19348        for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
19349            let c = WitContract {
19350                de: "cart".into(),
19351                para: "notifier".into(),
19352                wit: "nats:pub-sub".into(),
19353                endpoint: None,
19354                subject: Some(subject.into()),
19355                slot: None,
19356            };
19357            assert_eq!(
19358                c.subject(),
19359                Some(subject),
19360                "WitContract::subject must return :contratos :subject \
19361                 verbatim (got {:?}, expected Some({subject:?}))",
19362                c.subject(),
19363            );
19364            assert_eq!(
19365                c.subject(),
19366                c.subject.as_deref(),
19367                "WitContract::subject must byte-equal the .subject \
19368                 field's `.as_deref()` projection",
19369            );
19370        }
19371    }
19372
19373    #[test]
19374    fn wit_contract_subject_none_when_field_is_none() {
19375        // The absent-`:subject` arm of the per-`:contratos` pub-sub-
19376        // shaped payload-carrier accessor pin: when the typed slot is
19377        // absent — the canonical shape under a non-pub-sub `:wit` world
19378        // per the [`WitContract::target`]-enforced shape ↔ target
19379        // partition ([`WitTarget::Http`] carries `:endpoint`,
19380        // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
19381        // carries none) — [`WitContract::subject`] must return `None`.
19382        // Pins against a future silent detour that projected the absent
19383        // slot to a `Some("")` empty-string default (the canonical
19384        // `Option<String>` → `String` collapse footgun the sibling M2
19385        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
19386        // emptiness predicates already guard on the peer M2 typed-slot
19387        // surfaces), a `Some("None")` stringified-None round-trip, or a
19388        // `Some` arm whose contents were derived from a sibling slot (an
19389        // accidental fallback to the `:endpoint` / `:slot` payload that
19390        // read the HTTP / store payload into the subject axis). Three
19391        // contracts sweep the accept-set every non-pub-sub `:wit` world
19392        // lands on — HTTP proxy, key/value store, and payload-less
19393        // capability.
19394        for (wit, endpoint, slot) in [
19395            ("wasi:http/proxy", Some("/lookup"), None),
19396            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
19397            ("wasi:cli/environment", None, None),
19398        ] {
19399            let c = WitContract {
19400                de: "cart".into(),
19401                para: "downstream".into(),
19402                wit: wit.into(),
19403                endpoint: endpoint.map(str::to_string),
19404                subject: None,
19405                slot: slot.map(str::to_string),
19406            };
19407            assert!(
19408                c.subject().is_none(),
19409                "WitContract::subject must return None when the typed \
19410                 slot is absent under :wit {wit:?} (got {:?})",
19411                c.subject(),
19412            );
19413            assert_eq!(
19414                c.subject(),
19415                c.subject.as_deref(),
19416                "WitContract::subject must byte-equal the .subject \
19417                 field's `.as_deref()` projection in the absent arm",
19418            );
19419        }
19420    }
19421
19422    #[test]
19423    fn wit_contract_subject_borrows_from_subject_storage() {
19424        // The borrow-not-copy pin: [`WitContract::subject`] must return
19425        // an `Option<&str>` whose `Some` arm borrows from the typed
19426        // slot's own [`String`] storage — same-address invariant with
19427        // `c.subject.as_deref().unwrap()`. Pins against a future silent
19428        // detour that allocated a fresh `String`
19429        // (`self.subject.clone().map(...)` in the body would type-check
19430        // but silently drop the borrow, and every downstream consumer
19431        // that assumed the returned slice outlives `&self` would break
19432        // on a stale-reference use-after-free — the [`WitContract::target`]
19433        // PubSub-arm payload extraction rebinds the returned
19434        // `Option<&str>` through `.ok_or_else(...)` and threads the
19435        // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
19436        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
19437        // [`ContratoIdentity`] dedup key threads the returned
19438        // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
19439        // from the WitContract's own storage and each would silently
19440        // misbehave if this accessor produced a detached copy). Peer of
19441        // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
19442        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
19443        // shaped optional-scalar axis — second extension of the
19444        // `Option<&str>` borrow-not-copy discipline onto the
19445        // per-`:contratos` payload-carrier family, this time on the
19446        // pub-sub arm.
19447        let c = WitContract {
19448            de: "cart".into(),
19449            para: "notifier".into(),
19450            wit: "nats:pub-sub".into(),
19451            endpoint: None,
19452            subject: Some("orders.paid".into()),
19453            slot: None,
19454        };
19455        let sub = c.subject().expect("Some arm");
19456        let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
19457        assert_eq!(
19458            sub.as_ptr(),
19459            storage_slice.as_ptr(),
19460            "WitContract::subject must borrow from the .subject \
19461             String's backing storage — a fresh allocation here means \
19462             the accessor no longer names the substrate-primitive typed \
19463             dispatch and every downstream consumer would silently \
19464             carry a detached copy",
19465        );
19466        assert_eq!(
19467            sub.len(),
19468            storage_slice.len(),
19469            "WitContract::subject and .subject.as_deref() must byte-\
19470             equal in length as well as in address",
19471        );
19472    }
19473
19474    #[test]
19475    fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
19476        // The canonical per-`:contratos` key/value-store-shaped
19477        // `:slot`-scalar pin: [`WitContract::slot`] must return the
19478        // `:contratos :slot` field byte-for-byte, borrowed from the
19479        // typed slot's own `Option<String>` storage. Peer of the
19480        // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
19481        // [`WitContract::subject`] (90de675) accessor pins on the M3
19482        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
19483        // optional-scalar axis — same "the substrate-primitive
19484        // accessor must byte-equal the raw field access verbatim
19485        // across every author-declared value" discipline extended to
19486        // the store arm. Pins against a future silent detour that
19487        // re-canonicalized the slot template (an accidental
19488        // `.to_lowercase()` bucket-prefix normalization that didn't
19489        // reach the peer field-access site at the dedup key, a per-CR
19490        // fully-qualified prefix rewrite the operator authors on one
19491        // consumer without the other, or an M4 typed-key-template
19492        // `Display` re-canonicalization that silently drifted the
19493        // printer output from the source `caixa.lisp`). Four values
19494        // sweep the wasi:keyvalue accept-set every store-shaped
19495        // author-declared slot lands on (flat bucket, single-param
19496        // template, multi-param template, nested-hierarchy template).
19497        for slot in [
19498            "sessions",
19499            "carts/{cart_id}",
19500            "orders/{tenant}/{order_id}",
19501            "cache/tenant-a/orders/{id}",
19502        ] {
19503            let c = WitContract {
19504                de: "cart".into(),
19505                para: "kv".into(),
19506                wit: "wasi:keyvalue/store".into(),
19507                endpoint: None,
19508                subject: None,
19509                slot: Some(slot.into()),
19510            };
19511            assert_eq!(
19512                c.slot(),
19513                Some(slot),
19514                "WitContract::slot must return :contratos :slot \
19515                 verbatim (got {:?}, expected Some({slot:?}))",
19516                c.slot(),
19517            );
19518            assert_eq!(
19519                c.slot(),
19520                c.slot.as_deref(),
19521                "WitContract::slot must byte-equal the .slot field's \
19522                 `.as_deref()` projection",
19523            );
19524        }
19525    }
19526
19527    #[test]
19528    fn wit_contract_slot_none_when_field_is_none() {
19529        // The absent-`:slot` arm of the per-`:contratos` store-shaped
19530        // payload-carrier accessor pin: when the typed slot is absent —
19531        // the canonical shape under a non-store `:wit` world per the
19532        // [`WitContract::target`]-enforced shape ↔ target partition
19533        // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
19534        // carries `:subject`, [`WitTarget::Capability`] carries none) —
19535        // [`WitContract::slot`] must return `None`. Pins against a
19536        // future silent detour that projected the absent slot to a
19537        // `Some("")` empty-string default (the canonical
19538        // `Option<String>` → `String` collapse footgun the sibling M2
19539        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
19540        // emptiness predicates already guard on the peer M2 typed-slot
19541        // surfaces), a `Some("None")` stringified-None round-trip, or
19542        // a `Some` arm whose contents were derived from a sibling
19543        // slot (an accidental fallback to the `:endpoint` / `:subject`
19544        // payload that read the HTTP / pub-sub payload into the store
19545        // axis). Three contracts sweep the accept-set every non-store
19546        // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
19547        // payload-less capability.
19548        for (wit, endpoint, subject) in [
19549            ("wasi:http/proxy", Some("/lookup"), None),
19550            ("nats:pub-sub", None, Some("orders.paid")),
19551            ("wasi:cli/environment", None, None),
19552        ] {
19553            let c = WitContract {
19554                de: "cart".into(),
19555                para: "downstream".into(),
19556                wit: wit.into(),
19557                endpoint: endpoint.map(str::to_string),
19558                subject: subject.map(str::to_string),
19559                slot: None,
19560            };
19561            assert!(
19562                c.slot().is_none(),
19563                "WitContract::slot must return None when the typed \
19564                 slot is absent under :wit {wit:?} (got {:?})",
19565                c.slot(),
19566            );
19567            assert_eq!(
19568                c.slot(),
19569                c.slot.as_deref(),
19570                "WitContract::slot must byte-equal the .slot field's \
19571                 `.as_deref()` projection in the absent arm",
19572            );
19573        }
19574    }
19575
19576    #[test]
19577    fn wit_contract_slot_borrows_from_slot_storage() {
19578        // The borrow-not-copy pin: [`WitContract::slot`] must return
19579        // an `Option<&str>` whose `Some` arm borrows from the typed
19580        // slot's own [`String`] storage — same-address invariant with
19581        // `c.slot.as_deref().unwrap()`. Pins against a future silent
19582        // detour that allocated a fresh `String`
19583        // (`self.slot.clone().map(...)` in the body would type-check
19584        // but silently drop the borrow, and every downstream consumer
19585        // that assumed the returned slice outlives `&self` would
19586        // break on a stale-reference use-after-free — the
19587        // [`WitContract::target`] Store-arm payload extraction rebinds
19588        // the returned `Option<&str>` through `.ok_or_else(...)` and
19589        // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
19590        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
19591        // [`ContratoIdentity`] dedup key threads the returned
19592        // `Option<&str>` into the six-tuple's store arm — each borrow
19593        // from the WitContract's own storage and each would silently
19594        // misbehave if this accessor produced a detached copy). Peer
19595        // of the sibling per-`:contratos` [`WitContract::endpoint`]
19596        // (7020470) / [`WitContract::subject`] (90de675)
19597        // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
19598        // shaped optional-scalar axis — third and final extension of
19599        // the `Option<&str>` borrow-not-copy discipline onto the
19600        // per-`:contratos` payload-carrier family, this time on the
19601        // store arm.
19602        let c = WitContract {
19603            de: "cart".into(),
19604            para: "kv".into(),
19605            wit: "wasi:keyvalue/store".into(),
19606            endpoint: None,
19607            subject: None,
19608            slot: Some("carts/{cart_id}".into()),
19609        };
19610        let slot = c.slot().expect("Some arm");
19611        let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
19612        assert_eq!(
19613            slot.as_ptr(),
19614            storage_slice.as_ptr(),
19615            "WitContract::slot must borrow from the .slot String's \
19616             backing storage — a fresh allocation here means the \
19617             accessor no longer names the substrate-primitive typed \
19618             dispatch and every downstream consumer would silently \
19619             carry a detached copy",
19620        );
19621        assert_eq!(
19622            slot.len(),
19623            storage_slice.len(),
19624            "WitContract::slot and .slot.as_deref() must byte-equal \
19625             in length as well as in address",
19626        );
19627    }
19628
19629    #[test]
19630    fn membro_nome_returns_caixa_byte_equal_across_permutations() {
19631        // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
19632        // [`Membro::nome`] must return the `:membros :caixa` field
19633        // byte-for-byte, borrowed from the typed slot's own [`String`]
19634        // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
19635        // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
19636        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
19637        // slot-atom scalar-value axes — same "the substrate-primitive
19638        // accessor must byte-equal the raw field access verbatim across
19639        // every author-declared value" discipline extended to the
19640        // per-`:membros` member-identity arm. Pins against a future
19641        // silent detour that re-normalized the member identity (an
19642        // accidental `.to_lowercase()` — every `:membros :caixa` is
19643        // validated as a DNS-1123 label upstream via
19644        // [`validate_membro_caixa`], so any re-normalization is
19645        // redundant + a drift surface between the validator and the
19646        // accessor), a namespace-prefix rewrite (an accidental
19647        // `format!("{namespace}/{caixa}")` per-CR fully-qualified
19648        // rewrite that didn't land on the peer axes), or a per-cluster
19649        // alias stamp the operator authors on one consumer without the
19650        // other. Four values sweep the accept-set the DNS-1123 gate
19651        // upstream admits (short single-word / dashed / v-suffixed
19652        // member names).
19653        for name in ["cart", "checkout", "catalog", "orders-v2"] {
19654            let m = Membro {
19655                caixa: name.into(),
19656                versao: "^0.1".into(),
19657            };
19658            assert_eq!(
19659                m.nome(),
19660                name,
19661                "Membro::nome must return :membros :caixa verbatim \
19662                 (got {:?}, expected {name:?})",
19663                m.nome(),
19664            );
19665            assert_eq!(
19666                m.nome(),
19667                m.caixa.as_str(),
19668                "Membro::nome must byte-equal the .caixa field access",
19669            );
19670        }
19671    }
19672
19673    #[test]
19674    fn membro_nome_borrows_from_caixa_storage() {
19675        // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
19676        // slice that borrows from the typed slot's own [`String`]
19677        // storage — same-address invariant with `m.caixa.as_str()`. Pins
19678        // against a future silent detour that allocated a fresh `String`
19679        // (`self.caixa.clone()` in the body would type-check but
19680        // silently drop the borrow, and every downstream consumer that
19681        // assumed the returned slice outlives `&self` would break on a
19682        // stale-reference use-after-free — the `HashSet<&str>` collector
19683        // at [`AplicacaoSpec::validate`]'s `names` seed, the
19684        // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
19685        // [`AplicacaoSpec::detect_sync_cycles`], the
19686        // [`crate::render::insert_first_seen`] dedup key at
19687        // [`AplicacaoSpec::validate_membros`] — each borrow from the
19688        // Membro's own storage and each would silently misbehave if
19689        // this accessor produced a detached copy). Peer of the sibling
19690        // per-`:contratos` [`WitContract::source`] /
19691        // [`WitContract::destination`] and per-`:entrada`
19692        // [`Entrada::destination`] borrow-invariant pins on the mesh-
19693        // slot-atom scalar-value axes.
19694        let m = Membro {
19695            caixa: "checkout".into(),
19696            versao: "^0.1".into(),
19697        };
19698        let name = m.nome();
19699        let caixa_slice = m.caixa.as_str();
19700        assert_eq!(
19701            name.as_ptr(),
19702            caixa_slice.as_ptr(),
19703            "Membro::nome must borrow from the .caixa String's backing \
19704             storage — a fresh allocation here means the accessor no \
19705             longer names the substrate-primitive typed dispatch and \
19706             every downstream consumer would silently carry a detached \
19707             copy",
19708        );
19709        assert_eq!(
19710            name.len(),
19711            caixa_slice.len(),
19712            "Membro::nome and .caixa.as_str() must byte-equal in length \
19713             as well as in address",
19714        );
19715    }
19716
19717    #[test]
19718    fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
19719        // The canonical per-`:membros` member-`:versao`-scalar pin:
19720        // [`Membro::versao_requirement`] must return the
19721        // `:membros :versao` field byte-for-byte, borrowed from the typed
19722        // slot's own [`String`] storage. Sibling of the peer
19723        // `membro_nome_returns_caixa_byte_equal_across_permutations`
19724        // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
19725        // — same "the substrate-primitive accessor must byte-equal the
19726        // raw field access verbatim across every author-declared value"
19727        // discipline extended to the per-`:membros` member-`:versao`
19728        // requirement-string arm. Pins against a future silent detour
19729        // that re-canonicalized the requirement (an accidental
19730        // `.to_string()` via [`parse_requirement`] → [`Display`] round-
19731        // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
19732        // drifted the printer output away from the source `caixa.lisp`,
19733        // an accidental whitespace trim on `"^ 0.1"` that no consumer
19734        // ever produced from the field-access side, an accidental
19735        // per-cluster lacre-projected concrete-version rewrite that
19736        // didn't land on the peer field-access sites). Five values sweep
19737        // the accept-set the shared
19738        // [`crate::render::require_valid_versao_requirement`] gate
19739        // admits (caret / tilde / exact / wildcard / bare-major).
19740        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
19741            let m = Membro {
19742                caixa: "cart".into(),
19743                versao: req.into(),
19744            };
19745            assert_eq!(
19746                m.versao_requirement(),
19747                req,
19748                "Membro::versao_requirement must return :membros :versao \
19749                 verbatim (got {:?}, expected {req:?})",
19750                m.versao_requirement(),
19751            );
19752            assert_eq!(
19753                m.versao_requirement(),
19754                m.versao.as_str(),
19755                "Membro::versao_requirement must byte-equal the .versao \
19756                 field access",
19757            );
19758        }
19759    }
19760
19761    #[test]
19762    fn membro_versao_requirement_borrows_from_versao_storage() {
19763        // The borrow-not-copy pin: [`Membro::versao_requirement`] must
19764        // return a `&str` slice that borrows from the typed slot's own
19765        // [`String`] storage — same-address invariant with
19766        // `m.versao.as_str()`. Pins against a future silent detour that
19767        // allocated a fresh `String` (`self.versao.clone()` in the body
19768        // would type-check but silently drop the borrow, and every
19769        // downstream consumer that assumed the returned slice outlives
19770        // `&self` would break on a stale-reference use-after-free). Peer
19771        // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
19772        // per-`:contratos` [`WitContract::source`] /
19773        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
19774        // [`Entrada::destination`] (6db982c) borrow-invariant pins on
19775        // the mesh-slot-atom scalar-value axes.
19776        let m = Membro {
19777            caixa: "checkout".into(),
19778            versao: "^0.1".into(),
19779        };
19780        let req = m.versao_requirement();
19781        let versao_slice = m.versao.as_str();
19782        assert_eq!(
19783            req.as_ptr(),
19784            versao_slice.as_ptr(),
19785            "Membro::versao_requirement must borrow from the .versao \
19786             String's backing storage — a fresh allocation here means \
19787             the accessor no longer names the substrate-primitive typed \
19788             dispatch and every downstream consumer would silently carry \
19789             a detached copy",
19790        );
19791        assert_eq!(
19792            req.len(),
19793            versao_slice.len(),
19794            "Membro::versao_requirement and .versao.as_str() must byte-\
19795             equal in length as well as in address",
19796        );
19797    }
19798
19799    #[test]
19800    fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
19801        // Sibling-pair invariant pin composing both per-`:membros`
19802        // substrate-primitive typed dispatches — [`Membro::nome`]
19803        // (4a32abf) and [`Membro::versao_requirement`] — at the joint
19804        // `(nome(), versao_requirement())` call shape every renderer
19805        // that fans on per-member identity + version pin keys off. The
19806        // invariant, evaluated per-member:
19807        //
19808        //   (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
19809        //
19810        // Closes the last unlifted per-`:membros` scalar axis — every
19811        // downstream consumer that reads the pair now routes through
19812        // exactly two typed dispatches on the substrate primitive, not
19813        // one typed + one open-coded field access. A future refactor
19814        // that silently split either accessor's projection (an
19815        // accidental `nome()` namespace-prefix rewrite that didn't
19816        // reach the peer, an accidental `versao_requirement()` lacre-
19817        // projected concrete-version rewrite that didn't land on the
19818        // `nome()` peer) surfaces at caixa-core build time. Peer of the
19819        // sibling per-`:entrada` `(hostname(), destination())` and
19820        // per-`:contratos` `(source(), destination())` pair invariants
19821        // on the mesh-slot-atom scalar-value axes.
19822        for (caixa, versao) in [
19823            ("cart", "^0.1"),
19824            ("checkout", "~0.1.2"),
19825            ("catalog", "0.1.0"),
19826            ("orders-v2", "*"),
19827        ] {
19828            let m = Membro {
19829                caixa: caixa.into(),
19830                versao: versao.into(),
19831            };
19832            assert_eq!(
19833                (m.nome(), m.versao_requirement()),
19834                (m.caixa.as_str(), m.versao.as_str()),
19835                "(Membro::nome, Membro::versao_requirement) must project \
19836                 (.caixa, .versao) verbatim across every author-declared \
19837                 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
19838                m.nome(),
19839                m.versao_requirement(),
19840            );
19841        }
19842    }
19843
19844    #[test]
19845    fn validate_membros_empty_gate_routes_through_nome_accessor() {
19846        // Composition pin: [`AplicacaoSpec::validate_membros`]'s
19847        // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
19848        // not the raw `.caixa` field access. Structurally: setting
19849        // ONLY the `.caixa` field to `""` on an otherwise-well-formed
19850        // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
19851        // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
19852        // (i.e. the empty string) — so the emptiness predicate the
19853        // refusal arm reaches under is the accessor-projected value,
19854        // not a peer field that would silently drift under a future
19855        // accessor-side rewrite.
19856        //
19857        // Pins against a future silent detour that (a) re-derived the
19858        // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
19859        // instead of `self.nome().is_empty()`, silently disagreeing with
19860        // every peer consumer (the `validate_membro_caixa(m.nome())`
19861        // call one line below, the dedup-key `insert_first_seen(&mut
19862        // seen, m.nome(), …)` two lines below, the emit-side per-
19863        // `programs[]` entry-`name:` at caixa-mesh/src/lib.rs:133),
19864        // (b) accessor-side introduced a per-tenant alias arm the
19865        // caller was unaware of, silently rewriting an author-declared
19866        // `:caixa "checkout"` to `""` — the raw-field-access gate
19867        // would fail-open while the accessor-routed peer consumers
19868        // would fail-closed, splitting the diagnostic from the actual
19869        // failure surface.
19870        //
19871        // Peer of the sibling
19872        // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
19873        // (c0110f1) composition pin — same "the shape-gate predicate
19874        // must route through the substrate-primitive typed dispatch"
19875        // discipline extended onto the per-`:membros` empty-`:caixa`
19876        // refusal-arm axis. Closes the last unlifted `.caixa` production-
19877        // code read site on `Membro` — after this converge every
19878        // caixa-core `.caixa` field access outside the accessor's own
19879        // body is either a test-side field-setter (in-module tests
19880        // constructing invalid-shape inputs) or a doc-comment reference.
19881        let mut s = three_member_spec();
19882        s.membros[1].caixa = String::new();
19883        assert!(
19884            s.membros[1].nome().is_empty(),
19885            "Membro::nome must byte-equal the .caixa field access — an \
19886             accessor-side detour that no longer projects the raw field \
19887             would silently split this drift-detection test from the \
19888             validate() refusal arm",
19889        );
19890        assert_eq!(
19891            s.membros[1].nome(),
19892            s.membros[1].caixa.as_str(),
19893            "Membro::nome and .caixa.as_str() must byte-equal on an \
19894             empty-`:caixa` entry — the emptiness gate keys off the \
19895             accessor by construction",
19896        );
19897        assert_eq!(
19898            s.validate().unwrap_err(),
19899            AplicacaoError::MembroCaixaEmpty,
19900            "validate_membros' emptiness gate must fire MembroCaixaEmpty \
19901             on an entry whose accessor-projected `nome()` is empty",
19902        );
19903    }
19904
19905    #[test]
19906    fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
19907        // The canonical per-`:placement` Akka-cluster-sharding
19908        // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
19909        // the `:placement :shard-key` field byte-for-byte, borrowed
19910        // from the typed slot's own `Option<String>` storage. Peer of
19911        // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
19912        // per-`:contratos` [`WitContract::source`] /
19913        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
19914        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
19915        // slot-atom scalar-value axes — same "the substrate-primitive
19916        // accessor must byte-equal the raw field access verbatim across
19917        // every author-declared value" discipline extended to the
19918        // per-`:placement` Akka-cluster-sharding key extractor arm.
19919        // Pins against a future silent detour that re-normalized the
19920        // key (an accidental `.to_lowercase()` — every non-empty
19921        // `:shard-key` is validated as a printable-ASCII single-token
19922        // reference upstream via [`validate_placement_shard_key`], so
19923        // any re-normalization is redundant + a drift surface between
19924        // the validator and the accessor), a per-cluster alias rewrite
19925        // the operator authors on one consumer without the other, or an
19926        // accidental variable-prefix strip (`$tenantId` → `tenantId`)
19927        // that didn't land on the peer field-access sites. Four values
19928        // sweep the accept-set the shape gate admits — bare identifier,
19929        // `$`-prefixed variable, dotted path, `${}`-quoted variable —
19930        // the four canonical Akka-style entity-id extractor shapes the
19931        // future M4 cluster-sharding reconciler hashes.
19932        for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
19933            let p = Placement {
19934                estrategia: PlacementStrategy::Sharded,
19935                clusters: vec!["rio".into()],
19936                affinity: None,
19937                shard_key: Some(key.into()),
19938            };
19939            assert_eq!(
19940                p.shard_key(),
19941                Some(key),
19942                "Placement::shard_key must return :placement :shard-key \
19943                 verbatim (got {:?}, expected Some({key:?}))",
19944                p.shard_key(),
19945            );
19946            assert_eq!(
19947                p.shard_key(),
19948                p.shard_key.as_deref(),
19949                "Placement::shard_key must byte-equal the .shard_key \
19950                 field's `.as_deref()` projection",
19951            );
19952        }
19953    }
19954
19955    #[test]
19956    fn placement_shard_key_none_when_field_is_none() {
19957        // The absent-`:shard-key` arm of the per-`:placement`
19958        // Akka-cluster-sharding accessor pin: when the typed slot is
19959        // absent — the canonical shape under `:estrategia Replicated` /
19960        // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
19961        // enforced `shard_key.is_some() == matches!(estrategia,
19962        // Sharded)` partition — [`Placement::shard_key`] must return
19963        // `None`. Pins against a future silent detour that projected
19964        // the absent slot to a `Some("")` empty-string default (the
19965        // canonical `Option<String>` → `String` collapse footgun the
19966        // sibling M2 [`crate::LimitsSpec::is_empty`] /
19967        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
19968        // already guard on the peer M2 typed-slot surfaces), a
19969        // `Some("None")` stringified-None round-trip, or a `Some` arm
19970        // whose contents were derived from a sibling slot (an
19971        // accidental fallback to `estrategia.as_str()` that read the
19972        // strategy discriminator into the key axis). Two placements
19973        // sweep the accept-set every `validate`-passing non-`Sharded`
19974        // shape lands on — `Replicated` (Erlang/OTP distributed-app
19975        // takeover) and `SingleNode` (single-node hosting).
19976        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
19977            let p = Placement {
19978                estrategia,
19979                clusters: vec!["rio".into()],
19980                affinity: None,
19981                shard_key: None,
19982            };
19983            assert!(
19984                p.shard_key().is_none(),
19985                "Placement::shard_key must return None when the typed \
19986                 slot is absent under :estrategia {estrategia:?} (got {:?})",
19987                p.shard_key(),
19988            );
19989            assert_eq!(
19990                p.shard_key(),
19991                p.shard_key.as_deref(),
19992                "Placement::shard_key must byte-equal the .shard_key \
19993                 field's `.as_deref()` projection in the absent arm",
19994            );
19995        }
19996    }
19997
19998    #[test]
19999    fn placement_shard_key_borrows_from_shard_key_storage() {
20000        // The borrow-not-copy pin: [`Placement::shard_key`] must return
20001        // an `Option<&str>` whose `Some` arm borrows from the typed
20002        // slot's own [`String`] storage — same-address invariant with
20003        // `p.shard_key.as_deref().unwrap()`. Pins against a future
20004        // silent detour that allocated a fresh `String`
20005        // (`self.shard_key.clone().map(...)` in the body would type-
20006        // check but silently drop the borrow, and every downstream
20007        // consumer that assumed the returned slice outlives `&self`
20008        // would break on a stale-reference use-after-free — the
20009        // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
20010        // gate's `Some(k)`-bound match arm reads `k: &str` under the
20011        // accessor's return type and would silently misbehave if this
20012        // accessor produced a detached copy). Peer of the sibling
20013        // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
20014        // [`WitContract::source`] / [`WitContract::destination`]
20015        // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
20016        // (6db982c) borrow-invariant pins on the mesh-slot-atom
20017        // scalar-value axes — first extension of the discipline onto
20018        // an `Option<String>`-shaped optional-scalar axis.
20019        let p = Placement {
20020            estrategia: PlacementStrategy::Sharded,
20021            clusters: vec!["rio".into()],
20022            affinity: None,
20023            shard_key: Some("tenantId".into()),
20024        };
20025        let key = p.shard_key().expect("Some arm");
20026        let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
20027        assert_eq!(
20028            key.as_ptr(),
20029            storage_slice.as_ptr(),
20030            "Placement::shard_key must borrow from the .shard_key \
20031             String's backing storage — a fresh allocation here means \
20032             the accessor no longer names the substrate-primitive typed \
20033             dispatch and every downstream consumer would silently \
20034             carry a detached copy",
20035        );
20036        assert_eq!(
20037            key.len(),
20038            storage_slice.len(),
20039            "Placement::shard_key and .shard_key.as_deref() must byte-\
20040             equal in length as well as in address",
20041        );
20042    }
20043
20044    #[test]
20045    fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
20046        // The canonical per-`:placement` M3-Adaptive-compression-hint
20047        // scalar pin: [`Placement::affinity`] must return the
20048        // `:placement :affinity` field byte-for-byte, borrowed from the
20049        // typed slot's own `Option<String>` storage. Peer of the sibling
20050        // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
20051        // pin on the sibling `Option<&str>` optional-scalar axis — same
20052        // "the substrate-primitive accessor must byte-equal the raw
20053        // field access verbatim across every author-declared value"
20054        // discipline extended to the peer per-`:placement` M3-Adaptive-
20055        // compression-hint arm. Pins against a future silent detour
20056        // that re-normalized the hint (an accidental `.to_lowercase()`
20057        // — every `:affinity` is already validated as a DNS-1123 label
20058        // upstream via [`validate_placement_affinity`], so any re-
20059        // normalization is redundant + a drift surface between the
20060        // validator and the accessor), a per-cluster alias rewrite the
20061        // operator authors on one consumer without the other, or an
20062        // accidental hint-family collapse (`low-latency` → `latency`
20063        // that dropped the qualifier prefix). Four values sweep the
20064        // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
20065        // canonical adaptive-compression-weight biases the future M4
20066        // placement engine reads.
20067        for hint in [
20068            "data-locality",
20069            "low-latency",
20070            "high-throughput",
20071            "cost-optimized",
20072        ] {
20073            let p = Placement {
20074                estrategia: PlacementStrategy::Replicated,
20075                clusters: vec!["rio".into()],
20076                affinity: Some(hint.into()),
20077                shard_key: None,
20078            };
20079            assert_eq!(
20080                p.affinity(),
20081                Some(hint),
20082                "Placement::affinity must return :placement :affinity \
20083                 verbatim (got {:?}, expected Some({hint:?}))",
20084                p.affinity(),
20085            );
20086            assert_eq!(
20087                p.affinity(),
20088                p.affinity.as_deref(),
20089                "Placement::affinity must byte-equal the .affinity \
20090                 field's `.as_deref()` projection",
20091            );
20092        }
20093    }
20094
20095    #[test]
20096    fn placement_affinity_none_when_field_is_none() {
20097        // The absent-`:affinity` arm of the per-`:placement`
20098        // M3-Adaptive-compression-hint accessor pin: when the typed
20099        // slot is absent — the canonical shape of an Aplicacao that
20100        // leaves the compression weighting up to the placement engine's
20101        // cluster-default arm — [`Placement::affinity`] must return
20102        // `None`. Pins against a future silent detour that projected
20103        // the absent slot to a `Some("")` empty-string default (the
20104        // canonical `Option<String>` → `String` collapse footgun the
20105        // sibling M2 [`crate::LimitsSpec::is_empty`] /
20106        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
20107        // already guard on the peer M2 typed-slot surfaces), a
20108        // `Some("None")` stringified-None round-trip, a `Some` arm
20109        // whose contents were derived from a sibling slot (an
20110        // accidental fallback to `estrategia.as_str()` that read the
20111        // strategy discriminator into the hint axis), or a
20112        // `Some("default")` implicit-default that would silently biases
20113        // the routing without the author having written one. Three
20114        // placements sweep the accept-set every `validate`-passing
20115        // `:affinity None` shape lands on — one per PlacementStrategy
20116        // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
20117        // with a shard-key), since `:affinity` is orthogonal to
20118        // `:estrategia` in the typed grammar.
20119        for (estrategia, shard_key) in [
20120            (PlacementStrategy::SingleNode, None),
20121            (PlacementStrategy::Replicated, None),
20122            (PlacementStrategy::Sharded, Some("tenantId".to_string())),
20123        ] {
20124            let p = Placement {
20125                estrategia,
20126                clusters: vec!["rio".into()],
20127                affinity: None,
20128                shard_key,
20129            };
20130            assert!(
20131                p.affinity().is_none(),
20132                "Placement::affinity must return None when the typed \
20133                 slot is absent under :estrategia {estrategia:?} (got {:?})",
20134                p.affinity(),
20135            );
20136            assert_eq!(
20137                p.affinity(),
20138                p.affinity.as_deref(),
20139                "Placement::affinity must byte-equal the .affinity \
20140                 field's `.as_deref()` projection in the absent arm",
20141            );
20142        }
20143    }
20144
20145    #[test]
20146    fn placement_affinity_borrows_from_affinity_storage() {
20147        // The borrow-not-copy pin: [`Placement::affinity`] must return
20148        // an `Option<&str>` whose `Some` arm borrows from the typed
20149        // slot's own [`String`] storage — same-address invariant with
20150        // `p.affinity.as_deref().unwrap()`. Pins against a future
20151        // silent detour that allocated a fresh `String`
20152        // (`self.affinity.clone().map(...)` in the body would type-
20153        // check but silently drop the borrow, and every downstream
20154        // consumer that assumed the returned slice outlives `&self`
20155        // would break on a stale-reference use-after-free — the
20156        // [`AplicacaoSpec::validate_placement`] per-hint value-shape
20157        // gate reads the accessor's `&str` return through the
20158        // [`validate_placement_affinity`] `&str` parameter and would
20159        // silently misbehave if this accessor produced a detached
20160        // copy). Peer of the sibling per-`:placement`
20161        // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
20162        // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
20163        // extends the discipline onto the sibling per-`:placement`
20164        // M3-Adaptive-compression-hint arm.
20165        let p = Placement {
20166            estrategia: PlacementStrategy::Replicated,
20167            clusters: vec!["rio".into()],
20168            affinity: Some("data-locality".into()),
20169            shard_key: None,
20170        };
20171        let hint = p.affinity().expect("Some arm");
20172        let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
20173        assert_eq!(
20174            hint.as_ptr(),
20175            storage_slice.as_ptr(),
20176            "Placement::affinity must borrow from the .affinity \
20177             String's backing storage — a fresh allocation here means \
20178             the accessor no longer names the substrate-primitive typed \
20179             dispatch and every downstream consumer would silently \
20180             carry a detached copy",
20181        );
20182        assert_eq!(
20183            hint.len(),
20184            storage_slice.len(),
20185            "Placement::affinity and .affinity.as_deref() must byte-\
20186             equal in length as well as in address",
20187        );
20188    }
20189
20190    #[test]
20191    fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
20192        // The canonical per-`:placement` distribution-strategy-scalar
20193        // pin: [`Placement::estrategia`] must return the `:placement
20194        // :estrategia` field verbatim as a [`PlacementStrategy`],
20195        // `Copy`-projected from the typed slot's own `PlacementStrategy`
20196        // storage across every variant in the closed accept-set
20197        // (`SingleNode` — Erlang/OTP distributed-app takeover;
20198        // `Replicated` — active-active across every named cluster;
20199        // `Sharded` — Akka-style hash-keyed entity distribution). Pins
20200        // against a future silent detour that re-derived the strategy
20201        // from a peer axis (an accidental fallback to
20202        // `if shard_key.is_some() { Sharded } else { Replicated }`
20203        // collapse that read the shard-key axis into the strategy
20204        // discriminator), a variant remap the operator authors on one
20205        // consumer without the other, or a stale-derive detour that
20206        // substituted [`PlacementStrategy::default`] when the field
20207        // held any explicit variant (which would silently collapse the
20208        // distinction between "author explicitly declared `:estrategia
20209        // Replicated`" and "author omitted the slot and inherited the
20210        // default" the future per-cluster override slot depends on).
20211        // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
20212        // pin on the `Copy`-return `u16` scalar axis — same "the
20213        // substrate-primitive accessor must byte-equal the raw field
20214        // access verbatim across every author-declared value" discipline
20215        // extended onto the per-`:placement` distribution-strategy
20216        // `Copy`-composite-enum scalar axis.
20217        for estrategia in [
20218            PlacementStrategy::SingleNode,
20219            PlacementStrategy::Replicated,
20220            PlacementStrategy::Sharded,
20221        ] {
20222            let shard_key = estrategia.is_sharded().then(|| "tenantId".to_string());
20223            let p = Placement {
20224                estrategia,
20225                clusters: vec!["rio".into()],
20226                affinity: None,
20227                shard_key,
20228            };
20229            assert_eq!(
20230                p.estrategia(),
20231                estrategia,
20232                "Placement::estrategia must return :placement :estrategia \
20233                 verbatim (got {:?}, expected {estrategia:?})",
20234                p.estrategia(),
20235            );
20236            assert_eq!(
20237                p.estrategia(),
20238                p.estrategia,
20239                "Placement::estrategia accessor and .estrategia field \
20240                 access must byte-equal — the accessor is the substrate-\
20241                 primitive typed dispatch every downstream distribution-\
20242                 strategy consumer must route through",
20243            );
20244        }
20245    }
20246
20247    #[test]
20248    fn validate_placement_reads_through_lifted_estrategia_accessor() {
20249        // Three-consumer coherence pin: the
20250        // [`AplicacaoSpec::validate_placement`]
20251        // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
20252        // `estrategia:` field (which reads through
20253        // [`Placement::estrategia`] to name the strategy the empty
20254        // `:clusters` list was declared against), the same method's
20255        // `Sharded ↔ non-Sharded` `match` partition dispatch (which
20256        // reads through [`Placement::estrategia`] to fan across the
20257        // shape-gate cascades), and the non-`Sharded`-arm
20258        // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
20259        // `estrategia:` field (which reads through
20260        // [`Placement::estrategia`] to name the strategy the declared-
20261        // but-inert `:shard-key` was authored under) must all key off
20262        // the lifted accessor, so any future rebrand on the typed
20263        // slot's reader shape lands at exactly one place. Pins the
20264        // three-site coherence by exercising each error surface end-
20265        // to-end and asserting the surfaced `estrategia:` field byte-
20266        // equals the accessor's return. Peer of the sibling per-
20267        // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
20268        // pin on the M3 mesh-slot `Copy`-return scalar axis.
20269
20270        // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
20271        // whose `estrategia:` field must byte-equal the accessor's return
20272        // for every variant in the closed accept-set.
20273        for estrategia in [
20274            PlacementStrategy::SingleNode,
20275            PlacementStrategy::Replicated,
20276            PlacementStrategy::Sharded,
20277        ] {
20278            let mut spec = three_member_spec();
20279            spec.placement.estrategia = estrategia;
20280            spec.placement.clusters = Vec::new();
20281            spec.placement.shard_key = estrategia.is_sharded().then(|| "tenantId".to_string());
20282            let err = spec.validate().unwrap_err();
20283            match err {
20284                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
20285                    assert_eq!(
20286                        e,
20287                        spec.placement.estrategia(),
20288                        "PlacementWithoutClusters.estrategia must byte-equal \
20289                         Placement::estrategia() — the error carrier reads \
20290                         through the lifted accessor",
20291                    );
20292                }
20293                other => panic!(
20294                    "expected PlacementWithoutClusters, got {other:?} for \
20295                     estrategia={estrategia:?}"
20296                ),
20297            }
20298        }
20299
20300        // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
20301        // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
20302        // must byte-equal the accessor's return for both non-`Sharded`
20303        // strategies.
20304        for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
20305            let mut spec = three_member_spec();
20306            spec.placement.estrategia = estrategia;
20307            spec.placement.shard_key = Some("tenantId".into());
20308            let err = spec.validate().unwrap_err();
20309            match err {
20310                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
20311                    assert_eq!(
20312                        e,
20313                        spec.placement.estrategia(),
20314                        "ShardKeyOnNonSharded.estrategia must byte-equal \
20315                         Placement::estrategia() — the non-Sharded-arm \
20316                         refusal reads through the lifted accessor",
20317                    );
20318                }
20319                other => panic!(
20320                    "expected ShardKeyOnNonSharded, got {other:?} for \
20321                     estrategia={estrategia:?}"
20322                ),
20323            }
20324        }
20325    }
20326
20327    // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
20328    //
20329    // The [`Placement::clusters`] accessor lift is the second slice-return
20330    // (`&[T]`) accessor on any typed slot — sibling to the seed M2
20331    // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
20332    // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
20333    // below cover (1) the accessor's byte-equal projection against the raw
20334    // field access across the empty / singleton / cohort fixtures the
20335    // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
20336    // and the per-cluster validate loop fan between, and (2) the two-
20337    // consumer coherence of the paired pre-flight refusal probe and the
20338    // per-cluster validate loop routing through the accessor on both arms.
20339
20340    #[test]
20341    fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
20342        // The canonical per-`:placement` cluster-pool-scalar-shape pin:
20343        // [`Placement::clusters`] must return the `:placement :clusters`
20344        // typed `Vec<String>` verbatim as a `&[String]` slice-view over
20345        // the same backing buffer the raw `self.clusters.as_slice()`
20346        // field access borrows from, byte-equal across every
20347        // representative fixture in the accept-set — the empty slice
20348        // (the pre-validation sentinel every
20349        // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
20350        // the singleton slice (the minimal `SingleNode`-shape cohort),
20351        // and multi-entry cohorts (the peer `Replicated` / `Sharded`
20352        // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
20353        //
20354        // Pins against a future silent detour that returned
20355        // `&Vec<String>` (which would type-check but leak the storage-
20356        // side `Vec`'s grow/push/reserve surface no consumer of the
20357        // typed view reaches for), a fresh-allocated `Vec<String>` copy
20358        // (which would type-check via a coercion but silently break
20359        // every downstream caller that relied on the slice sharing the
20360        // backing buffer's identity), or an out-of-order or length-
20361        // drifted projection (which would silently split the paired
20362        // pre-flight `.is_empty()` refusal probe's input from the per-
20363        // cluster validate loop's traversal input).
20364        //
20365        // Peer of the sibling M2
20366        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
20367        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
20368        // `:supervisor` static-child-list axis, extended onto the M3
20369        // per-`:placement` distribution-target-list `Vec`-carry axis.
20370        let fixtures: Vec<Vec<String>> = vec![
20371            Vec::new(),
20372            vec!["rio".into()],
20373            vec!["rio".into(), "mar".into()],
20374            vec!["rio".into(), "mar".into(), "plo".into()],
20375        ];
20376        for clusters in fixtures {
20377            let p = Placement {
20378                clusters: clusters.clone(),
20379                ..Placement::default()
20380            };
20381            assert_eq!(
20382                p.clusters(),
20383                clusters.as_slice(),
20384                "Placement::clusters must return :placement :clusters \
20385                 verbatim (got {:?}, expected {:?})",
20386                p.clusters(),
20387                clusters.as_slice(),
20388            );
20389            assert_eq!(
20390                p.clusters(),
20391                p.clusters.as_slice(),
20392                "Placement::clusters accessor and .clusters.as_slice() \
20393                 field access must byte-equal — the accessor is the \
20394                 substrate-primitive typed dispatch every downstream \
20395                 cluster-pool consumer must route through",
20396            );
20397            assert_eq!(
20398                p.clusters().len(),
20399                p.clusters.len(),
20400                "Placement::clusters().len() must byte-equal \
20401                 self.clusters.len() — a length-drift would silently \
20402                 split the paired pre-flight `.is_empty()` refusal \
20403                 probe input from the per-cluster validate loop's \
20404                 traversal input",
20405            );
20406        }
20407    }
20408
20409    #[test]
20410    fn validate_placement_reads_through_lifted_clusters_accessor() {
20411        // Two-consumer coherence pin: the
20412        // [`AplicacaoSpec::validate_placement`] pre-flight
20413        // `self.placement.clusters().is_empty()` refusal probe (which
20414        // must trip [`AplicacaoError::PlacementWithoutClusters`] when
20415        // the accessor projects the empty slice) and the per-cluster
20416        // validate loop's `for c in self.placement.clusters()`
20417        // traversal (which must reach every entry in the same order
20418        // the accessor projects, so both the per-entry value-shape
20419        // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
20420        // and the duplicate-detection HashSet insert that trips
20421        // [`AplicacaoError::PlacementClusterDuplicate`] key off the
20422        // accessor's projection) must both key off the lifted
20423        // accessor, so any future rebrand on the typed slot's reader
20424        // shape lands at exactly one place. Pins the two-site
20425        // coherence by exercising each production consumer end-to-end:
20426        // (1) the `PlacementWithoutClusters` refusal under the empty
20427        // slice, (2) the `PlacementClusterInvalid` refusal fires on
20428        // the second entry of a two-cluster cohort whose head is
20429        // valid but tail is not (which requires the loop to reach the
20430        // second entry through the accessor), and (3) the
20431        // `PlacementClusterDuplicate` refusal fires on the second
20432        // entry of a two-cluster cohort that shares a name (which
20433        // requires the loop to reach both entries — a first-entry-only
20434        // projection would silently pass since the dedup HashSet has
20435        // room for the first insert).
20436        //
20437        // Peer of the sibling M2
20438        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
20439        // (bc92bce) coherence pin on the per-`:supervisor` static-
20440        // child-list axis, extended onto the M3 per-`:placement`
20441        // distribution-target-list `Vec`-carry axis.
20442
20443        // (1) Pre-flight `.is_empty()` probe: the empty slice must
20444        // trip `PlacementWithoutClusters`.
20445        let mut spec = three_member_spec();
20446        spec.placement.clusters = Vec::new();
20447        match spec.validate().unwrap_err() {
20448            AplicacaoError::PlacementWithoutClusters { .. } => {}
20449            other => panic!("expected PlacementWithoutClusters, got {other:?}"),
20450        }
20451        assert!(
20452            spec.placement.clusters().is_empty(),
20453            "the pre-flight refusal input must be the empty slice per \
20454             the accessor's projection",
20455        );
20456
20457        // (2) Per-cluster validate loop: a two-cluster cohort with an
20458        // invalid tail entry must trip `PlacementClusterInvalid` on
20459        // the tail — the loop must reach the second entry through
20460        // the accessor.
20461        let mut spec = three_member_spec();
20462        spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
20463        match spec.validate().unwrap_err() {
20464            AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
20465                assert_eq!(
20466                    cluster, "BAD_CLUSTER",
20467                    "PlacementClusterInvalid.cluster must carry the \
20468                     tail entry the loop reached through the accessor",
20469                );
20470            }
20471            other => panic!("expected PlacementClusterInvalid, got {other:?}"),
20472        }
20473        assert_eq!(
20474            spec.placement.clusters().len(),
20475            2,
20476            "the per-cluster validate loop's traversal input must be \
20477             a two-element slice per the accessor's projection",
20478        );
20479
20480        // (3) Per-cluster validate loop: a two-cluster cohort that
20481        // shares a name must trip `PlacementClusterDuplicate` on the
20482        // second entry — the loop must reach both entries through the
20483        // accessor for the dedup HashSet's second insert to collide.
20484        let mut spec = three_member_spec();
20485        spec.placement.clusters = vec!["rio".into(), "rio".into()];
20486        match spec.validate().unwrap_err() {
20487            AplicacaoError::PlacementClusterDuplicate { cluster } => {
20488                assert_eq!(
20489                    cluster, "rio",
20490                    "PlacementClusterDuplicate.cluster must carry the \
20491                     shared cluster name verbatim",
20492                );
20493            }
20494            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
20495        }
20496        assert_eq!(
20497            spec.placement.clusters().len(),
20498            2,
20499            "the per-cluster validate loop's traversal input must be \
20500             a two-element slice per the accessor's projection",
20501        );
20502    }
20503
20504    #[test]
20505    fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
20506        // The canonical per-`:membros` member-list-slice-shape pin:
20507        // [`AplicacaoSpec::membros`] must return the `:membros` typed
20508        // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
20509        // same backing buffer the raw `self.membros.as_slice()` field
20510        // access borrows from, byte-equal across every representative
20511        // fixture in the accept-set — the empty slice (the pre-
20512        // validation sentinel every [`AplicacaoError::NoMembros`]
20513        // refusal keys off), the singleton slice (the minimal one-
20514        // Servico Aplicacao shape), and multi-entry cohorts (the peer
20515        // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
20516        // load-bearing identity of the application graph).
20517        //
20518        // Pins against a future silent detour that returned
20519        // `&Vec<Membro>` (which would type-check but leak the storage-
20520        // side `Vec`'s grow/push/reserve surface no consumer of the
20521        // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
20522        // (which would type-check via a coercion but silently break
20523        // every downstream caller that relied on the slice sharing the
20524        // backing buffer's identity), or an out-of-order or length-
20525        // drifted projection (which would silently split the paired
20526        // `HashSet<&str>` name-set seed's collect input from the
20527        // pre-flight `.is_empty()` refusal probe's input from the per-
20528        // member validate loop's traversal input from the
20529        // programs.yaml emitter's per-entry fan-out loop's input from
20530        // the `feira app graph` per-member print traversal's input).
20531        //
20532        // Peer of the sibling M2
20533        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
20534        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
20535        // `:supervisor` static-child-list axis and the sibling M3
20536        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
20537        // (a6e18d7) `&[String]` byte-equal pin on the per-
20538        // `:placement` distribution-target-list axis — extends the
20539        // slice-return-accessor byte-equal-projection discipline onto
20540        // the outermost M3 mesh-slot type's per-Aplicacao member-list
20541        // `Vec`-carry axis.
20542        let fixtures: Vec<Vec<Membro>> = vec![
20543            Vec::new(),
20544            vec![membro("catalog", "^0.1")],
20545            vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
20546            vec![
20547                membro("catalog", "^0.1"),
20548                membro("cart", "^0.1"),
20549                membro("payment", "^0.2"),
20550            ],
20551        ];
20552        for membros in fixtures {
20553            let s = AplicacaoSpec {
20554                membros: membros.clone(),
20555                contratos: Vec::new(),
20556                politicas: MeshPolicy::default(),
20557                placement: Placement::default(),
20558                entrada: None,
20559            };
20560            assert_eq!(
20561                s.membros(),
20562                membros.as_slice(),
20563                "AplicacaoSpec::membros must return :membros verbatim \
20564                 (got {:?}, expected {:?})",
20565                s.membros(),
20566                membros.as_slice(),
20567            );
20568            assert_eq!(
20569                s.membros(),
20570                s.membros.as_slice(),
20571                "AplicacaoSpec::membros accessor and .membros.as_slice() \
20572                 field access must byte-equal — the accessor is the \
20573                 substrate-primitive typed dispatch every downstream \
20574                 member-list consumer must route through",
20575            );
20576            assert_eq!(
20577                s.membros().len(),
20578                s.membros.len(),
20579                "AplicacaoSpec::membros().len() must byte-equal \
20580                 self.membros.len() — a length-drift would silently \
20581                 split the paired `HashSet<&str>` name-set seed's \
20582                 collect input from the pre-flight `.is_empty()` \
20583                 refusal probe input from the per-member validate \
20584                 loop's traversal input",
20585            );
20586        }
20587    }
20588
20589    #[test]
20590    fn validate_reads_through_lifted_membros_accessor() {
20591        // Three-consumer coherence pin: the
20592        // [`AplicacaoSpec::validate_membros`] pre-flight
20593        // `self.membros().is_empty()` refusal probe (which must trip
20594        // [`AplicacaoError::NoMembros`] when the accessor projects the
20595        // empty slice), the same method's per-member validate loop's
20596        // `for m in self.membros()` traversal (which must reach every
20597        // entry in the same order the accessor projects, so both the
20598        // per-entry empty-`:caixa` gate that trips
20599        // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
20600        // detection `insert_first_seen` that trips
20601        // [`AplicacaoError::MembroDuplicate`] key off the accessor's
20602        // projection), and the peer [`AplicacaoSpec::validate`]'s
20603        // `HashSet<&str>` name-set seed's
20604        // `self.membros().iter().map(Membro::nome).collect()` collect
20605        // input (which every `:contratos` `:de` / `:para` membership
20606        // lookup rejects an unknown name against) must all three key
20607        // off the lifted accessor, so any future rebrand on the typed
20608        // slot's reader shape lands at exactly one place. Pins the
20609        // three-site coherence by exercising each production consumer
20610        // end-to-end: (1) the `NoMembros` refusal under the empty
20611        // slice, (2) the `MembroCaixaEmpty` refusal fires on the
20612        // second entry of a two-member cohort whose head is valid but
20613        // tail has an empty `:caixa` (which requires the loop to
20614        // reach the second entry through the accessor), and (3) the
20615        // `MembroDuplicate` refusal fires on the second entry of a
20616        // two-member cohort that shares a `:caixa` name (which
20617        // requires the loop to reach both entries through the
20618        // accessor for the dedup HashSet's second insert to collide).
20619        //
20620        // Peer of the sibling M2
20621        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
20622        // (bc92bce) coherence pin on the per-`:supervisor` static-
20623        // child-list axis and the sibling M3
20624        // `validate_placement_reads_through_lifted_clusters_accessor`
20625        // (a6e18d7) coherence pin on the per-`:placement` distribution-
20626        // target-list axis — extends the slice-return-accessor
20627        // multi-consumer coherence discipline onto the outermost M3
20628        // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
20629
20630        // (1) Pre-flight `.is_empty()` probe: the empty slice must
20631        // trip `NoMembros`.
20632        let mut spec = three_member_spec();
20633        spec.membros = Vec::new();
20634        assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
20635        assert!(
20636            spec.membros().is_empty(),
20637            "the pre-flight refusal input must be the empty slice per \
20638             the accessor's projection",
20639        );
20640
20641        // (2) Per-member validate loop: a two-member cohort with an
20642        // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
20643        // the tail — the loop must reach the second entry through
20644        // the accessor.
20645        let mut spec = three_member_spec();
20646        spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
20647        assert_eq!(
20648            spec.validate().unwrap_err(),
20649            AplicacaoError::MembroCaixaEmpty,
20650        );
20651        assert_eq!(
20652            spec.membros().len(),
20653            2,
20654            "the per-member validate loop's traversal input must be \
20655             a two-element slice per the accessor's projection",
20656        );
20657
20658        // (3) Per-member validate loop: a two-member cohort that
20659        // shares a `:caixa` name must trip `MembroDuplicate` on the
20660        // second entry — the loop must reach both entries through the
20661        // accessor for the dedup HashSet's second insert to collide.
20662        let mut spec = three_member_spec();
20663        spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
20664        match spec.validate().unwrap_err() {
20665            AplicacaoError::MembroDuplicate { caixa } => {
20666                assert_eq!(
20667                    caixa, "catalog",
20668                    "MembroDuplicate.caixa must carry the shared \
20669                     member name verbatim",
20670                );
20671            }
20672            other => panic!("expected MembroDuplicate, got {other:?}"),
20673        }
20674        assert_eq!(
20675            spec.membros().len(),
20676            2,
20677            "the per-member validate loop's traversal input must be \
20678             a two-element slice per the accessor's projection",
20679        );
20680    }
20681
20682    #[test]
20683    fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
20684        // The canonical per-`:contratos` contract-list-slice-shape pin:
20685        // [`AplicacaoSpec::contratos`] must return the `:contratos`
20686        // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
20687        // slice-view over the same backing buffer the raw
20688        // `self.contratos.as_slice()` field access borrows from, byte-
20689        // equal across every representative fixture in the accept-set —
20690        // the empty slice (the pre-validation "internal-only mesh" shape
20691        // an Aplicacao whose members exchange no typed edges renders
20692        // through), the singleton slice (the minimal one-edge Aplicacao
20693        // shape), and multi-entry cohorts (the peer multi-edge shapes
20694        // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
20695        // of the application graph).
20696        //
20697        // Pins against a future silent detour that returned
20698        // `&Vec<WitContract>` (which would type-check but leak the
20699        // storage-side `Vec`'s grow/push/reserve surface no consumer of
20700        // the typed view reaches for), a fresh-allocated
20701        // `Vec<WitContract>` copy (which would type-check via a coercion
20702        // but silently break every downstream caller that relied on the
20703        // slice sharing the backing buffer's identity), or an out-of-
20704        // order or length-drifted projection (which would silently split
20705        // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
20706        // seed's traversal input from the `detect_sync_cycles` per-edge
20707        // adjacency-list seed's traversal input from the
20708        // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
20709        // BTreeMap grouping loop's traversal input from the
20710        // `feira app graph` per-contract print traversal's input).
20711        //
20712        // Peer of the immediately-adjacent sibling M3
20713        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
20714        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
20715        // node-list axis, the sibling M3
20716        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
20717        // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
20718        // distribution-target-list axis, and the sibling M2
20719        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
20720        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
20721        // `:supervisor` static-child-list axis — extends the slice-
20722        // return-accessor byte-equal-projection discipline onto the
20723        // outermost M3 mesh-slot type's per-Aplicacao contract-list
20724        // `Vec`-carry axis, closing the last unlifted per-
20725        // `AplicacaoSpec` `Vec`-carry axis.
20726        let fixtures: Vec<Vec<WitContract>> = vec![
20727            Vec::new(),
20728            vec![contract_http("cart", "catalog", "/products/:id")],
20729            vec![
20730                contract_http("cart", "catalog", "/products/:id"),
20731                contract_http("cart", "payment", "/charge"),
20732            ],
20733            vec![
20734                contract_http("cart", "catalog", "/products/:id"),
20735                contract_http("cart", "payment", "/charge"),
20736                contract_http("payment", "catalog", "/audit"),
20737            ],
20738        ];
20739        for contratos in fixtures {
20740            let s = AplicacaoSpec {
20741                membros: vec![
20742                    membro("catalog", "^0.1"),
20743                    membro("cart", "^0.1"),
20744                    membro("payment", "^0.2"),
20745                ],
20746                contratos: contratos.clone(),
20747                politicas: MeshPolicy::default(),
20748                placement: Placement::default(),
20749                entrada: None,
20750            };
20751            assert_eq!(
20752                s.contratos(),
20753                contratos.as_slice(),
20754                "AplicacaoSpec::contratos must return :contratos verbatim \
20755                 (got {:?}, expected {:?})",
20756                s.contratos(),
20757                contratos.as_slice(),
20758            );
20759            assert_eq!(
20760                s.contratos(),
20761                s.contratos.as_slice(),
20762                "AplicacaoSpec::contratos accessor and \
20763                 .contratos.as_slice() field access must byte-equal — \
20764                 the accessor is the substrate-primitive typed dispatch \
20765                 every downstream contract-list consumer must route \
20766                 through",
20767            );
20768            assert_eq!(
20769                s.contratos().len(),
20770                s.contratos.len(),
20771                "AplicacaoSpec::contratos().len() must byte-equal \
20772                 self.contratos.len() — a length-drift would silently \
20773                 split the paired per-edge validate-loop's traversal \
20774                 input from the sync-cycle adjacency-list seed's \
20775                 traversal input from the cilium_network_policies \
20776                 per-`(:de, :para)` BTreeMap grouping loop's traversal \
20777                 input from the `feira app graph` per-contract print \
20778                 traversal's input",
20779            );
20780        }
20781    }
20782
20783    #[test]
20784    fn validate_reads_through_lifted_contratos_accessor() {
20785        // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
20786        // per-`:contratos` validate-loop's `for c in self.contratos()`
20787        // traversal (which must reach every entry in the same order the
20788        // accessor projects, so both the per-entry
20789        // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
20790        // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
20791        // dedup `HashSet` insert key off the accessor's projection),
20792        // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
20793        // `for c in self.contratos()` adjacency-list seed (which drives
20794        // the sync-subgraph deadlock-detection gate via
20795        // [`AplicacaoError::SyncCycle`]), and the peer
20796        // [`caixa_mesh::cilium_network_policies`]'s
20797        // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
20798        // grouping loop (which drives the per-CNP fan-out) must all
20799        // three key off the lifted accessor, so any future rebrand on
20800        // the typed slot's reader shape lands at exactly one place. Pins
20801        // the three-site coherence by exercising the two caixa-core
20802        // production consumers end-to-end: (1) the empty-`:contratos`
20803        // slice must validate without a per-edge diagnostic (the
20804        // per-edge loop is a no-op under the empty projection), (2) the
20805        // `ContratoMemberMissing` refusal fires on the second entry of a
20806        // two-edge cohort whose head references a valid member but tail
20807        // references a phantom name (which requires the loop to reach
20808        // the second entry through the accessor), and (3) the
20809        // `SyncCycle` refusal fires on a self-referential two-edge
20810        // cohort through the sync-cycle detector's peer projection
20811        // (which requires the detector to iterate the accessor's
20812        // projection to add the back-edge to its adjacency list).
20813        //
20814        // Peer of the sibling M3
20815        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
20816        // three-consumer coherence pin on the per-`:membros` node-list
20817        // axis and the sibling M3
20818        // `validate_placement_reads_through_lifted_clusters_accessor`
20819        // (a6e18d7) coherence pin on the per-`:placement` distribution-
20820        // target-list axis — extends the slice-return-accessor multi-
20821        // consumer coherence discipline onto the outermost M3 mesh-slot
20822        // type's per-Aplicacao contract-list `Vec`-carry axis.
20823
20824        // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
20825        // and no per-edge diagnostic surfaces. Validate succeeds on
20826        // the well-formed `:membros` head.
20827        let mut spec = three_member_spec();
20828        spec.contratos = Vec::new();
20829        assert!(
20830            spec.validate().is_ok(),
20831            "empty :contratos must validate — the per-edge loop is a \
20832             no-op under the accessor's empty projection",
20833        );
20834        assert!(
20835            spec.contratos().is_empty(),
20836            "the per-edge validate loop's traversal input must be the \
20837             empty slice per the accessor's projection",
20838        );
20839
20840        // (2) Per-edge validate loop: a two-edge cohort whose tail
20841        // references a phantom `:para` member must trip
20842        // `ContratoMemberMissing` on the tail — the loop must reach
20843        // the second entry through the accessor for the membership
20844        // lookup to fail on the phantom name.
20845        let mut spec = three_member_spec();
20846        spec.contratos = vec![
20847            contract_http("cart", "catalog", "/products/:id"),
20848            contract_http("cart", "phantom", "/x"),
20849        ];
20850        let err = spec.validate().unwrap_err();
20851        assert!(
20852            matches!(
20853                err,
20854                AplicacaoError::ContratoMemberMissing { ref caixa }
20855                    if caixa == "phantom"
20856            ),
20857            "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
20858        );
20859        assert_eq!(
20860            spec.contratos().len(),
20861            2,
20862            "the per-edge validate loop's traversal input must be \
20863             a two-element slice per the accessor's projection",
20864        );
20865
20866        // (3) Sync-cycle detector: a two-edge synchronous cohort
20867        // whose second edge closes the sync-subgraph back onto the
20868        // first must trip [`AplicacaoError::ContratoCycle`] — the
20869        // detector must iterate the accessor's projection to add
20870        // both edges to its adjacency list, so a length-drift on
20871        // the accessor's projection would silently disagree with
20872        // the sync-cycle detector on which edge closes the loop.
20873        // Peer projection to the `validate` per-edge loop above:
20874        // the sync-cycle detector routes through the same lifted
20875        // accessor, so a rebrand of the reader shape lands at one
20876        // place. Uses a two-edge cohort (cart → catalog → cart)
20877        // because the per-edge `ContratoSelfLoop` gate fires before
20878        // the sync-cycle detector on a single self-referential edge
20879        // (`cart → cart`) — the cycle-detector's input must be a
20880        // multi-edge cohort for its per-edge traversal input to be
20881        // observably wider than the per-edge validate loop's input.
20882        let mut spec = three_member_spec();
20883        spec.contratos = vec![
20884            contract_http("cart", "catalog", "/products/:id"),
20885            contract_http("catalog", "cart", "/callback"),
20886        ];
20887        let err = spec.validate().unwrap_err();
20888        assert!(
20889            matches!(err, AplicacaoError::ContratoCycle { .. }),
20890            "expected ContratoCycle from the sync-cycle detector on a \
20891             two-edge back-edge cohort, got {err:?}",
20892        );
20893        assert_eq!(
20894            spec.contratos().len(),
20895            2,
20896            "the sync-cycle detector's traversal input must be a \
20897             two-element slice per the accessor's projection",
20898        );
20899    }
20900
20901    #[test]
20902    fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
20903        // The canonical per-`:politicas` outer-composite-reference-shape
20904        // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
20905        // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
20906        // the same backing storage the raw `&self.politicas` field
20907        // access borrows from, byte-equal across every representative
20908        // fixture in the accept-set — the default `MeshPolicy` (the
20909        // author-empty "no policy on any axis" shape whose
20910        // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
20911        // shapes carrying one axis at a time
20912        // (`{mtls_required, timeout, retries, circuit_breaker,
20913        // rate_limit}` — the minimal five-axis fan-out over the
20914        // per-axis lifted accessor family every downstream mesh-artifact
20915        // emitter dispatches on), and the multi-axis composite (the
20916        // canonical `three_member_spec` fixture's `{timeout, retries,
20917        // mtls_required}` triple — the load-bearing shape every
20918        // Aplicacao-scoped fixture in this suite constructs).
20919        //
20920        // Pins against a future silent detour that returned a fresh-
20921        // cloned `MeshPolicy` copy (which would type-check via a `Clone`
20922        // impl but silently break every downstream caller that relied
20923        // on the reference sharing the composite's backing identity), a
20924        // reference to an operator-resolved overlay (the future
20925        // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
20926        // acknowledges — its resolution must land at exactly this
20927        // accessor body, not silently divert the raw slot away from a
20928        // second consumer), or an axis-shuffled projection (a future
20929        // detour that swapped `timeout` and `retries` through the
20930        // accessor would silently split the paired `validate_politicas`
20931        // per-axis bracket-dispatch's traversal input from the peer
20932        // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
20933        // emitter's fan-out input from the peer
20934        // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
20935        // overlay emitter's fan-out input).
20936        //
20937        // Peer of the sibling M3
20938        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
20939        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
20940        // node-list `Vec`-carry axis and the sibling M3
20941        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
20942        // (0dcc926) `&[WitContract]` byte-equal pin on the per-
20943        // `:contratos` edge-list `Vec`-carry axis — extends the outer-
20944        // accessor byte-equal-projection discipline onto the outermost
20945        // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
20946        // reference axis, the first `&Composite`-return accessor on the
20947        // outer [`AplicacaoSpec`] type.
20948        let fixtures: Vec<MeshPolicy> = vec![
20949            MeshPolicy::default(),
20950            MeshPolicy {
20951                mtls_required: Some(true),
20952                ..MeshPolicy::default()
20953            },
20954            MeshPolicy {
20955                mtls_required: Some(false),
20956                ..MeshPolicy::default()
20957            },
20958            MeshPolicy {
20959                timeout: Some(Duration::from_secs(30)),
20960                ..MeshPolicy::default()
20961            },
20962            MeshPolicy {
20963                retries: Some(3),
20964                ..MeshPolicy::default()
20965            },
20966            MeshPolicy {
20967                circuit_breaker: Some(CircuitBreaker {
20968                    max_failures: 5,
20969                    window: Duration::from_secs(30),
20970                }),
20971                ..MeshPolicy::default()
20972            },
20973            MeshPolicy {
20974                rate_limit: Some(RateLimit {
20975                    rate: 100,
20976                    window: Duration::from_secs(1),
20977                }),
20978                ..MeshPolicy::default()
20979            },
20980            MeshPolicy {
20981                timeout: Some(Duration::from_secs(30)),
20982                retries: Some(3),
20983                mtls_required: Some(true),
20984                ..MeshPolicy::default()
20985            },
20986        ];
20987        for politicas in fixtures {
20988            let s = AplicacaoSpec {
20989                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
20990                contratos: Vec::new(),
20991                politicas: politicas.clone(),
20992                placement: Placement::default(),
20993                entrada: None,
20994            };
20995            assert_eq!(
20996                *s.politicas(),
20997                politicas,
20998                "AplicacaoSpec::politicas must return :politicas verbatim \
20999                 (got {:?}, expected {:?})",
21000                s.politicas(),
21001                politicas,
21002            );
21003            assert!(
21004                std::ptr::eq(s.politicas(), &s.politicas),
21005                "AplicacaoSpec::politicas accessor and &self.politicas \
21006                 field access must borrow the same backing storage — \
21007                 the accessor is the substrate-primitive typed dispatch \
21008                 every downstream mesh-policy composite consumer must \
21009                 route through, and a reference-identity split would \
21010                 silently break every consumer that relied on the \
21011                 borrow sharing the composite's storage",
21012            );
21013            assert_eq!(
21014                s.politicas().is_empty(),
21015                s.politicas.is_empty(),
21016                "AplicacaoSpec::politicas().is_empty() must byte-equal \
21017                 self.politicas.is_empty() — an emptiness-drift would \
21018                 silently split the paired `validate_politicas` \
21019                 per-axis bracket-dispatch's seed from the peer \
21020                 caixa-mesh CNP mTLS-overlay emitter's key from the \
21021                 peer caixa-mesh HTTPRoute timeout+retry overlay \
21022                 emitter's key",
21023            );
21024        }
21025    }
21026
21027    #[test]
21028    fn validate_politicas_reads_through_lifted_politicas_accessor() {
21029        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
21030        // per-axis bracket-dispatch seed (`let p = self.politicas();`,
21031        // followed by the per-axis fan-out `p.timeout()` /
21032        // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
21033        // the lifted axis-level accessor family) must key off the
21034        // lifted outer accessor, so any future rebrand on the typed
21035        // slot's outer-composite reader shape lands at exactly one
21036        // place. Pins the multi-axis coherence by exercising each
21037        // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
21038        // a `Some(Duration::ZERO)` timeout under the outer accessor's
21039        // reference projection, (2) `PolicyRetriesZero` fires on a
21040        // `Some(0)` retries under the same projection, and (3) an
21041        // empty [`MeshPolicy::default`] passes `validate_politicas` —
21042        // the outer accessor's reference-projection reaches every
21043        // per-axis branch without silently short-circuiting any.
21044        //
21045        // Peer of the sibling M3
21046        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
21047        // three-consumer coherence pin on the per-`:membros` node-list
21048        // axis and the sibling M3
21049        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
21050        // three-consumer coherence pin on the per-`:contratos`
21051        // edge-list axis — extends the multi-consumer coherence
21052        // discipline onto the outermost M3 mesh-slot type's per-
21053        // Aplicacao mesh-policy composite-reference axis, the first
21054        // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
21055        // type.
21056
21057        // (1) `PolicyTimeoutZero` refusal under the outer accessor's
21058        // reference projection: a `Some(Duration::ZERO)` timeout must
21059        // trip the zero-floor gate. The bracket-dispatch's first arm
21060        // reads `p.timeout()` on the reference returned by the outer
21061        // accessor.
21062        let mut spec = three_member_spec();
21063        spec.politicas.timeout = Some(Duration::ZERO);
21064        spec.politicas.retries = None;
21065        spec.politicas.circuit_breaker = None;
21066        spec.politicas.rate_limit = None;
21067        assert_eq!(
21068            spec.validate().unwrap_err(),
21069            AplicacaoError::PolicyTimeoutZero,
21070        );
21071        assert!(
21072            std::ptr::eq(spec.politicas(), &spec.politicas),
21073            "the `validate_politicas` per-axis bracket-dispatch's \
21074             traversal input must be the same backing composite the \
21075             accessor's reference projection borrows from",
21076        );
21077
21078        // (2) `PolicyRetriesZero` refusal under the outer accessor's
21079        // reference projection: a `Some(0)` retries must trip the
21080        // zero-floor gate. The bracket-dispatch's second arm reads
21081        // `p.retries()` on the reference returned by the outer accessor.
21082        let mut spec = three_member_spec();
21083        spec.politicas.timeout = None;
21084        spec.politicas.retries = Some(0);
21085        spec.politicas.circuit_breaker = None;
21086        spec.politicas.rate_limit = None;
21087        assert_eq!(
21088            spec.validate().unwrap_err(),
21089            AplicacaoError::PolicyRetriesZero,
21090        );
21091
21092        // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
21093        // — every per-axis arm short-circuits on `None`, so the outer
21094        // accessor's reference projection reaches the fall-through
21095        // `Ok(())` without any per-axis refusal firing.
21096        let mut spec = three_member_spec();
21097        spec.politicas = MeshPolicy::default();
21098        assert!(
21099            spec.validate().is_ok(),
21100            "an empty `MeshPolicy` must pass `validate_politicas` — \
21101             every per-axis arm short-circuits on `None` under the \
21102             outer accessor's reference projection",
21103        );
21104        assert!(
21105            spec.politicas().is_empty(),
21106            "the outer accessor's reference projection must be the \
21107             empty composite per the `MeshPolicy::default()` fixture",
21108        );
21109    }
21110
21111    #[test]
21112    #[allow(clippy::too_many_lines)]
21113    fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
21114        // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
21115        // per-axis bracket-dispatch's `:timeout` and `:retries` arms
21116        // must both key off the lifted axis-level accessors
21117        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
21118        // the peer `:circuit-breaker` / `:rate-limit` arms already
21119        // routing through [`MeshPolicy::circuit_breaker`] /
21120        // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
21121        // per axis on the substrate primitive" shape at the fan-out
21122        // (four axes, four accessors, no raw-field-access site
21123        // anywhere on the bracket-dispatch). Pins the per-axis
21124        // coherence at the accept-set boundaries the bracket carves:
21125        //   1. accessor byte-equal to raw field on every representative
21126        //      accept-set value (`None`, sub-cap, at-cap, past-cap
21127        //      sentinel) — a future accessor drift that no longer
21128        //      shipped the raw slot verbatim would surface here,
21129        //   2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
21130        //      routed through the accessor's projection, proving the
21131        //      first arm reads through the accessor rather than a
21132        //      silent-detour peer-axis field access,
21133        //   3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
21134        //      through the accessor's projection, proving the second
21135        //      arm reads through the accessor,
21136        //   4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
21137        //      passes validate under the accessor projection (paired
21138        //      with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
21139        //      sibling axis), pinning the upper-boundary accept-arm
21140        //      also routes through the accessor.
21141        //
21142        // Peer of the sibling M3
21143        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
21144        // outer-composite-reference coherence pin (which asserts the
21145        // `let p = self.politicas()` seed); extends the discipline onto
21146        // the per-axis fan-out layer that consumes the seed's
21147        // reference. Same shape as
21148        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
21149        // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
21150        // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
21151        // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
21152
21153        // (1) Accessor byte-equal to raw field on the `:timeout` axis
21154        // across the accept-set boundaries the bracket dispatch's
21155        // three-arm gate carves out
21156        // ([`crate::render::require_positive_canonical_bounded_duration`]
21157        // — zero-floor + canonical-form + upper-cap).
21158        for timeout in [
21159            None,
21160            Some(Duration::ZERO),
21161            Some(Duration::from_millis(1)),
21162            Some(POLICY_TIMEOUT_MAX),
21163        ] {
21164            let p = MeshPolicy {
21165                timeout,
21166                ..MeshPolicy::default()
21167            };
21168            assert_eq!(
21169                p.timeout(),
21170                p.timeout,
21171                "MeshPolicy::timeout accessor must byte-equal the raw \
21172                 .timeout field across every accept-set boundary the \
21173                 validate_politicas :timeout arm carves out — a drift \
21174                 here would silently split the validate bracket's arm \
21175                 from the peer caixa-mesh HTTPRoute timeout-overlay \
21176                 emitter's read",
21177            );
21178        }
21179
21180        // (2) Accessor byte-equal to raw field on the `:retries` axis
21181        // across the accept-set boundaries the bracket dispatch's
21182        // two-arm gate carves out
21183        // ([`crate::render::require_positive_bounded_u32`] — zero-floor
21184        // + upper-cap).
21185        for retries in [
21186            None,
21187            Some(0u32),
21188            Some(1u32),
21189            Some(POLICY_RETRIES_MAX),
21190            Some(POLICY_RETRIES_MAX + 1),
21191            Some(u32::MAX),
21192        ] {
21193            let p = MeshPolicy {
21194                retries,
21195                ..MeshPolicy::default()
21196            };
21197            assert_eq!(
21198                p.retries(),
21199                p.retries,
21200                "MeshPolicy::retries accessor must byte-equal the raw \
21201                 .retries field across every accept-set boundary the \
21202                 validate_politicas :retries arm carves out — a drift \
21203                 here would silently split the validate bracket's arm \
21204                 from the peer caixa-mesh HTTPRoute retry-overlay \
21205                 emitter's read",
21206            );
21207        }
21208
21209        // (3) `PolicyTimeoutZero` fires on the accessor-projected
21210        // zero-floor boundary. A silent detour that no longer read
21211        // through `p.timeout()` (a peer-axis field read, an accidental
21212        // Option::and-then chain that collapsed the None arm to Some,
21213        // an accessor rebrand that clamped the return through the
21214        // upper cap) would fail to refuse here.
21215        let mut spec = three_member_spec();
21216        spec.politicas.timeout = Some(Duration::ZERO);
21217        spec.politicas.retries = None;
21218        spec.politicas.circuit_breaker = None;
21219        spec.politicas.rate_limit = None;
21220        assert_eq!(
21221            spec.politicas().timeout(),
21222            Some(Duration::ZERO),
21223            "the accessor projection must reflect the fixture's \
21224             `Some(Duration::ZERO)` :timeout verbatim",
21225        );
21226        assert_eq!(
21227            spec.validate().unwrap_err(),
21228            AplicacaoError::PolicyTimeoutZero,
21229            "the validate_politicas :timeout zero-floor arm must fire \
21230             through the lifted accessor's projection — a silent \
21231             detour to a peer-axis field would fail to refuse",
21232        );
21233
21234        // (4) `PolicyRetriesZero` fires on the accessor-projected
21235        // zero-floor boundary on the sibling `:retries` axis.
21236        let mut spec = three_member_spec();
21237        spec.politicas.timeout = None;
21238        spec.politicas.retries = Some(0);
21239        spec.politicas.circuit_breaker = None;
21240        spec.politicas.rate_limit = None;
21241        assert_eq!(
21242            spec.politicas().retries(),
21243            Some(0),
21244            "the accessor projection must reflect the fixture's \
21245             `Some(0)` :retries verbatim",
21246        );
21247        assert_eq!(
21248            spec.validate().unwrap_err(),
21249            AplicacaoError::PolicyRetriesZero,
21250            "the validate_politicas :retries zero-floor arm must fire \
21251             through the lifted accessor's projection — a silent \
21252             detour to a peer-axis field would fail to refuse",
21253        );
21254
21255        // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
21256        // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
21257        // must pass validate under the accessor projection — pins the
21258        // upper-boundary accept-arm also routes through the lifted
21259        // accessor (a drift that clamped or short-circuited at the
21260        // upper boundary would fail the whole-spec validate here).
21261        let mut spec = three_member_spec();
21262        spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
21263        spec.politicas.retries = Some(POLICY_RETRIES_MAX);
21264        spec.politicas.circuit_breaker = None;
21265        spec.politicas.rate_limit = None;
21266        assert_eq!(
21267            spec.politicas().timeout(),
21268            Some(POLICY_TIMEOUT_MAX),
21269            "the accessor projection must reflect the fixture's \
21270             at-cap :timeout verbatim",
21271        );
21272        assert_eq!(
21273            spec.politicas().retries(),
21274            Some(POLICY_RETRIES_MAX),
21275            "the accessor projection must reflect the fixture's \
21276             at-cap :retries verbatim",
21277        );
21278        assert!(
21279            spec.validate().is_ok(),
21280            "at-cap :timeout + :retries must pass validate under the \
21281             accessor projection — the upper-boundary accept-arm on \
21282             both axes routes through the lifted accessor",
21283        );
21284    }
21285
21286    #[test]
21287    fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
21288        // The canonical per-`:placement` outer-composite-reference-shape
21289        // pin: [`AplicacaoSpec::placement`] must return the `:placement`
21290        // typed `Placement` verbatim as a `&Placement` reference over the
21291        // same backing storage the raw `&self.placement` field access
21292        // borrows from, byte-equal across every representative fixture in
21293        // the accept-set — the default `Placement` (the substrate seed
21294        // shape whose [`PlacementStrategy::default`] evaluates to
21295        // `SingleNode` with an empty `:clusters` pool and both
21296        // optional-scalar axes `None`), and every canonical strategy /
21297        // cluster-pool / optional-scalar combination the
21298        // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
21299        // three [`PlacementStrategy`] variants — `SingleNode`,
21300        // `Replicated`, `Sharded` — cross-projected with a non-empty
21301        // `:clusters` pool and, on the `Sharded` arm, a non-empty
21302        // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
21303        // canonical `three_member_spec` `Replicated` fixture's
21304        // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
21305        //
21306        // Pins against a future silent detour that returned a fresh-
21307        // cloned `Placement` copy (which would type-check via a `Clone`
21308        // impl but silently break every downstream caller that relied on
21309        // the reference sharing the composite's backing identity), a
21310        // reference to an operator-resolved overlay (the future per-
21311        // cluster `:placement-overrides` slot MESH-COMPOSITION §V
21312        // acknowledges — its resolution must land at exactly this
21313        // accessor body, not silently divert the raw slot away from a
21314        // second consumer), or an axis-shuffled projection (a future
21315        // detour that swapped `clusters` and `affinity` through the
21316        // accessor would silently split the paired `validate_placement`
21317        // per-axis bracket-dispatch's traversal input from the peer
21318        // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
21319        // programs.yaml distribution-annotation emitter's fan-out input
21320        // from the peer `feira app graph` per-Aplicacao print line's
21321        // input).
21322        //
21323        // Peer of the sibling M3
21324        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
21325        // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
21326        // outer mesh-policy composite-reference axis, and of the sibling
21327        // slice-return `aplicacao_spec_membros_returns_membros_slice_
21328        // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
21329        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
21330        // across_permutations` (0dcc926) `&[WitContract]` pins — extends
21331        // the outer-accessor byte-equal-projection discipline onto the
21332        // outermost M3 mesh-slot type's per-Aplicacao distribution
21333        // composite-reference axis, the second `&Composite`-return
21334        // accessor on the outer [`AplicacaoSpec`] type.
21335        let fixtures: Vec<Placement> = vec![
21336            Placement::default(),
21337            Placement {
21338                estrategia: PlacementStrategy::SingleNode,
21339                clusters: vec!["rio".into()],
21340                affinity: None,
21341                shard_key: None,
21342            },
21343            Placement {
21344                estrategia: PlacementStrategy::Replicated,
21345                clusters: vec!["rio".into(), "mar".into()],
21346                affinity: None,
21347                shard_key: None,
21348            },
21349            Placement {
21350                estrategia: PlacementStrategy::Replicated,
21351                clusters: vec!["rio".into(), "mar".into()],
21352                affinity: Some("data-locality".into()),
21353                shard_key: None,
21354            },
21355            Placement {
21356                estrategia: PlacementStrategy::Sharded,
21357                clusters: vec!["rio".into(), "mar".into()],
21358                affinity: None,
21359                shard_key: Some("tenantId".into()),
21360            },
21361            Placement {
21362                estrategia: PlacementStrategy::Sharded,
21363                clusters: vec!["rio".into(), "mar".into(), "sol".into()],
21364                affinity: Some("low-latency".into()),
21365                shard_key: Some("metadata.tenantId".into()),
21366            },
21367        ];
21368        for placement in fixtures {
21369            let s = AplicacaoSpec {
21370                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
21371                contratos: Vec::new(),
21372                politicas: MeshPolicy::default(),
21373                placement: placement.clone(),
21374                entrada: None,
21375            };
21376            assert_eq!(
21377                *s.placement(),
21378                placement,
21379                "AplicacaoSpec::placement must return :placement verbatim \
21380                 (got {:?}, expected {:?})",
21381                s.placement(),
21382                placement,
21383            );
21384            assert!(
21385                std::ptr::eq(s.placement(), &s.placement),
21386                "AplicacaoSpec::placement accessor and &self.placement \
21387                 field access must borrow the same backing storage — the \
21388                 accessor is the substrate-primitive typed dispatch every \
21389                 downstream distribution-composite consumer must route \
21390                 through, and a reference-identity split would silently \
21391                 break every consumer that relied on the borrow sharing \
21392                 the composite's storage",
21393            );
21394            assert_eq!(
21395                s.placement().estrategia(),
21396                s.placement.estrategia,
21397                "AplicacaoSpec::placement().estrategia() must byte-equal \
21398                 self.placement.estrategia — a strategy-drift would \
21399                 silently split the paired `validate_placement` \
21400                 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
21401                 peer caixa-mesh programs.yaml `placement.estrategia` \
21402                 emitter's key from the peer `feira app graph` printer's \
21403                 strategy label",
21404            );
21405            assert_eq!(
21406                s.placement().clusters(),
21407                s.placement.clusters.as_slice(),
21408                "AplicacaoSpec::placement().clusters() must byte-equal \
21409                 self.placement.clusters — a cluster-pool drift would \
21410                 silently split the paired `validate_placement` \
21411                 pre-flight `.is_empty()` refusal probe's traversal from \
21412                 the peer caixa-mesh programs.yaml `placement.clusters` \
21413                 emitter's fan-out from the peer `feira app graph` \
21414                 printer's cluster list",
21415            );
21416        }
21417    }
21418
21419    #[test]
21420    fn validate_placement_reads_through_lifted_placement_accessor() {
21421        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
21422        // per-axis bracket-dispatch seed (`let p = self.placement();`,
21423        // followed by the per-axis fan-out `p.clusters()` /
21424        // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
21425        // lifted axis-level accessor family) must key off the lifted
21426        // outer accessor, so any future rebrand on the typed slot's
21427        // outer-composite reader shape lands at exactly one place. Pins
21428        // the multi-axis coherence by exercising each per-axis refusal
21429        // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
21430        // `:clusters` pool under the outer accessor's reference
21431        // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
21432        // strategy with a `None` `:shard-key` under the same projection,
21433        // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
21434        // with a `Some` `:shard-key` under the same projection, and
21435        // (4) the canonical `three_member_spec` `Replicated` fixture
21436        // passes `validate_placement` under the outer accessor's
21437        // reference projection — the accessor's reference-projection
21438        // reaches every per-axis branch (cluster-pool refusal, `Sharded`
21439        // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
21440        // without silently short-circuiting any.
21441        //
21442        // Peer of the sibling M3
21443        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
21444        // (534dc21) multi-axis coherence pin on the per-`:politicas`
21445        // outer mesh-policy composite-reference axis — extends the
21446        // multi-consumer coherence discipline onto the outermost M3
21447        // mesh-slot type's per-Aplicacao distribution composite-
21448        // reference axis, the second `&Composite`-return accessor on
21449        // the outer [`AplicacaoSpec`] type.
21450
21451        // (1) `PlacementWithoutClusters` refusal under the outer
21452        // accessor's reference projection: an empty `:clusters` pool
21453        // must trip the pre-flight refusal probe. The bracket-dispatch's
21454        // first arm reads `p.clusters()` on the reference returned by
21455        // the outer accessor.
21456        let mut spec = three_member_spec();
21457        spec.placement.clusters = Vec::new();
21458        assert_eq!(
21459            spec.validate().unwrap_err(),
21460            AplicacaoError::PlacementWithoutClusters {
21461                estrategia: PlacementStrategy::Replicated,
21462            },
21463        );
21464        assert!(
21465            std::ptr::eq(spec.placement(), &spec.placement),
21466            "the `validate_placement` per-axis bracket-dispatch's \
21467             traversal input must be the same backing composite the \
21468             accessor's reference projection borrows from",
21469        );
21470
21471        // (2) `ShardedWithoutKey` refusal under the outer accessor's
21472        // reference projection: a `Sharded` strategy with a `None`
21473        // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
21474        // The bracket-dispatch's third arm reads `p.estrategia()` for
21475        // the match scrutinee then `p.shard_key()` for the cascade
21476        // scrutinee, both on the reference returned by the outer
21477        // accessor.
21478        let mut spec = three_member_spec();
21479        spec.placement.estrategia = PlacementStrategy::Sharded;
21480        spec.placement.shard_key = None;
21481        assert_eq!(
21482            spec.validate().unwrap_err(),
21483            AplicacaoError::ShardedWithoutKey,
21484        );
21485
21486        // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
21487        // reference projection: a non-`Sharded` strategy with a `Some`
21488        // `:shard-key` must trip the declared-but-inert refusal. The
21489        // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
21490        // + `p.estrategia()` for the diagnostic on the reference
21491        // returned by the outer accessor.
21492        let mut spec = three_member_spec();
21493        spec.placement.estrategia = PlacementStrategy::Replicated;
21494        spec.placement.shard_key = Some("tenantId".into());
21495        assert_eq!(
21496            spec.validate().unwrap_err(),
21497            AplicacaoError::ShardKeyOnNonSharded {
21498                estrategia: PlacementStrategy::Replicated,
21499                shard_key: "tenantId".into(),
21500            },
21501        );
21502
21503        // (4) Canonical `three_member_spec` `Replicated` fixture passes
21504        // `validate_placement` — every per-axis arm reaches the fall-
21505        // through `Ok(())` without any per-axis refusal firing under the
21506        // outer accessor's reference projection.
21507        let spec = three_member_spec();
21508        assert!(
21509            spec.validate().is_ok(),
21510            "the canonical Replicated placement fixture must pass \
21511             `validate_placement` — every per-axis arm short-circuits on \
21512             valid input under the outer accessor's reference projection",
21513        );
21514        assert_eq!(
21515            spec.placement().estrategia(),
21516            PlacementStrategy::Replicated,
21517            "the outer accessor's reference projection must be the \
21518             canonical Replicated fixture's strategy",
21519        );
21520        assert_eq!(
21521            spec.placement().clusters(),
21522            &["rio", "mar"],
21523            "the outer accessor's reference projection must be the \
21524             canonical Replicated fixture's cluster pool",
21525        );
21526    }
21527
21528    #[test]
21529    fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
21530        // The canonical per-`:entrada` outer-composite-optional-
21531        // reference-shape pin: [`AplicacaoSpec::entrada`] must return
21532        // the `:entrada` typed `Option<Entrada>` verbatim as an
21533        // `Option<&Entrada>` reference over the same backing storage
21534        // the raw `self.entrada.as_ref()` field access borrows from,
21535        // byte-equal across every representative fixture in the
21536        // accept-set — the author-omitted `None` shape (the
21537        // "internal-only mesh" partition every downstream external-
21538        // gateway emitter treats as "emit nothing"), the minimal
21539        // singleton `:entrada` composite (host + destination + empty
21540        // paths + default port), the paths-carrying composite (the
21541        // canonical `three_member_spec` fixture's ["/api" "/health"]
21542        // path-list shape every HTTPRoute per-rule fan-out emitter
21543        // reads), and the non-default port composite (the canonical
21544        // custom-port shape the port-fallback resolver reads).
21545        //
21546        // Pins against a future silent detour that returned a fresh-
21547        // cloned `Entrada` copy (which would type-check via a `Clone`
21548        // impl but silently break every downstream caller that
21549        // relied on the reference sharing the composite's backing
21550        // identity), a reference to an operator-resolved overlay
21551        // (the future per-cluster `:entrada-overrides` slot the
21552        // MESH-COMPOSITION §V federation roadmap acknowledges — its
21553        // resolution must land at exactly this accessor body, not
21554        // silently divert the raw slot away from a second consumer),
21555        // a `None` → `Some(Entrada::default)` cluster-default
21556        // projection (which would collapse the load-bearing
21557        // "author-omitted `:entrada` ⇒ internal-only mesh" partition
21558        // the peer `gateway_routes` early-return + `feira app graph`
21559        // internal-only-mesh partition both read), or an axis-
21560        // shuffled projection (a future detour that swapped
21561        // `host` and `para` through the accessor would silently
21562        // split the paired `validate` per-`:entrada` shape-and-
21563        // membership gate's traversal input from the peer
21564        // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
21565        // fan-out input from the peer `feira app graph` external-
21566        // gateway summary line).
21567        //
21568        // Peer of the sibling M3
21569        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
21570        // (534dc21) `&MeshPolicy` byte-equal pin on the per-
21571        // `:politicas` outer mesh-policy composite-reference axis
21572        // and of the sibling M3
21573        // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
21574        // (9abb8f0) `&Placement` byte-equal pin on the per-
21575        // `:placement` outer distribution-composite composite-
21576        // reference axis — extends the outer-accessor byte-equal-
21577        // projection discipline onto the last unlifted outermost M3
21578        // mesh-slot type's per-Aplicacao external-gateway composite-
21579        // reference axis, the third and final `&Composite`-return
21580        // accessor on the outer [`AplicacaoSpec`] type.
21581        let fixtures: Vec<Option<Entrada>> = vec![
21582            None,
21583            Some(Entrada {
21584                host: "checkout.quero.cloud".into(),
21585                para: "cart".into(),
21586                paths: Vec::new(),
21587                port: DEFAULT_SERVICO_PORT,
21588            }),
21589            Some(Entrada {
21590                host: "checkout.quero.cloud".into(),
21591                para: "cart".into(),
21592                paths: vec!["/api".into(), "/health".into()],
21593                port: DEFAULT_SERVICO_PORT,
21594            }),
21595            Some(Entrada {
21596                host: "checkout.quero.cloud".into(),
21597                para: "cart".into(),
21598                paths: vec!["/api".into()],
21599                port: 9443,
21600            }),
21601        ];
21602        for entrada in fixtures {
21603            let s = AplicacaoSpec {
21604                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
21605                contratos: Vec::new(),
21606                politicas: MeshPolicy::default(),
21607                placement: Placement::default(),
21608                entrada: entrada.clone(),
21609            };
21610            assert_eq!(
21611                s.entrada(),
21612                entrada.as_ref(),
21613                "AplicacaoSpec::entrada must return :entrada verbatim \
21614                 (got {:?}, expected {:?})",
21615                s.entrada(),
21616                entrada.as_ref(),
21617            );
21618            match (s.entrada(), s.entrada.as_ref()) {
21619                (Some(a), Some(b)) => assert!(
21620                    std::ptr::eq(a, b),
21621                    "AplicacaoSpec::entrada accessor and \
21622                     self.entrada.as_ref() field access must borrow \
21623                     the same backing storage — the accessor is the \
21624                     substrate-primitive typed dispatch every \
21625                     downstream external-gateway composite consumer \
21626                     must route through, and a reference-identity \
21627                     split would silently break every consumer that \
21628                     relied on the borrow sharing the composite's \
21629                     storage",
21630                ),
21631                (None, None) => {}
21632                _ => panic!(
21633                    "AplicacaoSpec::entrada presence bit must byte-\
21634                     equal self.entrada.is_some() — a presence-bit \
21635                     drift would silently split the paired `validate` \
21636                     per-`:entrada` shape-and-membership gate's \
21637                     traversal head from the peer \
21638                     caixa-mesh gateway_routes early-return partition \
21639                     from the peer `feira app graph` internal-only-\
21640                     mesh partition",
21641                ),
21642            }
21643            assert_eq!(
21644                s.entrada().is_some(),
21645                s.entrada.is_some(),
21646                "AplicacaoSpec::entrada().is_some() must byte-equal \
21647                 self.entrada.is_some() — a presence-bit drift would \
21648                 silently split every downstream `Option<&Entrada>` \
21649                 consumer's partition on the internal-only-mesh arm",
21650            );
21651        }
21652    }
21653
21654    #[test]
21655    fn validate_reads_through_lifted_entrada_accessor() {
21656        // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
21657        // per-`:entrada` shape-and-membership gate (`if let Some(e) =
21658        // self.entrada() { … }`, followed by the per-axis fan-out
21659        // `validate_entrada_para(&e.para)` /
21660        // `EntradaMemberMissing` membership lookup /
21661        // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
21662        // per-`e.paths` `validate_entrada_path` traversal) must key
21663        // off the lifted outer accessor, so any future rebrand on
21664        // the typed slot's outer-composite reader shape lands at
21665        // exactly one place. Pins the multi-axis coherence by
21666        // exercising each per-axis refusal end-to-end: (1) the
21667        // author-omitted `None` shape short-circuits past every
21668        // per-`:entrada` refusal (the internal-only mesh partition
21669        // the accessor's `None` arm names), (2) `EntradaMemberMissing`
21670        // fires on a well-shaped but phantom `:para` under the outer
21671        // accessor's reference projection, and (3) the canonical
21672        // `three_member_spec` `:entrada` fixture passes `validate`
21673        // under the outer accessor's reference projection.
21674        //
21675        // Peer of the sibling M3
21676        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
21677        // (534dc21) multi-axis coherence pin on the per-`:politicas`
21678        // outer mesh-policy composite-reference axis and the sibling
21679        // M3
21680        // [`validate_placement_reads_through_lifted_placement_accessor`]
21681        // (9abb8f0) multi-axis coherence pin on the per-`:placement`
21682        // outer distribution-composite composite-reference axis —
21683        // extends the multi-consumer coherence discipline onto the
21684        // last unlifted outermost M3 mesh-slot type's per-Aplicacao
21685        // external-gateway composite-reference axis, the third and
21686        // final `&Composite`-return accessor on the outer
21687        // [`AplicacaoSpec`] type.
21688
21689        // (1) `None` :entrada — the internal-only-mesh partition
21690        // short-circuits past every per-`:entrada` refusal. The outer
21691        // accessor's reference projection reaches the fall-through
21692        // `Ok(())` on the `None` arm without any per-axis refusal
21693        // firing.
21694        let mut spec = three_member_spec();
21695        spec.entrada = None;
21696        assert!(
21697            spec.validate().is_ok(),
21698            "an author-omitted `:entrada` must pass `validate` — the \
21699             internal-only-mesh partition short-circuits past every \
21700             per-`:entrada` refusal under the outer accessor's \
21701             reference projection",
21702        );
21703        assert!(
21704            spec.entrada().is_none(),
21705            "the outer accessor's reference projection must name the \
21706             internal-only-mesh partition per the `None` fixture",
21707        );
21708
21709        // (2) `EntradaMemberMissing` refusal under the outer accessor's
21710        // reference projection: a well-shaped but phantom `:para` must
21711        // trip the membership-lookup refusal. The gate's second arm
21712        // reads `e.para` on the reference returned by the outer
21713        // accessor.
21714        let mut spec = three_member_spec();
21715        if let Some(e) = spec.entrada.as_mut() {
21716            e.para = "phantom".into();
21717        }
21718        assert_eq!(
21719            spec.validate().unwrap_err(),
21720            AplicacaoError::EntradaMemberMissing {
21721                para: "phantom".into(),
21722            },
21723        );
21724        match (spec.entrada(), spec.entrada.as_ref()) {
21725            (Some(a), Some(b)) => assert!(
21726                std::ptr::eq(a, b),
21727                "the `validate` per-`:entrada` gate's traversal head \
21728                 must be the same backing composite the accessor's \
21729                 reference projection borrows from",
21730            ),
21731            _ => panic!("fixture must carry Some(:entrada)"),
21732        }
21733
21734        // (3) Canonical `three_member_spec` `:entrada` fixture passes
21735        // `validate` — every per-axis arm reaches the fall-through
21736        // `Ok(())` without any per-axis refusal firing under the
21737        // outer accessor's reference projection.
21738        let spec = three_member_spec();
21739        assert!(
21740            spec.validate().is_ok(),
21741            "the canonical `:entrada` fixture must pass `validate` — \
21742             every per-axis arm short-circuits on valid input under \
21743             the outer accessor's reference projection",
21744        );
21745        assert!(
21746            spec.entrada().is_some(),
21747            "the outer accessor's reference projection must be the \
21748             canonical `:entrada` fixture's composite",
21749        );
21750    }
21751
21752    #[test]
21753    fn port_for_destination_reads_through_lifted_entrada_accessor() {
21754        // Peer coherence pin: the
21755        // [`AplicacaoSpec::port_for_destination`] per-destination
21756        // L4-port fallback resolver's composite-projection seed
21757        // (`self.entrada().filter(…).map_or(…)`) must key off the
21758        // lifted outer accessor. Pins the coherence by exercising
21759        // the resolver end-to-end: (1) the `None` `:entrada` shape
21760        // falls through to `DEFAULT_SERVICO_PORT` under the outer
21761        // accessor's reference projection, (2) a non-matching
21762        // destination falls through to `DEFAULT_SERVICO_PORT` under
21763        // the outer accessor's reference projection, and (3) the
21764        // matching destination resolves to the `:entrada :port`
21765        // value under the outer accessor's reference projection.
21766        //
21767        // Peer of the sibling
21768        // [`validate_reads_through_lifted_entrada_accessor`] multi-
21769        // consumer coherence pin on the same per-`:entrada` outer-
21770        // composite axis — extends the multi-consumer coherence
21771        // discipline onto the second per-`:entrada` production
21772        // consumer, the L4-port fallback resolver.
21773
21774        // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
21775        // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
21776        // arm under the outer accessor's reference projection.
21777        let mut spec = three_member_spec();
21778        spec.entrada = None;
21779        assert_eq!(
21780            spec.port_for_destination("cart"),
21781            DEFAULT_SERVICO_PORT,
21782            "the port-fallback resolver must fall through to \
21783             DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
21784             under the outer accessor's reference projection",
21785        );
21786
21787        // (2) Non-matching destination — the resolver's `filter(…)`
21788        // arm rejects a mismatched destination and falls through
21789        // to `DEFAULT_SERVICO_PORT` under the outer accessor's
21790        // reference projection.
21791        let mut spec = three_member_spec();
21792        if let Some(e) = spec.entrada.as_mut() {
21793            e.para = "cart".into();
21794            e.port = 9443;
21795        }
21796        assert_eq!(
21797            spec.port_for_destination("catalog"),
21798            DEFAULT_SERVICO_PORT,
21799            "the port-fallback resolver must fall through to \
21800             DEFAULT_SERVICO_PORT on a non-matching destination \
21801             under the outer accessor's reference projection",
21802        );
21803
21804        // (3) Matching destination — the resolver's `map_or(…)` arm
21805        // returns the `:entrada :port` value under the outer
21806        // accessor's reference projection.
21807        let mut spec = three_member_spec();
21808        if let Some(e) = spec.entrada.as_mut() {
21809            e.para = "cart".into();
21810            e.port = 9443;
21811        }
21812        assert_eq!(
21813            spec.port_for_destination("cart"),
21814            9443,
21815            "the port-fallback resolver must return the \
21816             `:entrada :port` value on a matching destination \
21817             under the outer accessor's reference projection",
21818        );
21819    }
21820
21821    #[test]
21822    fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
21823        // The canonical per-`:politicas` `:mtls-required` mTLS-
21824        // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
21825        // must return the `:politicas :mtls-required` typed bool
21826        // verbatim as an `Option<bool>`, byte-equal to the raw field
21827        // access across every value in the three-way accept-set —
21828        // `None` (cluster default applies), `Some(true)` (mTLS
21829        // handshake enforced — the sandboxing-by-default arm the
21830        // MeshPolicy's docstring names), `Some(false)` (handshake
21831        // skipped — the explicit debug-edge opt-out).
21832        //
21833        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
21834        // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
21835        // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
21836        // shape — first `Option<Copy-T>`-return accessor on the M3
21837        // mesh-slot family. Pins against a future silent detour that
21838        // re-derived the toggle from a peer axis (an accidental
21839        // `.circuit_breaker.is_some()` collapse that assumed mTLS on
21840        // whenever a breaker is set), a `None` → `Some(false)` cluster-
21841        // default projection (the canonical `Option<bool>` → `bool`
21842        // collapse footgun the surrounding `is_empty()` predicate
21843        // guards on the peer emptiness axis), or a `Some(true)` /
21844        // `Some(false)` variant swap that landed on one consumer
21845        // without the other.
21846        for required in [None, Some(true), Some(false)] {
21847            let p = MeshPolicy {
21848                mtls_required: required,
21849                ..MeshPolicy::default()
21850            };
21851            assert_eq!(
21852                p.mtls_required(),
21853                required,
21854                "MeshPolicy::mtls_required must return :politicas \
21855                 :mtls-required verbatim (got {:?}, expected {required:?})",
21856                p.mtls_required(),
21857            );
21858            assert_eq!(
21859                p.mtls_required(),
21860                p.mtls_required,
21861                "MeshPolicy::mtls_required must byte-equal the raw \
21862                 .mtls_required field access across every value in the \
21863                 three-way accept-set",
21864            );
21865        }
21866    }
21867
21868    #[test]
21869    fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
21870        // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
21871        // arm must key off [`MeshPolicy::mtls_required`], not the raw
21872        // `.mtls_required` field access. Structurally: toggling ONLY
21873        // the `mtls_required` slot on an otherwise-default MeshPolicy
21874        // must flip `is_empty()` from `true` (all-`None`) to `false`
21875        // (one axis carries a value); the flip must be observed for
21876        // both `Some(true)` and `Some(false)` since the emptiness
21877        // semantic reads "any axis carries a value" — not "any axis
21878        // carries a truthy value" — the same non-collapsing shape the
21879        // sibling M2 [`crate::LimitsSpec::is_empty`] /
21880        // [`crate::BehaviorSpec::is_empty`] predicates carry on their
21881        // peer `Option<T>`-typed slot surfaces.
21882        //
21883        // Pins against a future silent detour that re-derived the
21884        // emptiness predicate off a peer axis (an accidental
21885        // `.rate_limit.is_none()`-only chain that dropped the
21886        // `mtls_required` arm entirely), a `mtls_required == Some(_)`
21887        // collapse to a truthy-only check (which would silently
21888        // classify `Some(false)` as empty), or an accessor-side
21889        // detour that no longer names the substrate-primitive typed
21890        // dispatch (an accidental `self.mtls_required.unwrap_or(false)
21891        // == false` fallback in the accessor that would silently
21892        // classify both `None` and `Some(false)` as the same value).
21893        //
21894        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
21895        // (7cd2a28) accessor-composition pin on the sibling optional-
21896        // scalar axis — same "the emptiness / shape-gate predicate
21897        // must route through the substrate-primitive typed dispatch"
21898        // discipline extended onto the peer per-`:politicas` emptiness
21899        // predicate.
21900        let empty = MeshPolicy::default();
21901        assert!(
21902            empty.is_empty(),
21903            "MeshPolicy::default() must be is_empty() — every axis \
21904             defaults to None",
21905        );
21906        for required in [Some(true), Some(false)] {
21907            let p = MeshPolicy {
21908                mtls_required: required,
21909                ..MeshPolicy::default()
21910            };
21911            assert!(
21912                !p.is_empty(),
21913                "MeshPolicy::is_empty must return false when \
21914                 :mtls-required is {required:?} — the emptiness \
21915                 predicate reads \"any axis carries a value\", not \
21916                 \"any axis carries a truthy value\"",
21917            );
21918            assert_eq!(
21919                p.mtls_required().is_none(),
21920                p.is_empty(),
21921                "when :mtls-required is the only set axis, \
21922                 is_empty() must equal mtls_required().is_none() — \
21923                 the accessor and the emptiness predicate must \
21924                 route through the same substrate-primitive typed \
21925                 dispatch on the :mtls-required arm",
21926            );
21927        }
21928    }
21929
21930    #[test]
21931    fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
21932        // The by-copy pin: [`MeshPolicy::mtls_required`] returns
21933        // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
21934        // accessor must return by value, not by reference. Peer of the
21935        // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
21936        // borrow-invariant pin on the sibling `Option<String>` slot,
21937        // but extended onto the peer `Option<bool>` copy-invariant
21938        // shape — the accessor's returned `Option<bool>` must outlive
21939        // `&self` (multiple calls must return equal values from a
21940        // dropped-`&self` copy, since the returned Option carries no
21941        // borrow), and calling the accessor twice on the same
21942        // MeshPolicy must yield the same `Option<bool>` verbatim
21943        // (idempotent, no side effects on `&self`).
21944        //
21945        // Pins against a future silent detour that returned
21946        // `Option<&bool>` (which would type-check but silently break
21947        // every downstream caller — [`single_field_overlay`]'s first
21948        // parameter is `Option<T: Clone>`, and `&bool` would fold to a
21949        // detached copy at the call site), an accidental
21950        // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
21951        // would also type-check but return `Option<&bool>`), or a
21952        // one-arm-only accessor that reads `Some(*b)` in the Some arm
21953        // but reads a fresh Default::default() in the None arm.
21954        for required in [None, Some(true), Some(false)] {
21955            let p = MeshPolicy {
21956                mtls_required: required,
21957                ..MeshPolicy::default()
21958            };
21959            let first = p.mtls_required();
21960            let second = p.mtls_required();
21961            assert_eq!(
21962                first, second,
21963                "MeshPolicy::mtls_required must be idempotent — two \
21964                 successive calls on the same &self must return the \
21965                 same Option<bool>",
21966            );
21967            assert_eq!(
21968                first, required,
21969                "MeshPolicy::mtls_required must return :politicas \
21970                 :mtls-required verbatim by copy — got {first:?}, \
21971                 expected {required:?}",
21972            );
21973        }
21974    }
21975
21976    #[test]
21977    fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
21978        // The canonical per-`:politicas` `:retries` transient-failure-
21979        // retry-budget scalar pin: [`MeshPolicy::retries`] must return
21980        // the `:politicas :retries` typed `u32` verbatim as an
21981        // `Option<u32>`, byte-equal to the raw field access across every
21982        // representative value in the accept-set — `None` (cluster
21983        // default applies — typically "no retries beyond a single
21984        // dispatch attempt" the caixa-mesh `retry_overlay` builder
21985        // documents), `Some(1)` (the lower boundary of the
21986        // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
21987        // `AplicacaoSpec::validate_politicas` gate carves out on the
21988        // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
21989        // (the upper boundary the same gate carves out on the sibling
21990        // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
21991        // past-the-guard sentinel that pins the accessor doesn't perform
21992        // a silent bounds-collapse at the return path).
21993        //
21994        // Sibling of the peer per-`:politicas`
21995        // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
21996        // sibling `Option<Copy-T>` optional-scalar axis, extended to the
21997        // peer per-`:politicas` `Option<u32>` shape — second
21998        // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
21999        // Pins against a future silent detour that re-derived the retry
22000        // cap from a peer axis (an accidental `.circuit_breaker
22001        // .as_ref().map(|b| b.max_failures)` collapse that read the
22002        // breaker's max-failure count as a retry budget), a
22003        // `None → Some(0)` cluster-default projection (which would
22004        // silently re-introduce the `PolicyRetriesZero` refusal case at
22005        // the emit boundary), or a bounds-collapsing accessor that
22006        // clamped the return through `POLICY_RETRIES_MAX` (the
22007        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
22008        // must ship the raw slot verbatim so a validate-time gate
22009        // regression surfaces at the emit boundary rather than being
22010        // silently absorbed).
22011        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
22012            let p = MeshPolicy {
22013                retries,
22014                ..MeshPolicy::default()
22015            };
22016            assert_eq!(
22017                p.retries(),
22018                retries,
22019                "MeshPolicy::retries must return :politicas :retries \
22020                 verbatim (got {:?}, expected {retries:?})",
22021                p.retries(),
22022            );
22023            assert_eq!(
22024                p.retries(),
22025                p.retries,
22026                "MeshPolicy::retries must byte-equal the raw .retries \
22027                 field access across every value in the accept-set",
22028            );
22029        }
22030    }
22031
22032    #[test]
22033    fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
22034        // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
22035        // must key off [`MeshPolicy::retries`], not the raw `.retries`
22036        // field access. Structurally: toggling ONLY the `retries` slot
22037        // on an otherwise-default MeshPolicy must flip `is_empty()`
22038        // from `true` (all-`None`) to `false` (one axis carries a
22039        // value); the flip must be observed for every value in the
22040        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
22041        // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
22042        // the emptiness semantic reads "any axis carries a value" —
22043        // not "any axis carries a value the validate gate accepts" —
22044        // the same non-collapsing shape the peer M2
22045        // [`crate::LimitsSpec::is_empty`] /
22046        // [`crate::BehaviorSpec::is_empty`] predicates carry.
22047        //
22048        // Pins against a future silent detour that re-derived the
22049        // emptiness predicate off a peer axis (an accidental
22050        // `.rate_limit.is_none()`-only chain that dropped the
22051        // `retries` arm entirely), a `retries == Some(_)` collapse
22052        // that key-off a validate-gate-clamped bounds check (which
22053        // would silently classify a past-the-guard `Some(u32::MAX)`
22054        // as empty because it fails the `1..=POLICY_RETRIES_MAX`
22055        // check), or an accessor-side detour that no longer names the
22056        // substrate-primitive typed dispatch.
22057        //
22058        // Sibling of the peer per-`:politicas`
22059        // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
22060        // pin on the sibling `Option<Copy-T>` optional-scalar axis —
22061        // same "the emptiness predicate must route through the
22062        // substrate-primitive typed dispatch" discipline extended onto
22063        // the peer per-`:politicas` `Option<u32>` axis.
22064        let empty = MeshPolicy::default();
22065        assert!(
22066            empty.is_empty(),
22067            "MeshPolicy::default() must be is_empty() — every axis \
22068             defaults to None",
22069        );
22070        for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
22071            let p = MeshPolicy {
22072                retries,
22073                ..MeshPolicy::default()
22074            };
22075            assert!(
22076                !p.is_empty(),
22077                "MeshPolicy::is_empty must return false when \
22078                 :retries is {retries:?} — the emptiness \
22079                 predicate reads \"any axis carries a value\", not \
22080                 \"any axis carries a value the validate gate \
22081                 accepts\"",
22082            );
22083            assert_eq!(
22084                p.retries().is_none(),
22085                p.is_empty(),
22086                "when :retries is the only set axis, is_empty() \
22087                 must equal retries().is_none() — the accessor and \
22088                 the emptiness predicate must route through the same \
22089                 substrate-primitive typed dispatch on the :retries \
22090                 arm",
22091            );
22092        }
22093    }
22094
22095    #[test]
22096    fn mesh_policy_retries_projects_option_u32_by_copy() {
22097        // The by-copy pin: [`MeshPolicy::retries`] returns
22098        // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
22099        // accessor must return by value, not by reference. Sibling of
22100        // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
22101        // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
22102        // extended onto the sibling `Option<u32>` copy-invariant
22103        // shape — the accessor's returned `Option<u32>` must outlive
22104        // `&self` (multiple calls must return equal values from a
22105        // dropped-`&self` copy, since the returned Option carries no
22106        // borrow), and calling the accessor twice on the same
22107        // MeshPolicy must yield the same `Option<u32>` verbatim
22108        // (idempotent, no side effects on `&self`).
22109        //
22110        // Pins against a future silent detour that returned
22111        // `Option<&u32>` (which would type-check but silently break
22112        // every downstream caller — [`crate::render::single_field_overlay`]'s
22113        // first parameter is `Option<T: Clone>`, and `&u32` would
22114        // fold to a detached copy at the call site), an accidental
22115        // `Option::as_ref()` projection (`self.retries.as_ref()` would
22116        // also type-check but return `Option<&u32>`), or a one-arm-
22117        // only accessor that reads `Some(*n)` in the Some arm but
22118        // reads a fresh `Default::default()` (`0_u32`) in the None
22119        // arm.
22120        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
22121            let p = MeshPolicy {
22122                retries,
22123                ..MeshPolicy::default()
22124            };
22125            let first = p.retries();
22126            let second = p.retries();
22127            assert_eq!(
22128                first, second,
22129                "MeshPolicy::retries must be idempotent — two \
22130                 successive calls on the same &self must return the \
22131                 same Option<u32>",
22132            );
22133            assert_eq!(
22134                first, retries,
22135                "MeshPolicy::retries must return :politicas :retries \
22136                 verbatim by copy — got {first:?}, expected {retries:?}",
22137            );
22138        }
22139    }
22140
22141    #[test]
22142    fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
22143        // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
22144        // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
22145        // return the `:politicas :timeout` typed [`Duration`] verbatim
22146        // as an `Option<Duration>`, byte-equal to the raw field access
22147        // across every representative value in the accept-set — `None`
22148        // (cluster default applies — typically the gateway class's
22149        // implementation-side per-request wall-clock cap the caixa-mesh
22150        // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
22151        // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
22152        // set the surrounding `AplicacaoSpec::validate_politicas` gate
22153        // carves out on the sibling `PolicyTimeoutZero` /
22154        // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
22155        // (the upper boundary the same gate carves out on the sibling
22156        // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
22157        // (a past-the-guard sentinel that pins the accessor doesn't
22158        // perform a silent bounds-collapse into `None` on the zero-
22159        // Duration arm — validate rejects zero but the accessor must
22160        // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
22161        // past-the-guard sentinel that pins the accessor doesn't
22162        // perform a silent bounds-collapse at the return path).
22163        //
22164        // Sibling of the peer per-`:politicas`
22165        // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
22166        // `Option<u32>` optional-scalar axis and the peer per-
22167        // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
22168        // pin on the sibling `Option<bool>` optional-scalar axis,
22169        // extended onto the peer per-`:politicas` `Option<Duration>`
22170        // shape — third `Option<Copy-T>`-return accessor on the M3
22171        // mesh-slot family. Pins against a future silent detour that
22172        // re-derived the per-call cap from a peer axis (an accidental
22173        // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
22174        // read the breaker's rolling-window duration as a per-call
22175        // deadline), a `None → Some(Duration::MAX)` cluster-default
22176        // projection (which would silently re-introduce the
22177        // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
22178        // blocking" arm at the emit boundary), or a bounds-collapsing
22179        // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
22180        // (the `AplicacaoSpec::validate` gate owns the bounds; the
22181        // accessor must ship the raw slot verbatim so a validate-time
22182        // gate regression surfaces at the emit boundary rather than
22183        // being silently absorbed).
22184        for timeout in [
22185            None,
22186            Some(Duration::from_millis(1)),
22187            Some(POLICY_TIMEOUT_MAX),
22188            Some(Duration::ZERO),
22189            Some(Duration::MAX),
22190        ] {
22191            let p = MeshPolicy {
22192                timeout,
22193                ..MeshPolicy::default()
22194            };
22195            assert_eq!(
22196                p.timeout(),
22197                timeout,
22198                "MeshPolicy::timeout must return :politicas :timeout \
22199                 verbatim (got {:?}, expected {timeout:?})",
22200                p.timeout(),
22201            );
22202            assert_eq!(
22203                p.timeout(),
22204                p.timeout,
22205                "MeshPolicy::timeout must byte-equal the raw .timeout \
22206                 field access across every value in the accept-set",
22207            );
22208        }
22209    }
22210
22211    #[test]
22212    fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
22213        // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
22214        // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
22215        // field access. Structurally: toggling ONLY the `timeout` slot
22216        // on an otherwise-default MeshPolicy must flip `is_empty()`
22217        // from `true` (all-`None`) to `false` (one axis carries a
22218        // value); the flip must be observed for every value in the
22219        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
22220        // gate accepts (`Some(Duration::from_millis(1))`,
22221        // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
22222        // reads "any axis carries a value" — not "any axis carries a
22223        // value the validate gate accepts" — the same non-collapsing
22224        // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
22225        // [`crate::BehaviorSpec::is_empty`] predicates carry.
22226        //
22227        // Pins against a future silent detour that re-derived the
22228        // emptiness predicate off a peer axis (an accidental
22229        // `.rate_limit.is_none()`-only chain that dropped the
22230        // `timeout` arm entirely), a `timeout == Some(_)` collapse
22231        // that key-off a validate-gate-clamped bounds check (which
22232        // would silently classify a past-the-guard `Some(Duration::MAX)`
22233        // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
22234        // check), or an accessor-side detour that no longer names the
22235        // substrate-primitive typed dispatch.
22236        //
22237        // Sibling of the peer per-`:politicas`
22238        // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
22239        // the sibling `Option<u32>` optional-scalar axis and the peer
22240        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
22241        // accessor-composition pin on the sibling `Option<bool>`
22242        // optional-scalar axis — same "the emptiness predicate must
22243        // route through the substrate-primitive typed dispatch"
22244        // discipline extended onto the peer per-`:politicas`
22245        // `Option<Duration>` axis.
22246        let empty = MeshPolicy::default();
22247        assert!(
22248            empty.is_empty(),
22249            "MeshPolicy::default() must be is_empty() — every axis \
22250             defaults to None",
22251        );
22252        for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
22253            let p = MeshPolicy {
22254                timeout,
22255                ..MeshPolicy::default()
22256            };
22257            assert!(
22258                !p.is_empty(),
22259                "MeshPolicy::is_empty must return false when \
22260                 :timeout is {timeout:?} — the emptiness \
22261                 predicate reads \"any axis carries a value\", not \
22262                 \"any axis carries a value the validate gate \
22263                 accepts\"",
22264            );
22265            assert_eq!(
22266                p.timeout().is_none(),
22267                p.is_empty(),
22268                "when :timeout is the only set axis, is_empty() \
22269                 must equal timeout().is_none() — the accessor and \
22270                 the emptiness predicate must route through the same \
22271                 substrate-primitive typed dispatch on the :timeout \
22272                 arm",
22273            );
22274        }
22275    }
22276
22277    #[test]
22278    fn mesh_policy_timeout_projects_option_duration_by_copy() {
22279        // The by-copy pin: [`MeshPolicy::timeout`] returns
22280        // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
22281        // and the accessor must return by value, not by reference.
22282        // Sibling of the peer per-`:politicas`
22283        // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
22284        // sibling `Option<u32>` optional-scalar axis and the peer
22285        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
22286        // by-copy pin on the sibling `Option<bool>` optional-scalar
22287        // axis, extended onto the peer per-`:politicas`
22288        // `Option<Duration>` copy-invariant shape — the accessor's
22289        // returned `Option<Duration>` must outlive `&self` (multiple
22290        // calls must return equal values from a dropped-`&self`
22291        // copy, since the returned Option carries no borrow), and
22292        // calling the accessor twice on the same MeshPolicy must
22293        // yield the same `Option<Duration>` verbatim (idempotent, no
22294        // side effects on `&self`).
22295        //
22296        // Pins against a future silent detour that returned
22297        // `Option<&Duration>` (which would type-check but silently
22298        // break every downstream caller — [`crate::render::single_field_overlay`]'s
22299        // first parameter is `Option<T: Clone>`, and `&Duration`
22300        // would fold to a detached copy at the call site), an
22301        // accidental `Option::as_ref()` projection
22302        // (`self.timeout.as_ref()` would also type-check but return
22303        // `Option<&Duration>`), or a one-arm-only accessor that
22304        // reads `Some(*d)` in the Some arm but reads a fresh
22305        // `Default::default()` (`Duration::ZERO`) in the None arm
22306        // (which would silently re-classify every unset `:timeout`
22307        // as the `PolicyTimeoutZero`-refused zero-Duration value at
22308        // the accessor boundary).
22309        for timeout in [
22310            None,
22311            Some(Duration::from_millis(1)),
22312            Some(POLICY_TIMEOUT_MAX),
22313            Some(Duration::ZERO),
22314            Some(Duration::MAX),
22315        ] {
22316            let p = MeshPolicy {
22317                timeout,
22318                ..MeshPolicy::default()
22319            };
22320            let first = p.timeout();
22321            let second = p.timeout();
22322            assert_eq!(
22323                first, second,
22324                "MeshPolicy::timeout must be idempotent — two \
22325                 successive calls on the same &self must return the \
22326                 same Option<Duration>",
22327            );
22328            assert_eq!(
22329                first, timeout,
22330                "MeshPolicy::timeout must return :politicas :timeout \
22331                 verbatim by copy — got {first:?}, expected {timeout:?}",
22332            );
22333        }
22334    }
22335
22336    #[test]
22337    fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
22338        // The canonical per-`:politicas` `:rate-limit` Envoy-
22339        // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
22340        // [`MeshPolicy::rate_limit`] must return the `:politicas
22341        // :rate-limit` typed [`RateLimit`] verbatim as an
22342        // `Option<RateLimit>`, byte-equal to the raw field access
22343        // across every representative value in the accept-set — `None`
22344        // (cluster default applies — no per-Aplicacao rate declaration,
22345        // the gateway-class per-listener default arm the future caixa-
22346        // mesh `local_rate_limit_overlay` emitter documents),
22347        // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
22348        // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
22349        // accept-set the surrounding
22350        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
22351        // sibling `PolicyRateLimitZero` refusal, paired with the
22352        // canonical-window "1 second" arm of the three-unit
22353        // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
22354        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
22355        // (the upper boundary the same gate carves out on the sibling
22356        // `PolicyRateLimitExceedsCap` refusal, paired with the
22357        // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
22358        // (a past-the-guard sentinel that pins the accessor doesn't
22359        // perform a silent bounds-collapse into `None` on the
22360        // zero-rate/zero-window arm — validate rejects zero but the
22361        // accessor must ship the raw slot verbatim so a validate-time
22362        // gate regression surfaces at the emit boundary rather than
22363        // being silently absorbed), and
22364        // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
22365        // (a past-the-guard sentinel that pins the accessor doesn't
22366        // perform a silent bounds-collapse at the return path).
22367        //
22368        // First `Option<Copy-composite-T>`-return accessor pin on the
22369        // M3 mesh-slot family (peer of the sibling per-`:politicas`
22370        // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
22371        // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
22372        // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
22373        // Copy accessor pins, extended onto the peer per-`:politicas`
22374        // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
22375        // and the accessor returns by value). Pins against a future
22376        // silent detour that re-derived the rate declaration from a
22377        // peer axis (an accidental
22378        // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
22379        // collapse that read the breaker's trip threshold + rolling
22380        // window as a rate declaration), a `None → Some(default())`
22381        // cluster-default projection (which would silently re-
22382        // introduce a "cluster default is 0/s" arm the emit boundary
22383        // would take as "declared but inert" — the canonical
22384        // declared-but-inert footgun the sibling
22385        // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
22386        // amplification-shape axis), a bounds-collapsing accessor
22387        // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
22388        // clamped `rl.window` through [`is_canonical_rate_limit_window`]
22389        // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
22390        // accessor must ship the raw slot verbatim), or a
22391        // by-reference detour (`Option<&RateLimit>`) that broke every
22392        // downstream consumer keying off `Option<RateLimit>` by-copy.
22393        for rl in [
22394            None,
22395            Some(RateLimit {
22396                rate: 1,
22397                window: Duration::from_secs(1),
22398            }),
22399            Some(RateLimit {
22400                rate: POLICY_RATE_LIMIT_MAX,
22401                window: Duration::from_secs(3600),
22402            }),
22403            Some(RateLimit {
22404                rate: 0,
22405                window: Duration::ZERO,
22406            }),
22407            Some(RateLimit {
22408                rate: u32::MAX,
22409                window: Duration::MAX,
22410            }),
22411        ] {
22412            let p = MeshPolicy {
22413                rate_limit: rl,
22414                ..MeshPolicy::default()
22415            };
22416            assert_eq!(
22417                p.rate_limit(),
22418                rl,
22419                "MeshPolicy::rate_limit must return :politicas :rate-limit \
22420                 verbatim (got {:?}, expected {rl:?})",
22421                p.rate_limit(),
22422            );
22423            assert_eq!(
22424                p.rate_limit(),
22425                p.rate_limit,
22426                "MeshPolicy::rate_limit must byte-equal the raw \
22427                 .rate_limit field access across every value in the \
22428                 accept-set",
22429            );
22430        }
22431    }
22432
22433    #[test]
22434    fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
22435        // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
22436        // must key off [`MeshPolicy::rate_limit`], not the raw
22437        // `.rate_limit` field access. Structurally: toggling ONLY the
22438        // `rate_limit` slot on an otherwise-default MeshPolicy must
22439        // flip `is_empty()` from `true` (all-`None`) to `false` (one
22440        // axis carries a value); the flip must be observed for every
22441        // representative value in the accept-set the surrounding
22442        // [`AplicacaoSpec::validate_politicas`] gate accepts
22443        // (`Some(RateLimit { rate: 1, window: 1s })`,
22444        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
22445        // since the emptiness semantic reads "any axis carries a
22446        // value" — not "any axis carries a value the validate gate
22447        // accepts" — the same non-collapsing shape the peer M2
22448        // [`crate::LimitsSpec::is_empty`] /
22449        // [`crate::BehaviorSpec::is_empty`] predicates carry.
22450        //
22451        // Pins against a future silent detour that re-derived the
22452        // emptiness predicate off a peer axis (an accidental
22453        // `.timeout.is_none()`-only chain that dropped the
22454        // `rate_limit` arm entirely — the last unlifted inline field
22455        // access on `is_empty` before this lift), a `rate_limit ==
22456        // Some(_)` collapse that key-off a validate-gate-clamped
22457        // bounds check (which would silently classify a past-the-
22458        // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
22459        // because it fails the value-shape gate), or an accessor-
22460        // side detour that no longer names the substrate-primitive
22461        // typed dispatch.
22462        //
22463        // Fourth "the emptiness predicate must route through the
22464        // substrate-primitive typed dispatch" composition pin on the
22465        // M3 mesh-slot family — closes the last unlifted composition
22466        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
22467        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
22468        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
22469        // 7073d0f is_empty-composition pins on the sibling primitive-
22470        // Copy axes, extended onto the peer per-`:politicas`
22471        // composite-Copy `Option<RateLimit>` axis).
22472        let empty = MeshPolicy::default();
22473        assert!(
22474            empty.is_empty(),
22475            "MeshPolicy::default() must be is_empty() — every axis \
22476             defaults to None",
22477        );
22478        for rl in [
22479            RateLimit {
22480                rate: 1,
22481                window: Duration::from_secs(1),
22482            },
22483            RateLimit {
22484                rate: POLICY_RATE_LIMIT_MAX,
22485                window: Duration::from_secs(3600),
22486            },
22487        ] {
22488            let p = MeshPolicy {
22489                rate_limit: Some(rl),
22490                ..MeshPolicy::default()
22491            };
22492            assert!(
22493                !p.is_empty(),
22494                "MeshPolicy::is_empty must return false when \
22495                 :rate-limit is {rl:?} — the emptiness predicate \
22496                 reads \"any axis carries a value\", not \"any axis \
22497                 carries a value the validate gate accepts\"",
22498            );
22499            assert_eq!(
22500                p.rate_limit().is_none(),
22501                p.is_empty(),
22502                "when :rate-limit is the only set axis, is_empty() \
22503                 must equal rate_limit().is_none() — the accessor \
22504                 and the emptiness predicate must route through the \
22505                 same substrate-primitive typed dispatch on the \
22506                 :rate-limit arm",
22507            );
22508        }
22509    }
22510
22511    #[test]
22512    fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
22513        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
22514        // `:rate-limit` value-shape gate must key off
22515        // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
22516        // field bind. Structurally: a `MeshPolicy` whose only set
22517        // axis is a `Some(RateLimit { rate: 0, .. })` must surface
22518        // the `PolicyRateLimitZero` refusal exactly, and the same
22519        // MeshPolicy with the rate at the canonical lower boundary
22520        // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
22521        // The pair jointly pins the accessor + validate-gate
22522        // composition: any future silent detour that had the accessor
22523        // omit the `Some(RateLimit { rate: 0, .. })` arm (a
22524        // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
22525        // silently absorb the `PolicyRateLimitZero` refusal at the
22526        // accessor boundary — the composition pin catches that at
22527        // caixa-core build time.
22528        //
22529        // Sibling of the peer [`validate_politicas`]
22530        // `:mtls-required` / `:retries` / `:timeout` composition pins
22531        // on the sibling primitive-Copy optional-scalar axes — same
22532        // "the validate / shape-gate predicate must route through the
22533        // substrate-primitive typed dispatch" discipline extended
22534        // onto the peer per-`:politicas` composite-Copy
22535        // `Option<RateLimit>` axis. Second composition-with-accessor
22536        // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
22537        // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
22538        let mut spec = three_member_spec();
22539        spec.politicas = MeshPolicy {
22540            rate_limit: Some(RateLimit {
22541                rate: 0,
22542                window: Duration::from_secs(1),
22543            }),
22544            ..MeshPolicy::default()
22545        };
22546        assert!(
22547            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
22548            "validate_politicas must reject rate == 0 with \
22549             PolicyRateLimitZero — the accessor and the validate gate \
22550             must route through the same substrate-primitive typed \
22551             dispatch on the :rate-limit zero-floor arm",
22552        );
22553        spec.politicas = MeshPolicy {
22554            rate_limit: Some(RateLimit {
22555                rate: 1,
22556                window: Duration::from_secs(1),
22557            }),
22558            ..MeshPolicy::default()
22559        };
22560        assert!(
22561            spec.validate().is_ok(),
22562            "validate_politicas must accept rate == 1 (the canonical \
22563             lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
22564             set) with a canonical 1s window",
22565        );
22566    }
22567
22568    #[test]
22569    fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
22570        // The canonical per-`:politicas` `:circuit-breaker` Envoy-
22571        // `outlier_detection`-mesh consecutive-failure-ejection scalar
22572        // pin: [`MeshPolicy::circuit_breaker`] must return the
22573        // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
22574        // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
22575        // raw field access across every representative value in the
22576        // accept-set — `None` (cluster default applies — no
22577        // per-Aplicacao breaker declaration, the gateway-class per-
22578        // listener default arm the future caixa-mesh
22579        // `outlier_detection_overlay` emitter documents),
22580        // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
22581        // (the lower boundary of the accept-set the surrounding
22582        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
22583        // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
22584        // refusals),
22585        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
22586        // (the upper boundary the same gate carves out on the sibling
22587        // `PolicyBreakerMaxFailuresExceedsCap` /
22588        // `PolicyBreakerWindowExceedsCap` refusals),
22589        // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
22590        // (a past-the-guard sentinel that pins the accessor doesn't
22591        // perform a silent bounds-collapse into `None` on the
22592        // zero-failures/zero-window arm — validate rejects zero but
22593        // the accessor must ship the raw slot verbatim so a validate-
22594        // time gate regression surfaces at the emit boundary rather
22595        // than being silently absorbed), and
22596        // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
22597        // (a past-the-guard sentinel that pins the accessor doesn't
22598        // perform a silent bounds-collapse at the return path).
22599        //
22600        // Second `Option<Copy-composite-T>`-return accessor pin on the
22601        // M3 mesh-slot family (peer of the sibling per-`:politicas`
22602        // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
22603        // composite-Copy accessor pin, and of the sibling per-
22604        // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
22605        // [`MeshPolicy::retries`] bdfb399 /
22606        // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
22607        // accessor pins). Pins against a future silent detour that
22608        // re-derived the breaker declaration from a peer axis (an
22609        // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
22610        // collapse that read the rate-limit's bucket capacity + refill
22611        // period as a breaker declaration), a `None → Some(default())`
22612        // cluster-default projection (which would silently re-
22613        // introduce the `PolicyBreakerZeroFailures` /
22614        // `PolicyBreakerZeroWindow` refusal cases at the emit
22615        // boundary), a bounds-collapsing accessor that clamped
22616        // `cb.max_failures` through
22617        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
22618        // through [`POLICY_BREAKER_WINDOW_MAX`] (the
22619        // [`AplicacaoSpec::validate`] gate owns the bounds; the
22620        // accessor must ship the raw slot verbatim), or a
22621        // by-reference detour (`Option<&CircuitBreaker>`) that broke
22622        // every downstream consumer keying off `Option<CircuitBreaker>`
22623        // by-copy.
22624        for cb in [
22625            None,
22626            Some(CircuitBreaker {
22627                max_failures: 1,
22628                window: Duration::from_millis(1),
22629            }),
22630            Some(CircuitBreaker {
22631                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
22632                window: POLICY_BREAKER_WINDOW_MAX,
22633            }),
22634            Some(CircuitBreaker {
22635                max_failures: 0,
22636                window: Duration::ZERO,
22637            }),
22638            Some(CircuitBreaker {
22639                max_failures: u32::MAX,
22640                window: Duration::MAX,
22641            }),
22642        ] {
22643            let p = MeshPolicy {
22644                circuit_breaker: cb,
22645                ..MeshPolicy::default()
22646            };
22647            assert_eq!(
22648                p.circuit_breaker(),
22649                cb,
22650                "MeshPolicy::circuit_breaker must return :politicas \
22651                 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
22652                p.circuit_breaker(),
22653            );
22654            assert_eq!(
22655                p.circuit_breaker(),
22656                p.circuit_breaker,
22657                "MeshPolicy::circuit_breaker must byte-equal the raw \
22658                 .circuit_breaker field access across every value in \
22659                 the accept-set",
22660            );
22661        }
22662    }
22663
22664    #[test]
22665    fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
22666        // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
22667        // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
22668        // `.circuit_breaker` field access. Structurally: toggling ONLY
22669        // the `circuit_breaker` slot on an otherwise-default MeshPolicy
22670        // must flip `is_empty()` from `true` (all-`None`) to `false`
22671        // (one axis carries a value); the flip must be observed for
22672        // every representative value in the accept-set the surrounding
22673        // [`AplicacaoSpec::validate_politicas`] gate accepts
22674        // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
22675        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
22676        // since the emptiness semantic reads "any axis carries a
22677        // value" — not "any axis carries a value the validate gate
22678        // accepts" — the same non-collapsing shape the peer M2
22679        // [`crate::LimitsSpec::is_empty`] /
22680        // [`crate::BehaviorSpec::is_empty`] predicates carry.
22681        //
22682        // Pins against a future silent detour that re-derived the
22683        // emptiness predicate off a peer axis (an accidental
22684        // `.rate_limit.is_none()`-only chain that dropped the
22685        // `circuit_breaker` arm entirely — the last unlifted inline
22686        // field access on `is_empty` before this lift), a
22687        // `circuit_breaker == Some(_)` collapse that key-off a
22688        // validate-gate-clamped bounds check (which would silently
22689        // classify a past-the-guard `Some(CircuitBreaker { max_failures:
22690        // 0, window: 0s })` as empty because it fails the value-shape
22691        // gate), or an accessor-side detour that no longer names the
22692        // substrate-primitive typed dispatch.
22693        //
22694        // Fifth "the emptiness predicate must route through the
22695        // substrate-primitive typed dispatch" composition pin on the
22696        // M3 mesh-slot family — closes the last unlifted composition
22697        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
22698        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
22699        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
22700        // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
22701        // composition pins on the sibling primitive-Copy + composite-
22702        // Copy axes, extended onto the peer per-`:politicas`
22703        // composite-Copy `Option<CircuitBreaker>` axis).
22704        let empty = MeshPolicy::default();
22705        assert!(
22706            empty.is_empty(),
22707            "MeshPolicy::default() must be is_empty() — every axis \
22708             defaults to None",
22709        );
22710        for cb in [
22711            CircuitBreaker {
22712                max_failures: 1,
22713                window: Duration::from_millis(1),
22714            },
22715            CircuitBreaker {
22716                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
22717                window: POLICY_BREAKER_WINDOW_MAX,
22718            },
22719        ] {
22720            let p = MeshPolicy {
22721                circuit_breaker: Some(cb),
22722                ..MeshPolicy::default()
22723            };
22724            assert!(
22725                !p.is_empty(),
22726                "MeshPolicy::is_empty must return false when \
22727                 :circuit-breaker is {cb:?} — the emptiness predicate \
22728                 reads \"any axis carries a value\", not \"any axis \
22729                 carries a value the validate gate accepts\"",
22730            );
22731            assert_eq!(
22732                p.circuit_breaker().is_none(),
22733                p.is_empty(),
22734                "when :circuit-breaker is the only set axis, \
22735                 is_empty() must equal circuit_breaker().is_none() — \
22736                 the accessor and the emptiness predicate must route \
22737                 through the same substrate-primitive typed dispatch \
22738                 on the :circuit-breaker arm",
22739            );
22740        }
22741    }
22742
22743    #[test]
22744    fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
22745        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
22746        // `:circuit-breaker` value-shape gate must key off
22747        // [`MeshPolicy::circuit_breaker`], not the raw
22748        // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
22749        // whose only set axis is a `Some(CircuitBreaker { max_failures:
22750        // 0, .. })` must surface the `PolicyBreakerZeroFailures`
22751        // refusal exactly, and the same MeshPolicy with the breaker at
22752        // the canonical lower boundary
22753        // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
22754        // pass validate. The pair jointly pins the accessor +
22755        // validate-gate composition: any future silent detour that had
22756        // the accessor omit the `Some(CircuitBreaker { max_failures:
22757        // 0, .. })` arm (a
22758        // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
22759        // collapse) would silently absorb the
22760        // `PolicyBreakerZeroFailures` refusal at the accessor
22761        // boundary — the composition pin catches that at caixa-core
22762        // build time.
22763        //
22764        // Sibling of the peer [`validate_politicas`]
22765        // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
22766        // composition pins on the sibling primitive-Copy + composite-
22767        // Copy optional-scalar axes — same "the validate / shape-gate
22768        // predicate must route through the substrate-primitive typed
22769        // dispatch" discipline extended onto the peer per-`:politicas`
22770        // composite-Copy `Option<CircuitBreaker>` axis. Second
22771        // composition-with-accessor pin on the M3 mesh-slot
22772        // `Option<CircuitBreaker>` arm alongside the
22773        // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
22774        let mut spec = three_member_spec();
22775        spec.politicas = MeshPolicy {
22776            circuit_breaker: Some(CircuitBreaker {
22777                max_failures: 0,
22778                window: Duration::from_millis(1),
22779            }),
22780            ..MeshPolicy::default()
22781        };
22782        assert!(
22783            matches!(
22784                spec.validate(),
22785                Err(AplicacaoError::PolicyBreakerZeroFailures)
22786            ),
22787            "validate_politicas must reject max_failures == 0 with \
22788             PolicyBreakerZeroFailures — the accessor and the validate \
22789             gate must route through the same substrate-primitive \
22790             typed dispatch on the :circuit-breaker zero-floor arm",
22791        );
22792        spec.politicas = MeshPolicy {
22793            circuit_breaker: Some(CircuitBreaker {
22794                max_failures: 1,
22795                window: Duration::from_millis(1),
22796            }),
22797            ..MeshPolicy::default()
22798        };
22799        assert!(
22800            spec.validate().is_ok(),
22801            "validate_politicas must accept a CircuitBreaker at the \
22802             canonical lower boundary (max_failures = 1, window = \
22803             1ms) — the accessor and the validate gate must route \
22804             through the same substrate-primitive typed dispatch on \
22805             the :circuit-breaker arm",
22806        );
22807    }
22808
22809    #[test]
22810    fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
22811        // The canonical per-`:politicas :circuit-breaker` `:max-failures`
22812        // Envoy-outlier-detection trip-threshold scalar pin:
22813        // [`CircuitBreaker::max_failures`] must return the
22814        // `:politicas :circuit-breaker :max-failures` typed `u32`
22815        // verbatim, byte-equal to the raw field access across every
22816        // representative value in the accept-set — `1` (the lower
22817        // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
22818        // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
22819        // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
22820        // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
22821        // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
22822        // refusal), `0` (a past-the-guard sentinel that pins the accessor
22823        // doesn't perform a silent bounds-collapse into `1` on the zero
22824        // arm — validate rejects zero but the accessor must ship the
22825        // raw slot verbatim so a validate-time gate regression surfaces
22826        // at the emit boundary rather than being silently absorbed),
22827        // `u32::MAX` (a past-the-guard sentinel that pins the accessor
22828        // doesn't perform a silent bounds-collapse through
22829        // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
22830        //
22831        // First sub-struct required-scalar accessor pin on the M3
22832        // mesh-slot family — sibling in shape to the peer per-`:membros`
22833        // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
22834        // (a40b0e3) required-`String`-carry accessor pins and the peer
22835        // per-`:contratos` [`WitContract::source`] /
22836        // [`WitContract::destination`] (7f0fd43) required-`String`-carry
22837        // accessor pins, extended onto the peer per-`CircuitBreaker`
22838        // required-`u32` scalar-value axis. Pins against a future silent
22839        // detour that re-derived the trip threshold from a peer axis (an
22840        // accidental `self.window.as_secs() as u32` collapse that read
22841        // the breaker's rolling-window duration as a failure count), a
22842        // `0 → 1` cluster-default projection (which would silently absorb
22843        // the `PolicyBreakerZeroFailures` refusal case at the accessor
22844        // boundary), or a bounds-collapsing accessor that clamped the
22845        // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
22846        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
22847        // must ship the raw slot verbatim).
22848        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
22849            let cb = CircuitBreaker {
22850                max_failures,
22851                window: Duration::from_secs(60),
22852            };
22853            assert_eq!(
22854                cb.max_failures(),
22855                max_failures,
22856                "CircuitBreaker::max_failures must return :politicas \
22857                 :circuit-breaker :max-failures verbatim (got {}, \
22858                 expected {max_failures})",
22859                cb.max_failures(),
22860            );
22861            assert_eq!(
22862                cb.max_failures(),
22863                cb.max_failures,
22864                "CircuitBreaker::max_failures must byte-equal the raw \
22865                 .max_failures field access across every value in the \
22866                 u32 accept-set",
22867            );
22868        }
22869    }
22870
22871    #[test]
22872    fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
22873        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
22874        // `:circuit-breaker :max-failures` zero-floor arm must key off
22875        // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
22876        // field access. Structurally: a `CircuitBreaker { max_failures:
22877        // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
22878        // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
22879        // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
22880        // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
22881        // pass validate. The pair jointly pins the accessor +
22882        // validate-gate composition: any future silent detour that had
22883        // the accessor return a fresh `1` on the zero arm (a
22884        // `.max_failures().max(1)` collapse) would silently absorb the
22885        // `PolicyBreakerZeroFailures` refusal at the accessor boundary
22886        // and the validate gate would accept a struct-literal
22887        // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
22888        // catches that at caixa-core build time.
22889        //
22890        // Peer of the sibling per-`:politicas`
22891        // [`MeshPolicy::mtls_required`] (c0110f1) /
22892        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
22893        // (7073d0f) accessor-composition pins on the sibling optional-
22894        // scalar axes — same "the validate / shape-gate predicate must
22895        // route through the substrate-primitive typed dispatch"
22896        // discipline extended onto the peer per-`CircuitBreaker`
22897        // required-scalar composition axis.
22898        let mut spec = three_member_spec();
22899        spec.politicas = MeshPolicy {
22900            circuit_breaker: Some(CircuitBreaker {
22901                max_failures: 0,
22902                window: Duration::from_secs(60),
22903            }),
22904            ..MeshPolicy::default()
22905        };
22906        assert!(
22907            matches!(
22908                spec.validate(),
22909                Err(AplicacaoError::PolicyBreakerZeroFailures)
22910            ),
22911            "validate_politicas must reject max_failures == 0 with \
22912             PolicyBreakerZeroFailures — the accessor and the validate \
22913             gate must route through the same substrate-primitive typed \
22914             dispatch on the :max-failures zero-floor arm",
22915        );
22916        spec.politicas = MeshPolicy {
22917            circuit_breaker: Some(CircuitBreaker {
22918                max_failures: 1,
22919                window: Duration::from_secs(60),
22920            }),
22921            ..MeshPolicy::default()
22922        };
22923        assert!(
22924            spec.validate().is_ok(),
22925            "validate_politicas must accept max_failures == 1 (the \
22926             lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
22927             accept-set)",
22928        );
22929    }
22930
22931    #[test]
22932    fn circuit_breaker_max_failures_projects_u32_by_copy() {
22933        // The by-copy pin: [`CircuitBreaker::max_failures`] returns
22934        // `u32` by copy — `u32` is `Copy` and the accessor must return
22935        // by value, not by reference. Peer of the sibling
22936        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
22937        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
22938        // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
22939        // optional-scalar axes, extended onto the peer
22940        // per-`CircuitBreaker` required-`u32` copy-invariant shape —
22941        // the accessor's returned `u32` must outlive `&self` (multiple
22942        // calls must return equal values from a dropped-`&self` copy,
22943        // since the returned scalar carries no borrow), and calling
22944        // the accessor twice on the same CircuitBreaker must yield the
22945        // same `u32` verbatim (idempotent, no side effects on `&self`).
22946        //
22947        // Pins against a future silent detour that returned `&u32`
22948        // (which would type-check but silently break every downstream
22949        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
22950        // first parameter is `u32`, and `&u32` would fold to a detached
22951        // copy at the call site with a `*` deref the sibling accessors
22952        // don't need), an accidental `.max_failures.wrapping_add(0)`
22953        // detour that returned a fresh copy through an arithmetic
22954        // no-op (breaking a future `const fn` regression), or a
22955        // one-arm-only accessor that returned a saturating value on
22956        // some sentinel input (breaking the pass-through invariant the
22957        // sibling required-scalar accessors carry).
22958        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
22959            let cb = CircuitBreaker {
22960                max_failures,
22961                window: Duration::from_secs(60),
22962            };
22963            let first = cb.max_failures();
22964            let second = cb.max_failures();
22965            assert_eq!(
22966                first, second,
22967                "CircuitBreaker::max_failures must be idempotent — two \
22968                 successive calls on the same &self must return the \
22969                 same u32",
22970            );
22971            assert_eq!(
22972                first, max_failures,
22973                "CircuitBreaker::max_failures must return :politicas \
22974                 :circuit-breaker :max-failures verbatim by copy — \
22975                 got {first}, expected {max_failures}",
22976            );
22977        }
22978    }
22979
22980    #[test]
22981    fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
22982        // The canonical per-`:politicas :circuit-breaker` `:window`
22983        // Envoy-outlier-detection rolling-observation-interval scalar
22984        // pin: [`CircuitBreaker::window`] must return the
22985        // `:politicas :circuit-breaker :window` typed `Duration`
22986        // verbatim, byte-equal to the raw field access across every
22987        // representative value in the accept-set — `Duration::from_millis(1)`
22988        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
22989        // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
22990        // gate carves out on the sibling `PolicyBreakerZeroWindow`
22991        // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
22992        // same gate carves out on the sibling
22993        // `PolicyBreakerWindowExceedsCap` refusal),
22994        // `Duration::ZERO` (a past-the-guard sentinel that pins the
22995        // accessor doesn't perform a silent bounds-collapse into
22996        // `Duration::from_millis(1)` on the zero arm — validate rejects
22997        // zero but the accessor must ship the raw slot verbatim so a
22998        // validate-time gate regression surfaces at the emit boundary
22999        // rather than being silently absorbed),
23000        // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
23001        // far above the 1h cap — that pins the accessor doesn't perform
23002        // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
23003        // at the return path).
23004        //
23005        // Second sub-struct required-scalar accessor pin on the M3
23006        // mesh-slot family — sibling in shape to the just-landed
23007        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
23008        // (3a74062) required-`u32` accessor pin on the peer
23009        // per-`CircuitBreaker` required-axis, extended onto the
23010        // per-sub-struct required-`Duration` axis. Pins against a
23011        // future silent detour that re-derived the observation window
23012        // from a peer axis (an accidental
23013        // `Duration::from_secs(self.max_failures as u64)` collapse that
23014        // read the breaker's trip count as an observation-interval
23015        // duration), a `Duration::ZERO → Duration::from_millis(1)`
23016        // cluster-default projection (which would silently absorb the
23017        // `PolicyBreakerZeroWindow` refusal case at the accessor
23018        // boundary), or a bounds-collapsing accessor that clamped the
23019        // return through `POLICY_BREAKER_WINDOW_MAX` (the
23020        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
23021        // must ship the raw slot verbatim).
23022        for window in [
23023            Duration::from_millis(1),
23024            POLICY_BREAKER_WINDOW_MAX,
23025            Duration::ZERO,
23026            Duration::from_secs(86_400),
23027        ] {
23028            let cb = CircuitBreaker {
23029                max_failures: 5,
23030                window,
23031            };
23032            assert_eq!(
23033                cb.window(),
23034                window,
23035                "CircuitBreaker::window must return :politicas \
23036                 :circuit-breaker :window verbatim (got {:?}, \
23037                 expected {window:?})",
23038                cb.window(),
23039            );
23040            assert_eq!(
23041                cb.window(),
23042                cb.window,
23043                "CircuitBreaker::window must byte-equal the raw \
23044                 .window field access across every value in the \
23045                 Duration accept-set",
23046            );
23047        }
23048    }
23049
23050    #[test]
23051    fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
23052        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
23053        // `:circuit-breaker :window` zero-floor arm must key off
23054        // [`CircuitBreaker::window`], not the raw `.window` field
23055        // access. Structurally: a `CircuitBreaker { window:
23056        // Duration::ZERO, .. }` embedded in a
23057        // `:politicas :circuit-breaker` slot must surface the
23058        // `PolicyBreakerZeroWindow` refusal exactly, and a
23059        // `CircuitBreaker { window: Duration::from_millis(1), .. }`
23060        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
23061        // accept-set) must pass validate. The pair jointly pins the
23062        // accessor + validate-gate composition: any future silent
23063        // detour that had the accessor return a fresh
23064        // `Duration::from_millis(1)` on the zero arm (a
23065        // `.window().max(Duration::from_millis(1))` collapse) would
23066        // silently absorb the `PolicyBreakerZeroWindow` refusal at the
23067        // accessor boundary and the validate gate would accept a
23068        // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
23069        // — the composition pin catches that at caixa-core build time.
23070        //
23071        // Peer of the sibling per-`CircuitBreaker`
23072        // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
23073        // pin on the peer required-scalar `:max-failures` axis — same
23074        // "the validate / shape-gate predicate must route through the
23075        // substrate-primitive typed dispatch" discipline extended onto
23076        // the peer per-`CircuitBreaker` required-`Duration` composition
23077        // axis.
23078        let mut spec = three_member_spec();
23079        spec.politicas = MeshPolicy {
23080            circuit_breaker: Some(CircuitBreaker {
23081                max_failures: 5,
23082                window: Duration::ZERO,
23083            }),
23084            ..MeshPolicy::default()
23085        };
23086        assert!(
23087            matches!(
23088                spec.validate(),
23089                Err(AplicacaoError::PolicyBreakerZeroWindow)
23090            ),
23091            "validate_politicas must reject window == Duration::ZERO \
23092             with PolicyBreakerZeroWindow — the accessor and the \
23093             validate gate must route through the same substrate-\
23094             primitive typed dispatch on the :window zero-floor arm",
23095        );
23096        spec.politicas = MeshPolicy {
23097            circuit_breaker: Some(CircuitBreaker {
23098                max_failures: 5,
23099                window: Duration::from_millis(1),
23100            }),
23101            ..MeshPolicy::default()
23102        };
23103        assert!(
23104            spec.validate().is_ok(),
23105            "validate_politicas must accept window == \
23106             Duration::from_millis(1) (the lower boundary of the \
23107             1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
23108        );
23109    }
23110
23111    #[test]
23112    fn circuit_breaker_window_projects_duration_by_copy() {
23113        // The by-copy pin: [`CircuitBreaker::window`] returns
23114        // `Duration` by copy — `Duration` is `Copy` and the accessor
23115        // must return by value, not by reference. Peer of the sibling
23116        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
23117        // (3a74062) by-copy pin on the peer required-scalar
23118        // `:max-failures` axis, extended onto the peer
23119        // per-`CircuitBreaker` required-`Duration` copy-invariant shape
23120        // — the accessor's returned `Duration` must outlive `&self`
23121        // (multiple calls must return equal values from a
23122        // dropped-`&self` copy, since the returned scalar carries no
23123        // borrow), and calling the accessor twice on the same
23124        // CircuitBreaker must yield the same `Duration` verbatim
23125        // (idempotent, no side effects on `&self`).
23126        //
23127        // Pins against a future silent detour that returned
23128        // `&Duration` (which would type-check but silently break every
23129        // downstream `Duration`-by-value consumer —
23130        // [`crate::render::require_positive_canonical_bounded_duration`]'s
23131        // first parameter is `Duration`, and `&Duration` would fold to
23132        // a detached copy at the call site with a `*` deref the sibling
23133        // accessors don't need), an accidental `.window + Duration::ZERO`
23134        // detour that returned a fresh copy through an arithmetic
23135        // no-op (breaking a future `const fn` regression), or a
23136        // one-arm-only accessor that returned a saturating value on
23137        // some sentinel input (breaking the pass-through invariant the
23138        // sibling required-scalar accessors carry).
23139        for window in [
23140            Duration::from_millis(1),
23141            POLICY_BREAKER_WINDOW_MAX,
23142            Duration::ZERO,
23143            Duration::from_secs(86_400),
23144        ] {
23145            let cb = CircuitBreaker {
23146                max_failures: 5,
23147                window,
23148            };
23149            let first = cb.window();
23150            let second = cb.window();
23151            assert_eq!(
23152                first, second,
23153                "CircuitBreaker::window must be idempotent — two \
23154                 successive calls on the same &self must return the \
23155                 same Duration",
23156            );
23157            assert_eq!(
23158                first, window,
23159                "CircuitBreaker::window must return :politicas \
23160                 :circuit-breaker :window verbatim by copy — \
23161                 got {first:?}, expected {window:?}",
23162            );
23163        }
23164    }
23165
23166    #[test]
23167    fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
23168        // Apex-identity pair-invariant pin composing both substrate-
23169        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
23170        // and [`WitContract::destination`] — at the emit-side call shape
23171        // every per-`(:de, :para)` CNP L4 port reader now takes. The
23172        // invariant, evaluated per-edge:
23173        //
23174        //   spec.port_for_destination(c.destination()) == expected_port
23175        //
23176        // where `expected_port` is `entrada.port` when
23177        // `c.destination() == entrada.destination()` and
23178        // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
23179        // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
23180        // pin on the per-`:entrada` axis — that pin encodes the apex
23181        // ingress L4 identity via `entrada.destination()`; this pin
23182        // encodes the per-edge L4 identity via `c.destination()`, and
23183        // both compose on the same substrate-primitive resolver so a
23184        // future refactor that silently split either accessor's apex
23185        // behavior surfaces at caixa-core build time.
23186        let mut spec = three_member_spec();
23187        if let Some(e) = spec.entrada.as_mut() {
23188            e.para = "cart".into();
23189            e.port = 8443;
23190        }
23191        let apex_contract = WitContract {
23192            de: "checkout".into(),
23193            para: "cart".into(),
23194            wit: "wasi:http/proxy".into(),
23195            endpoint: Some("/hello".into()),
23196            subject: None,
23197            slot: None,
23198        };
23199        assert_eq!(
23200            spec.port_for_destination(apex_contract.destination()),
23201            8443,
23202            "`spec.port_for_destination(c.destination())` must equal \
23203             `entrada.port` when the contract callee names the ingress \
23204             apex — the CNP per-edge L4 port and the HTTPRoute apex \
23205             backendRef port share this substrate-primitive resolver.",
23206        );
23207        let non_apex_contract = WitContract {
23208            de: "cart".into(),
23209            para: "payment".into(),
23210            wit: "wasi:http/proxy".into(),
23211            endpoint: Some("/charge".into()),
23212            subject: None,
23213            slot: None,
23214        };
23215        assert_eq!(
23216            spec.port_for_destination(non_apex_contract.destination()),
23217            DEFAULT_SERVICO_PORT,
23218            "`spec.port_for_destination(c.destination())` must fall back \
23219             to the substrate-canonical port floor when the contract \
23220             callee is not the ingress apex — the resolver's non-apex \
23221             arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
23222        );
23223    }
23224
23225    #[test]
23226    fn membro_key_consts_are_lower_camel_case_shape() {
23227        // Shape-pin: every `MEMBRO_KEY_*` const must be a
23228        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
23229        // `kebab-case` hyphens, no leading colon, no `PascalCase`
23230        // leading capital, no whitespace / dots) — the canonical shape
23231        // the `#[serde(rename_all = "camelCase")]` derive produces on
23232        // [`Membro`]. A future flip to a non-camelCase attribute at
23233        // the derive surfaces both here (this test fails on the
23234        // stale-constant shape) and at
23235        // `membro_serde_keys_match_lifted_membro_key_consts` (that test
23236        // fails on the mismatch between const and derive). Peer with
23237        // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
23238        // on the sibling `SupervisorSpec` top-level axis.
23239        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
23240            assert!(
23241                !key.is_empty(),
23242                "MEMBRO_KEY_* must be non-empty (got {key:?})"
23243            );
23244            let first = key.chars().next().unwrap();
23245            assert!(
23246                first.is_ascii_lowercase(),
23247                "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
23248                 (got {key:?}, leads with {first:?})",
23249            );
23250            assert!(
23251                key.chars().all(|c| c.is_ascii_alphanumeric()),
23252                "MEMBRO_KEY_* must be ASCII-alphanumeric only \
23253                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
23254            );
23255        }
23256    }
23257
23258    // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
23259
23260    #[test]
23261    fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
23262        // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
23263        // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
23264        // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
23265        // keys the `#[serde(rename_all = "camelCase")]` attribute on
23266        // [`WitContract`] emits for the required-triad. The three
23267        // sibling payload-arm keys already pin under
23268        // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
23269        // `STORE_FIELD_NAME` — pin all six alongside so a future
23270        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
23271        // verbatim-field-name flip at the derive attribute (any of which
23272        // would silently break every downstream JSON consumer that
23273        // reaches for one of the six via `Value::get(...)`) surfaces
23274        // here as a build-time test failure at `aplicacao.rs`, not as an
23275        // apply-time `.get(<stale-canonical-const>)` returning `None`
23276        // far from the derive-attr drift's commit. Peer with the sibling
23277        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
23278        // pin on the M3 `:membros` per-entry axis — same discipline the
23279        // `Membro` per-entry lift established, extended here to the
23280        // sibling M3 `WitContract` per-`:contratos` entry axis, the last
23281        // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
23282        // axis on the Aplicacao surface without a lifted serde-key peer.
23283        let c = WitContract {
23284            de: "cart".into(),
23285            para: "catalog".into(),
23286            wit: "wasi:http/proxy".into(),
23287            endpoint: Some("/lookup".into()),
23288            subject: None,
23289            slot: None,
23290        };
23291        let json = serde_json::to_string(&c).unwrap();
23292        for key in [
23293            crate::CONTRATO_KEY_DE,
23294            crate::CONTRATO_KEY_PARA,
23295            crate::CONTRATO_KEY_WIT,
23296            WitTarget::HTTP_FIELD_NAME,
23297        ] {
23298            let quoted = format!("\"{key}\"");
23299            assert!(
23300                json.contains(&quoted),
23301                "serialized WitContract must carry the lifted \
23302                 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
23303                 {quoted} verbatim in the JSON emission (got: {json})",
23304            );
23305        }
23306
23307        // Pin the two remaining payload-arm keys by round-tripping a
23308        // `WitContract` under each payload-shape (pub-sub, store) — the
23309        // required-triad appears on every emission but the payload arms
23310        // only surface when their `Option<String>` field is `Some`.
23311        let pubsub = WitContract {
23312            de: "cart".into(),
23313            para: "events".into(),
23314            wit: "nats:pub-sub".into(),
23315            endpoint: None,
23316            subject: Some("orders.placed".into()),
23317            slot: None,
23318        };
23319        let pubsub_json = serde_json::to_string(&pubsub).unwrap();
23320        let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
23321        assert!(
23322            pubsub_json.contains(&pubsub_quoted),
23323            "serialized pub-sub WitContract must carry the lifted \
23324             WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
23325             verbatim in the JSON emission (got: {pubsub_json})",
23326        );
23327        let store = WitContract {
23328            de: "cart".into(),
23329            para: "sessions".into(),
23330            wit: "wasi:keyvalue/store".into(),
23331            endpoint: None,
23332            subject: None,
23333            slot: Some("cart/$id".into()),
23334        };
23335        let store_json = serde_json::to_string(&store).unwrap();
23336        let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
23337        assert!(
23338            store_json.contains(&store_quoted),
23339            "serialized store WitContract must carry the lifted \
23340             WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
23341             verbatim in the JSON emission (got: {store_json})",
23342        );
23343    }
23344
23345    #[test]
23346    fn contrato_key_consts_are_pairwise_distinct() {
23347        // Cross-axis drift-detection pin: a future collapse of the six
23348        // canonical [`WitContract`] per-entry byte-strings onto the same
23349        // value (e.g. an accidental copy-paste flip of
23350        // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
23351        // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
23352        // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
23353        // every downstream probe on one axis onto the sibling axis's
23354        // overlay entry and pass every propagation-probe test that
23355        // expected only the stale axis's value. Peer of the sibling
23356        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
23357        // widened here to the six-way axis the `WitContract`
23358        // required-triad + `WitTarget` payload-triad jointly cover.
23359        let all = [
23360            crate::CONTRATO_KEY_DE,
23361            crate::CONTRATO_KEY_PARA,
23362            crate::CONTRATO_KEY_WIT,
23363            WitTarget::HTTP_FIELD_NAME,
23364            WitTarget::PUBSUB_FIELD_NAME,
23365            WitTarget::STORE_FIELD_NAME,
23366        ];
23367        for (i, a) in all.iter().enumerate() {
23368            for b in all.iter().skip(i + 1) {
23369                assert_ne!(
23370                    a, b,
23371                    "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
23372                     must be pairwise-distinct canonical byte-sequences \
23373                     — got `{a}` == `{b}`",
23374                );
23375            }
23376        }
23377    }
23378
23379    #[test]
23380    fn contrato_key_consts_are_lower_camel_case_shape() {
23381        // Shape-pin: every `CONTRATO_KEY_*` (and every peer
23382        // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
23383        // byte-sequence (no `snake_case` underscores, no `kebab-case`
23384        // hyphens, no leading colon, no `PascalCase` leading capital, no
23385        // whitespace / dots) — the canonical shape the
23386        // `#[serde(rename_all = "camelCase")]` derive produces on
23387        // [`WitContract`]. A future flip to a non-camelCase attribute at
23388        // the derive surfaces both here (this test fails on the
23389        // stale-constant shape) and at
23390        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
23391        // (that test fails on the mismatch between const and derive).
23392        // Peer with `membro_key_consts_are_lower_camel_case_shape`
23393        // (ce80ca0) on the sibling `Membro` per-entry axis.
23394        for key in [
23395            crate::CONTRATO_KEY_DE,
23396            crate::CONTRATO_KEY_PARA,
23397            crate::CONTRATO_KEY_WIT,
23398            WitTarget::HTTP_FIELD_NAME,
23399            WitTarget::PUBSUB_FIELD_NAME,
23400            WitTarget::STORE_FIELD_NAME,
23401        ] {
23402            assert!(
23403                !key.is_empty(),
23404                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
23405                 non-empty (got {key:?})"
23406            );
23407            let first = key.chars().next().unwrap();
23408            assert!(
23409                first.is_ascii_lowercase(),
23410                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
23411                 with an ASCII-lowercase byte (got {key:?}, leads with \
23412                 {first:?})",
23413            );
23414            assert!(
23415                key.chars().all(|c| c.is_ascii_alphanumeric()),
23416                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
23417                 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
23418                 whitespace (got {key:?})",
23419            );
23420        }
23421    }
23422
23423    // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
23424
23425    #[test]
23426    fn entrada_serde_keys_match_lifted_entrada_key_consts() {
23427        // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
23428        // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
23429        // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
23430        // name the exact camelCase JSON keys the
23431        // `#[serde(rename_all = "camelCase")]` attribute on
23432        // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
23433        // pin that each canonical byte-sequence appears verbatim in the
23434        // JSON — a future accidental `rename_all = "snake_case"` /
23435        // `"kebab-case"` / verbatim-field-name flip at the derive
23436        // attribute (any of which would silently break every downstream
23437        // JSON consumer that reaches for one of the four consts via
23438        // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
23439        // emitter's per-Aplicacao hostname/paths/port projection, the
23440        // future `app-operator` reconciler's per-Aplicacao ingress
23441        // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
23442        // materializer's admission-time cross-check) surfaces here as
23443        // a build-time test failure at `aplicacao.rs`, not as an
23444        // apply-time `.get(<stale-canonical-const>)` returning `None`
23445        // far from the derive-attr drift's commit. Peer with the
23446        // sibling
23447        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
23448        // (ca463a4) and
23449        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
23450        // pins on the M3 collection-slot atom axes — same discipline
23451        // both collection-slot lifts established, extended here to the
23452        // singleton `:entrada` mesh-slot atom axis, the last M3
23453        // typed-struct top-level `#[serde(rename_all = "camelCase")]`
23454        // axis on the Aplicacao surface without a lifted serde-key
23455        // peer.
23456        let e = Entrada {
23457            host: "checkout.quero.cloud".into(),
23458            para: "cart".into(),
23459            paths: vec!["/cart".into()],
23460            port: 8080,
23461        };
23462        let json = serde_json::to_string(&e).unwrap();
23463        for key in [
23464            crate::ENTRADA_KEY_HOST,
23465            crate::ENTRADA_KEY_PARA,
23466            crate::ENTRADA_KEY_PATHS,
23467            crate::ENTRADA_KEY_PORT,
23468        ] {
23469            let quoted = format!("\"{key}\"");
23470            assert!(
23471                json.contains(&quoted),
23472                "serialized Entrada must carry the lifted ENTRADA_KEY_* \
23473                 byte-sequence {quoted} verbatim in the JSON emission \
23474                 (got: {json})",
23475            );
23476        }
23477    }
23478
23479    #[test]
23480    fn entrada_key_consts_are_pairwise_distinct() {
23481        // Cross-axis drift-detection pin: a future collapse of the four
23482        // canonical [`Entrada`] singleton byte-strings onto the same
23483        // value (e.g. an accidental copy-paste flip of
23484        // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
23485        // silently reroute every downstream probe on one axis onto the
23486        // sibling axis's overlay entry and pass every propagation-probe
23487        // test that expected only the stale axis's value — the
23488        // Gateway/HTTPRoute emitter would read the hostname string
23489        // where the destination-Servico name was expected (or vice
23490        // versa), the admission-webhook cross-check would compare the
23491        // wrong pair of values, and the resulting Gateway resource
23492        // would either be admitted with garbage or rejected at the
23493        // controller far from the rebrand commit's source. Peer of the
23494        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
23495        // tetrad (40cc4e5), the two-way distinct pin on the
23496        // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
23497        // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
23498        // triad (ca463a4).
23499        let all = [
23500            crate::ENTRADA_KEY_HOST,
23501            crate::ENTRADA_KEY_PARA,
23502            crate::ENTRADA_KEY_PATHS,
23503            crate::ENTRADA_KEY_PORT,
23504        ];
23505        for (i, a) in all.iter().enumerate() {
23506            for b in all.iter().skip(i + 1) {
23507                assert_ne!(
23508                    a, b,
23509                    "ENTRADA_KEY_* consts must be pairwise-distinct \
23510                     canonical byte-sequences — got `{a}` == `{b}`",
23511                );
23512            }
23513        }
23514    }
23515
23516    #[test]
23517    fn entrada_key_consts_are_lower_camel_case_shape() {
23518        // Shape-pin: every `ENTRADA_KEY_*` const must be a
23519        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
23520        // `kebab-case` hyphens, no leading colon, no `PascalCase`
23521        // leading capital, no whitespace / dots) — the canonical shape
23522        // the `#[serde(rename_all = "camelCase")]` derive produces on
23523        // [`Entrada`]. A future flip to a non-camelCase attribute at
23524        // the derive surfaces both here (this test fails on the
23525        // stale-constant shape) and at
23526        // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
23527        // test fails on the mismatch between const and derive). Peer
23528        // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
23529        // and `contrato_key_consts_are_lower_camel_case_shape`
23530        // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
23531        // entry axes.
23532        for key in [
23533            crate::ENTRADA_KEY_HOST,
23534            crate::ENTRADA_KEY_PARA,
23535            crate::ENTRADA_KEY_PATHS,
23536            crate::ENTRADA_KEY_PORT,
23537        ] {
23538            assert!(
23539                !key.is_empty(),
23540                "ENTRADA_KEY_* must be non-empty (got {key:?})"
23541            );
23542            let first = key.chars().next().unwrap();
23543            assert!(
23544                first.is_ascii_lowercase(),
23545                "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
23546                 (got {key:?}, leads with {first:?})",
23547            );
23548            assert!(
23549                key.chars().all(|c| c.is_ascii_alphanumeric()),
23550                "ENTRADA_KEY_* must be ASCII-alphanumeric only \
23551                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
23552            );
23553        }
23554    }
23555
23556    // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
23557
23558    #[test]
23559    fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
23560        // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
23561        // ([`crate::POLITICAS_KEY_TIMEOUT`] /
23562        // [`crate::POLITICAS_KEY_RETRIES`] /
23563        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
23564        // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
23565        // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
23566        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
23567        // on [`MeshPolicy`] emits. Three of the five axes
23568        // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
23569        // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
23570        // camelCase transforms — the derive-attribute is load-bearing
23571        // on those, unlike the sibling `Entrada` / `Membro` /
23572        // `WitContract` structs whose fields are all lowercase-single-
23573        // word and where the derive is a no-op on every axis.
23574        // Serialize a fully-populated [`MeshPolicy`] (every axis
23575        // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
23576        // on none of the five slots) and pin that each canonical
23577        // byte-sequence appears verbatim in the JSON — a future
23578        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
23579        // verbatim-field-name flip at the derive attribute (any of
23580        // which would silently break every downstream JSON consumer
23581        // that reaches for one of the five consts via
23582        // `Value::get(...)` — the future M4 per-edge `:politicas`
23583        // overlay projection onto Cilium `L7Rules` and Gateway API
23584        // `HTTPRoute` backend timeouts, the future
23585        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
23586        // admission-time mesh-policy cross-check, the future
23587        // `feira lint` per-`:politicas` bound-check gate) surfaces here
23588        // as a build-time test failure at `aplicacao.rs`, not as an
23589        // apply-time `.get(<stale-canonical-const>)` returning `None`
23590        // far from the derive-attr drift's commit. Peer with the
23591        // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
23592        // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
23593        // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
23594        // (ce80ca0) pins on the M3 collection-slot / singleton-slot
23595        // atom axes — same discipline every M3 sibling lift
23596        // established, extended here to the singleton `:politicas`
23597        // mesh-slot atom axis, closing the last M3 typed-struct
23598        // top-level `#[serde(rename_all = "camelCase")]` axis on the
23599        // Aplicacao surface without a lifted serde-key peer.
23600        let p = MeshPolicy {
23601            timeout: Some(Duration::from_secs(30)),
23602            retries: Some(3),
23603            circuit_breaker: Some(CircuitBreaker {
23604                max_failures: 5,
23605                window: Duration::from_secs(60),
23606            }),
23607            mtls_required: Some(true),
23608            rate_limit: Some(RateLimit {
23609                rate: 100,
23610                window: Duration::from_secs(1),
23611            }),
23612        };
23613        let json = serde_json::to_string(&p).unwrap();
23614        for key in [
23615            crate::POLITICAS_KEY_TIMEOUT,
23616            crate::POLITICAS_KEY_RETRIES,
23617            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
23618            crate::POLITICAS_KEY_MTLS_REQUIRED,
23619            crate::POLITICAS_KEY_RATE_LIMIT,
23620        ] {
23621            let quoted = format!("\"{key}\"");
23622            assert!(
23623                json.contains(&quoted),
23624                "serialized MeshPolicy must carry the lifted \
23625                 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
23626                 JSON emission (got: {json})",
23627            );
23628        }
23629    }
23630
23631    #[test]
23632    fn politicas_key_consts_are_pairwise_distinct() {
23633        // Cross-axis drift-detection pin: a future collapse of the five
23634        // canonical [`MeshPolicy`] singleton byte-strings onto the same
23635        // value (e.g. an accidental copy-paste flip of
23636        // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
23637        // would silently reroute every downstream probe on one axis
23638        // onto the sibling axis's overlay entry and pass every
23639        // propagation-probe test that expected only the stale axis's
23640        // value — the M4 per-edge `:politicas` overlay projection would
23641        // read the retry-count string where the timeout duration was
23642        // expected (or vice versa), the CR materializer's admission
23643        // cross-check would compare the wrong pair of values, and the
23644        // resulting mesh reconciler would either bind the wrong axis
23645        // or reject the resource at reconcile far from the rebrand
23646        // commit's source. Peer of the sibling four-way distinct pin
23647        // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
23648        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
23649        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
23650        // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
23651        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
23652        let all = [
23653            crate::POLITICAS_KEY_TIMEOUT,
23654            crate::POLITICAS_KEY_RETRIES,
23655            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
23656            crate::POLITICAS_KEY_MTLS_REQUIRED,
23657            crate::POLITICAS_KEY_RATE_LIMIT,
23658        ];
23659        for (i, a) in all.iter().enumerate() {
23660            for b in all.iter().skip(i + 1) {
23661                assert_ne!(
23662                    a, b,
23663                    "POLITICAS_KEY_* consts must be pairwise-distinct \
23664                     canonical byte-sequences — got `{a}` == `{b}`",
23665                );
23666            }
23667        }
23668    }
23669
23670    #[test]
23671    fn politicas_key_consts_are_lower_camel_case_shape() {
23672        // Shape-pin: every `POLITICAS_KEY_*` const must be a
23673        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
23674        // `kebab-case` hyphens, no leading colon, no `PascalCase`
23675        // leading capital, no whitespace / dots) — the canonical shape
23676        // the `#[serde(rename_all = "camelCase")]` derive produces on
23677        // [`MeshPolicy`]. A future flip to a non-camelCase attribute
23678        // at the derive surfaces both here (this test fails on the
23679        // stale-constant shape) and at
23680        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
23681        // (that test fails on the mismatch between const and derive).
23682        // Peer with `entrada_key_consts_are_lower_camel_case_shape`
23683        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
23684        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
23685        // (ca463a4) on the sibling M3 typed-struct axes.
23686        for key in [
23687            crate::POLITICAS_KEY_TIMEOUT,
23688            crate::POLITICAS_KEY_RETRIES,
23689            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
23690            crate::POLITICAS_KEY_MTLS_REQUIRED,
23691            crate::POLITICAS_KEY_RATE_LIMIT,
23692        ] {
23693            assert!(
23694                !key.is_empty(),
23695                "POLITICAS_KEY_* must be non-empty (got {key:?})"
23696            );
23697            let first = key.chars().next().unwrap();
23698            assert!(
23699                first.is_ascii_lowercase(),
23700                "POLITICAS_KEY_* must lead with an ASCII-lowercase \
23701                 byte (got {key:?}, leads with {first:?})",
23702            );
23703            assert!(
23704                key.chars().all(|c| c.is_ascii_alphanumeric()),
23705                "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
23706                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
23707            );
23708        }
23709    }
23710
23711    // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
23712
23713    #[test]
23714    fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
23715        // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
23716        // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
23717        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
23718        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
23719        // [`CircuitBreaker`] emits inside the
23720        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
23721        // two axes (`max_failures` → `maxFailures`) is a non-trivial
23722        // camelCase transform — the derive-attribute is load-bearing on
23723        // that axis, unlike the sibling `window` field where the derive
23724        // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
23725        // pin that each canonical byte-sequence appears verbatim in the
23726        // JSON — a future accidental `rename_all = "snake_case"` /
23727        // `"kebab-case"` / verbatim-field-name flip at the derive
23728        // attribute (any of which would silently break every downstream
23729        // JSON consumer that reaches for one of the two consts via
23730        // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
23731        // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
23732        // per-edge `:politicas` overlay projection onto the mesh's
23733        // per-backend consecutive-failure-counter tripping threshold, the
23734        // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
23735        // admission-time breaker cross-check, the future `feira lint`
23736        // per-`:politicas :circuit-breaker` bound-check gate) surfaces
23737        // here as a build-time test failure at `aplicacao.rs`, not as an
23738        // apply-time `.get(<stale-canonical-const>)` returning `None`
23739        // far from the derive-attr drift's commit. Peer with the sibling
23740        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
23741        // (b55cca7) parent-axis pin — that test pins the outer
23742        // sub-block key the derive on [`MeshPolicy`] emits, this test
23743        // pins the inner keys the derive on the payload type emits, so
23744        // the two together lock the whole [`MeshPolicy`] breaker-tuning
23745        // shape end-to-end at build time.
23746        let cb = CircuitBreaker {
23747            max_failures: 5,
23748            window: Duration::from_secs(60),
23749        };
23750        let json = serde_json::to_string(&cb).unwrap();
23751        for key in [
23752            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
23753            crate::CIRCUIT_BREAKER_KEY_WINDOW,
23754        ] {
23755            let quoted = format!("\"{key}\"");
23756            assert!(
23757                json.contains(&quoted),
23758                "serialized CircuitBreaker must carry the lifted \
23759                 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
23760                 in the JSON emission (got: {json})",
23761            );
23762        }
23763    }
23764
23765    #[test]
23766    fn circuit_breaker_key_consts_are_pairwise_distinct() {
23767        // Cross-axis drift-detection pin: a future collapse of the two
23768        // canonical [`CircuitBreaker`] sub-block byte-strings onto the
23769        // same value (e.g. an accidental copy-paste flip of
23770        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
23771        // `"maxFailures"`) would silently reroute every downstream
23772        // probe on one axis onto the sibling axis's overlay entry and
23773        // pass every propagation-probe test that expected only the
23774        // stale axis's value — the M4 per-edge `:politicas` overlay
23775        // projection would read the failure-count where the window
23776        // duration was expected (or vice versa), the CR materializer's
23777        // admission cross-check would compare the wrong pair of values,
23778        // and the resulting mesh reconciler would either bind the wrong
23779        // axis or reject the resource at reconcile far from the rebrand
23780        // commit's source. Peer of the sibling five-way distinct pin on
23781        // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
23782        // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
23783        // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
23784        // six-way distinct pin on the `CONTRATO_KEY_*` triad +
23785        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
23786        let all = [
23787            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
23788            crate::CIRCUIT_BREAKER_KEY_WINDOW,
23789        ];
23790        for (i, a) in all.iter().enumerate() {
23791            for b in all.iter().skip(i + 1) {
23792                assert_ne!(
23793                    a, b,
23794                    "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
23795                     canonical byte-sequences — got `{a}` == `{b}`",
23796                );
23797            }
23798        }
23799    }
23800
23801    #[test]
23802    fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
23803        // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
23804        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
23805        // `kebab-case` hyphens, no leading colon, no `PascalCase`
23806        // leading capital, no whitespace / dots) — the canonical shape
23807        // the `#[serde(rename_all = "camelCase")]` derive produces on
23808        // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
23809        // at the derive surfaces both here (this test fails on the
23810        // stale-constant shape) and at
23811        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
23812        // (that test fails on the mismatch between const and derive).
23813        // Peer with `politicas_key_consts_are_lower_camel_case_shape`
23814        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
23815        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
23816        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
23817        // (ca463a4) on the sibling M3 typed-struct axes.
23818        for key in [
23819            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
23820            crate::CIRCUIT_BREAKER_KEY_WINDOW,
23821        ] {
23822            assert!(
23823                !key.is_empty(),
23824                "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
23825            );
23826            let first = key.chars().next().unwrap();
23827            assert!(
23828                first.is_ascii_lowercase(),
23829                "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
23830                 byte (got {key:?}, leads with {first:?})",
23831            );
23832            assert!(
23833                key.chars().all(|c| c.is_ascii_alphanumeric()),
23834                "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
23835                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
23836            );
23837        }
23838    }
23839
23840    // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
23841
23842    #[test]
23843    fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
23844        // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
23845        // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
23846        // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
23847        // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
23848        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
23849        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
23850        // [`Placement`] emits. One of the four axes (`shard_key` →
23851        // `shardKey`) is a non-trivial camelCase transform — the
23852        // derive-attribute is load-bearing on that axis, unlike the
23853        // sibling `estrategia` / `clusters` / `affinity` axes whose
23854        // source-side field names carry no `_` and where the derive is a
23855        // no-op. Serialize a fully-populated [`Placement`] (both
23856        // `Option`-carrying axes `Some(_)` so
23857        // `skip_serializing_if = "Option::is_none"` fires on neither of
23858        // the two optional slots) and pin that each canonical
23859        // byte-sequence appears verbatim in the JSON — a future
23860        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
23861        // verbatim-field-name flip at the derive attribute (any of which
23862        // would silently break every downstream consumer that reaches
23863        // for one of the four consts via
23864        // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
23865        // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
23866        // aggregator's per-cluster fanout filter keying off
23867        // `placement.clusters`, the M3 shard-pool dispatch materializer
23868        // keying off `placement.shardKey`, the M3 Adaptive compression
23869        // pass weighting off `placement.affinity`, every downstream
23870        // dispatcher branching on `placement.estrategia`, the future
23871        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
23872        // admission-time placement cross-check, the future `feira lint`
23873        // per-`:placement` bound-check gate) surfaces here as a
23874        // build-time test failure at `aplicacao.rs`, not as an
23875        // apply-time `.get(<stale-canonical-const>)` returning `None`
23876        // far from the derive-attr drift's commit. Peer with the sibling
23877        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
23878        // (b55cca7),
23879        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
23880        // (468e959),
23881        // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
23882        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
23883        // (ca463a4), and
23884        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
23885        // pins on the M3 collection-slot / singleton-slot atom axes —
23886        // closes the last M3 typed-struct top-level
23887        // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
23888        // surface without a drift-detection pin.
23889        let p = Placement {
23890            estrategia: PlacementStrategy::Sharded,
23891            clusters: vec!["rio".into(), "mar".into()],
23892            affinity: Some("data-locality".into()),
23893            shard_key: Some("$tenantId".into()),
23894        };
23895        let json = serde_json::to_string(&p).unwrap();
23896        for key in [
23897            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
23898            crate::M3_PLACEMENT_KEY_CLUSTERS,
23899            crate::M3_PLACEMENT_KEY_AFFINITY,
23900            crate::M3_PLACEMENT_KEY_SHARD_KEY,
23901        ] {
23902            let quoted = format!("\"{key}\"");
23903            assert!(
23904                json.contains(&quoted),
23905                "serialized Placement must carry the lifted \
23906                 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
23907                 the JSON emission (got: {json})",
23908            );
23909        }
23910    }
23911
23912    #[test]
23913    fn m3_placement_key_consts_are_pairwise_distinct() {
23914        // Cross-axis drift-detection pin: a future collapse of the four
23915        // canonical [`Placement`] sub-block byte-strings onto the same
23916        // value (e.g. an accidental copy-paste flip of
23917        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
23918        // `"affinity"`) would silently reroute every downstream probe on
23919        // one axis onto the sibling axis's overlay entry and pass every
23920        // propagation-probe test that expected only the stale axis's
23921        // value — the M3 shard-pool dispatch materializer would read the
23922        // affinity placement-hint where the shard-selection template was
23923        // expected (or vice versa), the M3 Adaptive compression pass's
23924        // cross-check would compare the wrong pair of values, and the
23925        // resulting placement engine would either bind the wrong axis or
23926        // reject the resource at reconcile far from the rebrand commit's
23927        // source. Peer of the sibling two-way distinct pin on the
23928        // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
23929        // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
23930        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
23931        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
23932        // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
23933        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
23934        let all = [
23935            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
23936            crate::M3_PLACEMENT_KEY_CLUSTERS,
23937            crate::M3_PLACEMENT_KEY_AFFINITY,
23938            crate::M3_PLACEMENT_KEY_SHARD_KEY,
23939        ];
23940        for (i, a) in all.iter().enumerate() {
23941            for b in all.iter().skip(i + 1) {
23942                assert_ne!(
23943                    a, b,
23944                    "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
23945                     canonical byte-sequences — got `{a}` == `{b}`",
23946                );
23947            }
23948        }
23949    }
23950
23951    #[test]
23952    fn m3_placement_key_consts_are_lower_camel_case_shape() {
23953        // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
23954        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
23955        // `kebab-case` hyphens, no leading colon, no `PascalCase`
23956        // leading capital, no whitespace / dots) — the canonical shape
23957        // the `#[serde(rename_all = "camelCase")]` derive produces on
23958        // [`Placement`]. A future flip to a non-camelCase attribute at
23959        // the derive surfaces both here (this test fails on the stale-
23960        // constant shape) and at
23961        // `placement_serde_keys_match_lifted_m3_placement_key_consts`
23962        // (that test fails on the mismatch between const and derive).
23963        // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
23964        // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
23965        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
23966        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
23967        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
23968        // (ca463a4) on the sibling M3 typed-struct axes.
23969        for key in [
23970            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
23971            crate::M3_PLACEMENT_KEY_CLUSTERS,
23972            crate::M3_PLACEMENT_KEY_AFFINITY,
23973            crate::M3_PLACEMENT_KEY_SHARD_KEY,
23974        ] {
23975            assert!(
23976                !key.is_empty(),
23977                "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
23978            );
23979            let first = key.chars().next().unwrap();
23980            assert!(
23981                first.is_ascii_lowercase(),
23982                "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
23983                 byte (got {key:?}, leads with {first:?})",
23984            );
23985            assert!(
23986                key.chars().all(|c| c.is_ascii_alphanumeric()),
23987                "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
23988                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
23989            );
23990        }
23991    }
23992
23993    // ── AplicacaoSpec::port_for_destination — the substrate-canonical
23994    //    destination-facing L4 port resolver every per-Aplicacao renderer
23995    //    reaching for a per-destination Servico TCP port axis routes
23996    //    through. The four pin tests below fix the four-way accept-set
23997    //    the resolver must always honor: (:entrada-para-matches,
23998    //    :entrada-para-mismatches, :entrada-none-so-fallback,
23999    //    :entrada-port-non-default-honored) — drift on any arm surfaces
24000    //    at caixa-core build time rather than at cluster-apply time.
24001
24002    #[test]
24003    fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
24004        // The typed `:entrada` block's `:para "cart"` matches the
24005        // queried destination, so the resolver returns the author-
24006        // declared `:port` scalar verbatim — the canonical "the
24007        // destination Servico IS the ingress apex, honor the typed
24008        // listener port" arm of the port-resolution dispatch.
24009        let mut spec = three_member_spec();
24010        if let Some(e) = spec.entrada.as_mut() {
24011            e.para = "cart".into();
24012            e.port = 9090;
24013        }
24014        assert_eq!(
24015            spec.port_for_destination("cart"),
24016            9090,
24017            "port_for_destination(entrada.para) must return entrada.port \
24018             verbatim, not the DEFAULT_SERVICO_PORT fallback"
24019        );
24020    }
24021
24022    #[test]
24023    fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
24024        // The typed `:entrada` block names `:para "cart"`, but the
24025        // queried destination is `"payment"` — a Servico that
24026        // participates in the mesh graph but is not the ingress apex.
24027        // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
24028        // canonical port floor, closing the "non-apex destination reads
24029        // the substrate default" arm. Same fixture the peer
24030        // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
24031        // pin at caixa-mesh exercises through the CNP emit-side path;
24032        // this pin exercises the shared underlying resolver directly.
24033        let spec = three_member_spec();
24034        assert_eq!(
24035            spec.port_for_destination("payment"),
24036            DEFAULT_SERVICO_PORT,
24037            "port_for_destination(non-apex-destination) must route \
24038             through the lifted DEFAULT_SERVICO_PORT canonical port floor"
24039        );
24040    }
24041
24042    #[test]
24043    fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
24044        // Internal-only Aplicacao — no `:entrada` block declared. Every
24045        // per-destination port query falls back to the lifted
24046        // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
24047        // the Aplicacao surface admits `:entrada None` (internal mesh
24048        // with no external gateway); every downstream renderer's per-
24049        // destination port axis must still resolve to a well-defined
24050        // scalar even without an ingress apex.
24051        let mut spec = three_member_spec();
24052        spec.entrada = None;
24053        assert_eq!(
24054            spec.port_for_destination("cart"),
24055            DEFAULT_SERVICO_PORT,
24056            "port_for_destination on an internal-only Aplicacao must \
24057             fall back to the lifted DEFAULT_SERVICO_PORT floor for \
24058             every destination"
24059        );
24060        assert_eq!(
24061            spec.port_for_destination("payment"),
24062            DEFAULT_SERVICO_PORT,
24063            "port_for_destination on an internal-only Aplicacao must \
24064             fall back uniformly across every destination — the fallback \
24065             is not entrada-shape-conditional"
24066        );
24067    }
24068
24069    #[test]
24070    fn port_for_destination_honors_non_default_entrada_port_verbatim() {
24071        // Structural pin against a hypothetical future refactor that
24072        // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
24073        // the resolver (a "normalize to the default when the author's
24074        // port matches the substrate default" collapse) — that would
24075        // break renderer sites that carry meaning on the emitted port
24076        // value beyond bare equality (a future per-cluster listener-
24077        // audit that keys off the author-declared port, not the
24078        // resolved-with-fallback port). Pin that a non-default
24079        // entrada.port is returned verbatim so drift here surfaces at
24080        // caixa-core build time.
24081        let mut spec = three_member_spec();
24082        if let Some(e) = spec.entrada.as_mut() {
24083            e.para = "cart".into();
24084            e.port = 8443;
24085        }
24086        assert_ne!(
24087            8443, DEFAULT_SERVICO_PORT,
24088            "test fixture must probe a port distinct from \
24089             DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
24090        );
24091        assert_eq!(
24092            spec.port_for_destination("cart"),
24093            8443,
24094            "port_for_destination(entrada.para) must return entrada.port \
24095             verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
24096        );
24097    }
24098
24099    #[test]
24100    fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
24101        // Apex-identity pair-invariant pin composing both substrate-
24102        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
24103        // and [`Entrada::destination`] — at the emit-side call shape
24104        // every per-Aplicacao renderer's ingress-apex L4 port reader
24105        // now takes. The invariant:
24106        //
24107        //   spec.port_for_destination(entrada.destination()) == entrada.port
24108        //
24109        // holds by construction under today's single-destination
24110        // `:entrada` slot (`destination()` returns `entrada.para`, and
24111        // the resolver's apex arm matches `para == destination` and
24112        // returns `entrada.port`), and every downstream consumer that
24113        // composes the two accessors at the ingress apex — the
24114        // `caixa_mesh::gateway_routes` HTTPRoute per-rule
24115        // `backendRefs[0].port` emit-site path, the peer future M4 CR
24116        // materializer's admission-webhook that promotes the scalar to
24117        // a per-CR override overlay, every future per-Aplicacao snapshot
24118        // renderer's apex-facing L4 port reader — reaches through the
24119        // same composition. Pin the identity across four permutations
24120        // (`:para` × `:port` including a non-default port to exercise
24121        // the honor-verbatim arm and a non-cart `:para` to exercise
24122        // destination-agnostic identity) so a future refactor that
24123        // silently split either accessor's apex behavior surfaces at
24124        // caixa-core build time — a subtle `destination()` renaming
24125        // that returned `entrada.host.as_str()` instead of
24126        // `entrada.para.as_str()` would blow this pin loudly, closing
24127        // the last quiet failure mode the two lifts admit in composition.
24128        //
24129        // Peer discipline with the sibling caixa-mesh cross-crate pin
24130        // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
24131        // on the two-renderer pair-invariant axis; this pin encodes the
24132        // same two-consumer coherence rule at the substrate-primitive
24133        // level so the invariant survives even if every renderer is
24134        // deleted.
24135        for (para, port) in [
24136            ("cart", DEFAULT_SERVICO_PORT),
24137            ("cart", 8443u16),
24138            ("payment", 9090u16),
24139            ("catalog", 443u16),
24140        ] {
24141            let mut spec = three_member_spec();
24142            if let Some(e) = spec.entrada.as_mut() {
24143                e.para = para.into();
24144                e.port = port;
24145            }
24146            let expected_port = spec
24147                .entrada()
24148                .expect("three_member_spec carries a typed `:entrada` block")
24149                .port();
24150            let composed_port = {
24151                let entrada = spec.entrada().expect("entrada present");
24152                spec.port_for_destination(entrada.destination())
24153            };
24154            assert_eq!(
24155                composed_port, expected_port,
24156                "`spec.port_for_destination(entrada.destination())` must \
24157                 equal `entrada.port` under today's single-destination \
24158                 `:entrada` slot — this is the apex-identity contract \
24159                 every downstream ingress-apex L4 port reader relies on. \
24160                 Input :entrada :para: {para:?}, :entrada :port: {port}"
24161            );
24162        }
24163    }
24164
24165    #[test]
24166    fn port_for_destination_apex_arm_routes_through_destination_accessor() {
24167        // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
24168        // per-`:entrada` apex-arm membership probe must key off
24169        // [`Entrada::destination`], not the raw `.para` field access.
24170        // Structurally: setting ONLY the `:entrada :para` field to a
24171        // fresh non-cart destination on an otherwise-well-formed
24172        // Aplicacao must (1) leave `e.destination()` byte-equal to
24173        // `e.para.as_str()` (the accessor is byte-projective by
24174        // definition), and (2) cause the resolver's apex arm to fire
24175        // and return `entrada.port` at exactly that new destination
24176        // while every other destination string falls through to
24177        // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
24178        // membership check. Pins against a future silent detour that
24179        // (a) re-derived the apex-arm membership probe off
24180        // `e.para == destination` in `port_for_destination` instead of
24181        // `e.destination() == destination`, silently disagreeing with
24182        // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
24183        // consumers (`entrada.destination()` at
24184        // caixa-mesh/src/lib.rs:3173, `c.destination()` at
24185        // caixa-mesh/src/lib.rs:2739) that already reach through the
24186        // accessor, (b) accessor-side introduced a per-tenant alias
24187        // arm the caller was unaware of, silently rewriting an
24188        // author-declared `:para "cart"` value to a canary-aliased
24189        // form — the raw-field-access resolver would fall through to
24190        // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
24191        // while the peer emit-site consumers landed on the aliased
24192        // destination, splitting the ingress-apex L4 port at
24193        // cluster-apply time.
24194        //
24195        // Peer of the sibling
24196        // [`validate_membros_empty_gate_routes_through_nome_accessor`]
24197        // (d0de220) composition pin on the per-`:membros` refusal-arm
24198        // axis — same "the shape-gate predicate must route through the
24199        // substrate-primitive typed dispatch" discipline extended onto
24200        // the per-`:entrada` apex-arm membership-probe axis. Closes
24201        // the last unlifted `.para` production-code read site on
24202        // `Entrada` in `caixa-core` — after this converge every
24203        // `caixa-core` `.para` field access outside the accessor's own
24204        // body and outside the `WitContract` per-`:contratos` sibling
24205        // axis is either a test-side field-setter or a doc-comment
24206        // reference.
24207        for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
24208            let mut spec = three_member_spec();
24209            if let Some(e) = spec.entrada.as_mut() {
24210                e.para = para.into();
24211                e.port = port;
24212            }
24213            let e = spec
24214                .entrada
24215                .as_ref()
24216                .expect("three_member_spec carries a typed `:entrada` block");
24217            assert_eq!(
24218                e.destination(),
24219                e.para.as_str(),
24220                "Entrada::destination must byte-equal the .para field \
24221                 access — an accessor-side detour that no longer \
24222                 projects the raw field would silently split this \
24223                 drift-detection test from the port_for_destination \
24224                 apex-arm membership probe",
24225            );
24226            assert_eq!(
24227                spec.port_for_destination(para),
24228                port,
24229                "port_for_destination must key off the accessor-projected \
24230                 destination and return `entrada.port` on the apex arm — \
24231                 input :entrada :para: {para:?}, :entrada :port: {port}",
24232            );
24233            assert_eq!(
24234                spec.port_for_destination("ghost-destination-never-a-member"),
24235                DEFAULT_SERVICO_PORT,
24236                "port_for_destination must fall through to \
24237                 DEFAULT_SERVICO_PORT on a non-matching destination \
24238                 under the accessor-projected membership check — input \
24239                 :entrada :para: {para:?}, :entrada :port: {port}",
24240            );
24241        }
24242    }
24243
24244    #[test]
24245    fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
24246        // The canonical per-`:politicas :rate-limit` `:rate`
24247        // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
24248        // [`RateLimit::rate`] must return the `:politicas :rate-limit`
24249        // typed `u32` verbatim, byte-equal to the raw field access
24250        // across every representative value in the accept-set — `1` (the
24251        // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
24252        // the surrounding [`AplicacaoSpec::validate_politicas`] gate
24253        // carves out on the sibling `PolicyRateLimitZero` refusal),
24254        // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
24255        // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
24256        // `0` (a past-the-guard sentinel that pins the accessor doesn't
24257        // perform a silent bounds-collapse into `1` on the zero arm —
24258        // validate rejects zero but the accessor must ship the raw slot
24259        // verbatim so a validate-time gate regression surfaces at the
24260        // emit boundary rather than being silently absorbed), `u32::MAX`
24261        // (a past-the-guard sentinel that pins the accessor doesn't
24262        // perform a silent bounds-collapse through
24263        // `POLICY_RATE_LIMIT_MAX` at the return path).
24264        //
24265        // First sub-struct required-scalar accessor pin on the
24266        // `RateLimit` axis — sibling in shape to the peer
24267        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
24268        // required-`u32` accessor pin on the peer per-sub-struct
24269        // required-axis. Pins against a future silent detour that
24270        // re-derived the token capacity from a peer axis (an accidental
24271        // `self.window.as_secs() as u32` collapse that read the
24272        // rate-limit window duration as a token count), a `0 → 1`
24273        // cluster-default projection (which would silently absorb the
24274        // `PolicyRateLimitZero` refusal case at the accessor boundary),
24275        // or a bounds-collapsing accessor that clamped the return
24276        // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
24277        // gate owns the bounds; the accessor must ship the raw slot
24278        // verbatim).
24279        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
24280            let rl = RateLimit {
24281                rate,
24282                window: Duration::from_secs(1),
24283            };
24284            assert_eq!(
24285                rl.rate(),
24286                rate,
24287                "RateLimit::rate must return :politicas :rate-limit :rate \
24288                 verbatim (got {}, expected {rate})",
24289                rl.rate(),
24290            );
24291            assert_eq!(
24292                rl.rate(),
24293                rl.rate,
24294                "RateLimit::rate must byte-equal the raw .rate field \
24295                 access across every value in the u32 accept-set",
24296            );
24297        }
24298    }
24299
24300    #[test]
24301    fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
24302        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
24303        // `:rate-limit :rate` zero-floor arm must key off
24304        // [`RateLimit::rate`], not the raw `.rate` field access.
24305        // Structurally: a `RateLimit { rate: 0, window:
24306        // Duration::from_secs(1) }` embedded in a `:politicas
24307        // :rate-limit` slot must surface the `PolicyRateLimitZero`
24308        // refusal exactly, and a `RateLimit { rate: 1, window:
24309        // Duration::from_secs(1) }` (the lower boundary of the
24310        // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
24311        // The pair jointly pins the accessor + validate-gate composition:
24312        // any future silent detour that had the accessor return a fresh
24313        // `1` on the zero arm (a `.rate().max(1)` collapse) would
24314        // silently absorb the `PolicyRateLimitZero` refusal at the
24315        // accessor boundary and the validate gate would accept a
24316        // struct-literal `RateLimit { rate: 0, .. }` — the composition
24317        // pin catches that at caixa-core build time.
24318        //
24319        // Peer of the sibling per-`CircuitBreaker`
24320        // [`CircuitBreaker::max_failures`] (3a74062) /
24321        // [`CircuitBreaker::window`] (373957f) accessor-composition
24322        // pins on the peer required-scalar axes — same "the validate /
24323        // shape-gate predicate must route through the substrate-primitive
24324        // typed dispatch" discipline extended onto the peer
24325        // per-`RateLimit` required-`u32` composition axis.
24326        let mut spec = three_member_spec();
24327        spec.politicas = MeshPolicy {
24328            rate_limit: Some(RateLimit {
24329                rate: 0,
24330                window: Duration::from_secs(1),
24331            }),
24332            ..MeshPolicy::default()
24333        };
24334        assert!(
24335            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
24336            "validate_politicas must reject rate == 0 with \
24337             PolicyRateLimitZero — the accessor and the validate gate \
24338             must route through the same substrate-primitive typed \
24339             dispatch on the :rate zero-floor arm",
24340        );
24341        spec.politicas = MeshPolicy {
24342            rate_limit: Some(RateLimit {
24343                rate: 1,
24344                window: Duration::from_secs(1),
24345            }),
24346            ..MeshPolicy::default()
24347        };
24348        assert!(
24349            spec.validate().is_ok(),
24350            "validate_politicas must accept rate == 1 (the lower \
24351             boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
24352        );
24353    }
24354
24355    #[test]
24356    fn rate_limit_rate_projects_u32_by_copy() {
24357        // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
24358        // `u32` is `Copy` and the accessor must return by value, not by
24359        // reference. Peer of the sibling per-`CircuitBreaker`
24360        // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
24361        // peer required-scalar `:max-failures` axis, extended onto the
24362        // peer per-`RateLimit` required-`u32` copy-invariant shape —
24363        // the accessor's returned `u32` must outlive `&self` (multiple
24364        // calls must return equal values from a dropped-`&self` copy,
24365        // since the returned scalar carries no borrow), and calling the
24366        // accessor twice on the same RateLimit must yield the same
24367        // `u32` verbatim (idempotent, no side effects on `&self`).
24368        //
24369        // Pins against a future silent detour that returned `&u32`
24370        // (which would type-check but silently break every downstream
24371        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
24372        // first parameter is `u32`, and `&u32` would fold to a detached
24373        // copy at the call site with a `*` deref the sibling accessors
24374        // don't need), an accidental `.rate.wrapping_add(0)` detour that
24375        // returned a fresh copy through an arithmetic no-op (breaking a
24376        // future `const fn` regression), or a one-arm-only accessor
24377        // that returned a saturating value on some sentinel input
24378        // (breaking the pass-through invariant the sibling required-
24379        // scalar accessors carry).
24380        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
24381            let rl = RateLimit {
24382                rate,
24383                window: Duration::from_secs(1),
24384            };
24385            let first = rl.rate();
24386            let second = rl.rate();
24387            assert_eq!(
24388                first, second,
24389                "RateLimit::rate must be idempotent — two successive \
24390                 calls on the same &self must return the same u32",
24391            );
24392            assert_eq!(
24393                first, rate,
24394                "RateLimit::rate must return :politicas :rate-limit :rate \
24395                 verbatim by copy — got {first}, expected {rate}",
24396            );
24397        }
24398    }
24399
24400    #[test]
24401    fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
24402        // The canonical per-`:politicas :rate-limit` `:window`
24403        // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
24404        // pin: [`RateLimit::window`] must return the
24405        // `:politicas :rate-limit :window` typed `Duration` verbatim,
24406        // byte-equal to the raw field access across every
24407        // representative value in the accept-set — `Duration::from_secs(1)`
24408        // (the `"s"` canonical window, the lower row of
24409        // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
24410        // [`AplicacaoSpec::validate_politicas`] gate accepts via
24411        // [`is_canonical_rate_limit_window`]),
24412        // `Duration::from_secs(60)` (the `"m"` canonical window, the
24413        // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
24414        // window, the upper row), `Duration::ZERO` (a past-the-guard
24415        // sentinel that pins the accessor doesn't perform a silent
24416        // bounds-collapse into `Duration::from_secs(1)` on the zero
24417        // arm — validate rejects an off-set window through
24418        // `PolicyRateLimitWindowNotCanonical` but the accessor must
24419        // ship the raw slot verbatim so a validate-time gate
24420        // regression surfaces at the emit boundary rather than being
24421        // silently absorbed), `Duration::from_millis(500)` (a
24422        // sub-canonical past-the-guard sentinel that pins the accessor
24423        // doesn't silently normalize a non-canonical fractional
24424        // magnitude onto the nearest canonical row).
24425        //
24426        // Second sub-struct required-scalar accessor pin on the
24427        // `RateLimit` axis — sibling in shape to the just-landed
24428        // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
24429        // accessor pin on the peer per-sub-struct required-axis,
24430        // extended onto the per-`RateLimit` required-`Duration` axis.
24431        // Pins against a future silent detour that re-derived the
24432        // refill period from a peer axis (an accidental
24433        // `Duration::from_secs(self.rate as u64)` collapse that read
24434        // the rate-limit token capacity as a refill-interval
24435        // duration), a `Duration::ZERO → Duration::from_secs(1)`
24436        // canonical-default projection (which would silently absorb
24437        // the `PolicyRateLimitWindowNotCanonical` refusal case at the
24438        // accessor boundary), or a canonical-set-collapsing accessor
24439        // that clamped the return through [`rate_limit_window_unit`]
24440        // (the `AplicacaoSpec::validate` gate owns the canonical-set
24441        // membership; the accessor must ship the raw slot verbatim).
24442        for window in [
24443            Duration::from_secs(1),
24444            Duration::from_secs(60),
24445            Duration::from_secs(3600),
24446            Duration::ZERO,
24447            Duration::from_millis(500),
24448        ] {
24449            let rl = RateLimit { rate: 100, window };
24450            assert_eq!(
24451                rl.window(),
24452                window,
24453                "RateLimit::window must return :politicas :rate-limit :window \
24454                 verbatim (got {:?}, expected {window:?})",
24455                rl.window(),
24456            );
24457            assert_eq!(
24458                rl.window(),
24459                rl.window,
24460                "RateLimit::window must byte-equal the raw .window field \
24461                 access across every value in the Duration accept-set",
24462            );
24463        }
24464    }
24465
24466    #[test]
24467    fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
24468        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
24469        // `:rate-limit :window` canonical-set arm must key off
24470        // [`RateLimit::window`], not the raw `.window` field access.
24471        // Structurally: a `RateLimit { window: Duration::from_millis(500),
24472        // .. }` embedded in a `:politicas :rate-limit` slot must
24473        // surface the `PolicyRateLimitWindowNotCanonical` refusal
24474        // exactly (with the sub-canonical `Duration::from_millis(500)`
24475        // magnitude carried through verbatim), and a `RateLimit
24476        // { window: Duration::from_secs(1), .. }` (the lower row of
24477        // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
24478        // The pair jointly pins the accessor + validate-gate
24479        // composition: any future silent detour that had the accessor
24480        // normalize the off-set window to the nearest canonical row
24481        // (a `.window().max(Duration::from_secs(1))` collapse, or a
24482        // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
24483        // collapse) would silently absorb the
24484        // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
24485        // boundary — including a drift in the error's `window` payload
24486        // (the emit-side diagnostic reader keys off the offending
24487        // magnitude verbatim, so a normalization at the accessor
24488        // boundary would silently pin the wrong magnitude in the
24489        // refusal). The composition pin catches that at caixa-core
24490        // build time.
24491        //
24492        // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
24493        // (7f81a60) accessor-composition pin on the peer required-
24494        // scalar `:rate` axis — same "the validate / shape-gate
24495        // predicate must route through the substrate-primitive typed
24496        // dispatch, and the error payload must project through the
24497        // same accessor" discipline extended onto the peer
24498        // per-`RateLimit` required-`Duration` composition axis.
24499        let mut spec = three_member_spec();
24500        spec.politicas = MeshPolicy {
24501            rate_limit: Some(RateLimit {
24502                rate: 100,
24503                window: Duration::from_millis(500),
24504            }),
24505            ..MeshPolicy::default()
24506        };
24507        match spec.validate() {
24508            Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
24509                assert_eq!(
24510                    window,
24511                    Duration::from_millis(500),
24512                    "PolicyRateLimitWindowNotCanonical must carry the \
24513                     offending :window magnitude verbatim through the \
24514                     accessor — got {window:?}, expected 500ms",
24515                );
24516            }
24517            other => panic!(
24518                "validate_politicas must reject non-canonical :window \
24519                 with PolicyRateLimitWindowNotCanonical — the accessor \
24520                 and the validate gate must route through the same \
24521                 substrate-primitive typed dispatch on the :window \
24522                 canonical-set arm; got {other:?}",
24523            ),
24524        }
24525        spec.politicas = MeshPolicy {
24526            rate_limit: Some(RateLimit {
24527                rate: 100,
24528                window: Duration::from_secs(1),
24529            }),
24530            ..MeshPolicy::default()
24531        };
24532        assert!(
24533            spec.validate().is_ok(),
24534            "validate_politicas must accept window == Duration::from_secs(1) \
24535             (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
24536        );
24537    }
24538
24539    #[test]
24540    fn rate_limit_window_projects_duration_by_copy() {
24541        // The by-copy pin: [`RateLimit::window`] returns `Duration`
24542        // by copy — `Duration` is `Copy` and the accessor must return
24543        // by value, not by reference. Peer of the sibling per-`RateLimit`
24544        // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
24545        // required-scalar `:rate` axis, extended onto the peer
24546        // per-`RateLimit` required-`Duration` copy-invariant shape —
24547        // the accessor's returned `Duration` must outlive `&self`
24548        // (multiple calls must return equal values from a
24549        // dropped-`&self` copy, since the returned scalar carries no
24550        // borrow), and calling the accessor twice on the same
24551        // RateLimit must yield the same `Duration` verbatim
24552        // (idempotent, no side effects on `&self`).
24553        //
24554        // Pins against a future silent detour that returned
24555        // `&Duration` (which would type-check but silently break every
24556        // downstream `Duration`-by-value consumer —
24557        // [`is_canonical_rate_limit_window`]'s first parameter is
24558        // `Duration`, and `&Duration` would fold to a detached copy at
24559        // the call site with a `*` deref the sibling accessors don't
24560        // need), an accidental `.window + Duration::ZERO` detour that
24561        // returned a fresh copy through an arithmetic no-op (breaking
24562        // a future `const fn` regression), or a one-arm-only accessor
24563        // that returned a canonical fallback on some sentinel input
24564        // (breaking the pass-through invariant the sibling required-
24565        // scalar accessors carry).
24566        for window in [
24567            Duration::from_secs(1),
24568            Duration::from_secs(60),
24569            Duration::from_secs(3600),
24570            Duration::ZERO,
24571            Duration::from_millis(500),
24572        ] {
24573            let rl = RateLimit { rate: 100, window };
24574            let first = rl.window();
24575            let second = rl.window();
24576            assert_eq!(
24577                first, second,
24578                "RateLimit::window must be idempotent — two successive \
24579                 calls on the same &self must return the same Duration",
24580            );
24581            assert_eq!(
24582                first, window,
24583                "RateLimit::window must return :politicas :rate-limit :window \
24584                 verbatim by copy — got {first:?}, expected {window:?}",
24585            );
24586        }
24587    }
24588}